text
stringlengths
10
2.72M
package org.jphototagger.maintainance; import org.jphototagger.api.preferences.Preferences; import org.jphototagger.lib.swing.Dialog; import org.jphototagger.lib.swing.util.ComponentUtil; import org.jphototagger.lib.util.Bundle; import org.openide.util.Lookup; /** * @author Elmar Baumann */ public class RenameFilenamesInRepositoryDialog extends Dialog { private static final long serialVersionUID = 1L; public RenameFilenamesInRepositoryDialog() { super(ComponentUtil.findFrameWithIcon(), true); initComponents(); postInitComponents(); } private void postInitComponents() { setHelpPage(); Preferences prefs = Lookup.getDefault().lookup(Preferences.class); String key = RenameFilenamesInRepositoryDialog.class.getName(); prefs.applySize(key, this); prefs.applyLocation(key, this); } private void setHelpPage() { setHelpPageUrl(Bundle.getString(RenameFilenamesInRepositoryDialog.class, "RenameFilenamesInRepositoryDialog.HelpPage")); } private void checkClosing() { if (!panelDbFilenameReplace.runs()) { setVisible(false); } } @Override public void setVisible(boolean visible) { if (visible) { panelDbFilenameReplace.restore(); } else { panelDbFilenameReplace.persist(); } super.setVisible(visible); } @Override protected void escape() { checkClosing(); } /** * 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") private void initComponents() {//GEN-BEGIN:initComponents panelDbFilenameReplace = new org.jphototagger.maintainance.RenameFilenamesInRepositoryPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/maintainance/Bundle"); // NOI18N setTitle(bundle.getString("RenameFilenamesInRepositoryDialog.title")); // NOI18N setName("Form"); // NOI18N addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); panelDbFilenameReplace.setName("panelDbFilenameReplace"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelDbFilenameReplace, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelDbFilenameReplace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }//GEN-END:initComponents private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing checkClosing(); }//GEN-LAST:event_formWindowClosing // Variables declaration - do not modify//GEN-BEGIN:variables private org.jphototagger.maintainance.RenameFilenamesInRepositoryPanel panelDbFilenameReplace; // End of variables declaration//GEN-END:variables }
package com.cems.fragment; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cems.CEMSDataStore; import com.cems.R; import com.cems.activities.AddEventActivity; import com.cems.adapter.EventAdapter; import com.cems.databinding.FragmentEventBinding; import com.cems.databinding.FragmentRegisteredEventsBinding; import com.cems.model.Event; import com.cems.model.ServerResponse; import com.cems.model.UserType; import com.cems.network.ApiInstance; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * A simple {@link Fragment} subclass. * Use the {@link RegisteredEventsFragment#newInstance} factory method to * create an instance of this fragment. */ public class RegisteredEventsFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private FragmentRegisteredEventsBinding binding; private ProgressDialog progress; public RegisteredEventsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment RegisteredEventsFragment. */ // TODO: Rename and change types and number of parameters public static RegisteredEventsFragment newInstance(String param1, String param2) { RegisteredEventsFragment fragment = new RegisteredEventsFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_registered_events, container, false); progress = new ProgressDialog(getActivity()); progress.setMessage("Getting events..."); progress.setCancelable(false); progress.show(); Call<ServerResponse> data = ApiInstance.getClient().getRegisteredEvents((String) CEMSDataStore.getUserData().getApiKey()); data.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { if (response.isSuccessful()) { ServerResponse serverResponse = response.body(); if (serverResponse != null) { if (serverResponse.getStatusCode() == 0) { if (progress.isShowing()) { progress.dismiss(); } Type arrayList = new TypeToken<ArrayList<Event>>(){}.getType(); ArrayList<Event> events = new Gson().fromJson(serverResponse.getResponseJSON(), arrayList); EventAdapter adapter = new EventAdapter(getActivity(), events); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false); binding.registeredEventsRecyclerView.setLayoutManager(layoutManager); binding.registeredEventsRecyclerView.setAdapter(adapter); } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get events", "Invalid Request\n" + serverResponse.getMessage()); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get events", "Invalid Request\nResponse null"); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get events", "Invalid Request\nResponse failed"); } } @Override public void onFailure(Call<ServerResponse> call, Throwable t) { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot get events", "Server error occured"); } }); return binding.getRoot(); } private void showAlert(final String title, final String msg) { final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); if (title != null) alert.setTitle(title); alert.setMessage(msg); alert.setPositiveButton("Back", (arg0, arg1) -> alert.create().dismiss()); alert.create().show(); } }
package com.ipincloud.iotbj.srv.dao; import com.ipincloud.iotbj.srv.domain.VehicleHistory; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONObject; //(VehicleHistoryDao)车辆进出记录 表数据库访问层 //generate by redcloud,2020-07-24 19:59:21 public interface VehicleHistoryDao { //@param id 主键 //@return 实例对象VehicleHistory VehicleHistory queryById(Long id); //@param jsonObj 过滤条件等 //@return 实例对象 List<Map> vehicleHistoryList(@Param("jsonObj") JSONObject jsonObj); //@param jsonObj 过滤条件等 //@return 总条数list Integer countVehicleHistoryList(@Param("jsonObj") JSONObject jsonObj); //@param jsonObj 过滤条件等 //@return 实例对象VehicleHistory int addInst(@Param("jsonObj") JSONObject jsonObj); //@param jsonObj 过滤条件等 //@return 实例对象VehicleHistory int updateInst(@Param("jsonObj") JSONObject jsonObj); }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import USJavaAPI.AvsInfo; import USJavaAPI.CvdInfo; import USJavaAPI.USHttpsPostRequest; import USJavaAPI.USReceipt; import USJavaAPI.USCavvPurchase; public class TestCavvPurchase { public static void main(String args[]) throws IOException { /********************** Request Variables ****************************/ String host = "esplusqa.moneris.com"; String store_id = "monusqa002"; String api_token = "qatoken"; //boolean status = false; /********************** Transaction Variables ************************/ String order_id; String cust_id = "Customer1"; String amount = "1.00"; String card = "4242424242424242"; String exp = "0912"; String cavv = "AAABBJg0VhI0VniQEjRWAAAAAAA"; String commcard_invoice = "Invoice 5757FRJ8"; String commcard_tax_amount = "1.00"; InputStreamReader isr = new InputStreamReader( System.in ); BufferedReader stdin = new BufferedReader( isr ); System.out.print( "Please enter an order ID "); order_id = stdin.readLine(); /************************** AVS Variables ***************************/ String street_number = "212"; String street_name = "Michigan Avenue"; String zip_code = "87882"; /************************** CVD Variables ***************************/ String cvd_indicator = "1"; String cvd_code = "890"; /********************** Transaction Object **************************/ USCavvPurchase vbvPurchase = new USCavvPurchase (order_id, cust_id, amount, card, exp, cavv, commcard_invoice, commcard_tax_amount); /*************************** AVS Object *****************************/ AvsInfo avsCheck = new AvsInfo(street_number, street_name, zip_code); vbvPurchase.setAvsInfo (avsCheck); /*************************** CVD Object *****************************/ CvdInfo cvdCheck = new CvdInfo (cvd_indicator, cvd_code); vbvPurchase.setCvdInfo (cvdCheck); /************************* Request Object ***************************/ USHttpsPostRequest mpgReq = new USHttpsPostRequest(host, store_id, api_token, vbvPurchase); /*StatusCheck Example USHttpsPostRequest mpgReq = new USHttpsPostRequest(host, store_id, api_token, txnObject, status); */ /********************** Receipt Variables ************************/ try { USReceipt receipt = mpgReq.getReceipt(); System.out.println("CardType = " + receipt.getCardType()); System.out.println("TransAmount = " + receipt.getTransAmount()); System.out.println("TxnNumber = " + receipt.getTxnNumber()); System.out.println("ReceiptId = " + receipt.getReceiptId()); System.out.println("TransType = " + receipt.getTransType()); System.out.println("ReferenceNum = " + receipt.getReferenceNum()); System.out.println("ResponseCode = " + receipt.getResponseCode()); System.out.println("BankTotals = " + receipt.getBankTotals()); System.out.println("Message = " + receipt.getMessage()); System.out.println("AuthCode = " + receipt.getAuthCode()); System.out.println("Complete = " + receipt.getComplete()); System.out.println("TransDate = " + receipt.getTransDate()); System.out.println("TransTime = " + receipt.getTransTime()); System.out.println("Ticket = " + receipt.getTicket()); System.out.println("TimedOut = " + receipt.getTimedOut()); System.out.println("AVS Response = " + receipt.getAvsResultCode()); System.out.println("CVD Response = " + receipt.getCvdResultCode()); System.out.println("CavvResultCode = " + receipt.getCavvResultCode()); //System.out.println("StatusCode = " + receipt.getStatusCode()); //System.out.println("StatusMessage = " + receipt.getStatusMessage()); } catch (Exception e) { e.printStackTrace(); } } }
package de.digitalstreich.Manufact.factory; import de.digitalstreich.Manufact.db.ProductRepository; import de.digitalstreich.Manufact.db.ProductgroupRepository; import de.digitalstreich.Manufact.model.Manufacturer; import de.digitalstreich.Manufact.model.Product; import de.digitalstreich.Manufact.model.Productgroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductgroupFactory { private final ProductgroupRepository productgroupRepository; private final ProductRepository productRepository; @Autowired public ProductgroupFactory(ProductgroupRepository productgroupRepository, ProductRepository productRepository) { this.productgroupRepository = productgroupRepository; this.productRepository = productRepository; } public void createProductgroup(Manufacturer manufacturer) { List<Product> productList = productRepository.findAll(); Productgroup productgroup = new Productgroup( "FooRetailer", "Produkte für den FooRetailer", productList, manufacturer ); productgroupRepository.save(productgroup); } }
package com.alevohin.demo; import com.alevohin.demo.calculator.Calculator; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/") public class CalculatorResource { private final Calculator summator; private final Calculator multiplicator; private final Calculator divider; public CalculatorResource(final Calculator summator, final Calculator multiplicator, final Calculator divider) { this.summator = summator; this.multiplicator = multiplicator; this.divider = divider; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("add/{a}/{b}") public CalculatorResult add(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b) { List<BigDecimal> operands = Arrays.asList(a, b); Collections.sort(operands); return CalculatorResult.of(summator.calculate(operands)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("add/{a}/{b}/{c}") public CalculatorResult add(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b, @PathParam("c") BigDecimal c) { List<BigDecimal> operands = Arrays.asList(a, b, c); Collections.sort(operands); return CalculatorResult.of(summator.calculate(operands)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("subtract/{a}/{b}") public CalculatorResult subtract(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b) { return add(a, b.negate()); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("subtract/{a}/{b}/{c}") public CalculatorResult subtract(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b, @PathParam("c") BigDecimal c) { return add(a, b.negate(), c.negate()); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("multiply/{a}/{b}") public CalculatorResult multiply(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b) { List<BigDecimal> operands = Arrays.asList(a, b); Collections.sort(operands); return CalculatorResult.of(multiplicator.calculate(operands)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("multiply/{a}/{b}/{c}") public CalculatorResult multiply(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b, @PathParam("c") BigDecimal c) { List<BigDecimal> operands = Arrays.asList(a, b, c); Collections.sort(operands); return CalculatorResult.of(multiplicator.calculate(operands)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("divide/{a}/{b}") public CalculatorResult divide(@PathParam("a") BigDecimal a, @PathParam("b") BigDecimal b) { return CalculatorResult.of(divider.calculate(Arrays.asList(a, b))); } }
package plugins.fmp.fmpTools; import plugins.fmp.fmpSequence.SequenceVirtual; public class BuildKymographsOptions { public int analyzeStep = 1; public int startFrame = 1; public int endFrame = 99999999; public SequenceVirtual vSequence = null; public int diskRadius = 5; public boolean doRegistration = false; }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.export.metadata; import java.lang.reflect.Method; import org.springframework.lang.Nullable; /** * Interface used by the {@code MetadataMBeanInfoAssembler} to * read source-level metadata from a managed resource's class. * * @author Rob Harrop * @author Jennifer Hickey * @since 1.2 * @see org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler#setAttributeSource * @see org.springframework.jmx.export.MBeanExporter#setAssembler */ public interface JmxAttributeSource { /** * Implementations should return an instance of {@code ManagedResource} * if the supplied {@code Class} has the appropriate metadata. * Otherwise, should return {@code null}. * @param clazz the class to read the attribute data from * @return the attribute, or {@code null} if not found * @throws InvalidMetadataException in case of invalid attributes */ @Nullable ManagedResource getManagedResource(Class<?> clazz) throws InvalidMetadataException; /** * Implementations should return an instance of {@code ManagedAttribute} * if the supplied {@code Method} has the corresponding metadata. * Otherwise, should return {@code null}. * @param method the method to read the attribute data from * @return the attribute, or {@code null} if not found * @throws InvalidMetadataException in case of invalid attributes */ @Nullable ManagedAttribute getManagedAttribute(Method method) throws InvalidMetadataException; /** * Implementations should return an instance of {@code ManagedMetric} * if the supplied {@code Method} has the corresponding metadata. * Otherwise, should return {@code null}. * @param method the method to read the attribute data from * @return the metric, or {@code null} if not found * @throws InvalidMetadataException in case of invalid attributes */ @Nullable ManagedMetric getManagedMetric(Method method) throws InvalidMetadataException; /** * Implementations should return an instance of {@code ManagedOperation} * if the supplied {@code Method} has the corresponding metadata. * Otherwise, should return {@code null}. * @param method the method to read the attribute data from * @return the attribute, or {@code null} if not found * @throws InvalidMetadataException in case of invalid attributes */ @Nullable ManagedOperation getManagedOperation(Method method) throws InvalidMetadataException; /** * Implementations should return an array of {@code ManagedOperationParameter} * if the supplied {@code Method} has the corresponding metadata. Otherwise, * should return an empty array if no metadata is found. * @param method the {@code Method} to read the metadata from * @return the parameter information. * @throws InvalidMetadataException in the case of invalid attributes. */ ManagedOperationParameter[] getManagedOperationParameters(Method method) throws InvalidMetadataException; /** * Implementations should return an array of {@link ManagedNotification ManagedNotifications} * if the supplied {@code Class} has the corresponding metadata. Otherwise, * should return an empty array. * @param clazz the {@code Class} to read the metadata from * @return the notification information * @throws InvalidMetadataException in the case of invalid metadata */ ManagedNotification[] getManagedNotifications(Class<?> clazz) throws InvalidMetadataException; }
package by.htp.les02.main; public class EighthTask { public static void main(String[] args) { int a = 12; int b = 23; int x = 11; int y = 22; int z = 22; if (a > x & b > y | a > y & b > x | a > z & b > y | a > y & b > z | a > x & b > z | a > z & b > x) { System.out.println("Кирпич пройдёт через отверстие"); } else { System.out.println("Кирпич через отверстие не пройдёт"); } } }
package com.citibank.ods.persistence.pl.dao.rdb.oracle; import com.citibank.ods.persistence.util.CitiStatement; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import com.citibank.ods.common.connection.rdb.ManagedRdbConnection; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.dataset.ResultSetDataSet; import com.citibank.ods.common.exception.NoRowsReturnedException; import com.citibank.ods.common.exception.UnexpectedException; import com.citibank.ods.entity.pl.BaseTo3ProductAccountEntity; import com.citibank.ods.entity.pl.To3ProductAccountHistEntity; import com.citibank.ods.entity.pl.valueobject.To3ProductAccountHistEntityVO; import com.citibank.ods.persistence.pl.dao.To3ProductAccountHistDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory; /** * @author m.nakamura * * Implementação da interface para acesso ao banco de dados de histórico de * conta de produtos. */ public class OracleTo3ProductAccountHistDAO extends BaseOracleTo3ProductAccountDAO implements To3ProductAccountHistDAO { // Tabela TO3_PRODUCT_ACCOUNT_HIST private static final String C_TO3_PRODUCT_ACCOUNT_HIST = C_O3_SCHEMA + "TO3_PRODUCT_ACCOUNT_HIST"; // Data de referência do registro no histórico protected String C_PROD_ACCT_REF_DATE = "PROD_ACCT_REF_DATE"; // Tabela TPL_CUSTOMER_PRVT private static final String C_TPL_CUSTOMER_PRVT = C_PL_SCHEMA + "TPL_CUSTOMER_PRVT"; //Usuário que aprovou cadastro do registro protected String C_LAST_AUTH_USER_ID = "LAST_AUTH_USER_ID"; //Data/hora de aprovação do cadastro do registro protected String C_LAST_AUTH_DATE = "LAST_AUTH_DATE"; // Tabela TPL_PRODUCT private static final String C_TPL_PRODUCT = C_PL_SCHEMA + "TPL_PRODUCT"; //Tabele TBG_POINT_ACCT private static final String C_TBG_POINT_ACCT_INVST = C_BG_SCHEMA + "TBG_POINT_ACCT_INVST"; //Número da conta investimento protected String C_INVST_CUR_ACCT_NBR = "INVST_CUR_ACCT_NBR"; /** * @see com.citibank.ods.persistence.pl.dao.BaseTo3ProductAccountDAO#find(com.citibank.ods.entity.pl.BaseTo3ProductAccountEntity) */ public BaseTo3ProductAccountEntity find( BaseTo3ProductAccountEntity productAccountEntity_ ) { // Converte para o tipo correto para tornar acessível os atibutos da classe // filha. To3ProductAccountHistEntity productAccountEntity = ( To3ProductAccountHistEntity ) productAccountEntity_; To3ProductAccountHistEntityVO productAccountEntityVO = ( To3ProductAccountHistEntityVO ) productAccountEntity.getData(); ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; StringBuffer query = new StringBuffer(); ArrayList productAccountHistEntities; To3ProductAccountHistEntity productAccountHistEntity = null; try { connection = OracleODSDAOFactory.getConnection(); query.append( "SELECT " ); query.append( C_PROD_ACCT_CODE + ", " ); query.append( C_PROD_UNDER_ACCT_CODE + ", " ); query.append( C_CUST_NBR + ", " ); query.append( C_RELTN_NBR + ", " ); query.append( C_CUR_ACCT_NBR + ", " ); query.append( C_PROD_CODE + ", " ); query.append( C_SYS_CODE + ", " ); query.append( C_SYS_SEG_CODE + ", " ); query.append( C_ORIG_PROD_ACCT_NBR + ", " ); query.append( C_PROD_ACCT_STA_DATE + ", " ); query.append( C_PROD_ACCT_END_DATE + ", " ); query.append( C_PROD_ACCT_SIT_CODE + ", " ); query.append( C_PROD_ACCT_ISIN_CODE + ", " ); query.append( C_PROD_ACCT_LEGAL_BUS_CODE + ", " ); query.append( C_PROD_PLCY_23A_IND + ", " ); query.append( C_PROD_PLCY_23B_IND + ", " ); query.append( C_LAST_UPD_DATE + ", " ); query.append( C_LAST_UPD_USER_ID + ", " ); query.append( C_LAST_AUTH_DATE + ", " ); query.append( C_LAST_AUTH_USER_ID + ", " ); query.append( C_PROD_ACCT_PORTF_MGMT_CODE + ", " ); query.append( C_REC_STAT_CODE + ", " ); query.append( C_PROD_ACCT_REF_DATE ); query.append( " FROM " ); query.append( C_TO3_PRODUCT_ACCOUNT_HIST ); query.append( " WHERE " ); query.append( C_PROD_ACCT_CODE + " = ? AND " ); query.append( C_PROD_UNDER_ACCT_CODE + " = ? AND " ); query.append( C_PROD_ACCT_REF_DATE + " = ? " ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); preparedStatement.setLong( 1, productAccountEntityVO.getProdAcctCode().longValue() ); preparedStatement.setLong( 2, productAccountEntityVO.getProdUnderAcctCode().longValue() ); preparedStatement.setTimestamp( 3, new Timestamp( productAccountEntityVO.getProdAcctRefDate().getTime() ) ); resultSet = preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); productAccountHistEntities = instantiateFromResultSet( resultSet ); if ( productAccountHistEntities.size() == 0 ) { throw new NoRowsReturnedException(); } else if ( productAccountHistEntities.size() > 1 ) { throw new UnexpectedException( C_ERROR_TOO_MANY_ROWS_RETURNED ); } else { productAccountHistEntity = ( To3ProductAccountHistEntity ) productAccountHistEntities.get( 0 ); } return productAccountHistEntity; } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /** * Instancia entidades a partir do ResultSet. * * @param resultSet_ - ResultSet utilizado para instanciar entidades. * @return ArrayList - Entidades instanciadas a partir do ResultSet. */ private ArrayList instantiateFromResultSet( ResultSet resultSet_ ) { To3ProductAccountHistEntity productAccountHistEntity; To3ProductAccountHistEntityVO productAccountHistEntityVO; ArrayList productAccountHistEntities = new ArrayList(); try { while ( resultSet_.next() ) { productAccountHistEntity = new To3ProductAccountHistEntity(); productAccountHistEntityVO = ( To3ProductAccountHistEntityVO ) productAccountHistEntity.getData(); productAccountHistEntityVO.setProdAcctCode( new BigInteger( resultSet_.getString( this.C_PROD_ACCT_CODE ) ) ); productAccountHistEntityVO.setProdUnderAcctCode( new BigInteger( resultSet_.getString( this.C_PROD_UNDER_ACCT_CODE ) ) ); if ( resultSet_.getString( this.C_CUST_NBR ) != null ) { productAccountHistEntityVO.setCustNbr( new BigInteger( resultSet_.getString( this.C_CUST_NBR ) ) ); } if ( resultSet_.getString( this.C_RELTN_NBR ) != null ) { productAccountHistEntityVO.setReltnNbr( new BigInteger( resultSet_.getString( this.C_RELTN_NBR ) ) ); } if ( resultSet_.getString( this.C_CUR_ACCT_NBR ) != null ) { productAccountHistEntityVO.setCurAcctNbr( new BigInteger( resultSet_.getString( this.C_CUR_ACCT_NBR ) ) ); } if ( resultSet_.getString( this.C_PROD_CODE ) != null ) { productAccountHistEntityVO.setProdCode( resultSet_.getString( this.C_PROD_CODE ) ); } if ( resultSet_.getString( this.C_SYS_CODE ) != null ) { productAccountHistEntityVO.setSysCode( resultSet_.getString( this.C_SYS_CODE ) ); } if ( resultSet_.getString( this.C_SYS_SEG_CODE ) != null ) { productAccountHistEntityVO.setSysSegCode( new BigInteger( resultSet_.getString( this.C_SYS_SEG_CODE ) ) ); } if ( resultSet_.getString( this.C_ORIG_PROD_ACCT_NBR ) != null ) { productAccountHistEntityVO.setOrigProdAcctNbr( resultSet_.getString( this.C_ORIG_PROD_ACCT_NBR ) ); } if ( resultSet_.getTimestamp( this.C_PROD_ACCT_STA_DATE ) != null ) { productAccountHistEntityVO.setProdAcctStaDate( resultSet_.getTimestamp( this.C_PROD_ACCT_STA_DATE ) ); } if ( resultSet_.getTimestamp( this.C_PROD_ACCT_END_DATE ) != null ) { productAccountHistEntityVO.setProdAcctEndDate( resultSet_.getTimestamp( this.C_PROD_ACCT_END_DATE ) ); } if ( resultSet_.getTimestamp( this.C_PROD_ACCT_REF_DATE ) != null ) { productAccountHistEntityVO.setProdAcctRefDate( resultSet_.getTimestamp( this.C_PROD_ACCT_REF_DATE ) ); } if ( resultSet_.getString( this.C_PROD_ACCT_SIT_CODE ) != null ) { productAccountHistEntityVO.setProdAcctSitCode( resultSet_.getString( this.C_PROD_ACCT_SIT_CODE ) ); } if ( resultSet_.getString( this.C_PROD_ACCT_LEGAL_BUS_CODE ) != null ) { productAccountHistEntityVO.setProdAcctLegalBusCode( new BigInteger( resultSet_.getString( this.C_PROD_ACCT_LEGAL_BUS_CODE ) ) ); } productAccountHistEntityVO.setLastAuthDate( resultSet_.getTimestamp( this.C_LAST_AUTH_DATE ) ); productAccountHistEntityVO.setLastAuthUserId( resultSet_.getString( this.C_LAST_AUTH_USER_ID ) ); productAccountHistEntityVO.setLastUpdDate( resultSet_.getTimestamp( this.C_LAST_UPD_DATE ) ); productAccountHistEntityVO.setLastUpdUserId( resultSet_.getString( this.C_LAST_UPD_USER_ID ) ); productAccountHistEntityVO.setProdAcctIsinCode( resultSet_.getString( this.C_PROD_ACCT_ISIN_CODE ) ); productAccountHistEntityVO.setProdAcctPortfMgmtCode( resultSet_.getString( this.C_PROD_ACCT_PORTF_MGMT_CODE ) ); productAccountHistEntityVO.setProdAcctPlcy23aInd( resultSet_.getString( this.C_PROD_PLCY_23A_IND ) ); productAccountHistEntityVO.setProdAcctPlcy23bInd( resultSet_.getString( this.C_PROD_PLCY_23B_IND ) ); productAccountHistEntityVO.setRecStatCode( resultSet_.getString( this.C_REC_STAT_CODE ) ); productAccountHistEntities.add( productAccountHistEntity ); } } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e ); } return productAccountHistEntities; } /** * @see com.citibank.ods.persistence.pl.dao.To3ProductAccountHistDAO#list(java.math.BigInteger, * java.math.BigInteger, java.math.BigInteger, java.lang.String, * java.util.Date) */ public DataSet list( BigInteger reltnNbr_, BigInteger custNbr_, BigInteger curAcctNbr_, String prodCode_, Date prodAcctRefDate_, String custFullNameText_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; ResultSetDataSet rsds = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( "SELECT " ); query.append( "ACCT." + C_RELTN_NBR + ", " ); query.append( "ACCT." + C_CUST_NBR + ", " ); query.append( "ACCT." + C_CUR_ACCT_NBR + ", " ); query.append( "PROD." + C_PROD_NAME + ", " ); query.append( "ACCT." + C_SYS_SEG_CODE + ", " ); query.append( "ACCT." + C_PROD_CODE + ", " ); query.append( "ACCT." + C_SYS_CODE + ", " ); query.append( "ACCT." + C_PROD_ACCT_CODE + ", " ); query.append( "ACCT." + C_PROD_UNDER_ACCT_CODE + ", " ); query.append( "ACCT." + C_PROD_ACCT_REF_DATE + ", " ); query.append( "CUST." + C_CUST_FULL_NAME_TEXT + ", " ); query.append( " POINT." + C_INVST_CUR_ACCT_NBR ); query.append( " FROM " ); query.append( C_TO3_PRODUCT_ACCOUNT_HIST + " ACCT " ); query.append( " LEFT JOIN " ); query.append( C_TPL_CUSTOMER_PRVT + " CUST " ); query.append( " ON " ); query.append( " ACCT." + C_CUST_NBR + " = " + "CUST." + C_CUST_NBR ); query.append( " LEFT JOIN " ); query.append( C_TPL_PRODUCT + " PROD " ); query.append( " ON " ); query.append( " ACCT.PROD_CODE = " + "PROD.PROD_CODE AND" ); query.append( " ACCT.SYS_SEG_CODE = " + "PROD.SYS_SEG_CODE " ); query.append( " LEFT JOIN " ); query.append( C_TBG_POINT_ACCT_INVST + " POINT " ); query.append( " ON " ); query.append( " POINT." + C_CUR_ACCT_NBR + " = " ); query.append( "ACCT." + C_CUR_ACCT_NBR ); String criteria = ""; if ( reltnNbr_ != null ) { criteria = criteria + " ACCT." + C_RELTN_NBR + " = ? AND "; } if ( custNbr_ != null ) { criteria = criteria + " ACCT." + C_CUST_NBR + " = ? AND "; } if ( curAcctNbr_ != null ) { criteria = criteria + "ACCT." + C_CUR_ACCT_NBR + " = ? AND "; } if ( prodCode_ != null && !prodCode_.equals( "" ) ) { criteria = criteria + "UPPER(\"" + C_PROD_CODE + "\") LIKE ? AND "; } if ( prodAcctRefDate_ != null ) { criteria = criteria + "TRUNC (ACCT." + C_PROD_ACCT_REF_DATE + ") >= ? AND "; } if ( custFullNameText_ != null && custFullNameText_.length() > 0 ) { criteria = criteria + "UPPER( CUST." + C_CUST_FULL_NAME_TEXT + ") like ? AND "; } if ( criteria.length() > 0 ) { query.append( " WHERE " + criteria.substring( 0, criteria.length() - 5 ) ); } query.append( " ORDER BY " + C_PROD_ACCT_REF_DATE ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if ( reltnNbr_ != null ) { preparedStatement.setLong( count++, reltnNbr_.longValue() ); } if ( custNbr_ != null ) { preparedStatement.setLong( count++, custNbr_.longValue() ); } if ( curAcctNbr_ != null ) { preparedStatement.setLong( count++, curAcctNbr_.longValue() ); } if ( prodCode_ != null && !prodCode_.equals( "" ) ) { preparedStatement.setString( count++, prodCode_.toUpperCase() ); } if ( prodAcctRefDate_ != null ) { preparedStatement.setTimestamp( count++, new Timestamp( prodAcctRefDate_.getTime() ) ); } if ( custFullNameText_ != null && custFullNameText_.length() > 0 ) { preparedStatement.setString( count++, "%" + custFullNameText_.toUpperCase() + "%" ); } resultSet = preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); rsds = new ResultSetDataSet( resultSet ); resultSet.close(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } return rsds; } /** * @see com.citibank.ods.persistence.pl.dao.BaseTo3ProductAccountDAO#update(com.citibank.ods.entity.pl.BaseTo3ProductAccountEntity) */ public void insert( To3ProductAccountHistEntity productAccountHistEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); // Casting para a atribuicao das colunas especificas To3ProductAccountHistEntityVO to3ProductAccountHistEntityVO = ( To3ProductAccountHistEntityVO ) productAccountHistEntity_.getData(); try { connection = OracleODSDAOFactory.getConnection(); query.append( "INSERT INTO " ); query.append( C_TO3_PRODUCT_ACCOUNT_HIST ); query.append( " ( " ); query.append( C_PROD_ACCT_CODE + ", " ); query.append( C_PROD_UNDER_ACCT_CODE + ", " ); query.append( C_PROD_ACCT_REF_DATE + ", " ); query.append( C_CUST_NBR + ", " ); query.append( C_RELTN_NBR + ", " ); query.append( C_CUR_ACCT_NBR + ", " ); query.append( C_PROD_CODE + ", " ); query.append( C_PROD_PLCY_23A_IND + ", " ); query.append( C_PROD_PLCY_23B_IND + ", " ); query.append( C_PROD_ACCT_ISIN_CODE + ", " ); query.append( C_PROD_ACCT_PORTF_MGMT_CODE + ", " ); query.append( C_PROD_ACCT_LEGAL_BUS_CODE + ", " ); query.append( C_SYS_CODE + ", " ); query.append( C_SYS_SEG_CODE + ", " ); query.append( C_ORIG_PROD_ACCT_NBR + ", " ); query.append( C_PROD_ACCT_SIT_CODE + "," ); query.append( C_PROD_ACCT_END_DATE + "," ); query.append( C_PROD_ACCT_STA_DATE + ", " ); query.append( C_REC_STAT_CODE + ") " ); query.append( "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; preparedStatement.setLong( count++, productAccountHistEntity_.getData().getProdAcctCode().longValue() ); preparedStatement.setLong( count++, productAccountHistEntity_.getData().getProdUnderAcctCode().longValue() ); preparedStatement.setTimestamp( count++, new Timestamp( to3ProductAccountHistEntityVO.getProdAcctRefDate().getTime() ) ); if ( productAccountHistEntity_.getData().getCustNbr() != null ) { preparedStatement.setLong( count++, productAccountHistEntity_.getData().getCustNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getReltnNbr() != null ) { preparedStatement.setLong( count++, productAccountHistEntity_.getData().getReltnNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getCurAcctNbr() != null ) { preparedStatement.setLong( count++, productAccountHistEntity_.getData().getCurAcctNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdCode().trim() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctPlcy23aInd() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdAcctPlcy23aInd() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctPlcy23bInd() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdAcctPlcy23bInd() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctIsinCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdAcctIsinCode() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctPortfMgmtCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdAcctPortfMgmtCode() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctLegalBusCode() != null ) { preparedStatement.setLong( count++, productAccountHistEntity_.getData().getProdAcctLegalBusCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getSysCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getSysCode() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getSysSegCode() != null ) { preparedStatement.setLong( count++, productAccountHistEntity_.getData().getSysSegCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getOrigProdAcctNbr() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getOrigProdAcctNbr() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctSitCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getProdAcctSitCode() ); } else { preparedStatement.setString( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctEndDate() != null ) { preparedStatement.setTimestamp( count++, new Timestamp( productAccountHistEntity_.getData().getProdAcctEndDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( productAccountHistEntity_.getData().getProdAcctStaDate() != null ) { preparedStatement.setTimestamp( count++, new Timestamp( productAccountHistEntity_.getData().getProdAcctStaDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( productAccountHistEntity_.getData().getRecStatCode() != null ) { preparedStatement.setString( count++, productAccountHistEntity_.getData().getRecStatCode() ); } else { preparedStatement.setTimestamp( count++, null ); } preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } public ArrayList selectByPk( BigInteger prodAcctCode_, BigInteger prodUnderAcctCode_ ) { return null; } /* (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.BaseTo3ProductAccountDAO#findByPK(com.citibank.ods.entity.pl.BaseTo3ProductAccountEntity) */ public BaseTo3ProductAccountEntity findByPK(BaseTo3ProductAccountEntity productAccountEntity_) { // TODO Auto-generated method stub return null; } }
// $ANTLR 3.5 /Users/joanne/Desktop/tal_sql.g 2014-04-14 14:59:43 import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings("all") public class tal_sqlParser extends Parser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "ARTICLE", "CONJ", "MOT", "PAGE", "POINT", "SELECT", "VAR", "WS" }; public static final int EOF=-1; public static final int ARTICLE=4; public static final int CONJ=5; public static final int MOT=6; public static final int PAGE=7; public static final int POINT=8; public static final int SELECT=9; public static final int VAR=10; public static final int WS=11; // delegates public Parser[] getDelegates() { return new Parser[] {}; } // delegators public tal_sqlParser(TokenStream input) { this(input, new RecognizerSharedState()); } public tal_sqlParser(TokenStream input, RecognizerSharedState state) { super(input, state); } @Override public String[] getTokenNames() { return tal_sqlParser.tokenNames; } @Override public String getGrammarFileName() { return "/Users/joanne/Desktop/tal_sql.g"; } // $ANTLR start "listerequetes" // /Users/joanne/Desktop/tal_sql.g:27:1: listerequetes returns [String sql = \"\"] : r= requete POINT ; public final String listerequetes() throws RecognitionException { String sql = ""; Arbre r =null; Arbre lr_arbre; try { // /Users/joanne/Desktop/tal_sql.g:28:25: (r= requete POINT ) // /Users/joanne/Desktop/tal_sql.g:29:3: r= requete POINT { pushFollow(FOLLOW_requete_in_listerequetes158); r=requete(); state._fsp--; match(input,POINT,FOLLOW_POINT_in_listerequetes160); lr_arbre = r; sql = lr_arbre.sortArbre(); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return sql; } // $ANTLR end "listerequetes" // $ANTLR start "requete" // /Users/joanne/Desktop/tal_sql.g:36:1: requete returns [Arbre req_arbre = new Arbre(\"\")] : SELECT ( ARTICLE | PAGE ) MOT ps= params ; public final Arbre requete() throws RecognitionException { Arbre req_arbre = new Arbre(""); Arbre ps =null; Arbre ps_arbre; try { // /Users/joanne/Desktop/tal_sql.g:37:26: ( SELECT ( ARTICLE | PAGE ) MOT ps= params ) // /Users/joanne/Desktop/tal_sql.g:38:3: SELECT ( ARTICLE | PAGE ) MOT ps= params { match(input,SELECT,FOLLOW_SELECT_in_requete187); req_arbre.ajouteFils(new Arbre("","select distinct")); // /Users/joanne/Desktop/tal_sql.g:42:3: ( ARTICLE | PAGE ) int alt1=2; int LA1_0 = input.LA(1); if ( (LA1_0==ARTICLE) ) { alt1=1; } else if ( (LA1_0==PAGE) ) { alt1=2; } else { NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // /Users/joanne/Desktop/tal_sql.g:42:4: ARTICLE { match(input,ARTICLE,FOLLOW_ARTICLE_in_requete199); req_arbre.ajouteFils(new Arbre("","article")); } break; case 2 : // /Users/joanne/Desktop/tal_sql.g:46:6: PAGE { match(input,PAGE,FOLLOW_PAGE_in_requete211); req_arbre.ajouteFils(new Arbre("","page")); } break; } match(input,MOT,FOLLOW_MOT_in_requete221); req_arbre.ajouteFils(new Arbre("","from titreresume")); req_arbre.ajouteFils(new Arbre("","where")); pushFollow(FOLLOW_params_in_requete234); ps=params(); state._fsp--; ps_arbre = ps; req_arbre.ajouteFils(ps_arbre); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return req_arbre; } // $ANTLR end "requete" // $ANTLR start "params" // /Users/joanne/Desktop/tal_sql.g:62:1: params returns [Arbre les_pars_arbre = new Arbre(\"\")] : par1= param ( CONJ par2= param )* ; public final Arbre params() throws RecognitionException { Arbre les_pars_arbre = new Arbre(""); Arbre par1 =null; Arbre par2 =null; Arbre par1_arbre, par2_arbre; try { // /Users/joanne/Desktop/tal_sql.g:63:40: (par1= param ( CONJ par2= param )* ) // /Users/joanne/Desktop/tal_sql.g:64:3: par1= param ( CONJ par2= param )* { pushFollow(FOLLOW_param_in_params266); par1=param(); state._fsp--; par1_arbre = par1; les_pars_arbre.ajouteFils(par1_arbre); // /Users/joanne/Desktop/tal_sql.g:69:3: ( CONJ par2= param )* loop2: while (true) { int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==CONJ) ) { alt2=1; } switch (alt2) { case 1 : // /Users/joanne/Desktop/tal_sql.g:69:4: CONJ par2= param { match(input,CONJ,FOLLOW_CONJ_in_params277); pushFollow(FOLLOW_param_in_params283); par2=param(); state._fsp--; par2_arbre = par2; les_pars_arbre.ajouteFils(new Arbre("", "OR")); les_pars_arbre.ajouteFils(par2_arbre); } break; default : break loop2; } } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return les_pars_arbre; } // $ANTLR end "params" // $ANTLR start "param" // /Users/joanne/Desktop/tal_sql.g:78:1: param returns [Arbre lepar_arbre = new Arbre(\"\")] : a= VAR ; public final Arbre param() throws RecognitionException { Arbre lepar_arbre = new Arbre(""); Token a=null; try { // /Users/joanne/Desktop/tal_sql.g:78:51: (a= VAR ) // /Users/joanne/Desktop/tal_sql.g:79:2: a= VAR { a=(Token)match(input,VAR,FOLLOW_VAR_in_param311); lepar_arbre.ajouteFils(new Arbre("mot =", "'"+a.getText()+"'")); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return lepar_arbre; } // $ANTLR end "param" // Delegated rules public static final BitSet FOLLOW_requete_in_listerequetes158 = new BitSet(new long[]{0x0000000000000100L}); public static final BitSet FOLLOW_POINT_in_listerequetes160 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_SELECT_in_requete187 = new BitSet(new long[]{0x0000000000000090L}); public static final BitSet FOLLOW_ARTICLE_in_requete199 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_PAGE_in_requete211 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_MOT_in_requete221 = new BitSet(new long[]{0x0000000000000400L}); public static final BitSet FOLLOW_params_in_requete234 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_param_in_params266 = new BitSet(new long[]{0x0000000000000022L}); public static final BitSet FOLLOW_CONJ_in_params277 = new BitSet(new long[]{0x0000000000000400L}); public static final BitSet FOLLOW_param_in_params283 = new BitSet(new long[]{0x0000000000000022L}); public static final BitSet FOLLOW_VAR_in_param311 = new BitSet(new long[]{0x0000000000000002L}); }
package week07d04; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; public class ShoppingList { public long calculateSum(String path) { try { List<String> lines = Files.readAllLines(Path.of(path)); long sum = 0; for (String line : lines) { sum += getValueFromString(line); } return sum; } catch (IOException ex) { throw new IllegalStateException("File not found", ex); } } private long getValueFromString(String str) { try { String[] splittedStr = str.split(";"); return Long.parseLong(splittedStr[1]) * Long.parseLong(splittedStr[2]); } catch (NumberFormatException ex) { throw new IllegalStateException("Invalid string format"); } } }
package nl.jansneeuw.mineisland.commands; import com.sk89q.worldguard.bukkit.WGBukkit; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import nl.jansneeuw.mineisland.Mineisland; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; public class MIsland implements CommandExecutor { private Mineisland mineisland; public MIsland(Mineisland mineisland){ this.mineisland = mineisland; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 2 && sender instanceof Player && sender.hasPermission("mineisland.commands")){ Player player = (Player) sender; if (args[0].equalsIgnoreCase("define")){ if (WGBukkit.getRegionManager(player.getWorld()).getRegion(args[1]) != null){ if (!mineisland.getConfig().getList("regions").contains(args[1])){ List<String> list = mineisland.getConfig().getStringList("regions"); list.add(args[1]); mineisland.getConfig().set("regions", list); mineisland.saveConfig(); player.sendMessage(ChatColor.GREEN + "Added " + args[1] + " as a mine!"); }else{ player.sendMessage(ChatColor.RED + "That mineisland already exists!"); } }else{ player.sendMessage(ChatColor.RED + "That region does not exist!"); } }else if (args[0].equalsIgnoreCase("remove") && player.hasPermission("mineisland.commands")){ if (mineisland.getConfig().getList("regions") != null && mineisland.getConfig().getStringList("regions").contains(args[1])){ List<String> mines = mineisland.getConfig().getStringList("regions"); mines.remove(args[1]); mineisland.getConfig().set("regions", mines); mineisland.saveConfig(); mineisland.saveConfig(); player.sendMessage(ChatColor.GREEN + args[1] + " removed from mineislands."); }else{ player.sendMessage(ChatColor.RED + "Sorry, this region in not currently a mineisland."); } } } return true; } }
package com.stk123.model.elasticsearch; import com.stk123.model.elasticsearch.Condition; import com.stk123.model.elasticsearch.QueryParamData; import com.stk123.model.elasticsearch.RangeData; import com.stk123.model.elasticsearch.Condition.*; import com.stk123.model.elasticsearch.Type.FieldType; import com.stk123.model.elasticsearch.Type.BoolType; import com.stk123.model.elasticsearch.Type.SortType; import com.stk123.model.elasticsearch.Type.GeoRelationType; import com.stk123.model.elasticsearch.Type.AggType; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.geo.ShapeRelation; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.index.query.*; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.suggest.SuggestBuilder; import org.elasticsearch.search.suggest.SuggestBuilders; import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class EsQuery { // 搜索建议 private static int SUGGEST_DEFAULT_SIZE = 5; /** * 获取范围查询条件 * * @param rangeQueryCondition 范围查询条件 * @return */ public static RangeQueryBuilder getRangeQuery(RangeCondition rangeQueryCondition){ RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(rangeQueryCondition.getField()); RangeData rangeMin = rangeQueryCondition.getRangeMin(); RangeData rangeMax = rangeQueryCondition.getRangeMax(); if(rangeMin != null){ Object min = rangeMin.getValue(); boolean include = rangeMin.isInclude(); if(include){ rangeQueryBuilder.gte(min); }else{ rangeQueryBuilder.gt(min); } } if(rangeMax != null){ Object max = rangeMax.getValue(); boolean include = rangeMax.isInclude(); if(include){ rangeQueryBuilder.lte(max); }else{ rangeQueryBuilder.lt(max); } } return rangeQueryBuilder; } /** * 设置查询条件 * * @param boolQueryBuilder * @param queryBuilder * @param boolType */ public static void setBoolQuery(BoolQueryBuilder boolQueryBuilder, QueryBuilder queryBuilder, BoolType boolType){ switch (boolType){ // 且 case MUST: boolQueryBuilder.must(queryBuilder); break; // 或 case SHOULD: boolQueryBuilder.should(queryBuilder); break; // 非 case MUST_NOT: boolQueryBuilder.mustNot(queryBuilder); break; } } /** * 设置查询请求参数 * * @param queryParamData * @return */ public static SearchRequest createSearchRequest(QueryParamData queryParamData) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder filterBoolQueryBuilder = QueryBuilders.boolQuery(); // 查询条件 Condition[] conditions = queryParamData.getConditions(); // 页码 int pageIndex = queryParamData.getPageIndex(); // 每页显示的数量 int pageSize = queryParamData.getPageSize(); // 验证查询条件,过滤无效的查询条件 conditions = vaildConditions(conditions); List<AggregationBuilder> aggList = new ArrayList<>(); for(Condition condition : conditions){ // 字段 String field = condition.getField(); // 字段类型 FieldType fieldType = condition.getFieldType(); switch (fieldType){ // 聚合查询 case AGGS: AggCondition aggCondition = (AggCondition)condition; AggType aggType = aggCondition.getAggType(); String aggsName = ""; AggregationBuilder aggregationBuilder = null; switch (aggType){ case TERMS: aggsName = field + "_by"; aggregationBuilder = AggregationBuilders.terms(aggsName).field(field); break; case AVG: aggsName = field + "_avg"; aggregationBuilder = AggregationBuilders.avg(aggsName).field(field); break; case COUNT: aggsName = field + "_count"; aggregationBuilder = AggregationBuilders.count(aggsName).field(field); break; case MAX: aggsName = field + "_max"; aggregationBuilder = AggregationBuilders.max(aggsName).field(field); break; case MIN: aggsName = field + "_min"; aggregationBuilder = AggregationBuilders.min(aggsName).field(field); break; } if(!StringUtils.isEmpty(aggsName)){ aggList.add(aggregationBuilder); } break; // 匹配查询 case MATCH: CommonCondition matchCondition = (CommonCondition)condition; Object[] matchValue = matchCondition.getValues(); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(field, matchValue[0]); setBoolQuery(boolQueryBuilder, matchQueryBuilder, matchCondition.getBoolType()); break; // 准确值查询 case TERM: CommonCondition termCondition = (CommonCondition)condition; Object[] termValue = termCondition.getValues(); TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(field, termValue); setBoolQuery(filterBoolQueryBuilder, termsQueryBuilder, termCondition.getBoolType()); break; // 范围查询 case RANGE: RangeCondition rangeCondition = (RangeCondition)condition; RangeQueryBuilder rangeQueryBuilder = getRangeQuery(rangeCondition); setBoolQuery(filterBoolQueryBuilder, rangeQueryBuilder, rangeCondition.getBoolType()); break; // 搜索建议 case SUGGEST: CommonCondition suggestCondition = (CommonCondition)condition; Object[] suggestValue = suggestCondition.getValues(); CompletionSuggestionBuilder completionSuggestionBuilder = SuggestBuilders.completionSuggestion(field). prefix(String.valueOf(suggestValue[0])).skipDuplicates(true).size(SUGGEST_DEFAULT_SIZE); SuggestBuilder suggestBuilder = new SuggestBuilder(); suggestBuilder.addSuggestion("completion", completionSuggestionBuilder); searchSourceBuilder.suggest(suggestBuilder); break; // 排序 case SORT: SortCondition sortCondition = (SortCondition)condition; SortType sortType = sortCondition.getSortType(); switch (sortType){ case ASC: searchSourceBuilder.sort(field, SortOrder.ASC); break; case DESC: searchSourceBuilder.sort(field, SortOrder.DESC); break; } // 空间查询 case GEO: GeoCondition geoCondition = (GeoCondition)condition; // 查询空间对象 ShapeBuilder shapeBuilder = geoCondition.getShape(); GeoShapeQueryBuilder geoShapeQueryBuilder = QueryBuilders.geoShapeQuery(field, shapeBuilder); // 查询空间类型 GeoRelationType geoRelationType = geoCondition.getGeoRelationType(); switch (geoRelationType){ // 包含 case WITHIN: geoShapeQueryBuilder.relation(ShapeRelation.WITHIN); break; // 相离 case DISJOINT: geoShapeQueryBuilder.relation(ShapeRelation.DISJOINT); break; // 相交 case INTERSECTS: geoShapeQueryBuilder.relation(ShapeRelation.INTERSECTS); break; } setBoolQuery(filterBoolQueryBuilder, geoShapeQueryBuilder, geoCondition.getBoolType()); break; } } if(aggList.size() > 0 ){ AggregationBuilder aggregationBuilder = getAggrationBuilder(aggList); searchSourceBuilder.aggregation(aggregationBuilder); } searchSourceBuilder.size(pageSize); searchSourceBuilder.from((pageIndex - 1) * pageSize); searchSourceBuilder.query(boolQueryBuilder); searchSourceBuilder.postFilter(filterBoolQueryBuilder); SearchRequest searchRequest = new SearchRequest(); searchRequest.source(searchSourceBuilder); searchRequest.indices(queryParamData.getIndices()); return searchRequest; } /** * 获取聚合查询 * * @param aggList 聚合列表 * @return */ private static AggregationBuilder getAggrationBuilder(List<AggregationBuilder> aggList){ AggregationBuilder aggregationBuilder = null; int size = aggList.size(); for(int i = size -1; i >= 0; i--){ AggregationBuilder tempAggregationBuilder = aggList.get(i); if(i == size -1){ aggregationBuilder = tempAggregationBuilder; }else{ tempAggregationBuilder.subAggregation(aggregationBuilder); aggregationBuilder = tempAggregationBuilder; } } return aggregationBuilder; } /** * 验证查询条件是否有效 * * @param conditions 查询条件 * @return */ private static Condition[] vaildConditions(Condition[] conditions){ List<Condition> vaildedConditionList = new ArrayList<Condition>(); for(Condition condition : conditions){ FieldType fieldType = condition.getFieldType(); if(fieldType == FieldType.TERM || fieldType == FieldType.MATCH || fieldType == FieldType.SUGGEST ){ CommonCondition commonCondition = (CommonCondition)condition; Object[] values = commonCondition.getValues(); if(null == values || values.length == 0){ continue; } } vaildedConditionList.add(condition); } return vaildedConditionList.toArray(new Condition[]{}); } }
/* * Zzt_JIF_Classroomtype.java * * Created on __DATE__, __TIME__ */ package zzt.view; import ggc.dao.GGC_ClassroomtypeAddTable; import ggc.dao.GGC_OfficeAddTable; import ggc.view.throw_classroomtype; import ggc.view.throw_office; import global.dao.Classrommtypeaccess; import global.dao.Databaseconnection; import global.dao.Departmentaccess; import global.dao.ExcelFileFilter; import global.dao.Fileselection; import global.dao.Viewofficeaccess; import global.model.Department; import global.model.View_office; import global.model.View_teacher; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import czy.model.Tools; import zxx.dao.PrintObjectExcel; import zzt.model.Classroomtype; /** * * @author zzt */ public class Zzt_JIF_Classroomtype extends javax.swing.JInternalFrame { private View_teacher ct; private int ct_id; private int d_id_int; /** Creates new form Zzt_JIF_Classroomtype */ public Zzt_JIF_Classroomtype() { //初始化界面 initComponents(); } public Zzt_JIF_Classroomtype(View_teacher ct) { //初始化界面 initComponents(); //将传递的参数(登录用户的视图)传递给类的对应属性字段 this.ct = ct; fillroomtype(); // 调用函数初始化学院下拉列表 } public void fillroomtype() { //首先给ct_id变量设为初始0 int ct_id = 0; //声明DefaultTableModel 得到jtble1表格上的模型 DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); //设置表格的行数从0开始计数 dtm.setRowCount(0); //初始化ArrayList列表,通过ct_id主键查询classroomtype(部门表) ArrayList<Classroomtype> alist = Classrommtypeaccess .getClassroomtypes(ct_id); // 遍历教师类型的数组列表 for (int i = 0; i < alist.size(); i++) { // 取出对应字段信息 int ct_id_zzt = alist.get(i).getCt_id(); String ct_name = alist.get(i).getCt_name(); // 生成向量类型变量 Vector v = new Vector(); v.add(ct_id_zzt); v.add(ct_name); // 将向量添加到表格中 dtm.addRow(v); } } /** 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. */ //GEN-BEGIN:initComponents // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jButton7 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton7.setText("jButton7"); setTitle("\u6559\u5ba4\u7c7b\u578b"); jLabel1.setText("\u6559\u5ba4\u7c7b\u578b\u7f16\u53f7\uff1a"); jTextField1.setEditable(false); jLabel2.setText("\u6559\u5ba4\u7c7b\u578b\u540d\u79f0\uff1a"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object[][] { }, new String[] { "教室类型编号", "教室类型名称" }) { boolean[] canEdit = new boolean[] { false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); jTable1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable1MouseClicked(evt); } }); jScrollPane1.setViewportView(jTable1); jButton1.setText("\u6dfb\u52a0"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("\u4fee\u6539"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("\u5220\u9664"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("\u9000\u51fa"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setText("\u6570\u636e\u5bfc\u51fa"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.setText("\u5bfc\u5165"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton8.setText("\u5bfc\u5165\u683c\u5f0f\u5bfc\u51fa"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addComponent( jLabel1) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jLabel2) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)) .addComponent( jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent( jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44) .addComponent( jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent( jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton8))) .addContainerGap())); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent( jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(33, Short.MAX_VALUE))); pack(); }// </editor-fold> //GEN-END:initComponents private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //调用导出方法把文件的路径存放在tabletwo变量里 File Filename = Fileselection.exportselect(); File filenametow = new File(Filename + ".xls"); String filetable = filenametow.toString(); // System.out.println(Filename+".xls"); int ct_id = 0; //实例化部门列表,把部门信息存放在calist变量中 ArrayList<Classroomtype> caList =Classrommtypeaccess.getClassroomtypes(ct_id); List<Classroomtype> list = new ArrayList<Classroomtype>(); //设置excel表头信息 String[] header = { "教室类型编号", "教室类型名称"}; // File Filename =new File() ; // System.out.println(Filename); // JFileChooser fDialog = new JFileChooser(); if (Filename == null) { // System.out.println("文件名为null"); return; } //怎么拿到导出之后的文件名 if (filenametow.exists()) { System.out.println(filenametow.exists()); int overwriteSelect = JOptionPane.showConfirmDialog(this, "<html><font size=3>文件" + filenametow.getName() + "已存在,是否覆盖?</font><html>", "是否覆盖?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); System.out.println(overwriteSelect); if (overwriteSelect == JOptionPane.YES_OPTION) { List<String> aList = PrintObjectExcel.printExcel(caList, filetable, header); if (aList.size() == 0) { JOptionPane.showMessageDialog(this, "导出成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); } else { String str = ""; for (String item : aList) { str += item + "\n"; } JOptionPane.showMessageDialog(this, str, "错误信息", JOptionPane.ERROR_MESSAGE); } } else { return; } } List<String> aList = PrintObjectExcel.printExcel(caList, filetable, header); if (aList.size() == 0) { JOptionPane.showMessageDialog(this, "导出成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); } else { String str = ""; for (String item : aList) { str += item + "\n"; } JOptionPane.showMessageDialog(this, str, "错误信息", JOptionPane.ERROR_MESSAGE); } } private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //调用导出方法把文件的路径存放在tabletwo变量里 File Filename = Fileselection.exportselect(); File filenametow = new File(Filename + ".xls"); String filetable = filenametow.toString(); // System.out.println(Filename+".xls"); int ct_id = 0; //实例化部门列表,把部门信息存放在calist变量中 ArrayList<Classroomtype> caList = Classrommtypeaccess .getClassroomtypes(ct_id); List<Classroomtype> list = new ArrayList<Classroomtype>(); //设置excel表头信息 String[] header = { "教室类型编号", "教室类型名称" }; // File Filename =new File() ; // System.out.println(Filename); // JFileChooser fDialog = new JFileChooser(); if (Filename == null) { // System.out.println("文件名为null"); return; } //怎么拿到导出之后的文件名 if (filenametow.exists()) { System.out.println(filenametow.exists()); int overwriteSelect = JOptionPane.showConfirmDialog(this, "<html><font size=3>文件" + filenametow.getName() + "已存在,是否覆盖?</font><html>", "是否覆盖?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); System.out.println(overwriteSelect); if (overwriteSelect == JOptionPane.YES_OPTION) { List<String> aList = PrintObjectExcel.printExcel(caList, filetable, header); if (aList.size() == 0) { JOptionPane.showMessageDialog(this, "导出成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); } else { String str = ""; for (String item : aList) { str += item + "\n"; } JOptionPane.showMessageDialog(this, str, "错误信息", JOptionPane.ERROR_MESSAGE); } } else { return; } } List<String> aList = PrintObjectExcel.printExcel(caList, filetable, header); if (aList.size() == 0) { JOptionPane.showMessageDialog(this, "导出成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); } else { String str = ""; for (String item : aList) { str += item + "\n"; } JOptionPane.showMessageDialog(this, str, "错误信息", JOptionPane.ERROR_MESSAGE); } } private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFileChooser fDialog = new JFileChooser(); // 初始化ExcelFileFilter文件类型过滤类 ExcelFileFilter excelFilter = new ExcelFileFilter(); // 设置文本框类型 fDialog.addChoosableFileFilter(excelFilter); // 设置文件选择框的标题 fDialog.setFileFilter(excelFilter); // 浏览文件 fDialog.setDialogTitle("请选择文件"); // 弹出选择框 int returnVal = fDialog.showOpenDialog(null); // 定义table变量用来存储要浏览文件的路径 String table = fDialog.getSelectedFile().toString(); // System.out.println(table); // 初始化office_List数组,把判定的错误信息放在office_List数组列表里 List<String> classroomtype_List = GGC_ClassroomtypeAddTable.getClassroomtypeThrow(table); // System.out.println(department_List); // 判断office_List的错误信息个数,如果为空则导入成功,刷新页面 if (classroomtype_List.size() == 0 || classroomtype_List == null) { JOptionPane.showMessageDialog(this, "导入成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); fillroomtype(); } else { // 首先定义一个字符串变量为str String str = ""; // 遍历数组列表错误信息 for (String item : classroomtype_List) { // 把遍历过的错误信息,存放到str变量当中 str += item + "\n"; } // 提示信息:把错误信息输出到前台页面当中! // JOptionPane.showMessageDialog(this, str, "提示信息", // JOptionPane.ERROR_MESSAGE); throw_classroomtype th = new throw_classroomtype(null, true); th.infomation(str); th.setVisible(true); } } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: // TODO add your handling code here: // 记录jtble1表格当前的行 int i = jTable1.getSelectedRow(); // 如果i==-1,说明没有选中行 if (i == -1) { // 提示信息:请选中要修改的记录 JOptionPane.showMessageDialog(this, "请选中要修改的记录", "提示信息", JOptionPane.INFORMATION_MESSAGE); return; } // 如果教师类型编号文本框中没有输入内容 if (jTextField1.getText().equals("")) { // 提示信息:请输入部门编号 JOptionPane.showMessageDialog(this, "请输入教室类型编号!", "提示信息", JOptionPane.INFORMATION_MESSAGE); jTextField1.requestFocus(); return; } // 如果教师类型名称文本框中没有输入内容 if (jTextField2.getText().equals("")) { // 提示信息:请输入部门名称 JOptionPane.showMessageDialog(this, "请输入教室类型名称!", "提示信息", JOptionPane.INFORMATION_MESSAGE); jTextField2.requestFocus(); return; } // 定义一个变量来存放jtable1的第i行第0列的字符串 int ct_id = (Integer) jTable1.getValueAt(i, 0); // 定义一个变量来存放jtable1的第i行第1列的字符串 String ct_name = (String) jTable1.getValueAt(i, 1); // 定义一个d_id_zzt变量用来得到类型编号文本框的内容 int ct_id_zzt = Integer.parseInt(jTextField1.getText()); // 定义一个d_name_zzt用来得到类型名称文本框的内容 String ct_name_zzt = jTextField2.getText(); // 声明数据库为空 Connection con = null; try { // 创建数据库连接 con = Databaseconnection.getconnection(); //设置数据库的自动提交方式为false con.setAutoCommit(false); // 如果当前的文本框的内容和选中的对应的列的值不匹配的时,说明用户要修改信息! if (!(ct_id_zzt == ct_id)) { // 访问数据库查询部门编号字段值,如果当前数据库对应的字段里面的值等于用户当前已经输入的值的情况下 if (Classrommtypeaccess.findid(con, ct_id_zzt)) { // 提示信息:类型编号已经存在 JOptionPane.showMessageDialog(this, "教室类型编号已经存在请重新输入", "错误信息", JOptionPane.ERROR_MESSAGE); // 类型编号文本框获得焦点 jTextField1.requestFocus(); // 类型名称文本框全选 jTextField1.selectAll(); return; } } if (!(ct_name_zzt.equals(ct_name))) { if (Classrommtypeaccess.findname(con, ct_name_zzt)) { // 提示信息:部门名称已经存在 JOptionPane.showMessageDialog(this, "教室类型名称已经存在请重新输入", "错误信息", JOptionPane.ERROR_MESSAGE); // jTextField1文本框获得焦点 jTextField2.requestFocus(); // jtexfField1文本框全选 jTextField2.selectAll(); return; } } // 判定当前的输入的类型编号和类型名称与数据库里面的是否重复,如果重复则提示信息 if ((ct_id_zzt == ct_id) && (ct_name_zzt.equals(ct_name))) { // 提示信息:请输入您要修改的信息! JOptionPane.showMessageDialog(this, "请输入您要修改的信息!", "提示信息", JOptionPane.INFORMATION_MESSAGE); return; } // 定义一个变量r用来存储update方法返回的结果集 int r = Classrommtypeaccess.update(con, ct_id, new Classroomtype( ct_id_zzt, jTextField2.getText())); // 如果结果集大于0的话 if (r > 0) { // 提示信息修改成功 JOptionPane.showMessageDialog(this, "修改成功", "提示信息", JOptionPane.INFORMATION_MESSAGE); jTextField1.setText(""); jTextField2.setText(""); //开启数据库手动提交方式 con.commit(); // 调用fillroomtype方法进行实时刷新表格 fillroomtype(); } else { // 否则提示信息:修改失败请联系管理员 JOptionPane.showMessageDialog(this, "修改失败请联系管理员", "提示信息", JOptionPane.ERROR_MESSAGE); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block try { //如果数据库访问异常,则回滚 con.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //记录jtble1面板当前的行数 int i = jTable1.getSelectedRow(); jTable1.setRowSelectionAllowed(true); String zztString = ""; String zzt = ""; int ct_id = 0; int number = 0; //如果i==-1,说明没有选中行 if (i == -1) { //提示信息:请选中要修改的记录 JOptionPane.showMessageDialog(this, "请选中要删除的记录", "提示信息", JOptionPane.INFORMATION_MESSAGE); return; } else { //定义一个数组变量row存放当前选中的所有行 int[] row = jTable1.getSelectedRows(); //定义一个count用来存放行数 int count = row.length; //遍历行数 for (int a = 0; a < count; a++) { //定义一个变量来存放部门编号的第row[a]行第0列 ct_id = (Integer) jTable1.getValueAt(row[a], 0); //定义一个空字符串变量st String st = ","; zzt = "(" + (zztString += ct_id + (st)) + ")"; //用来存放满足删除多条语句要求的sql语句 if (zzt.endsWith(")")) { zzt = zzt.substring(0, zzt.length() - 2) + ")"; } } //提示信息,确认要删除当前记录嘛?,如果确定,则删除当前选中的记录 int r = JOptionPane.showConfirmDialog(this, "确认要删除当前记录嘛?", "确认信息", JOptionPane.OK_CANCEL_OPTION); if (r == 0) { Connection con = null; try { //创建数据库连接 con = Databaseconnection.getconnection(); //设置数据库连接的自动提交为(false) con.setAutoCommit(false); //定义一个整型变量re来存放结果集 int re; //用re来记录删除部门编号的方法的结果集 re = Classrommtypeaccess.Delete(con, zzt); //如果结果集 > 0 则删除成功 if (re > 0) { JOptionPane.showMessageDialog(this, "删除记录成功!", "确认信息", JOptionPane.INFORMATION_MESSAGE); //开启数据库的手动提交 con.commit(); //实时刷新jtble1表格数据 fillroomtype(); jTextField1.setText(""); jTextField2.setText(""); } else { JOptionPane.showMessageDialog(this, "删除失败,请联系管理员进行相关操作!", "错误信息", JOptionPane.ERROR_MESSAGE); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block //捕获错误异常情况进行处理,定义一个str变量,用来存放访问sql语句错误的状态值 String str = "23000"; //如果当前访问的状态值等于str,则提示相应信息 if (e.getSQLState().equals(str)) { JOptionPane.showMessageDialog(this, "由于此编号有外键约束影响,暂时不能删除!", "提示信息", JOptionPane.INFORMATION_MESSAGE); } } } } } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.dispose(); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String ct_name = jTextField2.getText(); // 如果教师类型名称文本框内容为空 if (ct_name.equals("")) { // 提示信息:教师类型名称不能为空! JOptionPane.showMessageDialog(this, "部门名称不能为空!"); jTextField2.requestFocus(); return; } Connection con = null; int zhujian = 0; int ct_int = 0; try { // 创建数据库连接 con = Databaseconnection.getconnection(); //把查询教师类型编号的最大值存入max的结果集 ResultSet max = Classrommtypeaccess.findmax(con); //遍历结果集的所有数据找到最大值赋值给zhujian变量 while (max.next()) { zhujian = max.getInt("ct_id"); } //如果部门编号没用数据,则添加一条编号为“01”的数据 if (zhujian == 0) { ct_int = 1; } else { //定义一个整形变量,从来存放当前部门编号里面的最大值加一 ct_int = (zhujian) + 1; //在把已经加过一的整形变量转换为字符串放在d_str变量里 } //实例化教师类型的构造方法 Classroomtype cy = new Classroomtype(ct_int, ct_name); // 设置数据库的自动提交方式为false con.setAutoCommit(false); // 访问数据库查询教师类型名称字段值,如果当前数据库对应的教师类型名称字段里面的值等于用户当前已经输入的值的情况下 if (Classrommtypeaccess.findname(con, ct_name)) { // 提示信息:类型名称已经存在 JOptionPane.showMessageDialog(this, "部门名称已经存在请重新输入", "错误信息", JOptionPane.ERROR_MESSAGE); // 教师类型名称文本框获得焦点 jTextField2.requestFocus(); // 教师类型名称文本框全选 jTextField2.selectAll(); return; } // 定义r变量存放结果集 int r = Classrommtypeaccess.insert(con, cy); // 如果r>=1 if (r >= 1) { // 则提示信息:添加成功! JOptionPane.showMessageDialog(this, "添加成功!"); // 开始数据库的手动提交方式 con.commit(); fillroomtype(); jTextField1.setText(""); jTextField2.setText(""); } // 如果r大于1则提示信息部门编号插入失败,请联系系统管理员! if (r < 1) { Tools.connectionroolback(con, "部门编号插入失败,请联系系统管理员!"); return; } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { } finally { try { con.rollback(); if (!con.isClosed()) con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: int row = jTable1.getSelectedRow(); jTextField1.setText(jTable1.getValueAt(row, 0).toString()); jTextField2.setText((String) jTable1.getValueAt(row, 1)); } //GEN-BEGIN:variables // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
package com.tripper.db.entities; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "event") public class Event { @PrimaryKey(autoGenerate = true) public long id; @ColumnInfo(name="trip_id") public long tripId; @ColumnInfo(name="name") public String name; @ColumnInfo(name="location_lat") public String locationLat; @ColumnInfo(name="location_lon") public String locationLon; @ColumnInfo(name="segment_id") public long segmentId; }
package org.data.persistance.repository; import java.util.List; import org.data.persistance.model.Users; public interface UserRepositoryCustom { List<Users> searchUsers(String firstName,String lastName, String username, String role); }
package com.ecommerceserver.model; import java.util.List; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Document(collection = "user") @Data @NoArgsConstructor @AllArgsConstructor public class Seller extends User { List<Product> listProduct; List<Bill> listBill; }
/** * */ package org.jenkinsci.plugins.deploy.weblogic.data; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.deploy.weblogic.Messages; /** * @author Raphael * */ @Extension public class DeploymentTaskDescriptor extends Descriptor<DeploymentTask> { /** * */ public DeploymentTaskDescriptor() { super(DeploymentTask.class); } /* * (non-Javadoc) * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return Messages.DeploymentTaskDescriptor_DisplayName(); } /** * @return the weblogicStageMode */ public WebLogicStageMode[] getWeblogicStageModes() { return WebLogicStageMode.values(); } }
package com.wq.dubboprovider; import java.util.Map; public interface IotServerService { Object handle(Map<String, String> param); }
import java.io.*; import java.math.*; import java.util.*; public class solutionOfLab3B { static int ans; static int sumList[] = new int[21]; static int word[][] = new int[21][21]; static ArrayList<Integer> arrayList = new ArrayList<>(); public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) { HashMap<Character,Integer> map = new HashMap(); putInMap(map); int N = in.nextInt(); while(N-->0){ String str = in.next(); char arr[]; ans =0; Arrays.fill(sumList,0); for(int i =0;i<21;i++) Arrays.fill(word[i],0); arr=str.toCharArray(); for(int i =0 ;i<arr.length-1;i++) { if (map.containsKey(arr[i]) && map.containsKey(arr[i + 1])) { int a = map.get(arr[i]).intValue(); int b = map.get(arr[i + 1]).intValue(); if (a == b) { continue; } word[a][b] += 1; word[b][a] += 1; sumList[a] += 1; sumList[b] += 1; } } out.println( DFS(0,0)); } } } static void putInMap(HashMap map){ map.put('b',0); map.put('c',1); map.put('d',2); map.put('f',3); map.put('g',4); map.put('h',5); map.put('j',6); map.put('k',7); map.put('l',8); map.put('m',9); map.put('n',10); map.put('p',11); map.put('q',12); map.put('r',13); map.put('s',14); map.put('t',15); map.put('v',16); map.put('w',17); map.put('x',18); map.put('y',19); map.put('z',20); // map.put('B',21); // map.put('C',22); // map.put('D',23); // map.put('F',24); // map.put('G',25); // map.put('H',26); // map.put('J',27); // map.put('K',28); // map.put('L',29); // map.put('M',30); // map.put('N',31); // map.put('P',32); // map.put('Q',33); // map.put('R',34); // map.put('S',35); // map.put('T',36); // map.put('V',37); // map.put('W',38); // map.put('X',39); // map.put('Y',40); // map.put('Z',41); } public static int DFS(int index,int ans){ if(index == 20 ){ int temp = 0; for(int i =0;i<arrayList.size();i++){ temp += word[index][arrayList.get(i)]<<1; } ans +=Math.max(0,sumList[index]-temp); return ans; }else if(sumList[index] == 0){ return DFS(index+1,ans); }else { int tempAns = ans + sumList[index]; for(int i =0;i<arrayList.size();i++){ tempAns -= word[index][arrayList.get(i)]<<1; } arrayList.add(index); int temp1 = DFS(index+1,tempAns); arrayList.remove((Integer) index); int temp2 = DFS(index+1,ans); return Math.max(temp1,temp2); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public boolean hasNext() { try { String string = reader.readLine(); if (string == null) { return false; } tokenizer = new StringTokenizer(string); return tokenizer.hasMoreTokens(); } catch (IOException e) { return false; } } public BigInteger nextBigInteger() { return new BigInteger(next()); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * * * @author Kevin Hartman <kfh6034@rit.edu> */ public class Scheduler extends ScheduledThreadPoolExecutor { private long startNanos; public Scheduler(int corePoolSize) { super(corePoolSize); this.startNanos = System.nanoTime(); } public boolean registerEvent(final Runnable event, final Employee employee, long nanosFromNow, final boolean lastTask) { this.schedule(new Callable<Boolean>(){ @Override public Boolean call() { return employee.enqueueTask(event, lastTask); } }, nanosFromNow, TimeUnit.NANOSECONDS); return true; } public long getStartTimeInNanos() { return startNanos; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_CONTRIBUTOR$$ */ package Utils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author philippe Gouttefarde */ public class ListNetworkInterfaces { public static void main(String args[]) throws SocketException { System.out.println(getNetworkInterfacesList()); } /** * * @return an ArrayList of the network interface of the current computer. */ public static ArrayList<String> getNetworkInterfacesList() { ArrayList<String> interfacesList = null; try { interfacesList = new ArrayList<String>(); Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) interfacesList.add(getInterfaceInformation(netint)); return interfacesList; } catch (SocketException ex) { Logger.getLogger(ListNetworkInterfaces.class.getName()).log(Level.SEVERE, null, ex); } return interfacesList; } /** * * @param netint : id of the interface * @return the complete name of the interface * @throws SocketException */ public static String getInterfaceInformation(NetworkInterface netint) throws SocketException { final StringBuilder netintDescription = new StringBuilder(); netintDescription.append(netint.getName() + " "); final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { netintDescription.append(inetAddress + " "); } netintDescription.append(netint.getDisplayName()); return netintDescription.toString(); } }
package com.revature.ers.dao; import java.util.List; import com.revature.ers.model.Company; public interface CompanyDao { public List<Company> getCompanies(); public Company getCompany(int id); public boolean createCompany(Company company); public boolean updateCompany(int id, Company company); public boolean deleteCompany(int id); }
package fr.skytasul.quests.gui; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public abstract interface CustomInventory { /** * Called when opening inventory * @param p Player to open * @return inventory opened */ public abstract Inventory open(Player p); /** * Called when clicking on an item * @param p Player who clicked * @param inv Inventory clicked * @param current Item clicked * @param slot Slot of item clicked * @param click Type of click * @return Cancel click */ public abstract boolean onClick(Player p, Inventory inv, ItemStack current, int slot, ClickType click); /** * Called when clicking on an item <b>with something on the cursor</b> * @param p Player who clicked * @param inv Inventory clicked * @param current Item clicked * @param cursor Item on the cursor when click * @param slot Slot of item clicked * @return Cancel click */ public default boolean onClickCursor(Player p, Inventory inv, ItemStack current, ItemStack cursor, int slot){return true;} /** * Called when closing the inventory * @param p Player who has the inventory opened * @param inv Inventory closed * @return Remove player from inventories system */ public default CloseBehavior onClose(Player p, Inventory inv){return CloseBehavior.CONFIRM;} /** * Opens the inventory to the player. Direct reference to {@link Inventories#create(Player, CustomInventory)} * @param p Player * @see Inventories#create(Player, CustomInventory) */ public default void create(Player p) { Inventories.create(p, this); } public static enum CloseBehavior{ REOPEN, CONFIRM, REMOVE, NOTHING; } }
package dao; import app.Principal; import entidades.Periodo; import javax.persistence.EntityManager; import javax.swing.JOptionPane; import javax.swing.table.TableModel; import util.FrmListaGenerico; import view.FrmCadPeriodo; import view.FrmListaPeriodo; public class ConsultaPeriodo extends FrmListaGenerico { public ConsultaPeriodo() { setTitle("Cadastro de Periodo de vendas"); } @Override public TableModel getTableModel() { return new FrmListaPeriodo(); } @Override public void excluir() { int linhaSelecionada = tbDados.getSelectedRow(); FrmListaPeriodo lis = (FrmListaPeriodo) tbDados.getModel(); Periodo p = lis.getLista().get(linhaSelecionada); EntityManager em = Principal.emf.createEntityManager(); em.getTransaction().begin(); p = em.find(Periodo.class, p.getId()); if (p == null) { JOptionPane.showMessageDialog(this, "Este registro já foi excluído", "Aviso", JOptionPane.WARNING_MESSAGE); } else { em.remove(p); em.getTransaction().commit(); } atualizaTabela(); } @Override public void alterar() { int linhaSelecionada = tbDados.getSelectedRow(); FrmListaPeriodo lis = (FrmListaPeriodo) tbDados.getModel(); Periodo p = lis.getLista().get(linhaSelecionada); EntityManager em = Principal.emf.createEntityManager(); p = em.find(Periodo.class, p.getId()); if (p == null) { JOptionPane.showMessageDialog(this, "Este registro já foi excluído", "Aviso", JOptionPane.WARNING_MESSAGE); } else { FrmCadPeriodo md = new FrmCadPeriodo(null, true); md.setEntidade(p); md.entidadeTela(); md.setVisible(true); p = md.getEntidade(); if (p != null) { em.getTransaction().begin(); em.merge(p); em.getTransaction().commit(); } } atualizaTabela(); } @Override public void inserir() { Periodo p = new Periodo(); FrmCadPeriodo md = new FrmCadPeriodo(null, true); md.setEntidade(p); md.setVisible(true); p = md.getEntidade(); if (p != null) { EntityManager em = Principal.emf.createEntityManager(); em.getTransaction().begin(); em.persist(p); em.getTransaction().commit(); atualizaTabela(); } } private void atualizaTabela() { tbDados.setModel(new FrmListaPeriodo()); tbDados.updateUI(); } @Override public Object selecionar() { throw new UnsupportedOperationException("Not supported yet."); } }
/* * 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 Forms; import java.awt.Color; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import javax.swing.JOptionPane; /** * * @author HermanCosta */ public class MoneyCounter extends javax.swing.JFrame { String tillClosingDate; double totalMoney = 0; int input500Qty, input200Qty, input100Qty, input50Qty, input20Qty, input10Qty, input5Qty; int input2Qty, input1Qty, input50cQty, input20cQty, input10cQty, input5cQty, input2cQty, input1cQty; int countBankNotes, countTotalCoins; public MoneyCounter() { initComponents(); setResizable(false); } public void calcMoneyCounter() { double total500 = 500 * input500Qty; double total200 = 200 * input200Qty; double total100 = 100 * input100Qty; double total50 = 50 * input50Qty; double total20 = 20 * input20Qty; double total10 = 10 * input10Qty; double total5 = 5 * input5Qty; double total2 = 2 * input2Qty; double total1 = 1 * input1Qty; double total50c = 0.5 * input50cQty; double total20c = 0.2 * input20cQty; double total10c = 0.1 * input10cQty; double total5c = 0.05 * input5cQty; double total2c = 0.02 * input2cQty; double total1c = 0.01 * input1cQty; totalMoney = total500 + total200 + total100 + total50 + total20 + total10 + total5 + total2 + total1 + total50c + +total20c + total10c + total5c + total2c + total1c; totalMoney = Math.round(totalMoney * 100d) / 100d; txt_total_money.setText(String.valueOf(totalMoney)); //count bank notes qty countBankNotes = input500Qty + input200Qty + input100Qty + input50Qty + input20Qty + input10Qty + input5Qty; txt_total_bank_notes.setText(String.valueOf(countBankNotes)); //count coins qty countTotalCoins = input2Qty + input1Qty + input50cQty + input20cQty + input10cQty + input5cQty + input2cQty + input1cQty; txt_total_coins.setText(String.valueOf(countTotalCoins)); } /** * 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() { panel_euro_money_counter = new javax.swing.JPanel(); panel_bank_notes = new javax.swing.JPanel(); txt_500 = new javax.swing.JTextField(); txt_200 = new javax.swing.JTextField(); txt_100 = new javax.swing.JTextField(); txt_50 = new javax.swing.JTextField(); txt_10 = new javax.swing.JTextField(); txt_20 = new javax.swing.JTextField(); txt_5 = new javax.swing.JTextField(); lbl_€500 = new javax.swing.JLabel(); lbl_€200 = new javax.swing.JLabel(); lbl_€100 = new javax.swing.JLabel(); lbl_€50 = new javax.swing.JLabel(); lbl_€20 = new javax.swing.JLabel(); lbl_€10 = new javax.swing.JLabel(); lbl_€5 = new javax.swing.JLabel(); lbl_500_result = new javax.swing.JLabel(); lbl_200_result = new javax.swing.JLabel(); lbl_100_result = new javax.swing.JLabel(); lbl_50_result = new javax.swing.JLabel(); lbl_20_result = new javax.swing.JLabel(); lbl_10_result = new javax.swing.JLabel(); lbl_5_result = new javax.swing.JLabel(); panel_coins = new javax.swing.JPanel(); txt_2 = new javax.swing.JTextField(); txt_1 = new javax.swing.JTextField(); txt_50c = new javax.swing.JTextField(); txt_20c = new javax.swing.JTextField(); txt_10c = new javax.swing.JTextField(); txt_5c = new javax.swing.JTextField(); txt_2c = new javax.swing.JTextField(); txt_1c = new javax.swing.JTextField(); lbl_2 = new javax.swing.JLabel(); lbl_1 = new javax.swing.JLabel(); lbl_50c = new javax.swing.JLabel(); lbl_20c = new javax.swing.JLabel(); lbl_10c = new javax.swing.JLabel(); lbl_5c = new javax.swing.JLabel(); lbl_2c = new javax.swing.JLabel(); lbl_1c = new javax.swing.JLabel(); lbl_2_result = new javax.swing.JLabel(); lbl_1_result = new javax.swing.JLabel(); lbl_50c_result = new javax.swing.JLabel(); lbl_20c_result = new javax.swing.JLabel(); lbl_10c_result = new javax.swing.JLabel(); lbl_5c_result = new javax.swing.JLabel(); lbl_2c_result = new javax.swing.JLabel(); lbl_1c_result = new javax.swing.JLabel(); txt_total_money = new javax.swing.JTextField(); txt_total_bank_notes = new javax.swing.JTextField(); txt_total_coins = new javax.swing.JTextField(); lbl_total_money = new javax.swing.JLabel(); lbl_bank_notes = new javax.swing.JLabel(); lbl_coins = new javax.swing.JLabel(); btn_copy = new javax.swing.JButton(); btn_clear = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); panel_euro_money_counter.setBackground(new java.awt.Color(204, 204, 204)); panel_euro_money_counter.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "EURO Money Counter", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("sansserif", 1, 16))); // NOI18N panel_euro_money_counter.setMaximumSize(new java.awt.Dimension(690, 360)); panel_euro_money_counter.setPreferredSize(new java.awt.Dimension(690, 360)); panel_euro_money_counter.setVerifyInputWhenFocusTarget(false); panel_bank_notes.setBackground(new java.awt.Color(204, 204, 204)); panel_bank_notes.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Bank Notes", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("sansserif", 0, 14))); // NOI18N panel_bank_notes.setMaximumSize(new java.awt.Dimension(665, 114)); panel_bank_notes.setPreferredSize(new java.awt.Dimension(0, 0)); txt_500.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_500.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_500ActionPerformed(evt); } }); txt_500.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_500KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_500KeyReleased(evt); } }); txt_200.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_200.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_200ActionPerformed(evt); } }); txt_200.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_200KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_200KeyReleased(evt); } }); txt_100.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_100.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_100ActionPerformed(evt); } }); txt_100.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_100KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_100KeyReleased(evt); } }); txt_50.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_50.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_50KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_50KeyReleased(evt); } }); txt_10.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_10.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_10KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_10KeyReleased(evt); } }); txt_20.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_20.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_20ActionPerformed(evt); } }); txt_20.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_20KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_20KeyReleased(evt); } }); txt_5.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_5.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_5KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_5KeyReleased(evt); } }); lbl_€500.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€500.setText("€500"); lbl_€200.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€200.setText("€200"); lbl_€100.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€100.setText("€100"); lbl_€50.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€50.setText("€50"); lbl_€20.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€20.setText("€20"); lbl_€10.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€10.setText("€10"); lbl_€5.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_€5.setText("€5"); lbl_500_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_500_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_500_result.setText("€500Rst"); lbl_500_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_500_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_500_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_200_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_200_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_200_result.setText("€200Rst"); lbl_200_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_200_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_200_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_100_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_100_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_100_result.setText("€100Rst"); lbl_100_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_100_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_100_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_50_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_50_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_50_result.setText("€50Rst"); lbl_50_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_50_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_50_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_20_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_20_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_20_result.setText("€20Rst"); lbl_20_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_20_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_20_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_10_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_10_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_10_result.setText("€10Rst"); lbl_10_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_10_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_10_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_5_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_5_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_5_result.setText("€5Rst"); lbl_5_result.setMaximumSize(new java.awt.Dimension(63, 15)); lbl_5_result.setMinimumSize(new java.awt.Dimension(63, 15)); lbl_5_result.setPreferredSize(new java.awt.Dimension(0, 15)); javax.swing.GroupLayout panel_bank_notesLayout = new javax.swing.GroupLayout(panel_bank_notes); panel_bank_notes.setLayout(panel_bank_notesLayout); panel_bank_notesLayout.setHorizontalGroup( panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_500, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_500_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_200_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_200, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_100, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_100_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_50, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_50_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(lbl_20_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_bank_notesLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txt_20, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_10, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_10_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_5_result, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_5, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(lbl_€500) .addGap(51, 51, 51) .addComponent(lbl_€200) .addGap(53, 53, 53) .addComponent(lbl_€100) .addGap(56, 56, 56) .addComponent(lbl_€50) .addGap(59, 59, 59) .addComponent(lbl_€20) .addGap(57, 57, 57) .addComponent(lbl_€10) .addGap(68, 68, 68) .addComponent(lbl_€5))) .addContainerGap(25, Short.MAX_VALUE)) ); panel_bank_notesLayout.setVerticalGroup( panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addContainerGap(10, Short.MAX_VALUE) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_€500) .addComponent(lbl_€200)) .addGap(30, 30, 30)) .addGroup(panel_bank_notesLayout.createSequentialGroup() .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_€100) .addComponent(lbl_€50) .addComponent(lbl_€20) .addComponent(lbl_€10) .addComponent(lbl_€5)) .addGap(1, 1, 1) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_200, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_500, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_100, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_50, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_10, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_20, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, 0) .addGroup(panel_bank_notesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_500_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_200_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_100_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_50_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_20_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_10_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_5_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); panel_coins.setBackground(new java.awt.Color(204, 204, 204)); panel_coins.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Bank Notes", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("sansserif", 0, 14))); // NOI18N panel_coins.setMaximumSize(new java.awt.Dimension(665, 114)); panel_coins.setPreferredSize(new java.awt.Dimension(0, 0)); txt_2.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_2ActionPerformed(evt); } }); txt_2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_2KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_2KeyReleased(evt); } }); txt_1.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_1ActionPerformed(evt); } }); txt_1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_1KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_1KeyReleased(evt); } }); txt_50c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_50c.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_50cActionPerformed(evt); } }); txt_50c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_50cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_50cKeyReleased(evt); } }); txt_20c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_20c.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_20cActionPerformed(evt); } }); txt_20c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_20cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_20cKeyReleased(evt); } }); txt_10c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_10c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_10cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_10cKeyReleased(evt); } }); txt_5c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_5c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_5cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_5cKeyReleased(evt); } }); txt_2c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_2c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_2cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_2cKeyReleased(evt); } }); txt_1c.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_1c.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_1cActionPerformed(evt); } }); txt_1c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_1cKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txt_1cKeyReleased(evt); } }); lbl_2.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_2.setText("€2"); lbl_1.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_1.setText("€1"); lbl_50c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_50c.setText("50c"); lbl_20c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_20c.setText("20c"); lbl_10c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_10c.setText("10c"); lbl_5c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_5c.setText("5c"); lbl_2c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_2c.setText("2c"); lbl_1c.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N lbl_1c.setText("1c"); lbl_2_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_2_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_2_result.setText("€2Rst"); lbl_2_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_2_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_2_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_1_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_1_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_1_result.setText("€1Rst"); lbl_1_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_1_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_1_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_50c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_50c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_50c_result.setText("50cRst"); lbl_50c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_50c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_50c_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_20c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_20c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_20c_result.setText("20cRst"); lbl_20c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_20c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_20c_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_10c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_10c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_10c_result.setText("10cRst"); lbl_10c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_10c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_10c_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_5c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_5c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_5c_result.setText("5cRst"); lbl_5c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_5c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_5c_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_2c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_2c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_2c_result.setText("2cRst"); lbl_2c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_2c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_2c_result.setPreferredSize(new java.awt.Dimension(0, 15)); lbl_1c_result.setBackground(new java.awt.Color(204, 204, 204)); lbl_1c_result.setForeground(new java.awt.Color(204, 204, 204)); lbl_1c_result.setText("1cRst"); lbl_1c_result.setMaximumSize(new java.awt.Dimension(57, 15)); lbl_1c_result.setMinimumSize(new java.awt.Dimension(57, 15)); lbl_1c_result.setPreferredSize(new java.awt.Dimension(0, 15)); javax.swing.GroupLayout panel_coinsLayout = new javax.swing.GroupLayout(panel_coins); panel_coins.setLayout(panel_coinsLayout); panel_coinsLayout.setHorizontalGroup( panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(lbl_2) .addGap(64, 64, 64) .addComponent(lbl_1)) .addGroup(panel_coinsLayout.createSequentialGroup() .addContainerGap() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_2, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_2_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_1_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_50c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_50c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(36, 36, 36) .addComponent(lbl_50c))) .addGap(19, 19, 19) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_20c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_20c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_coinsLayout.createSequentialGroup() .addComponent(lbl_20c) .addGap(39, 39, 39))) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_10c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_10c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_coinsLayout.createSequentialGroup() .addComponent(lbl_10c) .addGap(35, 35, 35))) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_5c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_5c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(lbl_5c))) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_2c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_2c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_1c, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbl_1c_result, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(panel_coinsLayout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(lbl_2c) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_1c) .addGap(27, 27, 27)))) ); panel_coinsLayout.setVerticalGroup( panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_coinsLayout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_10c) .addComponent(lbl_20c) .addComponent(lbl_50c) .addComponent(lbl_1)) .addGap(0, 0, 0) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_10c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_20c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panel_coinsLayout.createSequentialGroup() .addComponent(lbl_2) .addGap(0, 0, 0) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_50c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, 0) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_50c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_20c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_10c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_2c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_1c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_5c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_2c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_1c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panel_coinsLayout.createSequentialGroup() .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_5c) .addComponent(lbl_2c) .addComponent(lbl_1c)) .addGap(30, 30, 30))) .addGap(0, 0, 0) .addComponent(lbl_5c_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panel_coinsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_1_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_2_result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); txt_total_money.setEditable(false); txt_total_money.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_total_money.setFocusable(false); txt_total_bank_notes.setEditable(false); txt_total_bank_notes.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_total_bank_notes.setFocusable(false); txt_total_bank_notes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_total_bank_notesActionPerformed(evt); } }); txt_total_coins.setEditable(false); txt_total_coins.setFont(new java.awt.Font("sansserif", 1, 15)); // NOI18N txt_total_coins.setFocusable(false); txt_total_coins.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_total_coinsActionPerformed(evt); } }); lbl_total_money.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N lbl_total_money.setText("Total Money €"); lbl_bank_notes.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N lbl_bank_notes.setText("Bank notes"); lbl_coins.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N lbl_coins.setText("Coins"); btn_copy.setBackground(new java.awt.Color(0, 0, 0)); btn_copy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_copy.png"))); // NOI18N btn_copy.setToolTipText("Copy to total money to clipboard"); btn_copy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_copyActionPerformed(evt); } }); btn_clear.setBackground(new java.awt.Color(0, 0, 0)); btn_clear.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_erase.png"))); // NOI18N btn_clear.setToolTipText("Clear fields"); btn_clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_clearActionPerformed(evt); } }); javax.swing.GroupLayout panel_euro_money_counterLayout = new javax.swing.GroupLayout(panel_euro_money_counter); panel_euro_money_counter.setLayout(panel_euro_money_counterLayout); panel_euro_money_counterLayout.setHorizontalGroup( panel_euro_money_counterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_euro_money_counterLayout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(lbl_total_money) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txt_total_money, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_clear, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbl_bank_notes) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txt_total_bank_notes, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lbl_coins) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txt_total_coins, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(panel_coins, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(panel_bank_notes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE) ); panel_euro_money_counterLayout.setVerticalGroup( panel_euro_money_counterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_euro_money_counterLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(panel_bank_notes, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(panel_coins, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(panel_euro_money_counterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_euro_money_counterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_total_money, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_total_money) .addComponent(txt_total_bank_notes, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_bank_notes) .addComponent(txt_total_coins, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_coins)) .addComponent(btn_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_clear, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); getContentPane().add(panel_euro_money_counter, java.awt.BorderLayout.CENTER); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txt_200ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_200ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_200ActionPerformed private void txt_total_coinsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_total_coinsActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_total_coinsActionPerformed private void btn_copyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_copyActionPerformed // TODO add your handling code here: StringSelection stringSelection = new StringSelection(txt_total_money.getText()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); JOptionPane.showMessageDialog(this, txt_total_money.getText() + " Copied to Clipboard"); }//GEN-LAST:event_btn_copyActionPerformed private void btn_clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_clearActionPerformed // TODO add your handling code here: txt_500.setText(""); txt_200.setText(""); txt_100.setText(""); txt_50.setText(""); txt_10.setText(""); txt_20.setText(""); txt_5.setText(""); txt_2.setText(""); txt_1.setText(""); txt_50c.setText(""); txt_20c.setText(""); txt_10c.setText(""); txt_5c.setText(""); txt_2c.setText(""); txt_1c.setText(""); txt_total_money.setText(""); txt_total_bank_notes.setText(""); txt_total_coins.setText(""); input500Qty = 0; input200Qty = 0; input100Qty = 0; input50Qty = 0; input20Qty = 0; input10Qty = 0; input5Qty = 0; input2Qty = 0; input1Qty = 0; input50cQty = 0; input20cQty = 0; input10cQty = 0; input5cQty = 0; input2cQty = 0; input1cQty = 0; totalMoney = 0; countBankNotes = 0; countTotalCoins = 0; lbl_500_result.setForeground(new Color(204, 204, 204)); lbl_200_result.setForeground(new Color(204, 204, 204)); lbl_100_result.setForeground(new Color(204, 204, 204)); lbl_50_result.setForeground(new Color(204, 204, 204)); lbl_20_result.setForeground(new Color(204, 204, 204)); lbl_10_result.setForeground(new Color(204, 204, 204)); lbl_5_result.setForeground(new Color(204, 204, 204)); lbl_2_result.setForeground(new Color(204, 204, 204)); lbl_1_result.setForeground(new Color(204, 204, 204)); lbl_50c_result.setForeground(new Color(204, 204, 204)); lbl_20c_result.setForeground(new Color(204, 204, 204)); lbl_10c_result.setForeground(new Color(204, 204, 204)); lbl_5c_result.setForeground(new Color(204, 204, 204)); lbl_2c_result.setForeground(new Color(204, 204, 204)); lbl_1c_result.setForeground(new Color(204, 204, 204)); txt_500.requestFocus(); }//GEN-LAST:event_btn_clearActionPerformed private void txt_total_bank_notesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_total_bank_notesActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_total_bank_notesActionPerformed private void txt_500KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_500KeyReleased // TODO add your handling code here: if (txt_500.getText().trim().isEmpty()) { input500Qty = 0; lbl_500_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input500Qty = Integer.parseInt(txt_500.getText()); lbl_500_result.setText(String.valueOf(500 * input500Qty)); lbl_500_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_500KeyReleased private void txt_200KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_200KeyReleased // TODO add your handling code here: if (txt_200.getText().trim().isEmpty()) { input200Qty = 0; lbl_200_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input200Qty = Integer.parseInt(txt_200.getText()); lbl_200_result.setText(String.valueOf(200 * input200Qty)); lbl_200_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_200KeyReleased private void txt_100KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_100KeyReleased // TODO add your handling code here: if (txt_100.getText().trim().isEmpty()) { input100Qty = 0; lbl_100_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input100Qty = Integer.parseInt(txt_100.getText()); lbl_100_result.setText(String.valueOf(100 * input100Qty)); lbl_100_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_100KeyReleased private void txt_50KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_50KeyReleased // TODO add your handling code here: if (txt_50.getText().trim().isEmpty()) { input50Qty = 0; lbl_50_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input50Qty = Integer.parseInt(txt_50.getText()); lbl_50_result.setText(String.valueOf(50 * input50Qty)); lbl_50_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_50KeyReleased private void txt_10KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_10KeyReleased // TODO add your handling code here: if (txt_10.getText().trim().isEmpty()) { input10Qty = 0; lbl_10_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input10Qty = Integer.parseInt(txt_10.getText()); lbl_10_result.setText(String.valueOf(10 * input10Qty)); lbl_10_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_10KeyReleased private void txt_20KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_20KeyReleased // TODO add your handling code here: if (txt_20.getText().trim().isEmpty()) { input20Qty = 0; lbl_20_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input20Qty = Integer.parseInt(txt_20.getText()); lbl_20_result.setText(String.valueOf(20 * input20Qty)); lbl_20_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_20KeyReleased private void txt_5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_5KeyReleased // TODO add your handling code here: if (txt_5.getText().trim().isEmpty()) { input5Qty = 0; lbl_5_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input5Qty = Integer.parseInt(txt_5.getText()); lbl_5_result.setText(String.valueOf(5 * input5Qty)); lbl_5_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_5KeyReleased private void txt_2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_2KeyReleased // TODO add your handling code here: if (txt_2.getText().trim().isEmpty()) { input2Qty = 0; lbl_2_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input2Qty = Integer.parseInt(txt_2.getText()); lbl_2_result.setText(String.valueOf(2 * input2Qty)); lbl_2_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_2KeyReleased private void txt_1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_1KeyReleased // TODO add your handling code here: if (txt_1.getText().trim().isEmpty()) { input1Qty = 0; lbl_1_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input1Qty = Integer.parseInt(txt_1.getText()); lbl_1_result.setText(String.valueOf(1 * input1Qty)); lbl_1_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_1KeyReleased private void txt_50cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_50cKeyReleased // TODO add your handling code here: if (txt_50c.getText().trim().isEmpty()) { input50cQty = 0; lbl_50c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input50cQty = Integer.parseInt(txt_50c.getText()); lbl_50c_result.setText(String.valueOf(Math.floor(0.50 * input50cQty * 100) / 100)); lbl_50c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_50cKeyReleased private void txt_20cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_20cKeyReleased // TODO add your handling code here: if (txt_20c.getText().trim().isEmpty()) { input20cQty = 0; lbl_20c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input20cQty = Integer.parseInt(txt_20c.getText()); lbl_20c_result.setText(String.valueOf(Math.floor(0.20 * input20cQty * 100) / 100)); lbl_20c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_20cKeyReleased private void txt_10cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_10cKeyReleased // TODO add your handling code here: if (txt_10c.getText().trim().isEmpty()) { input10cQty = 0; lbl_10c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input10cQty = Integer.parseInt(txt_10c.getText()); lbl_10c_result.setText(String.valueOf(Math.floor(0.10 * input10cQty * 100) / 100)); lbl_10c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_10cKeyReleased private void txt_5cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_5cKeyReleased // TODO add your handling code here: if (txt_5c.getText().trim().isEmpty()) { input5cQty = 0; lbl_5c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input5cQty = Integer.parseInt(txt_5c.getText()); lbl_5c_result.setText(String.valueOf(Math.floor(0.05 * input5cQty * 100) / 100)); lbl_5c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_5cKeyReleased private void txt_2cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_2cKeyReleased // TODO add your handling code here: if (txt_2c.getText().trim().isEmpty()) { input2cQty = 0; lbl_2c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input2cQty = Integer.parseInt(txt_2c.getText()); lbl_2c_result.setText(String.valueOf(Math.floor(0.02 * input2cQty * 100) / 100)); lbl_2c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_2cKeyReleased private void txt_1cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_1cKeyReleased // TODO add your handling code here: if (txt_1c.getText().trim().isEmpty()) { input1cQty = 0; lbl_1c_result.setForeground(new Color(204, 204, 204)); calcMoneyCounter(); } else { input1cQty = Integer.parseInt(txt_1c.getText()); lbl_1c_result.setText(String.valueOf(Math.floor(0.01 * input1cQty * 100) / 100)); lbl_1c_result.setForeground(Color.black); calcMoneyCounter(); } }//GEN-LAST:event_txt_1cKeyReleased private void txt_20cActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_20cActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_20cActionPerformed private void txt_500KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_500KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_500.setEditable(false); } else { txt_500.setEditable(true); } }//GEN-LAST:event_txt_500KeyPressed private void txt_200KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_200KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_200.setEditable(false); } else { txt_200.setEditable(true); } }//GEN-LAST:event_txt_200KeyPressed private void txt_100KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_100KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_100.setEditable(false); } else { txt_100.setEditable(true); } }//GEN-LAST:event_txt_100KeyPressed private void txt_50KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_50KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_50.setEditable(false); } else { txt_50.setEditable(true); } }//GEN-LAST:event_txt_50KeyPressed private void txt_10KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_10KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_10.setEditable(false); } else { txt_10.setEditable(true); } }//GEN-LAST:event_txt_10KeyPressed private void txt_20KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_20KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_20.setEditable(false); } else { txt_20.setEditable(true); } }//GEN-LAST:event_txt_20KeyPressed private void txt_5KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_5KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_5.setEditable(false); } else { txt_5.setEditable(true); } }//GEN-LAST:event_txt_5KeyPressed private void txt_2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_2KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_2.setEditable(false); } else { txt_2.setEditable(true); } }//GEN-LAST:event_txt_2KeyPressed private void txt_1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_1KeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_1.setEditable(false); } else { txt_1.setEditable(true); } }//GEN-LAST:event_txt_1KeyPressed private void txt_20cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_20cKeyPressed // TODO add your handling code here: //Accepts number characters only if (Character.isLetter(evt.getKeyChar())) { txt_20c.setEditable(false); } else { txt_20c.setEditable(true); } }//GEN-LAST:event_txt_20cKeyPressed private void txt_50cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_50cKeyPressed // TODO add your handling code here: if (Character.isLetter(evt.getKeyChar())) { txt_50c.setEditable(false); } else { txt_50c.setEditable(true); } }//GEN-LAST:event_txt_50cKeyPressed private void txt_10cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_10cKeyPressed // TODO add your handling code here: if (Character.isLetter(evt.getKeyChar())) { txt_10c.setEditable(false); } else { txt_10c.setEditable(true); } }//GEN-LAST:event_txt_10cKeyPressed private void txt_5cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_5cKeyPressed // TODO add your handling code here: if (Character.isLetter(evt.getKeyChar())) { txt_5c.setEditable(false); } else { txt_5c.setEditable(true); } }//GEN-LAST:event_txt_5cKeyPressed private void txt_2cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_2cKeyPressed // TODO add your handling code here: if (Character.isLetter(evt.getKeyChar())) { txt_2c.setEditable(false); } else { txt_2c.setEditable(true); } }//GEN-LAST:event_txt_2cKeyPressed private void txt_1cKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_1cKeyPressed // TODO add your handling code here: if (Character.isLetter(evt.getKeyChar())) { txt_1c.setEditable(false); } else { txt_1c.setEditable(true); } }//GEN-LAST:event_txt_1cKeyPressed private void txt_2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_2ActionPerformed private void txt_500ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_500ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_500ActionPerformed private void txt_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_1ActionPerformed private void txt_50cActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_50cActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_50cActionPerformed private void txt_20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_20ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_20ActionPerformed private void txt_100ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_100ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_100ActionPerformed private void txt_1cActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_1cActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_1cActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_clear; private javax.swing.JButton btn_copy; private javax.swing.JLabel lbl_1; private javax.swing.JLabel lbl_100_result; private javax.swing.JLabel lbl_10_result; private javax.swing.JLabel lbl_10c; private javax.swing.JLabel lbl_10c_result; private javax.swing.JLabel lbl_1_result; private javax.swing.JLabel lbl_1c; private javax.swing.JLabel lbl_1c_result; private javax.swing.JLabel lbl_2; private javax.swing.JLabel lbl_200_result; private javax.swing.JLabel lbl_20_result; private javax.swing.JLabel lbl_20c; private javax.swing.JLabel lbl_20c_result; private javax.swing.JLabel lbl_2_result; private javax.swing.JLabel lbl_2c; private javax.swing.JLabel lbl_2c_result; private javax.swing.JLabel lbl_500_result; private javax.swing.JLabel lbl_50_result; private javax.swing.JLabel lbl_50c; private javax.swing.JLabel lbl_50c_result; private javax.swing.JLabel lbl_5_result; private javax.swing.JLabel lbl_5c; private javax.swing.JLabel lbl_5c_result; private javax.swing.JLabel lbl_bank_notes; private javax.swing.JLabel lbl_coins; private javax.swing.JLabel lbl_total_money; private javax.swing.JLabel lbl_€10; private javax.swing.JLabel lbl_€100; private javax.swing.JLabel lbl_€20; private javax.swing.JLabel lbl_€200; private javax.swing.JLabel lbl_€5; private javax.swing.JLabel lbl_€50; private javax.swing.JLabel lbl_€500; private javax.swing.JPanel panel_bank_notes; private javax.swing.JPanel panel_coins; private javax.swing.JPanel panel_euro_money_counter; private javax.swing.JTextField txt_1; private javax.swing.JTextField txt_10; private javax.swing.JTextField txt_100; private javax.swing.JTextField txt_10c; private javax.swing.JTextField txt_1c; private javax.swing.JTextField txt_2; private javax.swing.JTextField txt_20; private javax.swing.JTextField txt_200; private javax.swing.JTextField txt_20c; private javax.swing.JTextField txt_2c; private javax.swing.JTextField txt_5; private javax.swing.JTextField txt_50; private javax.swing.JTextField txt_500; private javax.swing.JTextField txt_50c; private javax.swing.JTextField txt_5c; private javax.swing.JTextField txt_total_bank_notes; private javax.swing.JTextField txt_total_coins; private javax.swing.JTextField txt_total_money; // End of variables declaration//GEN-END:variables }
package com.midea.thread; import java.rmi.StubNotFoundException; //锁的种类: 乐观锁(自旋锁) ,悲观锁(synchronized) ,共享锁(读锁) , 排他锁(写锁) , 阶段锁 //compare and swap public class CAS { //cas(v,期待值,新值) //if v==E // v=new // 否则继续尝试或者失败 // CAS 是cpu指令级别的操作 是无法打断的 //ABA问题 用版本号 /** * unsafe这个类可以 直接操作jvm内存 * 直接生成类实例 * 直接操作类或实例变量 * 比如操作某个类的属性 可以直接从unsafe直接从内存中改 */ }
package LearningJava.Lessons.Lesson3ArraysAndStrings; public class Strings { public static void main(String[] args) { String greeting = "Hello"; System.out.println(greeting); // Hello String name = "Stephen"; System.out.println(name); // Stephen System.out.println(greeting + ", " + name); // Hello, Stephen String message = greeting + ", " + name; System.out.println(message); // Hello, Stephen // Find the length of a string System.out.println(name.length()); // 7 System.out.println(message.length()); // 14 int messageLength = message.length(); int nameLength = name.length(); int messageNameLength = messageLength + nameLength; System.out.println(messageNameLength); // 21 String upperCase = greeting.toUpperCase(); System.out.println(upperCase); // HELLO String firstSubstring = name.substring(1); System.out.println(firstSubstring); // tephen String secondSubstring = "hello world".substring(6); System.out.println(secondSubstring); // world String thirdSubstring = message.substring(1, 3); System.out.println(thirdSubstring); // message = hello so substring(1, 3) = el String names = "Peter, John, Andy, David"; String[] splitNames = names.split(", "); System.out.println(names); for (String temp : splitNames) { System.out.println(temp); } } }
package com.bestom.aihome.imple.inter.Listener; /** * 接收到数据监听 */ public interface DataReceivedListener<T> { void data(T data); }
package com.zc.pivas.docteradvice.bean; import java.io.Serializable; public class TrackingRecord implements Serializable { /** * 注释内容 */ private static final long serialVersionUID = 2664119747162670727L; String id; String operator; String operation_time; String type_num; String type_name; String relevance; /** * @return 返回 id */ public String getId() { return id; } /** * 对id进行赋值 * @param */ public void setId(String id) { this.id = id; } /** * @return 返回 operator */ public String getOperator() { return operator; } /** * 对operator进行赋值 * @param */ public void setOperator(String operator) { this.operator = operator; } /** * @return 返回 operation_time */ public String getOperation_time() { return operation_time; } /** * 对operation_time进行赋值 * @param */ public void setOperation_time(String operation_time) { this.operation_time = operation_time; } /** * @return 返回 type_num */ public String getType_num() { return type_num; } /** * 对type_num进行赋值 * @param */ public void setType_num(String type_num) { this.type_num = type_num; } /** * @return 返回 type_name */ public String getType_name() { return type_name; } /** * 对type_name进行赋值 * @param */ public void setType_name(String type_name) { this.type_name = type_name; } /** * @return 返回 relevance */ public String getRelevance() { return relevance; } /** * 对relevance进行赋值 * @param */ public void setRelevance(String relevance) { this.relevance = relevance; } }
package com.model.db; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.types.ObjectId; import com.model.dao.impl.DaoImpl; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; public class BsonUtil { public static <T> List<T> toBeans(List<Document> documents, Class<T> clazz) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { List<T> list = new ArrayList<T>(); for (int i = 0; null != documents && i < documents.size(); i++) { list.add(toBean(documents.get(i), clazz)); } return list; } public static String readKey(Field field) { String fname = field.getName(); Column column = field.getAnnotation(Column.class); if (null != column && null != column.name()) { return column.name(); } else if ("id".equals(fname)) { return "_id"; } return fname; } private static boolean isLinkedDoc(Object docVal,Field field) { if(field.getName().equals("id")) { return false; } return ((docVal instanceof String) || (docVal instanceof ObjectId)) && !isJavaClass(field.getType()) ; } /* * 将Bson 转化为对象 * * @param:Bson文档 * * @param:类pojo * * @param:返回对象 */ public static <T> T toBean(Document document, Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if(document == null) { return null; } T obj = clazz.newInstance();// 声明一个对象 Field[] fields = clazz.getDeclaredFields();// 获取所有属性 Method[] methods = clazz.getMethods();// 获取所有的方法 /* * 查找所有的属性,并通过属性名和数据库字段名通过相等映射 */ for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = fields[i].getName(); String key = readKey(fields[i]); Object bson = document.get(key); if(key.equals("deviceDicts")) { System.out.println(key + " is list -----------" + bson); //System.out.println(key + " is list -----------" + bson.getClass().getName()); } if (null == bson) { continue; }else if(isLinkedDoc(bson,field)) { bson = DaoImpl.get(field.getType(), bson); } else if (bson instanceof Document) {// 如果字段是文档了递归调用 bson = toBean((Document) bson, fields[i].getType()); } else if (bson instanceof List) {// 如果字段是文档集了调用colTOList方法 bson = colToList((List<Object>)bson, fields[i]); } for (int j = 0; j < methods.length; j++) {// 为对象赋值 String metdName = methods[j].getName(); if (equalFieldAndSet(fieldName, metdName)) { methods[j].invoke(obj, bson); break; } } } return obj; } public static List<Document> toBsons(List<Object> objs) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { List<Document> documents = new ArrayList<Document>(); for (int i = 0; null != objs && i < objs.size(); i++) { documents.add(toBson(objs.get(i))); } return documents; } public static ObjectId readId(Object obj) { if(obj == null) { return null; } Method[] linkedMs = obj.getClass().getDeclaredMethods(); for(Method m : linkedMs) { if("getId".equals(m.getName())) { try { Object id = m.invoke(obj); if(id != null && (id instanceof ObjectId)) { return (ObjectId)id; } } catch (Exception e) {} } } return null; } public static boolean notColumn(Field field) { NotColumn notColumn = field.getAnnotation(NotColumn.class);// 获取否列 return notColumn != null; } /* * 将对象转化为Bson文档 * * @param:对象 * * @param:类型 * * @return:文档 */ public static Document toBson(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchFieldException { if (null == obj) { return null; } Class<? extends Object> clazz = obj.getClass(); Document document = new Document(); Method[] methods = clazz.getDeclaredMethods(); Field[] fields = clazz.getDeclaredFields(); for (int i = 0; null != fields && i < fields.length; i++) { Field field = fields[i]; if(notColumn(field)) { continue; } //Column column = field.getAnnotation(Column.class);// 获取列注解内容 String key = readKey(field);// 对应的文档键值 String fieldName = field.getName(); /* * 获取对象属性值并映射到Document中 */ for (int j = 0; null != methods && j < methods.length; j++) { String methdName = methods[j].getName(); Class returnClazz = methods[j].getReturnType(); if (null != fieldName && equalFieldAndGet(fieldName, methdName)) { Object val = methods[j].invoke(obj);// 得到值 //System.out.println(fieldName + "---- " + methdName +", val : " + val); if (null == val) { continue; } if(val instanceof ObjectId) { document.append(key, val); continue; } if(isList(returnClazz)) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) val; List<Document> documents = new ArrayList<Document>(); for (Object obj1 : list) { documents.add(toBson(obj1)); } document.append(key, documents); continue; } if (isJavaClass(returnClazz)) { document.append(key, val); } else {// 自定义类型 ObjectId lid = readId(val); if(lid != null) { document.append(key,lid); }else { document.append(key, toBson(val)); } } } } } return document; } public static boolean isList(Class cls) { if(cls == null)return false; return cls.getName().equals("java.util.List"); } /* * 是否是自定义类型】 * * false:是自定义 */ private static boolean isJavaClass(Class<?> clz) { return clz != null && clz.getClassLoader() == null; } private static List<Object> colToList(List<Object> datas, Field field) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if(datas == null) { return null; } ParameterizedType pt = (ParameterizedType) field.getGenericType();// 获取列表的类型 List<Object> objs = new ArrayList<Object>(); for(Object obj : datas) { @SuppressWarnings("rawtypes") Class clz = (Class) pt.getActualTypeArguments()[0];// 获取元素类型 Object bean = obj; if(obj instanceof Document) { bean = toBean((Document)obj, clz); } objs.add(bean); } return objs; } /* * 将文档集转化为列表 * * @param:文档集 * * @param:属性类型 * * @return:返回列表 */ private static List<Object> colToList(Object bson, Field field) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { ParameterizedType pt = (ParameterizedType) field.getGenericType();// 获取列表的类型 System.out.println(" pt : " + pt.getActualTypeArguments()[0]); List<Object> objs = new ArrayList<Object>(); @SuppressWarnings("unchecked") MongoCollection<Document> cols = (MongoCollection<Document>) bson; MongoCursor<Document> cursor = cols.find().iterator(); while (cursor.hasNext()) { Document child = cursor.next(); @SuppressWarnings("rawtypes") Class clz = (Class) pt.getActualTypeArguments()[0];// 获取元素类型 @SuppressWarnings("unchecked") Object obj = toBean(child, clz); System.out.println(child); objs.add(obj); } return objs; } /* * 比较setter方法和属性相等 */ private static boolean equalFieldAndSet(String field, String name) { if (name.toLowerCase().matches("set" + field.toLowerCase())) { return true; } else { return false; } } /* * 比较getter方法和属性相等 */ private static boolean equalFieldAndGet(String field, String name) { if (name.toLowerCase().matches("get" + field.toLowerCase())) { return true; } else { return false; } } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.migration.itemexport; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import net.datacrow.util.Converter; public abstract class XmlBaseWriter { protected final String uberTag = "data-crow-objects"; protected final BufferedOutputStream bos; protected XmlBaseWriter(BufferedOutputStream bos) { this.bos = bos; } protected XmlBaseWriter(String filename) throws IOException { FileOutputStream fos = new FileOutputStream(filename); bos = new BufferedOutputStream(fos); } protected String getValidTag(String s) { return Converter.getValidXmlTag(s); } protected void newLine() throws IOException { bos.write("\r\n".getBytes()); } protected void writeLine(String s, int level) throws IOException { for (int i = 0; i < level; i++) bos.write(" ".getBytes()); writeTag(s); newLine(); } protected void writeTag(String s) throws IOException { bos.write(s.getBytes("UTF8")); } }
package otf.obj.msg; import otf.model.ClientDataModel; import otf.obj.BloodSugarValueEntity; /** * @author &#8904 * */ public class DeletedBloodSugarValue { private BloodSugarValueEntity bz; private ClientDataModel model; public DeletedBloodSugarValue(BloodSugarValueEntity bz, ClientDataModel model) { this.bz = bz; this.model = model; } /** * @return the bz */ public BloodSugarValueEntity getBz() { return this.bz; } /** * @param bz * the bz to set */ public void setBz(BloodSugarValueEntity bz) { this.bz = bz; } /** * @return the model */ public ClientDataModel getModel() { return this.model; } /** * @param model * the model to set */ public void setModel(ClientDataModel model) { this.model = model; } }
package org.shujito.cartonbox.model.db; import org.shujito.cartonbox.model.Site; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; // so useful: // http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ public final class SitesDB extends DB<Site> { /* static */ static final String DB_NAME = "sites.db3"; static final int VERSION = 0x00000002; static final String TABLE_SITES = "sites"; static final String KEY_ID = "id"; static final String KEY_ICON = "icon"; static final String KEY_URL = "url"; static final String KEY_TYPE = "type"; static final String KEY_NAME = "name"; static final String KEY_POST_VIEW_API = "post_view_api"; static final String KEY_POSTS_API = "posts_api"; static final String KEY_POOLS_API = "pools_api"; static final String KEY_COMMENTS_API = "comments_api"; static final String KEY_NOTES_API = "notes_api"; static final String KEY_ARTISTS_API = "artists_api"; static final String KEY_TAGS_API = "tags_api"; /* constructor */ public SitesDB(Context context) { super(context, DB_NAME, VERSION, TABLE_SITES, KEY_ID, KEY_NAME, true); } /* meth */ @Override protected ContentValues fromRecord(Site record) { ContentValues values = new ContentValues(); values.put(KEY_ID, record.getId()); values.put(KEY_URL, record.getUrl()); values.put(KEY_TYPE, record.getType().getValue()); values.put(KEY_ICON, record.getIconFile()); values.put(KEY_NAME, record.getName()); values.put(KEY_POST_VIEW_API, record.getPostViewApi()); values.put(KEY_POSTS_API, record.getPostsApi()); values.put(KEY_POOLS_API, record.getPoolsApi()); values.put(KEY_COMMENTS_API, record.getCommentsApi()); values.put(KEY_NOTES_API, record.getNotesApi()); values.put(KEY_ARTISTS_API, record.getArtistsApi()); values.put(KEY_TAGS_API, record.getTagsApi()); return values; } @Override protected Site fromCursor(Cursor cursor) { // Good, now THIS looks DRY int iType = cursor.getInt(cursor.getColumnIndex(KEY_TYPE)); Site.Type type = null; switch(iType) { case 1: type = Site.Type.Danbooru1; break; case 2: type = Site.Type.Danbooru2; break; case 3: type = Site.Type.Gelbooru; break; } Site site = new Site() .setId(cursor.getLong(cursor.getColumnIndex(KEY_ID))) .setUrl(cursor.getString(cursor.getColumnIndex(KEY_URL))) .setType(type) .setIconFile(cursor.getString(cursor.getColumnIndex(KEY_ICON))) .setName(cursor.getString(cursor.getColumnIndex(KEY_NAME))) .setPostViewApi(cursor.getString(cursor.getColumnIndex(KEY_POST_VIEW_API))) .setPostsApi(cursor.getString(cursor.getColumnIndex(KEY_POSTS_API))) .setPoolsApi(cursor.getString(cursor.getColumnIndex(KEY_POOLS_API))) .setCommentsApi(cursor.getString(cursor.getColumnIndex(KEY_COMMENTS_API))) .setNotesApi(cursor.getString(cursor.getColumnIndex(KEY_NOTES_API))) .setArtistsApi(cursor.getString(cursor.getColumnIndex(KEY_ARTISTS_API))) .setTagsApi(cursor.getString(cursor.getColumnIndex(KEY_TAGS_API))); return site; } /* override */ @Override public void onCreate(SQLiteDatabase db) { String[][] fields = { { SQL_PK, KEY_ID }, { SQL_TEXT, KEY_URL }, { SQL_INTEGER, KEY_TYPE }, { SQL_TEXT, KEY_ICON }, // filename { SQL_TEXT, KEY_NAME }, { SQL_TEXT, KEY_POST_VIEW_API }, { SQL_TEXT, KEY_POSTS_API }, { SQL_TEXT, KEY_POOLS_API }, { SQL_TEXT, KEY_COMMENTS_API }, { SQL_TEXT, KEY_NOTES_API }, { SQL_TEXT, KEY_ARTISTS_API }, { SQL_TEXT, KEY_TAGS_API } }; this.createTable(db, fields); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(String.format(SQL_DROP, TABLE_SITES)); this.onCreate(db); } public boolean delete(Site site) { return this.delete(site, site.getId()); } public void update(Site site) { this.update(site, site.getId()); } }
package com.isg.ifrend.core.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * Bean class for memo. * * Classification: Auto, Manual * * AUTO memoType:: * MAINT,TCLI,PCLI,DDA BLKCD,POT, PYOUT ,CLSACC * REISS,CRDREP,PINREQ,LOST,STOLEN,DISPUTE,REGENST * AUTREV, MANADJ * * MANUAL memoType: * COMPLIANT, OTHERS * */ public class Memo implements Serializable { private static final long serialVersionUID = 6820066397637484979L; private String callId; private String memoId; private String memoType; private String classification; private Date transactionDate; private Date postdate; private String operatorID; private String description; private String ranCode; private String sourceCode; private String posEntryMode; private String referenceNbr; private String interchangeReferenceNbr; private String cardNbr; private BigDecimal disputeAmount; private String remarks; public Memo(){ } public Memo(String callId, String memoId, String memoType, String classification, Date transactionDate, Date postdate, String operatorID, String description, String ranCode, String sourceCode, String posEntryMode, String referenceNbr, String interchangeReferenceNbr, String cardNbr, BigDecimal disputeAmount, String remarks) { super(); this.callId = callId; this.memoId = memoId; this.memoType = memoType; this.classification = classification; this.transactionDate = transactionDate; this.postdate = postdate; this.operatorID = operatorID; this.description = description; this.ranCode = ranCode; this.sourceCode = sourceCode; this.posEntryMode = posEntryMode; this.referenceNbr = referenceNbr; this.interchangeReferenceNbr = interchangeReferenceNbr; this.cardNbr = cardNbr; this.disputeAmount = disputeAmount; this.remarks = remarks; } /** getter and setter **/ public String getCallId() { return callId; } public void setCallId(String callId) { this.callId = callId; } public String getMemoId() { return memoId; } public void setMemoId(String memoId) { this.memoId = memoId; } public String getMemoType() { return memoType; } public void setMemoType(String memoType) { this.memoType = memoType; } public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } public Date getTransactionDate() { return transactionDate; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } public Date getPostdate() { return postdate; } public void setPostdate(Date postdate) { this.postdate = postdate; } public String getOperatorID() { return operatorID; } public void setOperatorID(String operatorID) { this.operatorID = operatorID; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRanCode() { return ranCode; } public void setRanCode(String ranCode) { this.ranCode = ranCode; } public String getSourceCode() { return sourceCode; } public void setSourceCode(String sourceCode) { this.sourceCode = sourceCode; } public String getPosEntryMode() { return posEntryMode; } public void setPosEntryMode(String posEntryMode) { this.posEntryMode = posEntryMode; } public String getReferenceNbr() { return referenceNbr; } public void setReferenceNbr(String referenceNbr) { this.referenceNbr = referenceNbr; } public String getInterchangeReferenceNbr() { return interchangeReferenceNbr; } public void setInterchangeReferenceNbr(String interchangeReferenceNbr) { this.interchangeReferenceNbr = interchangeReferenceNbr; } public String getCardNbr() { return cardNbr; } public void setCardNbr(String cardNbr) { this.cardNbr = cardNbr; } public BigDecimal getDisputeAmount() { return disputeAmount; } public void setDisputeAmount(BigDecimal disputeAmount) { this.disputeAmount = disputeAmount; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
package color; /** * Clase que contiene la declaración de las <strong>constantes con los códigos * de color ANSI</strong> utilizados en la aplicación. * <p> * Esta clase no contiene ningún método, solo atributos de clase, estáticos * finales y públicos.</p> * <p> * Más información sobre códigos ANSI en:<br> * <a href="https://es.wikipedia.org/wiki/Instituto_Nacional_Estadounidense_de_Est%C3%A1ndares">Entrada * en wikipedia de ANSI</a><br> * <a href="https://www.campusmvp.es/recursos/post/como-cambiar-los-colores-de-la-consola-con-java-y-system-out-println.aspx">Cómo * cambiar los colores de la consola con Java y System.out.println - Entrada en * el blog de José Manuel Alarcón</a> * </p> * * @author Sebastián López * @version febrero/2021 */ public class ANSI { //Códigos de color de fondo /** * Constante que contiene el código de color ANSI fondo dialogo {@value} */ public static final String FONDO_VERDE = "\u001b[42m"; /** * Constante que contiene el código de color ANSI fondo error {@value} */ public static final String FONDO_ROJO = "\u001b[41m"; /** * Constante que contiene el código de color ANSI fondo amarillo {@value} */ public static final String FONDO_AMARILLO = "\u001b[43m"; /** * Constante que contiene el código de color ANSI fondo cian {@value} */ public static final String FONDO_CIAN = "\u001b[46m"; /** * Constante que contiene el código de color ANSI fondo menu {@value} */ public static final String FONDO_AZUL = "\u001b[44m"; /** * Constante que contiene el código de color ANSI fondo blanco {@value} */ public static final String FONDO_BLANCO = "\u001b[47m"; //Códigos de color de carácter /** * Constante que contiene el código de color ANSI carácter blanco {@value} */ public static final String LETRA_BLANCA = "\u001B[37m"; /** * Constante que contiene el código de color ANSI carácter menu {@value} */ public static final String LETRA_AZUL = "\u001B[34m"; /** * Constante que contiene el código de color ANSI carácter error {@value} */ public static final String LETRA_ROJA = "\u001B[31m"; /** * Constante que contiene el código de color ANSI carácter amaillo {@value} */ public static final String LETRA_AMARILLA = "\u001B[33m"; /** * Constante que contiene el código de color ANSI carácter dialogo {@value} */ public static final String LETRA_VERDE = "\u001B[32m"; /** * Constante que contiene el código ANSI para volver a los colores normales * {@value} */ public static final String RESET = "\u001B[0m"; //Constructor privado para evitar instanciar objetos de esta clase. private ANSI() { } }
package sr.hakrinbank.intranet.api.model; import org.hibernate.envers.Audited; import sr.hakrinbank.intranet.api.util.Constant; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.validation.constraints.Size; @Entity @Audited @DiscriminatorValue(Constant.GREY) public class ListedPersonGrey extends ListedPerson { private String alias; private String birthPlace; private String passportOrId; @ManyToOne private Nationality nationality; @Size(max = 1000) private String reason; public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getBirthPlace() { return birthPlace; } public void setBirthPlace(String birthPlace) { this.birthPlace = birthPlace; } public String getPassportOrId() { return passportOrId; } public void setPassportOrId(String passportOrId) { this.passportOrId = passportOrId; } public Nationality getNationality() { return nationality; } public void setNationality(Nationality nationality) { this.nationality = nationality; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
package com.logicbig.example; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; @EnableWebMvc @Configuration public class MyWebConfig { @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasenames("ValidationMessages"); return messageSource; } @Bean public UserRegistrationController userRegistrationController() { return new UserRegistrationController(); } @Bean public UserService userService() { return new InMemoryUserService(); } @Bean public ViewResolver viewResolver () { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
import java.time.*; //Timer class to time our methods public class timer { boolean startStop; Instant startTime; Instant endTime; //constructor timer() { startStop = true; startTime = Instant.now(); } //grabs the end time public void stopTime() { if(!startStop) { endTime = Instant.now(); } } //prints out the time public void printTime(String method) { System.out.println(method + " time to run was: " + (endTime.toEpochMilli() - startTime.toEpochMilli()) + " milliseconds"); } }
package com.maxmind.geoip2.model; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonProperty; import com.maxmind.geoip2.record.City; import com.maxmind.geoip2.record.Continent; import com.maxmind.geoip2.record.Country; import com.maxmind.geoip2.record.Location; import com.maxmind.geoip2.record.MaxMind; import com.maxmind.geoip2.record.Postal; import com.maxmind.geoip2.record.RepresentedCountry; import com.maxmind.geoip2.record.Subdivision; import com.maxmind.geoip2.record.Traits; import java.util.List; /** * This class provides a model for the data returned by the Insights web * service. * * @see <a href="https://dev.maxmind.com/geoip/docs/web-services?lang=en">GeoIP2 Web * Services</a> */ public class InsightsResponse extends AbstractCityResponse { public InsightsResponse( @JsonProperty("city") City city, @JsonProperty("continent") Continent continent, @JsonProperty("country") Country country, @JsonProperty("location") Location location, @JsonProperty("maxmind") MaxMind maxmind, @JsonProperty("postal") Postal postal, @JsonProperty("registered_country") Country registeredCountry, @JsonProperty("represented_country") RepresentedCountry representedCountry, @JsonProperty("subdivisions") List<Subdivision> subdivisions, @JacksonInject("traits") @JsonProperty("traits") Traits traits ) { super(city, continent, country, location, maxmind, postal, registeredCountry, representedCountry, subdivisions, traits); } }
package com.threadlocal; import java.util.HashMap; public class MyThreadLocal<T> { static HashMap<Thread,HashMap<MyThreadLocal<?>,Object>> threadLocalMap = new HashMap<>(); synchronized static HashMap<MyThreadLocal<?>,Object> getMap(){ Thread thread = Thread.currentThread(); if(!threadLocalMap.containsKey(thread)){ threadLocalMap.put(thread,new HashMap<MyThreadLocal<?>,Object>()); } return threadLocalMap.get(thread); } protected T initialValue(){ return null; } public T get(){ HashMap<MyThreadLocal<?>, Object> map = getMap(); if(!map.containsKey(this)){ map.put(this,initialValue()); } return (T) map.get(this); } public void set(T v){ HashMap<MyThreadLocal<?>, Object> map = getMap(); map.put(this,v); } }
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.ProxyConfig; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; import com.gargoylesoftware.htmlunit.util.Cookie; import com.gargoylesoftware.htmlunit.util.NameValuePair; import com.google.common.collect.Maps; import com.google.common.io.ByteStreams; import java.util.concurrent.locks.ReentrantLock; public class Pwq { public static void main(String[] args) { System.out.println("contentEncoding:"); ReentrantLock // //创建HttpClientBuilder // HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // //HttpClient // CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // // HttpGet httpGet = new HttpGet("http://www.gxnu.edu.cn/default.html"); // System.out.println(httpGet.getRequestLine()); // try { // //执行get请求 // HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // //获取响应消息实体 // HttpEntity entity = httpResponse.getEntity(); // //响应状态 // System.out.println("status:" + httpResponse.getStatusLine()); // //判断响应实体是否为空 // if (entity != null) { // System.out.println("contentEncoding:" + entity.getContentEncoding()); // System.out.println("response content:" + EntityUtils.toString(entity)); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // //关闭流并释放资源 // closeableHttpClient.close(); // } catch (IOException e) { // e.printStackTrace(); // } String url = "http://www.google.com.hk"; // // final WebClient webClient = new WebClient(); // HtmlPage htmlPage = webClient.getPage(url); // } } }
package com.tvm.beanlifecycle; import java.util.Arrays; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * * * */ @Component public class AwareBean implements ApplicationContextAware, BeanNameAware, BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("setBeanFactory method is called"); System.out.println("setBeanFactory : Aware bean singleton= " + beanFactory.isSingleton("user")); } @Override public void setBeanName(String beanName ) { System.out.println("setBeanName method is called"); System.out.println("Bean Name Defined in context " + beanName); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("setApplicationContext method is called"); System.out.println("setApplicationContext :: Bean Definition Name =" + Arrays.toString(applicationContext.getBeanDefinitionNames())); } }
package cpup.poke4j.plugin.input; import cpup.poke4j.Buffer; import cpup.poke4j.BufferPos; import cpup.poke4j.Poke; import cpup.poke4j.ui.PokeUI; import cpup.poke4j.ui.UI; import java.awt.event.MouseEvent; public class MouseInput implements Input { protected final Poke poke; protected final Buffer buffer; protected final PokeUI pokeUI; protected final UI activeUI; protected final Type type; protected final MouseEvent e; protected final BufferPos pos; public MouseInput(Poke _poke, Buffer _buffer, PokeUI _pokeUI, UI _activeUI, Type _type, MouseEvent _e, BufferPos _pos) { poke = _poke; buffer = _buffer; pokeUI = _pokeUI; activeUI = _activeUI; type = _type; e = _e; pos = _pos; } // Getters and Setters public Poke getPoke() { return poke; } public Buffer getBuffer() { return buffer; } public PokeUI getPokeUI() { return pokeUI; } public UI getActiveUI() { return activeUI; } public Type getType() { return type; } public MouseEvent getEvent() { return e; } public BufferPos getPos() { return pos; } public boolean isShiftDown() { return e.isShiftDown(); } public boolean isControlDown() { return e.isControlDown(); } public boolean isMetaDown() { return e.isMetaDown(); } public boolean isAltDown() { return e.isAltDown(); } public boolean isAltGraphDown() { return e.isAltGraphDown(); } public int getModifiers() { return e.getModifiers(); } public int getModifiersEx() { return e.getModifiersEx(); } public static enum Type { click, drag, press } }
package de.amr.games.pacman.lib; import java.time.LocalTime; import java.time.format.DateTimeFormatter; /** * Log messages. * * @author Armin Reichert * */ public class Logging { public static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); public static void log(String msg, Object... args) { String timestamp = TIME_FORMAT.format(LocalTime.now()); String message = String.format(msg, args); System.err.printf("[%s] %s\n", timestamp, message); } }
package ch05; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; @SuppressWarnings("serial") public class FunctionPrinter extends JComponent{ public static final int WIDTH = 400; public static final int HEIGHT = 300; private final int MARGIN = 20; private final int XMIN = MARGIN; private final int XMAX = WIDTH - MARGIN; private final int STEPS = 100; private final int STEPSIZE = (XMAX - XMIN) / STEPS; public FunctionPrinter(){ } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; for(int i = XMIN; i <= XMAX - STEPSIZE; i += STEPSIZE) { g2.drawLine(i, (int)f(i), i + STEPSIZE, (int)f(i + STEPSIZE)); } } public double f(double x) { return 0.00005*Math.pow(x, 3) - 0.03*Math.pow(x, 2) + 4*x + 200; } }
package com.wangyang.basic.dao.impl; import com.wangyang.basic.dao.IClassroomDao; import com.wangyang.model.Classroom; import com.wangyang.util.BaseDao; import org.springframework.stereotype.Repository; @Repository("classroomDao") public class ClassroomDao extends BaseDao<Classroom> implements IClassroomDao { }
public class sphere extends threeDimensionalShape { private double radius; public sphere(double r) { radius = r; } public double getArea() { return (4 * Math.PI * radius * radius); } public double getVolume() { return (4.0 / 3.0 * Math.PI * radius * radius * radius); } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.sql.ast.statement; import com.alibaba.druid.sql.ast.SQLCommentHint; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLStatementImpl; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.visitor.SQLASTVisitor; import java.util.List; public class SQLShowIndexesStatement extends SQLStatementImpl implements SQLShowStatement { private SQLExprTableSource table; private List<SQLCommentHint> hints; private SQLExpr where; private String type; public SQLExprTableSource getTable() { return table; } public void setTable(SQLName table) { setTable(new SQLExprTableSource(table)); } public void setTable(SQLExprTableSource table) { this.table = table; } public SQLName getDatabase() { SQLExpr expr = table.getExpr(); if (expr instanceof SQLPropertyExpr) { return (SQLName) ((SQLPropertyExpr) expr).getOwner(); } return null; } public SQLExpr getWhere() { return where; } public void setWhere(SQLExpr where) { this.where = where; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setDatabase(String database) { table.setSchema(database); } public void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, table); acceptChild(visitor, where); } visitor.endVisit(this); } public List<SQLCommentHint> getHints() { return hints; } public void setHints(List<SQLCommentHint> hints) { this.hints = hints; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.security.Principal; import java.util.List; import java.util.Map; import org.springframework.http.HttpHeaders; import org.springframework.lang.Nullable; /** * A WebSocket session abstraction. Allows sending messages over a WebSocket * connection and closing it. * * @author Rossen Stoyanchev * @since 4.0 */ public interface WebSocketSession extends Closeable { /** * Return a unique session identifier. */ String getId(); /** * Return the URI used to open the WebSocket connection. */ @Nullable URI getUri(); /** * Return the headers used in the handshake request (never {@code null}). */ HttpHeaders getHandshakeHeaders(); /** * Return the map with attributes associated with the WebSocket session. * <p>On the server side the map can be populated initially through a * {@link org.springframework.web.socket.server.HandshakeInterceptor * HandshakeInterceptor}. On the client side the map can be populated via * {@link org.springframework.web.socket.client.WebSocketClient * WebSocketClient} handshake methods. * @return a Map with the session attributes (never {@code null}) */ Map<String, Object> getAttributes(); /** * Return a {@link java.security.Principal} instance containing the name * of the authenticated user. * <p>If the user has not been authenticated, the method returns <code>null</code>. */ @Nullable Principal getPrincipal(); /** * Return the address on which the request was received. */ @Nullable InetSocketAddress getLocalAddress(); /** * Return the address of the remote client. */ @Nullable InetSocketAddress getRemoteAddress(); /** * Return the negotiated sub-protocol. * @return the protocol identifier, or {@code null} if no protocol * was specified or negotiated successfully */ @Nullable String getAcceptedProtocol(); /** * Configure the maximum size for an incoming text message. */ void setTextMessageSizeLimit(int messageSizeLimit); /** * Get the configured maximum size for an incoming text message. */ int getTextMessageSizeLimit(); /** * Configure the maximum size for an incoming binary message. */ void setBinaryMessageSizeLimit(int messageSizeLimit); /** * Get the configured maximum size for an incoming binary message. */ int getBinaryMessageSizeLimit(); /** * Determine the negotiated extensions. * @return the list of extensions, or an empty list if no extension * was specified or negotiated successfully */ List<WebSocketExtension> getExtensions(); /** * Send a WebSocket message: either {@link TextMessage} or {@link BinaryMessage}. * <p><strong>Note:</strong> The underlying standard WebSocket session (JSR-356) does * not allow concurrent sending. Therefore, sending must be synchronized. To ensure * that, one option is to wrap the {@code WebSocketSession} with the * {@link org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator * ConcurrentWebSocketSessionDecorator}. * @see org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator */ void sendMessage(WebSocketMessage<?> message) throws IOException; /** * Whether the underlying connection is open. */ boolean isOpen(); /** * Close the WebSocket connection with status 1000, i.e. equivalent to: * <pre class="code"> * session.close(CloseStatus.NORMAL); * </pre> */ @Override void close() throws IOException; /** * Close the WebSocket connection with the given close status. */ void close(CloseStatus status) throws IOException; }
package nl.topicus.wqplot.components.plugins; /** * @author Ernesto Reinaldo Barreiro */ public class JQPlotCanvasTextRenderer extends Renderer { private static final JQPlotCanvasTextRenderer INSTANCE = new JQPlotCanvasTextRenderer(); private JQPlotCanvasTextRenderer() { super("$.jqplot.CanvasTextRenderer", JQPlotCanvasTextRendererResourceReference.get()); } public static JQPlotCanvasTextRenderer get() { return INSTANCE; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.maven.model.transform; import java.io.IOException; import java.util.stream.Stream; import org.apache.maven.model.transform.pull.BufferingParser; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * Remove the root attribute on the model * * @author Guillaume Nodet * @since 4.0.0 */ class RootXMLFilter extends BufferingParser { RootXMLFilter(XmlPullParser xmlPullParser) { super(xmlPullParser); } @Override protected boolean accept() throws XmlPullParserException, IOException { if (xmlPullParser.getEventType() == XmlPullParser.START_TAG) { if (xmlPullParser.getDepth() == 1 && "project".equals(xmlPullParser.getName())) { Event event = bufferEvent(); event.attributes = Stream.of(event.attributes) .filter(a -> !"root".equals(a.name)) .toArray(Attribute[]::new); pushEvent(event); 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 unt.herrera.prog2.tp5; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * * @author jonas */ public interface IGestorTrabajos { public String nuevoTrabajo(String titulo,int duracion,LocalDate fechaPresentacion, LocalDate fechaAprobacion,List<Area> areas,List<RolEnTrabajo> profesores, List<AlumnoEnTrabajo> aet); public Trabajo dameTrabajo(String titulo); public List<Trabajo> buscarTrabajos(String titulo); public void mostrarTrabajos(); public void ordenarTrabajos(); public String finalizarAlumno(Trabajo trabajo, Alumno alumno, LocalDate fechaHasta,String razon); public String finalizarTrabajo(Trabajo trabajo, LocalDate fechaExposicion); public String borrarTrabajo(Trabajo trabajo); public String reemplazarProfesor(Trabajo trabajo, Profesor profesorReemplazado, LocalDate fechaHasta, String razon, Profesor nuevoProfesor); public String nuevoTrabajo(String titulo, ArrayList<Area> area,int duracion, LocalDate fechaPresentacion,LocalDate fechaAprobacion, ArrayList<AlumnoEnTrabajo> listaAlumnoEnT, ArrayList<RolEnTrabajo> listaRolEnT); }
package com.jushu.video.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.jushu.video.common.IpUtil; import com.jushu.video.entity.GmAdmin; import com.jushu.video.entity.GmLog; import com.jushu.video.mapper.GmAdminMapper; import com.jushu.video.mapper.GmLogMapper; import com.jushu.video.service.IGmAdminService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.Calendar; import java.util.Date; import java.util.UUID; /** * <p> * 管理后台管理员用户表 服务实现类 * </p> * * @author chen * @since 2020-01-07 */ @Service public class GmAdminServiceImpl extends ServiceImpl<GmAdminMapper, GmAdmin> implements IGmAdminService { private Logger logger = LoggerFactory.getLogger(GmAdminServiceImpl.class); @Autowired private GmLogMapper gmLogMapper; @Override public boolean save(GmAdmin entity) { entity.setAdminId(UUID.randomUUID().toString()); entity.setCreateTime(new Date()); return baseMapper.insert(entity) > 0; } @Override public GmAdmin login(GmAdmin gmAdmin, HttpServletRequest request) { logger.info("用户登录开始---"); QueryWrapper<GmAdmin> gmAdminQueryWrapper = new QueryWrapper<>(); gmAdminQueryWrapper.eq("account", gmAdmin.getAccount()); gmAdminQueryWrapper.eq("password", gmAdmin.getPassword()); GmAdmin gmAdmins = baseMapper.selectOne(gmAdminQueryWrapper); logger.info("用户信息:" + gmAdmins.getAdminName()); if(gmAdmins != null) { GmLog gmLog = new GmLog(); Calendar calendar = Calendar.getInstance(); //获取当前年份 int year = calendar.get(Calendar.YEAR); //获取当前月份 int month = calendar.get(Calendar.MONTH) + 1; //当前表名 String tableName = null; //如果当前月份长度为1 则在前面加上0 if(String.valueOf(month).length() == 1) { tableName = "gm_log_" + year + 0 + month; } else { tableName = "gm_log_" + year + month; } int isTable = gmLogMapper.existTable(tableName); logger.info("当前日志表:" + tableName); //如果该表找不到,则对该表进行新建 if(isTable == 0) { logger.info("当前不存在该表---"); int newTable = gmLogMapper.createNewTable(tableName); //newTable 等于0 代表新建成功 if(newTable == 0) { logger.info("创建该表"); gmLog.setUserName(gmAdmins.getAdminName()); gmLog.setLoginIp(IpUtil.getIpAddr(request)); gmLog.setLoginTime(new Date()); gmLog.setUserCreateTime(gmAdmins.getCreateTime()); gmLog.setUserId(gmAdmins.getAdminId()); int insert = gmLogMapper.insert(tableName, gmLog); if(insert > 0) { logger.info("日志添加成功!"); return gmAdmins; } else { return null; } } else { return null; } } else { gmLog.setUserName(gmAdmins.getAdminName()); gmLog.setLoginIp(IpUtil.getIpAddr(request)); gmLog.setLoginTime(new Date()); gmLog.setUserCreateTime(gmAdmins.getCreateTime()); gmLog.setUserId(gmAdmins.getAdminId()); int insert = gmLogMapper.insert(tableName, gmLog); if(insert > 0) { logger.info("该表为已存在的表,日志添加成功!"); return gmAdmins; } else { return null; } } } else { logger.info("登录失败,用户不存在!"); return null; } } }
// https://leetcode.com/problems/insertion-sort-list/discuss/190913/Java-Python-with-Explanations class Solution { public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) return head; ListNode preInsert, toInsert, dummyHead = new ListNode(0); dummyHead.next = head; while (head != null && head.next != null) { if (head.val <= head.next.val) { head = head.next; } else { toInsert = head.next; preInsert = dummyHead; while (preInsert.next.val < toInsert.val) { preInsert = preInsert.next; } head.next = toInsert.next; toInsert.next = preInsert.next; preInsert.next = toInsert; } } return dummyHead.next; } }
import java.util.*; class date { int month,day,year; //user input date(int m,int d,int y) { this.month=m; this.day=d; this.year=y; } //default date date() { this.month=1; this.day=1; this.year=2000; } void display() { System.out.println(day+"/ "+month+"/ "+year); } } class dateTest { public static void main(String[] args) { Scanner in=new Scanner (System.in); System.out.println("Enter the month: "); int month=in.nextInt(); System.out.println("Enter the day: "); int day=in.nextInt(); System.out.println("Enter the year: "); int year=in.nextInt(); //if we have to check valid input /*if(month>12) { return; } else if(year%4==0) { return; } else if(month==1||month==3||month==5||month==7||month==12||month==8||month==10) { if(day==31) { return; } else if(day!=31) { System.out.println("False Input"); } } else if(month==4||month==6||month==9||month==11) { if(day==30) { return; } else if(day!=31) { System.out.println("False Input"); } } else if(month==2) { if(year%4==0) { if (day==29) { return; } else if(day!=29) { System.out.println("False Input"); } } else if(year%4 !=0) { if(day==28) { return; } else if(day!=28) { System.out.println("False Input"); } } }*/ date d1=new date(month,day,year); date d2=new date(); System.out.println("The date formatt is: "); d2.display();//default date System.out.println("Today'sdate is "); d1.display();//user entered } }
package com.alex.patterns.compositor.example; /* Leaf object that does not have any child */ public class CircleLeaf implements Graphic { @Override public void draw() { System.out.println("o"); } }
package com.fuzzy.metro.components; import java.awt.Color; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JTextArea; import javax.swing.border.Border; import com.fuzzy.metro.listeners.MyFocusListener; public class MyTextArea extends JTextArea{ /** * */ private static final long serialVersionUID = 1L; private String placeholder = ""; public MyTextArea(String placeholder){ this(30, placeholder); } public MyTextArea(int cols, String placeholder){ super(); setPlaceHolder(placeholder); setSettings(); } private void setSettings() { // TODO Auto-generated method stub /*setLineWrap(true); setWrapStyleWord(true);*/ } private void setPlaceHolder(String placeholder) { // TODO Auto-generated method stub setText(placeholder); this.setPlaceholder(placeholder); setForeground(new Color(216,225,228)); setOpaque(false); Font font = new MyFont().getFont(); font = font.deriveFont(Font.PLAIN, 10); addFocusListener(new MyFocusListener(this, placeholder)); setSettingBorder(); } private void setSettingBorder() { // TODO Auto-generated method stub Border padding = BorderFactory.createEmptyBorder(10, 15, 10, 15); Border outer = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(216,225,228))); setBorder(BorderFactory.createCompoundBorder(outer, padding)); } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public void setColumns(int columns){ setColumns(columns); } }
package com.easyapp.mobilepad; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ConnectingProgress extends Fragment { public ConnectingProgress() { } public static ConnectingProgress newInstance() { ConnectingProgress fragment = new ConnectingProgress(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) return; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_connecting_progress, container, false); return view; } }
package com.fm.scheduling.ui.appointment; import com.fm.scheduling.domain.Appointment; import com.fm.scheduling.domain.Customer; import javafx.event.EventHandler; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class AppointmentWeekCalendarHelper extends AppointmentCalendarHelper{ public AppointmentWeekCalendarHelper(){ super(); } public void nextPeriod(){ dateTime = dateTime.plusWeeks(1); } public void previousPeriod(){ dateTime = dateTime.minusWeeks(1); } public GridPane getCalendarPanel(){ fillAppointmentList(); GridPane calendarView = new GridPane(); LocalDate startOfWeek = dateTime.minusDays(dateTime.getDayOfWeek().getValue() - 1) ; LocalDate endOfWeek = startOfWeek.plusDays(6); for(LocalDate day = startOfWeek; !day.isAfter(endOfWeek); day = day.plusDays(1)){ calendarView.add(new HeaderSlot(day.getDayOfWeek().name() + " " + day.getDayOfMonth()), day.getDayOfWeek().getValue() - 1, 0); } for(LocalDate day = startOfWeek; !day.isAfter(endOfWeek); day = day.plusDays(1)){ calendarView.add(new DayWeekSlot(day,appointmentList),day.getDayOfWeek().getValue() - 1, 1); } calendarView.getStyleClass().add("monthCalendarGrid"); calendarView.setGridLinesVisible(true); return calendarView; } class HeaderSlot extends Label{ private final String CSS_CLASS = "weekHeadCell"; HeaderSlot(String text){ super(text); this.getStyleClass().add(CSS_CLASS); } } class DayWeekSlot extends VBox { private LocalDate localDate; private final String CSS_CLASS = "weekCell"; DayWeekSlot(LocalDate localDate, List<Appointment> appointments) { super(); this.localDate = localDate; this.getStyleClass().add(CSS_CLASS); setAppointmentsDateRange(appointments); } private void setAppointmentsDateRange(List<Appointment> appointments) { LocalDateTime localDateTime; if (appointments != null) { for (Appointment appointment : appointments) { if (appointment.getStart().toLocalDate().equals(localDate)) this.getChildren().add(new AppointmentSlot(appointment)); } } } } class AppointmentSlot extends VBox{ private final String CSS_CLASS = "appointmentWeekSlot"; private Appointment appointment; AppointmentSlot(Appointment appointment){ this.appointment = appointment; this.getStyleClass().add(CSS_CLASS); Label label = new Label(); label.setText(appointment.getTitle() + "\n" + appointment.getStart().getHour() + ":" + appointment.getStart().getMinute() + " - " + appointment.getEnd().getHour() + ":" + appointment.getEnd().getMinute() + "\n" + appointment.getCustomer().getCustomerName()); label.setTooltip(addToolTipText(appointment)); this.getChildren().add(label); this.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isSecondaryButtonDown()) { getContextMenu(appointment, label).show(AppointmentSlot.this, event.getScreenX(), event.getScreenY()); } } }); } private Tooltip addToolTipText(Appointment appointment){ final Tooltip tooltip = new Tooltip(); tooltip.setText(appointment.getTitle() + "\n" + appointment.getStart().getHour() + ":" + appointment.getStart().getMinute() + " - " + appointment.getEnd().getHour() + ":" + appointment.getEnd().getMinute() + "\n" + appointment.getCustomer().getCustomerName() ); return tooltip; } } }
package com.cmi.bache24.ui.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.cmi.bache24.R; import com.cmi.bache24.ui.adapter.TutorialSlideAdapter; import com.cmi.bache24.ui.fragment.TutorialFragment; import com.cmi.bache24.util.PreferencesManager; import java.util.ArrayList; import java.util.List; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class TutorialActivity extends AppCompatActivity implements View.OnClickListener { private TutorialSlideAdapter mPagerAdapter; private List<Fragment> mFragmentsList; private ViewPager mPager; private Button mButtonNext; private ImageView mImgIndicator1; private ImageView mImgIndicator2; private ImageView mImgIndicator3; private int mTutorialPosition = 0; boolean isFromHelp = false; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_tutorial); if (getIntent() != null) isFromHelp = getIntent().getBooleanExtra("_IS_FROM_HELP", false); mFragmentsList = new ArrayList<>(); mFragmentsList.add(TutorialFragment.newInstance(0)); mFragmentsList.add(TutorialFragment.newInstance(1)); mFragmentsList.add(TutorialFragment.newInstance(2)); mPager = (ViewPager) findViewById(R.id.tutorial_pager); mButtonNext = (Button) findViewById(R.id.button_next); mImgIndicator1 = (ImageView) findViewById(R.id.image_indicator_1); mImgIndicator2 = (ImageView) findViewById(R.id.image_indicator_2); mImgIndicator3 = (ImageView) findViewById(R.id.image_indicator_3); mButtonNext.setVisibility(View.INVISIBLE); mButtonNext.setOnClickListener(this); setupViewPager(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_tutorial, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override public void onClick(View view) { if (view.getId() == mButtonNext.getId()) { if (mTutorialPosition + 1 == mPagerAdapter.getCount()) { finishTutorial(); } else { mPager.setCurrentItem(mTutorialPosition + 1); } } } private void setupViewPager() { mPagerAdapter = new TutorialSlideAdapter(getSupportFragmentManager(), mFragmentsList); mPager.setAdapter(mPagerAdapter); mPager.setOffscreenPageLimit(mFragmentsList.size()); mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mTutorialPosition = position; showPagerIndicator(mTutorialPosition); } @Override public void onPageScrollStateChanged(int state) { } }); } private void showPagerIndicator(int position) { mImgIndicator1.setImageResource(R.drawable.circular_shape_pager_deselected); mImgIndicator2.setImageResource(R.drawable.circular_shape_pager_deselected); mImgIndicator3.setImageResource(R.drawable.circular_shape_pager_deselected); switch (position) { case 0: mImgIndicator1.setImageResource(R.drawable.circular_shape_pager_selected); mButtonNext.setVisibility(View.INVISIBLE); break; case 1: mImgIndicator2.setImageResource(R.drawable.circular_shape_pager_selected); mButtonNext.setVisibility(View.INVISIBLE); break; case 2: mImgIndicator3.setImageResource(R.drawable.circular_shape_pager_selected); mButtonNext.setVisibility(View.VISIBLE); break; default: mImgIndicator1.setImageResource(R.drawable.circular_shape_pager_selected); break; } } private void finishTutorial() { if (!isFromHelp) { PreferencesManager.getInstance().setTutorialFinished(this, true); Intent loginActivityIntent = new Intent(this, LoginActivity.class); loginActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(loginActivityIntent); overridePendingTransition(R.anim.enter_from_right, R.anim.enter_from_left); } else finish(); } }
package com.jushu.video.controller; import com.jushu.video.api.Response; import com.jushu.video.common.IpUtil; import com.jushu.video.entity.MenuMovieType; import com.jushu.video.service.IGmOperationService; import com.jushu.video.service.IMenuMovieTypeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.List; /** * <p> * 客户端-筛选菜单配置表 前端控制器 * </p> * * @author chen * @since 2020-02-13 */ @Controller @RequestMapping("/video/menu-movie-type") public class MenuMovieTypeController { @Autowired private IMenuMovieTypeService iMenuMovieTypeService; @Autowired private IGmOperationService iGmOperationService; @GetMapping("/list") public String list(){ return "menuMovieTypeList";} @PostMapping("/list") @ResponseBody public Response list(HttpServletRequest request, HttpSession session) { //获取当前方法名 String method = Thread.currentThread().getStackTrace()[1].getMethodName(); //操作事件 String operation = "查询客户端筛选配置列表"; //当前用户登录IP String loginIp = IpUtil.getIpAddr(request); //操作是否成功 int isSuccess = 0; //备注:查询成功 String remark = "查询成功"; boolean flag = iGmOperationService.saveOperation(method, loginIp, operation, isSuccess, remark, session); if (flag) { List<MenuMovieType> lists = iMenuMovieTypeService.recommendList(); return new Response(lists); } else { return new Response("数据出现问题,请联系管理员!"); } } @PostMapping("/delete") @ResponseBody public Response delete(@RequestBody String [] ids, HttpServletRequest request, HttpSession session) { //获取当前方法名 String method = Thread.currentThread().getStackTrace()[1].getMethodName(); //操作事件 String operation = "删除筛选标题"; //当前用户登录IP String loginIp = IpUtil.getIpAddr(request); //操作是否成功 int isSuccess = 0; //备注:查询成功 String remark = "删除成功"; boolean flag = iGmOperationService.saveOperation(method, loginIp, operation, isSuccess, remark, session); if(flag) { boolean delete = iMenuMovieTypeService.delete(ids); if (delete) { return new Response("删除成功!"); } else { return new Response("删除失败!"); } } else { return new Response("删除失败!"); } } @PostMapping("/insert") @ResponseBody public Response insert(@RequestBody(required = false) MenuMovieType menuMovieType, HttpServletRequest request, HttpSession session) { //获取当前方法名 String method = Thread.currentThread().getStackTrace()[1].getMethodName(); //操作事件 String operation = "添加筛选标题"; //当前用户登录IP String loginIp = IpUtil.getIpAddr(request); //操作是否成功 int isSuccess = 0; //备注:查询成功 String remark = "添加成功"; if(menuMovieType.getTitle() == null) { return new Response("标题不能为空!"); } boolean flag = iGmOperationService.saveOperation(method, loginIp, operation, isSuccess, remark, session); if(flag) { boolean update = iMenuMovieTypeService.create(menuMovieType); if (update) { return new Response("添加成功!"); } else { return new Response("添加失败!"); } } else { return new Response("添加失败!"); } } }
package net.cglab.hotelpraktikum.interceptor; import java.util.LinkedList; import javax.servlet.http.HttpServletRequest; import net.cglab.hotelpraktikum.action.TargetAware; import net.cglab.hotelpraktikum.utils.ApplicationConstants; import org.apache.log4j.Logger; import org.apache.struts2.StrutsStatics; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; public class SetTargetInterceptor extends MethodFilterInterceptor implements Interceptor{ /** * */ private static final long serialVersionUID = -5251411303130516199L; public final static Logger LOG = Logger.getLogger(SetTargetInterceptor.class); @Override public String doIntercept(ActionInvocation invocation) { Object action = invocation.getAction(); // invocation.getAction() // invocation. HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST); if (action instanceof TargetAware) { TargetAware targetAwareAction = (TargetAware) action; if (targetAwareAction.getTarget() == null) targetAwareAction.setTarget(getCurrentUri(request)); } try { return invocation.invoke(); } catch (Exception e) { // TODO Auto-generated catch block LOG.fatal(e); } return ApplicationConstants.RETURN_SUCCESS; } // I'm sure we can find a better implementation of this... @SuppressWarnings("unchecked") private static String getCurrentUri(HttpServletRequest request) { // String url = request.getRequestURI(); // String queryString = request.getQueryString(); LinkedList<String> browseHistory = (LinkedList<String>)request.getSession().getAttribute("browseHistory"); try{ String queryString = (String)browseHistory.getLast(); if ( request.getSession().getAttribute(ApplicationConstants.BROWSE_HISTORY) != null && ((LinkedList<String>)request.getSession().getAttribute(ApplicationConstants.BROWSE_HISTORY)).getLast().toString() != ""){ return queryString; }else{ return request.getRequestURL().toString(); } }catch(Exception e){ return "/showLogin.action"; } } public void init() { /* do nothing */ } public void destroy() { /* do nothing */ } }
package me.rainnny.command; import lombok.val; import me.rainnny.Settings; import me.rainnny.util.Style; import me.rainnny.util.UtilServer; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; public class StaffChatCommand extends Command { public StaffChatCommand() { super("staffchat", "qbungee.staff", new String[] { "sc" }); } public void execute(CommandSender sender, String[] args) { if (args.length < 1) { sender.sendMessage("§cUsage: /staffchat <message>"); } else { String message = String.join(" ", args); if (sender instanceof ProxiedPlayer) { val player = (ProxiedPlayer) sender; UtilServer.sendToStaff(Style.color(Settings.STAFF_STAFFCHAT.replace("$player", player.getDisplayName()).replace("$message", message))); } else { UtilServer.sendToStaff(Style.color(Settings.STAFF_STAFFCHAT.replace("$player", "&4&lCONSOLE").replace("$message", "&c" + message))); } } } }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.*; import java.util.concurrent.TimeUnit; public class NegativeSuit extends MainClass{ @Test //TestCase1 public void AllEmptyFieldsTest() { loginPage.register("", ""); String error = loginPage.getErrorEmptyLogFieldText(); String error2 = loginPage.getErrorEmptyPasswFieldText(); Assert.assertEquals("Field can't be empty and less then 3 symbol", error); Assert.assertEquals("Field can't be empty and less then 3 symbol", error2); } @Test //TestCase2 public void EmptyLoginField() { loginPage.register("", "ABC123"); String error3 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Field can't be empty and less then 3 symbol", error3); } @Test //TestCase3 public void EmptyPasswordField() { loginPage.register("TestUser1", ""); String error4 = loginPage.getErrorEmptyPasswFieldText(); Assert.assertEquals("Field can't be empty and less then 3 symbol", error4); } @Test //TestCase4 public void IncorrectPasswordField() { loginPage.register("TestUser1", "ABC1234"); String error5 = loginPage.getErrorIncorrLogPasswText(); Assert.assertEquals("Incorrect login or password.", error5); } @Test //TestCase5 public void IncorrectLoginField() { loginPage.register("TestUser2", "ABC123"); String error5 = loginPage.getErrorIncorrLogPasswText(); Assert.assertEquals("Incorrect login or password.", error5); } @Test //TestCase6 public void BothIncorrectField() { loginPage.register("TestUser2", "ABC1234"); String error5 = loginPage.getErrorIncorrLogPasswText(); Assert.assertEquals("Incorrect login or password.", error5); } @Test //TestCase7 public void BothSpacesField() { loginPage.register(" ", " "); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCase8 public void BeginWithSpacesField() { loginPage.register(" TestUser1", " ABC123"); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCase9 public void EndingWithSpacesField() { loginPage.register("TestUser1 ", "ABC123 "); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCase10 public void LoginWithRegister() { loginPage.register("tEStuSer1", "ABC123"); String error7 = loginPage.getErrorIncorrLogPasswText(); Assert.assertEquals("Not valid field", error7); } @Test //TestCas11 public void SpecialCharactersUsage() { loginPage.register("@#$%&*!", "@#$%&*!"); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCas12 public void CyrillicAlphabetUsage() { loginPage.register("ФпоЗпр", "мсШсмиТ"); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCas13 public void SQLInjectionUsage() { loginPage.register("Robert'); DROP TABLE Students;--", "Robert'); DROP TABLE Students;--"); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCas14 public void JSInjectionUsage() { loginPage.register("Nice site, I think I'll take it. <script>alert('Executing JS')</script>", "Nice site, I think I'll take it. <script>alert('Executing JS')</script>"); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCas15 public void MaxFieldsLength() { loginPage.register("James Dr No From Russia with Love Goldfinger Thunderball You Only Live Twice On Her Majesty’s Secret Service Diamonds Are Forever Live and Let Die The Man with the Golden Gun The Spy Who Loved Me Moonraker For Your Eyes Only Octopussy A View to a Kill The Living Daylights Licence to Kill Golden Eye Tomorrow Never Dies The World Is Not Enough Die Another Day Casino Royale Bond", "123.456,789.098.765,432."); String error6 = loginPage.getErrorEmptyLogFieldText(); Assert.assertEquals("Not valid field", error6); } @Test //TestCas16 public void MinFieldsLength() { loginPage.register("aA", "01"); String error7 = loginPage.getErrorEmptyLogFieldText(); String error8 = loginPage.getErrorEmptyPasswFieldText(); Assert.assertEquals("Field can't be empty and less then 3 symbol", error7); Assert.assertEquals("Field can't be empty and less then 3 symbol", error8); } }
package my.learning.strings; import java.util.regex.Pattern; public class ReverseWords { public boolean validation(String str) { Pattern pattern = Pattern.compile("//S"); String[] tempStr = pattern.split(str); if (str instanceof String) { if (str.length() == 0 || str == null) { System.out.println("String is empty"); return false; } if (tempStr.length == 1) { System.out .println("Cannnot revsese the words, please enter the string with more than one word"); return false; } return true; } return false; } public String reverseWords(String str) { StringBuilder sb = new StringBuilder(); // Pattern pattern = Pattern.compile("//s"); String[] strArray = str.split(" "); for (int i = strArray.length-1; i >= 0; --i) { if(!strArray[i].equals("")) { sb.append(strArray[i]).append(" "); } } return sb.toString(); } public static void main(String[] args) { ReverseWords rw = new ReverseWords(); String str = "My name is pushpak"; System.out.println("After reverse-->" + rw.reverseWords(str)); } }
package edu.jak.dummymailers.sb.dao.crud; import javax.ejb.Local; import edu.jak.dummymailers.model.eb.Mail; import edu.jak.dummymailers.sb.dao.base.BaseFacadeLocal; @Local public interface MailFacadeLocal extends BaseFacadeLocal<Mail, Integer> { public void saveMail(Mail mail); public void deleteMail(Integer id); public Mail updateMail(Mail mail); public Mail getMail(Integer id); }
package com.company; import com.company.Animal; public class Dog extends Animal implements Drawable,SoundProducable { public Dog(){ super("Sobaka"); } @Override public String draw() { return "\ud83d\udc29"; }public String callSound(){ return ""; } }
package Testscripts; import java.util.concurrent.TimeUnit; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import Libraryfiles.Libraryfilesbaseclass; public class Vehiclelistpageforbike extends Libraryfilesbaseclass{ public static Vehiclelistpageforcar car; @BeforeMethod public void setup() { initialization(); car = new Vehiclelistpageforcar(); } @Test(priority=1) public void calenderselect() throws InterruptedException { car.venueclick(); Thread.sleep(2000); findelementandclick(clickonbike); Thread.sleep(4000); Assert.assertEquals(findelementreturn(Nofueltext), "No-fuel"); Thread.sleep(3000); //car.selectcalender(); driver.manage().timeouts().implicitlyWait(11, TimeUnit.SECONDS); // Thread.sleep(2000); findelementandclick(startdateclick); //Thread.sleep(3000); findelementdate(pop.getProperty("date1")); findelementandclick(enddateclick); findelementdate(pop.getProperty("date2")); findelementandclicktext(pop.getProperty("searchtext")); Thread.sleep(3000); } @Test(priority=2) public void checkfuelpackage() throws InterruptedException { car.venueclick(); Thread.sleep(5000); findelementandclick(clickonbike); Thread.sleep(5000); findelementdate(pop.getProperty("startdate11")); Thread.sleep(5000); findelementandclick(clickonbikes); Thread.sleep(4000); scrollpagedown(); Thread.sleep(2000); Assert.assertEquals(findelementandreturntext(pop.getProperty("getdays1")), "Duration\n" + "7d"); Thread.sleep(4000); driver.navigate().back(); Thread.sleep(4000); findelementdate(pop.getProperty("startdate12")); Thread.sleep(2000); scrollpageup(); Thread.sleep(3000); findelementandclick(clickonbikes); Thread.sleep(4000); scrollpagedown(); Thread.sleep(2000); Assert.assertEquals(findelementandreturntext(pop.getProperty("getdays2")), "Duration\n" + "15d"); Thread.sleep(4000); driver.navigate().back(); Thread.sleep(4000); findelementdate(pop.getProperty("startdate13")); Thread.sleep(2000); scrollpageup(); Thread.sleep(4000); findelementandclick(clickonbikes); Thread.sleep(4000); scrollpagedown(); Thread.sleep(2000); Assert.assertEquals(findelementandreturntext(pop.getProperty("getdays3")), "Duration\n" + "30d"); Thread.sleep(3000); } @AfterMethod public void teardown() { driver.quit(); } }
package javafxtt.model; import javafxtt.model.Game.PointType; /** * * @author LMI */ public class LastPoint { private boolean homePoint; private Game.PointType pointType; public LastPoint(boolean homePoint, PointType pointType) { this.homePoint = homePoint; this.pointType = pointType; } public boolean isHomePoint() { return homePoint; } public void setHomePoint(boolean homePoint) { this.homePoint = homePoint; } public PointType getPointType() { return pointType; } public void setPointType(PointType pointType) { this.pointType = pointType; } }
/** * Shortest Path BFS */ import java.util.*; public class ShortestPathBFS { private Graph map; private int to; private int from; private int[] predNode; public ShortestPathBFS(Graph map, int to, int from) { this.map = map; this.to = to; this.from = from; predNode = new int[map.length + 1]; Queue<Integer> pq = (Queue<Integer>)new LinkedList<Integer>(); pq.add(to); predNode[to] = to; while (!(pq.size() == 0)) { int v = pq.poll(); Iterator<Edge> neighbors = map.flightsFor(v).iterator(); while (neighbors.hasNext()) { Edge edge = neighbors.next(); if (predNode[edge.id] == 0) { pq.add(edge.id); predNode[edge.id] = v; } } } } public void print() { int currentID = this.from; StringBuilder str = new StringBuilder(); try { while(currentID != this.to) { if (currentID == 0) { throw new FlightNotFoundException(); } str.append(map.getCity(currentID).name); str.append(" --> "); currentID = predNode[currentID]; str.append(map.getCity(currentID).name + "\n"); } System.out.println("Flights (in reverse order):"); System.out.print(str); } catch (FlightNotFoundException e) { System.out.println("Flight path not found."); } } }
/** * A generic back-off abstraction. */ @NonNullApi @NonNullFields package org.springframework.util.backoff; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.marcioalexfig.blognoticias; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import layout.ConfigFragment; import layout.NewsFragment; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager vp = (ViewPager) findViewById(R.id.pager); vp.setAdapter(new MeuAdapter(getSupportFragmentManager())); } public class MeuAdapter extends FragmentPagerAdapter { public MeuAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new NewsFragment(); } else { return new ConfigFragment(); } } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { if (position == 0) { return "NOTÍCIAS"; } else { return "CONFIGURAÇÕES"; } } } }
package egovframework.usr.hom.service.Impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import egovframework.usr.hom.dao.PortalActionMainDAO; import egovframework.usr.hom.service.PortalActionMainService; @Service("portalActionMainService") public class PortalActionMainServiceImpl extends EgovAbstractServiceImpl implements PortalActionMainService{ @Resource(name="portalActionMainDAO") private PortalActionMainDAO portalActionMainDAO; /** * 권한 셀렉트 박스 * @param commandMap * @param issuccess * @return * @throws Exception */ public List selectAuthList(Map<String, Object> commandMap) throws Exception{ return portalActionMainDAO.selectAuthList(commandMap); } /** * 공지 팝업리스트 * @param commandMap * @return * @throws Exception */ public List selectNoticePopUpList(Map<String, Object> commandMap) throws Exception{ return portalActionMainDAO.selectNoticePopUpList(commandMap); } /** * 최근 공지 게시물리스트 * @param commandMap * @return * @throws Exception */ public List selectNoticeTopList(Map<String, Object> commandMap) throws Exception{ return portalActionMainDAO.selectNoticeTopList(commandMap); } /** * 전체과정리스트 * @param commandMap * @return * @throws Exception */ public List selectTrainingList(Map<String, Object> commandMap) throws Exception{ return portalActionMainDAO.selectTrainingList(commandMap); } }
package edu.barrons.page.javin; import java.util.*; import edu.jenks.dist.barrons.*; public class Sentence extends AbstractSentence{ public Sentence() { super(); } public Sentence(String sentence) { super(sentence); } @Override public int countWords() { int words = 1; String theWord = sentence; while(theWord.indexOf(" ") != -1) { words++; theWord = theWord.substring(theWord.indexOf(" ") + 1); } return words; } @Override public List<Integer> getBlankPositions() { List<Integer> pos = new ArrayList<>(); for(int i = 0; i < sentence.length(); i++) { if(sentence.indexOf(" ", i) == -1) break; pos.add(sentence.indexOf(" ", i)); i = sentence.indexOf(" ", i); } return pos; } @Override public String[] getWords() { List<String> words = new ArrayList<>(); String theWords = sentence; while(theWords.indexOf(" ") != -1) { words.add(theWords.substring(0, theWords.indexOf(" "))); theWords = theWords.substring(theWords.indexOf(" ") + 1); } words.add(theWords); return words.toArray(new String[0]); } public static void main(String[] args) { Sentence kevinhart = new Sentence("Hello World You Suck Crack"); System.out.println(kevinhart.getBlankPositions().toString()); } }
package com.example.khoa.fragments; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import com.example.khoa.activities.MainActivity; import com.example.khoa.models.PostDatabaseHelper; /** * Created by khoa.nguyen on 3/4/2016. */ public class MyAlertDialogFragment extends DialogFragment { public interface CallBack{ void nameTextChange(String name, int position); } public MyAlertDialogFragment() { // Empty constructor required for DialogFragment } public static MyAlertDialogFragment newInstance(String title, int position) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); args.putInt("position", position); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final String title = getArguments().getString("title"); final int position = getArguments().getInt("position"); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setTitle(title); alertDialogBuilder.setMessage("Are you sure?"); alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // on success CallBack listener = (CallBack) getActivity(); if (listener != null) { listener.nameTextChange(title, position); } dismiss(); } }); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } }
package GearBox; public class GearBox { // Fields int gear; public int getGear() { return this.gear; } public int changeGear(int i) { if(((this.gear == i + 1) | (this.gear == i - 1)) & ((i<=5) & (-1 <= i)) ){ return this.gear = i; } else if ((this.gear == 1 & i == -1) | (this.gear == -1 & i == 1)) { return this.gear = i; } else{ throw new IllegalGearChangeException(); } } }
package com.gmail.ptimofejev; public class Phone { private String model; private double balance; private Network network; private String number; private boolean netCoverage; public Phone() { } public Phone(String model, double balance, Network network, String number, boolean netCoverage) { super(); this.model = model; this.balance = balance; this.network = network; this.number = number; this.netCoverage = netCoverage; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public Network getNetwork() { return network; } public void setNetwork(Network network) { this.network = network; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public boolean isNetCoverage() { return netCoverage; } public void setNetCoverage(boolean netCoverage) { this.netCoverage = netCoverage; } public void call(String outNumber) { if (!isNetCoverage()) { System.out.println(number + ": No Network coverage."); return; } if (!checkBalance()) { System.out.println(number + ": Insufficient funds."); return; } if (number.equals(outNumber)) { System.out.println(number + ": You tried calling your own number."); return; } if (!checkCorrectNumber(outNumber)) { System.out.println(number + ": Incorrect number format."); return; } if (network.checkOutNumber(outNumber)) { System.out.println(number + ": You successfully called " + outNumber); network.initIncCall(number, outNumber); } } public void incomingCall(String inNumber) { System.out.println(number + ": Incoming call from " + inNumber); } public void register() { if (isNetCoverage()) { System.out.println(number + ": Number is already registered in Network."); return; } if (checkCorrectNumber(number)) { network.addToDatabase(this); setNetCoverage(true); System.out.println(number + ": Number has been registered in Network"); return; } System.out.println(number + ": Incorrect number format."); } public void unregister() { if (!isNetCoverage()) { System.out.println(number + ": Number has not been registered in Network."); return; } network.removeFromDatabase(this); setNetCoverage(false); System.out.println(number + ": Number has been unregistered from Network."); } public boolean checkCorrectNumber(String numberToCheck) { if (numberToCheck.length() != 13) { return false; } if (!(numberToCheck.substring(0, 4).equals(network.getCountryCode()))) { return false; } for (int i = 3; i < numberToCheck.length(); i++) { if (!(Character.isDigit(numberToCheck.toCharArray()[i]))) { return false; } } return true; } public boolean checkBalance() { if (balance > 0) { return true; } return false; } @Override public String toString() { return "Phone [model=" + model + ", balance=" + balance + ", network=" + network.getName() + ", number=" + number + ", netCoverage=" + netCoverage + "]"; } }
package com.aowin.Exceptions; import javax.swing.JOptionPane; public class IDExistedException extends Exception { public IDExistedException(){ super("编号已经存在!"); JOptionPane.showMessageDialog(null, "编号已经存在!"); } }
package com.baytie.baytie.Intro; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.media.Image; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; import com.baytie.api.request.RetrievalRequest; import com.baytie.baytie.Catering.CateringMainActivity; import com.baytie.baytie.Delivery.DeliveryMainActivity; import com.baytie.baytie.Menu.MenuMain; import com.baytie.baytie.MyApp; import com.baytie.baytie.Pickup.PickUpMain; import com.baytie.baytie.R; import com.baytie.baytie.Reservation.ReservationMain; import com.baytie.common.Uitils; import com.baytie.customview.ProgressDialogManage; import com.baytie.customview.ProgressHUD; import com.baytie.data.JsonResponse; import com.baytie.data.ResponseCallBack; import com.baytie.vo.AreaVO; import com.baytie.vo.CityDataVO; import com.baytie.vo.CuisineVO; import com.baytie.vo.FoodTypeVO; import com.baytie.vo.RestroCategoryVO; import com.bumptech.glide.util.Util; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.io.IOException; import java.util.List; /** * Created by Administrator on 9/14/2016. */ public class MainHome extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_home); setStatusBarTranslucent(true); //load country, areas, cuisine, food restaurantCategory from server. SystemBarTintManager tintManager = new SystemBarTintManager(this); // enable status bar tint tintManager.setStatusBarTintEnabled(true); tintManager.setTintColor(Color.parseColor("#70cd00")); // set a custom navigation bar resource // set a custom status bar drawable // tintManager.setStatusBarTintDrawable(MyDrawable); ///////////////// String token = (String) Uitils.getAccessToken(this); getRetrievalData(token); getCuisineFoodRstaurantCategory(token); ImageButton btnMenu = (ImageButton)findViewById(R.id.btn_menu); Button btnDelivery = (Button)findViewById(R.id.btn_delivery); Button btnPickup = (Button)findViewById(R.id.btn_pickup); Button btnCatering = (Button)findViewById(R.id.btn_catering); Button btnReservation = (Button)findViewById(R.id.btn_reservation); btnMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), MenuMain.class); startActivity(intent); } }); btnPickup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApp.getInstance().serviceType = 4; Intent intent = new Intent(getApplicationContext(), PickUpMain.class); startActivity(intent); } }); btnReservation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApp.getInstance().serviceType = 3; Intent intent = new Intent(getApplicationContext(), ReservationMain.class); startActivity(intent); } }); btnCatering.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApp.getInstance().serviceType = 2; Intent intent = new Intent(getApplicationContext(), CateringMainActivity.class); startActivity(intent); } }); btnDelivery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApp.getInstance().serviceType = 1; Intent intent = new Intent(getApplicationContext(), DeliveryMainActivity.class); startActivity(intent); } }); } protected void setStatusBarTranslucent(boolean makeTranslucent) { if (makeTranslucent) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } private void getRetrievalData(String token) { final String stringType = ""; final String access_token = token; RetrievalRequest.getCityList(access_token, stringType, new ResponseCallBack<List<CityDataVO>>() { @Override public void onCompleted(JsonResponse<List<CityDataVO>> response) throws IOException { if (response.isSuccess()) { MyApp.getInstance().g_cityList.clear(); MyApp.getInstance().g_cityList.addAll(response.getData()); RetrievalRequest.getAreaList(access_token,stringType, new ResponseCallBack<List<AreaVO>>() { @Override public void onCompleted(JsonResponse<List<AreaVO>> response) throws IOException { if (response.isSuccess()) { MyApp.getInstance().g_AreaList.clear(); MyApp.getInstance().g_AreaList.addAll(response.getData()); // Uitils.toActivity(Splash.this, MainHome.class, true); // FIXME // getCuisineFoodRstaurantCategory(access_token); } else { // MyApp.getInstance().showSimpleAlertDiloag(Splash.this, response.getErrorMessage(), null); // Toast.makeText(Splash.this, response.getErrorMessage(), Toast.LENGTH_LONG).show(); // Uitils.toActivity(Splash.this, MainHome.class, true); // FIXME } } }); } else { // Toast.makeText(Splash.this, response.getErrorMessage(), Toast.LENGTH_LONG).show(); // Uitils.toActivity(Splash.this, MainHome.class, true); // FIXME } } }); } private void getCuisineFoodRstaurantCategory(String token) { ProgressDialogManage.show(this); final String access_token = token; final String stringType = ""; RetrievalRequest.getCuisineList(access_token,stringType, new ResponseCallBack<List<CuisineVO>>() { @Override public void onCompleted(JsonResponse<List<CuisineVO>> response) throws IOException { if (response.isSuccess()) { MyApp.getInstance().g_cuisineList.clear(); MyApp.getInstance().g_cuisineList.addAll(response.getData()); RetrievalRequest.getFoodTypeList(access_token, stringType, new ResponseCallBack<List<FoodTypeVO>>() { @Override public void onCompleted(JsonResponse<List<FoodTypeVO>> response) throws IOException { if (response.isSuccess()) { MyApp.getInstance().g_foodTypeList.clear(); MyApp.getInstance().g_foodTypeList.addAll(response.getData()); RetrievalRequest.getRestroCategoryList(access_token, stringType, new ResponseCallBack<List<RestroCategoryVO>>() { @Override public void onCompleted(JsonResponse<List<RestroCategoryVO>> response) throws IOException { if (response.isSuccess()) { MyApp.getInstance().g_restroCategoryList.clear(); MyApp.getInstance().g_restroCategoryList.addAll(response.getData()); ProgressDialogManage.hide(); } else { ProgressDialogManage.hide(); } } }); }else { ProgressDialogManage.hide(); } } }); } else { // MyApp.getInstance().showSimpleAlertDiloag(Splash.this, response.getErrorMessage(), null); ProgressDialogManage.hide(); } } }); } }
package POMchase1; import common.CommonAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.testng.annotations.Ignore; import org.testng.annotations.Test; public class HomepageWebElement extends CommonAPI{ @FindBy(xpath ="//span[@class='chase-text']") public static WebElement chaseLogoWebElement; @FindBy(xpath = "//a[@class='header__section--dropdown__title__link chaseanalytics-track-link']") public static WebElement openAnACoountDD; @FindBy(xpath = "//div[@id='icon1']") public static WebElement creditCard; @FindBy(xpath = "//div[@id='icon2']") public static WebElement checkingAccount; @FindBy(xpath = "//div[@class='header__section--dropdown__tiles row']//div[2]") public static WebElement savingAccount; @FindBy(xpath = "//div[@id='icon4']") public static WebElement CDS; @FindBy(xpath = "//div[@id='icon5']") public static WebElement carLones; @FindBy(xpath = "//div[@id='icon6']") public static WebElement homeMortgage; @FindBy(xpath = "//div[@id='icon7']") public static WebElement chaseForBusiness; @FindBy(xpath = "//div[@id='icon8']") public static WebElement commercialBanking; @FindBy(xpath = "//div[@id='icon9']") public static WebElement seeAllOption; public static WebElement getChaseLogoWebElement(){ return chaseLogoWebElement; } public void chaseLogo(){ getChaseLogoWebElement().click(); //Assert.assertEquals(chaseLogo.isDisplayed(),true); } public static void mouseOverAccountDropDown(){ mouseOver("//a[@class='header__section--dropdown__title__link chaseanalytics-track-link']"); Assert.assertEquals(checkingAccount.isDisplayed(),true); } public void mouseOverValidate(){ Assert.assertEquals(openAnACoountDD.isDisplayed(),true); } public void openAccDDmouseOver(){ // mouseOver(openAnACoountDD); } public static void applyForCC(){ openAnACoountDD.click(); checkingAccount.click(); //chaseLogo.click(); } public static void openAccountDD(){ WebElement element =driver.findElement(By.id("//a[@class='header__section--dropdown__title__link chaseanalytics-track-link']")); //WebElement element = openAnACoountDD; Select searchBar_Dropdown = new Select(element); searchBar_Dropdown.selectByIndex(1); //driver.findElement(By.id("twotabsearchtextbox")).sendKeys("cloths"); } }
package frc.robot.subsystems.drive; import edu.wpi.first.wpilibj2.command.CommandBase; public class JoystickDriveCommand extends CommandBase { private final DriveSubsystem drive; private boolean slowMode, toggleLastFrame; private static final double SLOW_SPEED = 0.5; private static final double SLOW_TURN = 0.5; private static final double FAST_SPEED = 0.9; private static final double FAST_TURN = 0.7; public JoystickDriveCommand(DriveSubsystem drive) { addRequirements(drive); this.drive = drive; } @Override public void execute() { if (!toggleLastFrame && drive.container.pilot.getRawButton(2)) { slowMode = !slowMode; toggleLastFrame = true; } else if (!drive.container.pilot.getRawButton(2)) { toggleLastFrame = false; } var speed = slowMode ? SLOW_SPEED : FAST_SPEED; var turn = slowMode ? SLOW_TURN : FAST_TURN; drive.arcadeDrive(drive.container.pilot.getRawAxis(1), -drive.container.pilot.getRawAxis(4), speed, turn); } }
package net3.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class Server_rec_thread extends Thread{ private Socket socket; public Server_rec_thread(Socket socket) { this.socket=socket; } public void run() { BufferedReader read=null; try { read=new BufferedReader(new InputStreamReader(socket.getInputStream())); while(true) { String msg=read.readLine(); if(msg==null) break; System.out.println("¼ö½Å"+msg); } } catch (IOException e) { System.out.println(e); }finally{ if(read!=null)try{read.close();}catch(IOException e){System.out.println(e.getMessage());} } } }
package canilho.paulo.bacalhau.renderer; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Point; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import canilho.paulo.bacalhau.renderer.player.Bacalhau; import canilho.paulo.bacalhau.renderer.player.Entity; import canilho.paulo.bacalhau.renderer.player.Weapon; public class GameSystem { // RENDER private Entity player; private List<Weapon> bacalhaus; public GameSystem(Entity player) { this.player = player; init(); } private void init() { String name = JOptionPane.showInputDialog("What is your name?"); if (name == null || name.isEmpty() || name.length() < 3) { JOptionPane.showMessageDialog(null, "Name cannot be empty and has to be more than 3 characters!", "Error", JOptionPane.ERROR_MESSAGE); name = "Rambo"; init(); } bacalhaus = new ArrayList<Weapon>(); player.setName(name); } public void render(Graphics2D g2d, Point mouse_location) { // RENDER NAME renderName(g2d); // RENDER PLAYER LOCATION renderPlayerLocation(g2d); // RENDER ENTITY renderEntity(g2d, mouse_location); // RENDER BACALHAU SHOTS renderBacalhaus(g2d); } private void renderBacalhaus(Graphics2D g2d) { for(Weapon bacalhau: bacalhaus){ g2d.drawImage(bacalhau.getImage(), bacalhau.getEntityLocation().x, bacalhau.getEntityLocation().y, Entity.entity_max_size.width, Entity.entity_max_size.height,null); } } public void fireBacalhau(Point mouse_location){ Weapon bacalhau = new Bacalhau(); bacalhau.setTarget(player.getEntityLocation(), mouse_location); bacalhau.start(); bacalhaus.add(bacalhau); } private void renderPlayerLocation(Graphics2D g2d) { String message = "X: " + player.getEntityLocation().x + " ,Y: " + player.getEntityLocation().y; int font_size = 12; if (g2d != null) { g2d.setColor(Color.WHITE); g2d.setFont(new Font("Verdana", 0, font_size)); g2d.drawString(message, 10, 50); } } private void renderEntity(Graphics2D g2d, Point mouse_location) { g2d.drawImage(player.getImage(), player.getEntityLocation().x, player.getEntityLocation().y, Entity.entity_max_size.width, Entity.entity_max_size.height, null); } private void renderName(Graphics2D g2d) { int font_size = 17; if (g2d != null) { g2d.setColor(Color.WHITE); g2d.setFont(new Font("Verdana", 0, 17)); g2d.drawString("Player: " + player.getName(), 10, font_size + 10); } } }
package android.record.model; import java.sql.Timestamp; import java.util.List; public interface RecordDAO_interface { public void insert(RecordVO recordVO); public void delete(Timestamp start_time ,String mem_no); public List<RecordVO> findByPrimaryKey(String mem_no); public List<RecordVO> getAll(); //下面4個是我手機用的 //抓圖 byte[] getImage(Timestamp start_time , String mem_no); //上傳 回傳布林值 public boolean add(Timestamp start_time,Timestamp end_time,String mem_no,Double distance,Integer elevation,Integer duration,String route_no,String pic); //傳到Redis資料庫 public boolean addinToRedis(String mem_no , String route_no , List<String> list); //從Redis獲取資料 public List<String> findBylatlng(String mem_no , String route_no); //update 圖片 public boolean update(String mem_no , Timestamp start_time , String pic); }
package com.kakaopay.exception; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class ReadExpiredException extends SprinkleException { public ReadExpiredException(LocalDateTime createDate) { super( "뿌린지 7일이 지난 조회 요청은 처리할 수 없습니다. createDate: " + createDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } }
package craterstudio.util.concur; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import craterstudio.func.Transformer; public class LockStepExecutor<I, O> { private final ExecutorService service; public LockStepExecutor(ExecutorService service) { this.service = service; } private final List<I> inputs = new ArrayList<>(); private final List<O> outputs = new ArrayList<>(); private final List<Future<O>> futures = new ArrayList<>(); public void addInput(I input) { this.inputs.add(input); } public List<O> lockstep(final Transformer<I, O> task) { futures.clear(); for (final I input : inputs) { Callable<O> call = new Callable<O>() { @Override public O call() throws Exception { return task.transform(input); } }; futures.add(this.service.submit(call)); } inputs.clear(); outputs.clear(); for (Future<O> future : futures) { O output; try { output = future.get(); } catch (InterruptedException | ExecutionException exc) { throw new IllegalStateException(exc); } outputs.add(output); } return outputs; } }
package egovframework.adm.cfg.cod.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import egovframework.adm.cfg.cod.dao.CodeManageDAO; import egovframework.adm.cfg.cod.service.CodeManageService; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; @Service("codeManageService") public class CodeManageServiceImpl extends EgovAbstractServiceImpl implements CodeManageService{ @Resource(name="codeManageDAO") private CodeManageDAO codeManageDAO; public List selectListCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectListCode(commandMap); } public Map selectViewCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectViewCode(commandMap); } public int updateCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.updateCode(commandMap); } public int deleteCode(Map<String, Object> commandMap) throws Exception{ int isOk = 1; codeManageDAO.deleteCode(commandMap); codeManageDAO.deleteSubCode(commandMap); return isOk; } public int insertCode(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ codeManageDAO.insertCode(commandMap); }catch(Exception ex){ isOk = 0; ex.printStackTrace(); } return isOk; } public List selectSubListCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectSubListCode(commandMap); } public Map selectSubViewCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectSubViewCode(commandMap); } public int subUpdateData(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.subUpdateData(commandMap); } public int subDeleteData(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.subDeleteData(commandMap); } public int subInsertData(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ codeManageDAO.subInsertData(commandMap); }catch(Exception ex){ isOk = 0; ex.printStackTrace(); } return isOk; } /** * 과정분류 대분류코드 리스트 * @param commandMap * @return * @throws Exception */ public List selectCursBunryuList(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectCursBunryuList(commandMap); } /** * 교육관련 코드 리스트(tk_edu000t) * @param commandMap * @return * @throws Exception */ public List selectEduListCode(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectEduListCode(commandMap); } /** * 설문지 리스트 가져오기 * @param commandMap * @return * @throws Exception */ public List selectSulPaperList(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectSulPaperList(commandMap); } /** * 출석고사장 학교 리스트 * @param commandMap * @return * @throws Exception */ public List selectSchoolRoomList(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectSchoolRoomList(commandMap); } /** * 기관코드 리스트 * @param commandMap * @return * @throws Exception */ public List selectEduOrgList(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectEduOrgList(commandMap); } /** * 설문척도 리스트 * @param commandMap * @return * @throws Exception */ public List selectSulScaleList(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectSulScaleList(commandMap); } /** * 검색에서 평가의 대한 종류를 가져오는 쿼리 * @param commandMap * @return * @throws Exception */ public List selectExamResultPaperNum(Map<String, Object> commandMap) throws Exception{ return codeManageDAO.selectExamResultPaperNum(commandMap); } }
package uk.ac.ebi.intact.view.webapp.it; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.Select; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class AdvancedSearchIT extends IntactViewIT { @Test public void whenIClickOnAddAndSearchIShouldHaveCorrectResults() throws Exception { // Given: I want to do a query using the advanced search from the home page goToTheStartPage(); // When: I query 11554746 using Publication ID and click on the Add & Search button showAdvancedFields(); selectAdvancedFieldByLabel("Publication id (Ex: 10837477)"); typeAdvancedQuery("11554746"); clickOnAddAndSearch(); // Then: I expect 4 interactions in total assertThat(numberOfResultsDisplayed(), is(equalTo(3))); } @Test public void whenISelectDetectionMethodUsingTreeIShouldHaveCorrectResults() throws Exception { // Given: I want to do a query using the advanced search from the home page goToTheStartPage(); // When: I choose Detection Method and browse the tree selecting "imaging technique" showAdvancedFields(); selectAdvancedFieldByLabel("Interaction detection method (Ex: pull down)"); clickOnBrowseIcon(); selectImagingTechniqueInDialog(); clickOnAddAndSearch(); // Then: I expect 2 interactions in total assertThat(numberOfResultsDisplayed(), is(equalTo(2))); } private void typeAdvancedQuery(String search) { driver.findElement(By.id("newQuerytxt")).sendKeys(search); } private void selectAdvancedFieldByLabel(String fieldValue) { changeSelectToLabel(By.id("newQueryField"), fieldValue); waitUntilLoadingIsComplete(); } private void showAdvancedFields() { driver.findElement(By.id("addFieldBtn")).click(); waitUntilElementIsVisible(By.id("newQuerytxt")); } private void changeSelectToLabel(By element, String label) { Select select = new Select(driver.findElement(element)); select.selectByVisibleText(label); } private void clickOnAddAndSearch() { driver.findElement(By.id("addAndSearchBtn")).click(); } private void selectImagingTechniqueInDialog() { //We need wait to avoid "Element is not currently visible exception" sleep(100); driver.findElement(By.xpath("//li[@id='ontologyTree:0']/div/span/span")).click(); waitUntilElementIsVisible(By.id("ontologyTree:0_1:termTxt")); driver.findElement(By.id("ontologyTree:0_1:termTxt")).click(); waitUntilElementHasValue(By.id("newQuerytxt"), "MI:0428"); } private void clickOnBrowseIcon() { waitUntilElementIsVisible(By.id("browseOntologyImg")); driver.findElement(By.id("browseOntology")).click(); } }
import java.util.Scanner; class Lesson_33_Activity_Three { public static void printit(int[] x) { for (int i = 0; i < x.length; i ++) { System.out.print(x[i] + " "); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] list = new int[100]; printit(list); } }
package com.zantong.mobilecttx.user.activity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.R; import com.zantong.mobilecttx.api.CallBack; import com.zantong.mobilecttx.api.CarApiClient; import com.zantong.mobilecttx.base.activity.BaseMvpActivity; import com.zantong.mobilecttx.base.interf.IBaseView; import com.zantong.mobilecttx.base.bean.BaseResult; import com.zantong.mobilecttx.home.bean.UpdateInfo; import com.zantong.mobilecttx.user.dto.LiYingRegDTO; import com.zantong.mobilecttx.presenter.UpdateNickNamePresenter; import com.zantong.mobilecttx.utils.rsa.RSAUtils; import com.zantong.mobilecttx.utils.RefreshNewTools.UserInfoRememberCtrl; import com.zantong.mobilecttx.interf.ModelView; import java.util.HashMap; import butterknife.Bind; import butterknife.OnClick; public class UpdateNickName extends BaseMvpActivity<IBaseView, UpdateNickNamePresenter> implements View.OnClickListener, IBaseView, ModelView { @Bind(R.id.nick_name_edit) EditText nickNameEdit; @Bind(R.id.image_delete) ImageView imageDelete; @Override public UpdateNickNamePresenter initPresenter() { return new UpdateNickNamePresenter(UpdateNickName.this); } @Override protected int getContentResId() { return R.layout.update_nick_name; } @Override public void initView() { setTitleText("修改昵称"); setEnsureText("保存"); nickNameEdit.setText(PublicData.getInstance().mLoginInfoBean.getNickname()); } @Override public void initData() { nickNameEdit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() > 0) { imageDelete.setVisibility(View.VISIBLE); } else { imageDelete.setVisibility(View.GONE); } } }); } public HashMap<String, String> mapData() { HashMap<String, String> mHashMap = new HashMap<>(); mHashMap.put("nickname", nickNameEdit.getText().toString()); return mHashMap; } @Override protected void baseGoBack() { finish(); // super.baseGoBack(); } @Override protected void baseGoEnsure() { presenter.loadView(1); } @Override public void showLoading() { } @Override public void hideLoading() { } private void init() { } @OnClick({R.id.nick_name_edit, R.id.image_delete}) public void onClick(View view) { switch (view.getId()) { case R.id.nick_name_edit: break; case R.id.image_delete: nickNameEdit.setText(""); break; } } @Override public void showProgress() { } @Override public void updateView(Object object, int index) { switch (index) { case 1: if (PublicData.getInstance().success.equals(((UpdateInfo) object).getSYS_HEAD().getReturnCode())) { liyingreg(); PublicData.getInstance().mLoginInfoBean.setNickname(nickNameEdit.getText().toString()); UserInfoRememberCtrl.saveObject(PublicData.getInstance().mLoginInfoBean); finish(); } break; } } private void liyingreg() { String phone = RSAUtils.strByEncryptionLiYing(PublicData.getInstance().mLoginInfoBean.getPhoenum(), true); LiYingRegDTO liYingRegDTO = new LiYingRegDTO(); liYingRegDTO.setPhoenum(phone); liYingRegDTO.setUsrid(RSAUtils.strByEncryptionLiYing(PublicData.getInstance().userID, true)); liYingRegDTO.setNickname(nickNameEdit.getText().toString()); CarApiClient.liYingReg(getApplicationContext(), liYingRegDTO, new CallBack<BaseResult>() { @Override public void onSuccess(BaseResult result) { } }); } @Override public void hideProgress() { } }
package com.fanoi.dream.model.bean; import java.io.Serializable; /** * 登录 * Created by Jette on 2016/4/1. */ public class Login implements Serializable{ private String token; private Profile profile; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } @Override public String toString() { return "Login{" + "token='" + token + '\'' + ", profile=" + profile + '}'; } }
package at.ac.tuwien.sepm.groupphase.backend.integrationtest; import at.ac.tuwien.sepm.groupphase.backend.basetest.TestData; import at.ac.tuwien.sepm.groupphase.backend.config.properties.SecurityProperties; import at.ac.tuwien.sepm.groupphase.backend.endpoint.dto.*; import at.ac.tuwien.sepm.groupphase.backend.endpoint.mapper.CustomerMapper; import at.ac.tuwien.sepm.groupphase.backend.entity.*; import at.ac.tuwien.sepm.groupphase.backend.repository.AddressRepository; 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.security.JwtTokenizer; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CacheEvict; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.time.LocalDateTime; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles("test") @AutoConfigureMockMvc class MeEndpointTest implements TestData { @Autowired private MockMvc mockMvc; @Autowired private AddressRepository addressRepository; @Autowired CacheManager cacheManager; @Autowired private ObjectMapper objectMapper; @Autowired private JwtTokenizer jwtTokenizer; @Autowired private CustomerRepository customerRepository; @Autowired private OrderRepository orderRepository; @Autowired private InvoiceRepository invoiceRepository; @Autowired private InvoiceItemRepository invoiceItemRepository; @Autowired private ProductRepository productRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private TaxRateRepository taxRateRepository; @Autowired private SecurityProperties securityProperties; @Autowired private CustomerMapper customerMapper; private final Address address = new Address(TEST_ADDRESS_STREET, TEST_ADDRESS_POSTALCODE, TEST_ADDRESS_HOUSENUMBER, 0, "0"); private final Customer customer = new Customer(TEST_CUSTOMER_EMAIL, TEST_CUSTOMER_PASSWORD, TEST_CUSTOMER_NAME, TEST_CUSTOMER_LOGINNAME, address, 0L, "1"); private final Customer customer2 = new Customer("mail@gmail.com", TEST_CUSTOMER_PASSWORD, TEST_CUSTOMER_NAME, "login", address, 0L, ""); private final Customer customer3 = new Customer("somemail@gmail.com", TEST_CUSTOMER_PASSWORD, TEST_CUSTOMER_NAME, "login3", address, 0L, ""); private final Invoice invoice = new Invoice(); private final InvoiceItemKey invoiceItemKey = new InvoiceItemKey(); private final InvoiceItem invoiceItem = new InvoiceItem(); private final Product product = new Product(); private final Category category = new Category(); private final TaxRate taxRate = new TaxRate(); @BeforeEach @CacheEvict(value = "counts", allEntries = true) public void beforeEach() { orderRepository.deleteAll(); customerRepository.deleteAll(); invoiceRepository.deleteAll(); invoiceItemRepository.deleteAll(); Customer customer = new Customer(TEST_CUSTOMER_EMAIL, TEST_CUSTOMER_PASSWORD, TEST_CUSTOMER_NAME, TEST_CUSTOMER_LOGINNAME, address, 0L, "1"); Customer customer2 = new Customer("mail@gmail.com", TEST_CUSTOMER_PASSWORD, TEST_CUSTOMER_NAME, "login", address, 0L, ""); invoiceRepository.deleteAll(); categoryRepository.deleteAll(); taxRateRepository.deleteAll(); productRepository.deleteAll(); invoiceRepository.deleteAll(); product.setId(0L); product.setName(TEST_PRODUCT_NAME); product.setDescription(TEST_PRODUCT_DESCRIPTION); product.setPrice(TEST_PRODUCT_PRICE); category.setId(1L); category.setName(TEST_CATEGORY_NAME); taxRate.setId(1L); taxRate.setPercentage(TEST_TAX_RATE_PERCENTAGE); taxRate.setCalculationFactor((TEST_TAX_RATE_PERCENTAGE/100)+1); // product product.setId(0L); product.setName(TEST_PRODUCT_NAME); product.setDescription(TEST_PRODUCT_DESCRIPTION); product.setPrice(TEST_PRODUCT_PRICE); product.setTaxRate(taxRateRepository.save(taxRate)); product.setCategory(categoryRepository.save(category)); // invoiceItem invoiceItemKey.setInvoiceId(null); invoiceItemKey.setProductId(product.getId()); invoiceItem.setId(invoiceItemKey); invoiceItem.setProduct(productRepository.save(product)); invoiceItem.setNumberOfItems(10); } @Test void givenNothing_whenPut_then404() throws Exception { customer.setId(1L); CustomerRegistrationDto customerDto = customerMapper.customerToCustomerRegistrationDto(customer); String body = objectMapper.writeValueAsString(customerDto); MvcResult mvcResult = this.mockMvc.perform(put(ME_BASE_URI) .contentType(MediaType.APPLICATION_JSON) .content(body) .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(TEST_CUSTOMER_LOGINNAME, CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertAll( () -> assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus()) ); } @Test void givenOneCustomer_whenPutByExistingId_thenVerifyCustomerChanged() throws Exception { addressRepository.save(address); Customer updatedCustomer = customerRepository.save(customer); updatedCustomer.setName("New Name"); updatedCustomer.setPassword("unchanged"); CustomerRegistrationDto customerDto = customerMapper.customerToCustomerRegistrationDto(updatedCustomer); String body = objectMapper.writeValueAsString(customerDto); MvcResult mvcResult = this.mockMvc.perform(put(ME_BASE_URI) .contentType(MediaType.APPLICATION_JSON) .content(body) .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(TEST_CUSTOMER_LOGINNAME, CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertEquals(HttpStatus.OK.value(), response.getStatus()); assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType()); CustomerRegistrationDto customerResponse = objectMapper.readValue(response.getContentAsString(), CustomerRegistrationDto.class); assertNotNull(customerResponse.getId()); assertNotNull(customerResponse.getName()); assertNotNull(customerResponse.getLoginName()); assertNotNull(customerResponse.getEmail()); assertNotNull(customerResponse.getAddress()); customerResponse.setPassword(null); assertAll( () -> assertEquals(updatedCustomer.getId(), customerMapper.customerDtoToCustomer(customerResponse).getId()), () -> assertEquals(updatedCustomer.getEmail(), customerMapper.customerDtoToCustomer(customerResponse).getEmail()), () -> assertEquals(updatedCustomer.getName(), customerMapper.customerDtoToCustomer(customerResponse).getName()), () -> assertEquals(updatedCustomer.getLoginName(), customerMapper.customerDtoToCustomer(customerResponse).getLoginName()), () -> assertEquals(updatedCustomer.getAddress(), customerMapper.customerDtoToCustomer(customerResponse).getAddress()), () -> assertEquals(updatedCustomer.getPhoneNumber(), customerMapper.customerDtoToCustomer(customerResponse).getPhoneNumber()) ); } @Test void givenTwoCustomers_whenPutByExistingIdAndIllegalAccess_then403() throws Exception { addressRepository.save(address); customerRepository.save(customer); Customer updatedCustomer = customerRepository.save(customer2); updatedCustomer.setName("New Name"); updatedCustomer.setPassword("unchanged"); CustomerRegistrationDto customerDto = customerMapper.customerToCustomerRegistrationDto(updatedCustomer); String body = objectMapper.writeValueAsString(customerDto); MvcResult mvcResult = this.mockMvc.perform(put(ME_BASE_URI) .contentType(MediaType.APPLICATION_JSON) .content(body) .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(TEST_CUSTOMER_LOGINNAME, CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertAll( () -> assertEquals(HttpStatus.FORBIDDEN.value(), response.getStatus()) ); } @Test void givenTwoCustomers_whenPutByExistingIdAndChangedCustomerAlreadyExists_then422() throws Exception { addressRepository.save(address); Customer firstCustomer = customerRepository.save(customer); Customer updatedCustomer = customerRepository.save(customer2); updatedCustomer.setLoginName(firstCustomer.getLoginName()); updatedCustomer.setEmail(firstCustomer.getEmail()); updatedCustomer.setPassword("unchanged"); CustomerRegistrationDto customerDto = customerMapper.customerToCustomerRegistrationDto(updatedCustomer); String body = objectMapper.writeValueAsString(customerDto); MvcResult mvcResult = this.mockMvc.perform(put(ME_BASE_URI) .contentType(MediaType.APPLICATION_JSON) .content(body) .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(customer2.getLoginName(), CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertAll( () -> assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), response.getStatus()) ); } @Test void givenOneCustomerOneOrderAndOneInvoice_whenGet_verifyOrder() throws Exception { addressRepository.save(address); invoice.setInvoiceType(InvoiceType.customer); invoice.setDate(LocalDateTime.now()); invoice.setInvoiceNumber("123"); invoice.setAmount(50.0); invoiceRepository.save(invoice); Customer newCustomer = customerRepository.save(customer3); Order order = new Order(invoice, newCustomer); Order newOrder = orderRepository.save(order); PaginationRequestDto paginationRequestDto = new PaginationRequestDto(); paginationRequestDto.setPage(0); paginationRequestDto.setPageCount(5); String body = objectMapper.writeValueAsString(paginationRequestDto); MvcResult mvcResult = this.mockMvc.perform(get(ME_BASE_URI + "/orders") .contentType(MediaType.APPLICATION_JSON) .content(body) .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(newCustomer.getLoginName(), CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertEquals(HttpStatus.OK.value(), response.getStatus()); PaginationDto<OrderDto> paginationDto = objectMapper.readValue(response.getContentAsString(), new TypeReference<>() { }); List<OrderDto> orders = paginationDto.getItems(); OrderDto checkOrder = orders.get(0); assertAll( () -> assertEquals(1, orders.size()), () -> assertEquals(1, paginationDto.getTotalItemCount()), () -> assertNotNull(checkOrder), () -> assertEquals(newOrder.getCustomer().getName(), customerMapper.dtoToCustomer(checkOrder.getCustomer()).getName()), () -> assertEquals(newOrder.getInvoice().getAmount(), checkOrder.getInvoice().getAmount()) ); } @Test void givenOneCustomerOneOrderAndOneInvoice_whenGet_verifyValidPDFInvoice() throws Exception { addressRepository.save(address); Customer newCustomer = customerRepository.save(customer3); invoice.setInvoiceType(InvoiceType.customer); invoice.setDate(LocalDateTime.now()); invoice.setInvoiceNumber("1456"); invoice.setAmount(150.0); invoice.setCustomerId(newCustomer.getId()); invoice.setOrderNumber("asd"); Set<InvoiceItem> items = new HashSet<>(); items.add(invoiceItem); invoice.setItems(null); Invoice newInvoice = invoiceRepository.save(invoice); for (InvoiceItem item : items) { item.setInvoice(newInvoice); invoiceItemRepository.save(item); } Order order = new Order(invoice, newCustomer); orderRepository.save(order); MvcResult mvcResult = this.mockMvc.perform(get(ME_BASE_URI + "/invoices/" + newInvoice.getId() + "/pdf") .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(newCustomer.getLoginName(), CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertEquals(HttpStatus.OK.value(), response.getStatus()); assertAll( () -> assertEquals(MediaType.APPLICATION_PDF_VALUE, response.getContentType()), () -> assertNotNull(response) ); } @Test void givenOneCustomerOneInvoiceAndNoOrder_whenGet_then404() throws Exception { addressRepository.save(address); Customer newCustomer = customerRepository.save(customer3); invoice.setInvoiceType(InvoiceType.customer); invoice.setDate(LocalDateTime.now()); invoice.setInvoiceNumber("1456"); invoice.setAmount(150.0); invoice.setCustomerId(newCustomer.getId()); Invoice newInvoice = invoiceRepository.save(invoice); MvcResult mvcResult = this.mockMvc.perform(get(ME_BASE_URI + "/invoices/" + newInvoice.getId() + "/pdf") .header(securityProperties.getAuthHeader(), jwtTokenizer.getAuthToken(newCustomer.getLoginName(), CUSTOMER_ROLES))) .andDo(print()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatus()); } }
/* * SendArticle.java * * Created on 2006年11月5日, 上午9:16 */ package tot.servlet; import tot.util.*; import tot.dao.DaoFactory; import tot.global.Sysconfig; import tot.exception.*; import tot.db.DBUtils; import java.io.*; import java.net.*; import java.util.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author Administrator * @version 1.0 */ public class SendArticle extends HttpServlet { private static Log log = LogFactory.getLog(SendArticle.class); ServletContext sc; public void init(ServletConfig config) throws ServletException { super.init(config); sc=config.getServletContext(); } /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //数据库变量 Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; //权限判断 HttpSession session=request.getSession(); String admin=null; String haspriv=null; Locale locale=request.getLocale(); if(session.getAttribute("admin")!=null){ admin=(String)session.getAttribute("admin"); } if(session.getAttribute("role")!=null){ haspriv=(String)session.getAttribute("role"); } if(admin==null || haspriv==null){ response.sendRedirect("login.jsp"); } if(!DaoFactory.getAdminDAO().ifHasPrivilege(haspriv,"p06")) throw new ServletException("you don't have privilege"); //读取参数 String by=RequestUtil.getString(request,"by"); int interval=RequestUtil.getInt(request,"interval"); int start=RequestUtil.getInt(request,"start"); int id=RequestUtil.getInt(request,"id"); if(id==0) id=DaoFactory.getArticleDAO().getLastId(); //缓存处理 if(sc.getAttribute("totcms_reset_robot")==null) sc.setAttribute("totcms_reset_robot",0); if(sc.getAttribute("totcms_reset_total")==null) sc.setAttribute("totcms_reset_total",0); if(start==1) sc.setAttribute("totcms_reset_robot",0); String paraStr="by="+by+"&interval="+interval; // String sqlQuery=""; int databaseType=DBUtils.getDatabaseType(); int startId=0; int endId=0; //date Timestamp dateStart=null; Timestamp dateEnd=null; if(by.equalsIgnoreCase("all")){ if (databaseType == DBUtils.DATABASE_SQLSERVER) { sqlQuery="select top 1 id from t_article where IsOutLink=0 and id<? order by id desc"; }else if(databaseType == DBUtils.DATABASE_MYSQL){ sqlQuery="select id from t_article where IsOutLink=0 and id<? order by id desc limit 0,1"; }else if(databaseType==DBUtils.DATABASE_IMFORMIX){//imformix sqlQuery="select FIRST 1 id from t_article where IsOutLink=0 and id<? order by id desc"; }else if(databaseType==DBUtils.DATABASE_ORACLE){//oracle sqlQuery="select id from t_article where IsOutLink=0 and id<? and ROWNUM=1 order by id desc"; }else if(databaseType==DBUtils.DATABASE_POSTGRESQL){//pgsql sqlQuery="select id from t_article where IsOutLink=0 and id<? order by id desc limit 1"; }else if(databaseType==DBUtils.DATABASE_DB2){//db2 sqlQuery="select id from t_article where IsOutLink=0 and id<? order by id desc fetch first 1 rows only"; } }else if(by.equalsIgnoreCase("date")){ String dateStartStr=RequestUtil.getString(request,"DateStart"); String dateEndStr=RequestUtil.getString(request,"DateEnd"); dateStart=new Timestamp(DateUtil.strToBirthday(dateStartStr).getTime()); dateEnd=new Timestamp(DateUtil.strToBirthday(dateEndStr).getTime()); paraStr=paraStr+"&DateStart="+dateStartStr+"&DateEnd="+dateEndStr; if (databaseType == DBUtils.DATABASE_SQLSERVER) { sqlQuery="select top 1 id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? order by id desc"; }else if(databaseType == DBUtils.DATABASE_MYSQL){ sqlQuery="select id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? order by id desc limit 0,1"; }else if(databaseType==DBUtils.DATABASE_IMFORMIX){//imformix sqlQuery="select FIRST 1 id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? order by id desc"; }else if(databaseType==DBUtils.DATABASE_ORACLE){//oracle sqlQuery="select id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? and ROWNUM=1 order by id desc"; }else if(databaseType==DBUtils.DATABASE_POSTGRESQL){//pgsql sqlQuery="select id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? order by id desc limit 1"; }else if(databaseType==DBUtils.DATABASE_DB2){//db2 sqlQuery="select id from t_article where IsOutLink=0 and id<? and ModiTime>? and ModiTime<? order by id desc fetch first 1 rows only"; } }else if(by.equalsIgnoreCase("id")){ startId=RequestUtil.getInt(request,"StartId"); endId=RequestUtil.getInt(request,"EndId"); if(endId>id) endId=id; if(start==1){ id=endId; }else{ //id=id-1; } paraStr=paraStr+"&StartId="+startId+"&EndId="+endId; if (databaseType == DBUtils.DATABASE_SQLSERVER) { sqlQuery="select top 1 id from t_article where IsOutLink=0 and id<? and id>? order by id desc"; }else if(databaseType == DBUtils.DATABASE_MYSQL){ sqlQuery="select id from t_article where IsOutLink=0 and id<? and id>? order by id desc limit 0,1"; }else if(databaseType==DBUtils.DATABASE_IMFORMIX){//imformix sqlQuery="select FIRST 1 id from t_article where IsOutLink=0 and id<? and id>? order by id desc"; }else if(databaseType==DBUtils.DATABASE_ORACLE){//oracle sqlQuery="select id from t_article where IsOutLink=0 and id<? and id>? and ROWNUM=1 order by id desc"; }else if(databaseType==DBUtils.DATABASE_POSTGRESQL){//pgsql sqlQuery="select id from t_article where IsOutLink=0 and id<? and id>? order by id desc limit 1"; }else if(databaseType==DBUtils.DATABASE_DB2){//db2 sqlQuery="select id from t_article where IsOutLink=0 and id<? and id>? order by id desc fetch first 1 rows only"; } }else if(by.equalsIgnoreCase("template")){ int templateid=RequestUtil.getInt(request,"TemplateId"); paraStr=paraStr+"&TemplateId="+templateid; if (databaseType == DBUtils.DATABASE_SQLSERVER) { sqlQuery="select top 1 id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" order by id desc"; }else if(databaseType == DBUtils.DATABASE_MYSQL){ sqlQuery="select id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" order by id desc limit 0,1"; }else if(databaseType==DBUtils.DATABASE_IMFORMIX){//imformix sqlQuery="select FIRST 1 id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" order by id desc"; }else if(databaseType==DBUtils.DATABASE_ORACLE){//oracle sqlQuery="select id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" and ROWNUM=1 order by id desc"; }else if(databaseType==DBUtils.DATABASE_POSTGRESQL){//pgsql sqlQuery="select id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" order by id desc limit 1"; }else if(databaseType==DBUtils.DATABASE_DB2){//db2 sqlQuery="select id from t_article where IsOutLink=0 and id<? and TemplateId="+templateid+" order by id desc fetch first 1 rows only"; } } String sqlCount="select count(*) from t_article where IsOutLink=0"; if(by!=null && start==1){ if(by.equalsIgnoreCase("all")){ int totalNum=DaoFactory.getArticleDAO().getTotalCount(0); if(totalNum==0) totalNum=1; sc.setAttribute("totcms_reset_total",totalNum); } else if(by.equalsIgnoreCase("date")){ int totalNum=0; if (databaseType == DBUtils.DATABASE_SQLSERVER) { sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; }else if(databaseType == DBUtils.DATABASE_MYSQL){ sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; }else if(databaseType==DBUtils.DATABASE_IMFORMIX){//imformix sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; }else if(databaseType==DBUtils.DATABASE_ORACLE){//oracle sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; }else if(databaseType==DBUtils.DATABASE_POSTGRESQL){//pgsql sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; }else if(databaseType==DBUtils.DATABASE_DB2){//db2 sqlCount="select count(*) from t_article where IsOutLink=0 and ModiTime>? and ModiTime<?"; } try{ conn = DBUtils.getConnection(); ps=conn.prepareStatement(sqlCount); ps.setTimestamp(1,dateStart); ps.setTimestamp(2,dateEnd); rs=ps.executeQuery(); if(rs.next()){ totalNum=rs.getInt(1); } }catch(SQLException e){ } finally{ DBUtils.closeResultSet(rs); DBUtils.closePrepareStatement(ps); DBUtils.closeConnection(conn); } if(totalNum==0) totalNum=1; sc.setAttribute("totcms_reset_total",totalNum); }else if(by.equalsIgnoreCase("id")){ sqlCount="select count(*) from t_article where IsOutLink=0 and id>"+startId+" and id<"+endId; int totalNum=DaoFactory.getArticleDAO().getDataCount(sqlCount); if(totalNum==0) totalNum=1; sc.setAttribute("totcms_reset_total",totalNum); }else if(by.equalsIgnoreCase("template")){ int templateid=RequestUtil.getInt(request,"TemplateId"); sqlCount="select count(*) from t_article where IsOutLink=0 and TemplateId="+templateid; int totalNum=DaoFactory.getArticleDAO().getDataCount(sqlCount); if(totalNum==0) totalNum=1; sc.setAttribute("totcms_reset_total",totalNum); } } //读取数据库 boolean hasNext=false; //log.info(sqlQuery); try{ conn = DBUtils.getConnection(); ps=conn.prepareStatement(sqlQuery); ps.setInt(1,id); if(by.equalsIgnoreCase("date")){ ps.setTimestamp(2,dateStart); ps.setTimestamp(3,dateEnd); }else if(by.equalsIgnoreCase("id")){ ps.setInt(2,startId); } rs=ps.executeQuery(); if(rs.next()){ id=rs.getInt(1); hasNext=true; sc.setAttribute("totcms_reset_robot",(Integer)sc.getAttribute("totcms_reset_robot")+1); }else{ hasNext=false; } } catch(SQLException e){ log.error("get last id",e); } finally{ DBUtils.closeResultSet(rs); DBUtils.closePrepareStatement(ps); DBUtils.closeConnection(conn); } // int sendPercent=((Integer)sc.getAttribute("totcms_reset_robot")*100)/(Integer)sc.getAttribute("totcms_reset_total"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); if(hasNext){ out.print("<meta http-equiv=\"refresh\" content=\""+interval+";URL=?"+paraStr+"&id="+id+"\">\n"); } out.print("<title>send article</title>\n"); out.print("</head>\n"); out.print("<body>\n"); if(hasNext){ out.print("<table width=\"400\" height=\"20\" border=\"1\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#D4D0C8\" bgcolor=\"#FFFFFF\">\n"); out.print("<tr>\n"); out.print("<td>\n"); out.print("<table id=\"stat_w\" style=\"width:1%;\" border=\"0\" align=\"left\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#003399\">\n"); out.print("<tr>\n"); out.print("<td>&nbsp;</td>\n"); out.print("</tr>\n"); out.print("</table>\n"); out.print("<span class=\"style1\" id=\"P_num\"></span></td>\n"); out.print("</tr>\n"); out.print("</table>\n"); out.print("<br>"+ResourceBundleUtil.getString(locale,"totcms.admin.send.msg.nowstatus")+":"+sc.getAttribute("totcms_reset_total")+"/"+sc.getAttribute("totcms_reset_robot")+"\n"); out.print("<script src=\"js/xmlhttp_utf8.js\" type=\"text/javascript\"></script>\n"); // ajax vbs out.print("<script type=\"text/javascript\" language=\"javascript\">\n"); out.print("var HTTP;\n"); out.print("function CallServer(Url)\n"); out.print("{\n"); out.print(" HTTP=getXMLRequester();\n"); out.print(" HTTP.onreadystatechange = doAction;\n"); out.print(" var ReturnValue=HTTP.open(\"POST\",Url,true);\n"); out.print(" HTTP.send(\"\");\n"); out.print(" return HTTP.responseText;\n"); out.print("}\n"); out.print("function doAction() {\n"); out.print(" if (HTTP.readyState == 4)\n"); out.print(" {\n"); out.print(" if (HTTP.status == 500) {\n"); out.print(" //alert(\"Get error on publish aritlce by id:"+id+"!\"); \n"); out.print("\n"); out.print(" }\n"); out.print(" else if (HTTP.status == 200) {\n"); out.print(" //document.write(HTTP.responseText);\n"); //out.print(" document.write(\"id:\"+"+id+"+\"<br>\");\n"); out.print(" document.getElementById('stat_w').style.width =\""+sendPercent+"%\";\n"); out.print(" document.getElementById('P_num').innerHTML =\""+sendPercent+"%\";\n"); out.print(" } \n"); out.print(" else {\n"); out.print(" alert(HTTP.status);\n"); out.print(" }\n"); out.print(" }\n"); out.print("}\n"); out.print("function resetHtml()\n"); out.print("{\n"); out.print(" var ReturnValue; \n"); out.print(" ReturnValue=CallServer('ArticleReset?id="+id+"');\n"); out.print(" document.write(ReturnValue);\n"); out.print("}\n"); out.print("resetHtml();\n"); out.print("</script>\n"); } else{ out.print(ResourceBundleUtil.getString(locale,"totcms.admin.send.msg.sucsend")+":"+sc.getAttribute("totcms_reset_robot")); } out.print("</body>\n"); out.print("</html>\n"); out.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }
package referencetype.practice; public class NullPointerExceptionExample { public static void main(String[] args) { String str = "Jayden"; System.out.println("총 문자수: " + str.length()); int[] intArray = {1,2,3,4,5}; intArray[0] = 10; for(int i=0; i<intArray.length; i++) { System.out.println(intArray[i]); } } }
package algorithms.graph.process; import java.util.ArrayDeque; import java.util.BitSet; import java.util.Deque; import algorithms.graph.Graph; public class DepthFirstDirectedCycleDetection implements CycleDetection { private BitSet marked; private int[] edgesTo; private BitSet onStack; private Deque<Integer> cycle; @Override public void init(Graph graph) { edgesTo = new int[graph.verticesCount()]; marked = new BitSet(graph.verticesCount()); onStack = new BitSet(); for (Integer v : graph.getVertices()) { if (hasCycle()) { break; } if (!marked.get(v)) { dfs(graph, v); } } } /** * be careful to terminate recursive call */ private void dfs(Graph graph, int vertex) { marked.set(vertex); onStack.set(vertex); for (Integer adjacentVertex : graph.adjacentVertices(vertex)) { if (hasCycle()) { //be careful to terminate recursive call return; } else if (!marked.get(adjacentVertex)) { edgesTo[adjacentVertex] = vertex; dfs(graph, adjacentVertex); } else if (onStack.get(adjacentVertex)) { cycle = new ArrayDeque<>(); for (int x = vertex; x != adjacentVertex; x = edgesTo[x]) { cycle.push(x); } cycle.push(adjacentVertex); cycle.push(vertex); return; } } onStack.set(vertex, false); } @Override public boolean hasCycle() { return cycle != null; } @Override public Iterable<Integer> cycle() { return cycle; } }
package com.transport.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; /** * * @author edwarddavid * @since 24Apr2020 */ public class RptTireStatusSummaryFormBean extends TransportFormBean { /** * */ private static final long serialVersionUID = 1L; private String searchValue; public RptTireStatusSummaryFormBean(){} public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub ActionErrors errors = new ActionErrors(); return errors; } }
package msip.go.kr.board.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import msip.go.kr.board.entity.BoardMaster; import msip.go.kr.board.service.BoardMasterService; import msip.go.kr.common.entity.Tree; /** * 게시판 속성 Controller 클래스 * * @author 양준호 * @since 2015.07.15 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * --------------------------------------------------------------------------------- * 2015.07.15 양준호 최초생성 * 2015.07.31 양준호 menu(Model model) 추가 * </pre> */ @Controller public class BoardMasterController { @Resource(name = "boardMasterService") private BoardMasterService boardMasterService; /** * 게시판 마스터 관리 페이지로 이동 * * @param model * @return "msip/admin/board/master" * @throws Exception */ @RequestMapping(value = "/admin/board/master") public String manage(Model model) throws Exception { return "msip/admin/board/master"; } /** * 게시판 마스터 정보 신규 입력 * @param multiRequest * @param entity * @param model * @return * @throws Exception */ @RequestMapping(value = "/admin/board/master/regist", method = RequestMethod.POST) @ResponseBody public String regist(BoardMaster entity, ModelMap model) throws Exception { String message = "success"; try { boardMasterService.persist(entity); } catch (Exception e) { e.printStackTrace(); message = "fail"; } return message; } @RequestMapping(value = "/admin/board/master/update", method = RequestMethod.POST) @ResponseBody public String update(BoardMaster entity, ModelMap model) throws Exception { String message = "success"; try { boardMasterService.merge(entity); } catch (Exception e) { e.printStackTrace(); message = "fail"; } return message; } @RequestMapping(value = "/admin/board/master/remove", method = RequestMethod.POST) @ResponseBody public String remove(BoardMaster entity, ModelMap model) throws Exception { String message = "success"; try { boardMasterService.remove(entity); } catch (Exception e) { e.printStackTrace(); message = "fail"; } return message; } @RequestMapping(value = "/board/master", method = RequestMethod.GET) @ResponseBody public List<BoardMaster> find(Model model) throws Exception { return boardMasterService.findAll(); } @RequestMapping(value = "/board/master/{id}", method = RequestMethod.GET) @ResponseBody public BoardMaster find(@PathVariable Long id, Model model) throws Exception { return boardMasterService.findById(id); } @RequestMapping(value = "/board/master/tree", method = RequestMethod.GET) @ResponseBody public List<Tree> tree(Model model) throws Exception { List<Tree> list = boardMasterService.treeList(); return list; } @RequestMapping(value = "/board/menu", method = RequestMethod.GET) @ResponseBody public List<Map<String, Object>> menu(Model model) throws Exception { List<BoardMaster> list = boardMasterService.findAll(true); List<Map<String, Object>> menuList = new ArrayList<Map<String, Object>>(); for(BoardMaster entity : list) { Map<String, Object> menu = new HashMap<String, Object>(); menu.put("id", entity.getId()); menu.put("url", "/board/"+entity.getId()); menu.put("title", entity.getBoardNm()); menuList.add(menu); } return menuList; } @RequestMapping(value = "/admin/board/menu", method = RequestMethod.GET) @ResponseBody public List<Map<String,String>> adminMenu(Model model) throws Exception { List<BoardMaster> list = boardMasterService.findAll(true); List<Map<String,String>> menuList = new ArrayList<Map<String, String>>(); for(BoardMaster entity : list) { Map<String, String> menu = new HashMap<String, String>(); menu.put("url", "/admin/board/"+entity.getId()); menu.put("title", entity.getBoardNm()); menuList.add(menu); } return menuList; } }
public class Main { public static void main(String[] args) { System.out.println(NumberPalindrome.isPalindrome(121)); // int reverse = 0; // int number =123; // while(number > 0) { // int lastDigit = number % 10; // reverse = (reverse * 10) + lastDigit; // number = number / 10; // } // System.out.println(reverse); } }