text
stringlengths
10
2.72M
/* * Copyright 2002-2019 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.sockjs.frame; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link org.springframework.web.socket.sockjs.frame.SockJsFrame}. * * @author Rossen Stoyanchev * @since 4.1 */ public class SockJsFrameTests { @Test public void openFrame() { SockJsFrame frame = SockJsFrame.openFrame(); assertThat(frame.getContent()).isEqualTo("o"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.OPEN); assertThat(frame.getFrameData()).isNull(); } @Test public void heartbeatFrame() { SockJsFrame frame = SockJsFrame.heartbeatFrame(); assertThat(frame.getContent()).isEqualTo("h"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.HEARTBEAT); assertThat(frame.getFrameData()).isNull(); } @Test public void messageArrayFrame() { SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), "m1", "m2"); assertThat(frame.getContent()).isEqualTo("a[\"m1\",\"m2\"]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.MESSAGE); assertThat(frame.getFrameData()).isEqualTo("[\"m1\",\"m2\"]"); } @Test public void messageArrayFrameEmpty() { SockJsFrame frame = new SockJsFrame("a"); assertThat(frame.getContent()).isEqualTo("a[]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.MESSAGE); assertThat(frame.getFrameData()).isEqualTo("[]"); frame = new SockJsFrame("a[]"); assertThat(frame.getContent()).isEqualTo("a[]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.MESSAGE); assertThat(frame.getFrameData()).isEqualTo("[]"); } @Test public void closeFrame() { SockJsFrame frame = SockJsFrame.closeFrame(3000, "Go Away!"); assertThat(frame.getContent()).isEqualTo("c[3000,\"Go Away!\"]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.CLOSE); assertThat(frame.getFrameData()).isEqualTo("[3000,\"Go Away!\"]"); } @Test public void closeFrameEmpty() { SockJsFrame frame = new SockJsFrame("c"); assertThat(frame.getContent()).isEqualTo("c[]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.CLOSE); assertThat(frame.getFrameData()).isEqualTo("[]"); frame = new SockJsFrame("c[]"); assertThat(frame.getContent()).isEqualTo("c[]"); assertThat(frame.getType()).isEqualTo(SockJsFrameType.CLOSE); assertThat(frame.getFrameData()).isEqualTo("[]"); } }
package Visao.Consultar; public class ConsultarFuncionario { }
package com.cb.cbfunny.qb.task; import android.os.AsyncTask; import com.cb.cbfunny.qb.bean.Article; import com.cb.cbfunny.utils.ArticleGetUtils; import java.util.List; public class HomeAsyncTask extends AsyncTask<String, Void, List<Article>> { String type; HomeAsyncCallBack callBack; public HomeAsyncTask(String type,HomeAsyncCallBack callBack) { this.type = type; this.callBack = callBack; } public interface HomeAsyncCallBack{ public void beforeLoad(); public void afterLoad(List<Article> list); } @Override protected void onPreExecute() { callBack.beforeLoad(); super.onPreExecute(); } @Override protected List<Article> doInBackground(String... params) { try { return ArticleGetUtils.getArticleList(null, 1, type); } catch (Exception e) { return null; } } @Override protected void onPostExecute(List<Article> result) { callBack.afterLoad(result); super.onPostExecute(result); } }
package Parte02.calculadora; public class Calculadora { private double memoria = 0; public Calculadora(double memoria) { this.memoria = memoria; } public Calculadora() { } public double getMemoria() { return memoria; } public void setMemoria(double memoria) { this.memoria = memoria; } public double somar(double valor){ memoria = valor + memoria; return memoria; } public double subtrair(double valor){ memoria = memoria - valor; return memoria; } public double multiplicar(double valor){ memoria = memoria * valor; return memoria; } public double dividir(double valor){ memoria = memoria / valor; return memoria; } public double exibeMemoria(){ return memoria; } }
/* $Id$ */ package djudge.acmcontester; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import djudge.acmcontester.admin.AdminClient; import djudge.acmcontester.server.interfaces.AuthentificationDataProvider; import djudge.acmcontester.server.interfaces.TeamXmlRpcInterface; import djudge.acmcontester.structures.LanguageData; import djudge.acmcontester.structures.ProblemData; import djudge.utils.xmlrpc.HashMapSerializer; import utils.FileTools; public class JTestPanel extends JPanel implements ActionListener, Updateble { private static final long serialVersionUID = 1L; JComboBox jcbLanguages; JComboBox jcbProblems; JLabel glblLanguage; JLabel glblProblem; JTextField jtfFile; JLabel jlblFile; JButton jbtnChooseFile; JTextArea jtaSource; JButton jbtnSubmit; TeamXmlRpcInterface serverInterface; AuthentificationDataProvider authProvider; public JTestPanel(TeamXmlRpcInterface serverInterface, AuthentificationDataProvider authProvider) { this.serverInterface = serverInterface; this.authProvider = authProvider; setupGUI(); setVisible(true); } private void setupGUI() { jcbLanguages = new JComboBox(HashMapSerializer .deserializeFromHashMapArray(serverInterface.getTeamLanguages( authProvider.getUsername(), authProvider.getPassword()), LanguageData.class)); jcbLanguages.setPreferredSize(new Dimension(30, 30)); glblLanguage = new JLabel("Language"); jcbProblems = new JComboBox(HashMapSerializer .deserializeFromHashMapArray(serverInterface.getTeamProblems( authProvider.getUsername(), authProvider.getPassword()), ProblemData.class)); jcbProblems.setPreferredSize(new Dimension(30, 30)); glblProblem = new JLabel("Problem"); jtfFile = new JTextField(); jtfFile.setEnabled(false); jtfFile.setPreferredSize(new Dimension(25, 25)); jlblFile = new JLabel("File"); jbtnChooseFile = new JButton("Choose File"); jbtnChooseFile.addActionListener(this); jtaSource = new JTextArea(); jtaSource.setFont(new Font("Courier New", Font.PLAIN, 14)); JScrollPane tScrollPane = new JScrollPane(jtaSource); tScrollPane.setBorder(BorderFactory.createTitledBorder("Load or Paste Your Source")); jbtnSubmit = new JButton("Submit"); jbtnSubmit.addActionListener(this); setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.EAST; c.gridx = 3; c.gridy = 0; c.gridwidth = 7; c.gridheight = 1; c.weightx = 1; c.insets = new Insets(10, 10, 5, 5); add(jcbProblems, c); c.gridy = 1; add(jcbLanguages, c); c.gridy = 2; c.gridwidth = 3; add(jtfFile, c); c.gridx = 6; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; c.weightx = 0; add(jbtnChooseFile, c); c.gridx = 8; c.gridy = 2; c.gridwidth = 2; c.gridheight = 1; c.weightx = 0; add(jbtnSubmit, c); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 1; c.weightx = 0; add(glblProblem, c); c.gridy = 1; add(glblLanguage, c); c.gridy = 2; add(jlblFile, c); c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 3; c.gridwidth = 10; c.gridheight = 7; c.weightx = 2; c.weighty = 1; add(tScrollPane, c); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.EAST; c.gridx = 9; c.gridy = 10; c.gridwidth = 1; c.gridheight = 1; c.weightx = 0; c.weighty = 0; //add(jbtnSubmit, c); } private void doChooseFile() { FileDialog fd = new FileDialog((JFrame) null, "Open source", FileDialog.LOAD); fd.setVisible(true); if (fd.getFile() != null) { String filename = fd.getDirectory() + fd.getFile(); jtfFile.setText(filename); String content = FileTools.readFile(filename); jtaSource.setText(content); } } private void doSubmitSolution() { LanguageData ld = (LanguageData) jcbLanguages.getSelectedItem(); ProblemData pd = (ProblemData) jcbProblems.getSelectedItem(); if (JOptionPane.showConfirmDialog(this, "Do You Really Want to Test This Solution for\nProblem " + jcbProblems.getSelectedItem() + "\nin Language" + jcbLanguages.getSelectedItem() + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) { if (serverInterface.testSolution(authProvider.getUsername(), authProvider.getPassword(), pd.id, ld.id, jtaSource.getText())) { JOptionPane.showMessageDialog(this, "Submitted Ok"); } else { JOptionPane.showMessageDialog(this, "Error occured"); } } } @Override public void actionPerformed(ActionEvent arg0) { Object src = arg0.getSource(); if (src.equals(jbtnChooseFile)) { doChooseFile(); } else if (src.equals(jbtnSubmit)) { doSubmitSolution(); } } public static void main(String[] args) { new AdminClient(); } @Override public boolean updateState() { // TODO implement me return false; } }
package com.proxiad.games.extranet.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.proxiad.games.extranet.model.Room; @Repository public interface RoomRepository extends CrudRepository<Room, Integer> { List<Room> findAll(); Optional<Room> findByNameIgnoreCase(String name); @Query("Select r from Room r where r.connectedToken.token = :token") Optional<Room> findByToken(@Param("token") String token); }
package com.zxt.framework.page.dialect; import java.sql.Types; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.sql.JoinFragment; import org.hibernate.sql.OracleJoinFragment; import com.zxt.framework.common.log.LogHelper; /** * Title: Dialect Description: Oracle Dialect Create DateTime: 2010-9-29 * * @author xxl * @since v1.0 * */ public class OracleDialect extends Oracle9Dialect { private static final LogHelper log = new LogHelper(OracleDialect.class); /** * oracle方式 */ public OracleDialect() { super(); log .warn("The OracleDialect dialect has been deprecated; use Oracle8iDialect instead"); } public JoinFragment createOuterJoinFragment() { return new OracleJoinFragment(); } public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } /** * 获取分页 * @param sql * @param hasOffset * @return */ public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" for update")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); if (hasOffset) { pagingSelect .append("select * from ( select row_.*, rownum rownum_ from ( "); } else { pagingSelect.append("select * from ( "); } pagingSelect.append(sql); if (hasOffset) { pagingSelect.append(" ) row_ ) where rownum_ <= ? and rownum_ > ?"); } else { pagingSelect.append(" ) where rownum <= ?"); } if (isForUpdate) { pagingSelect.append(" for update"); } return pagingSelect.toString(); } public String getSelectClauseNullString(int sqlType) { switch (sqlType) { case Types.VARCHAR: case Types.CHAR: return "to_char(null)"; case Types.DATE: case Types.TIMESTAMP: case Types.TIME: return "to_date(null)"; default: return "to_number(null)"; } } public String getCurrentTimestampSelectString() { return "select sysdate from dual"; } public String getCurrentTimestampSQLFunctionName() { return "sysdate"; } }
package oo.abstraction; import java.util.Scanner; public class Ticket { int serialnumber; String name; String time; char area; int seat; int price; int status; public Ticket(String name, String time, char area, int seat){ this.name = name; this.time = time; this.area = area; this.seat = seat; } public void bookTicket(int s){ status = s; } public int changeSeat(int status){ if (status!=0){ Scanner scanner = new Scanner(System.in); System.out.println("請輸入您欲更換的座位號碼:"); String string = scanner.nextLine(); seat = Integer.parseInt(string); return seat; }else{ System.out.println("您尚未訂購票卷"); return status; } } public void cancelTicket(){ status = 0;//未訂票 } }
package com.bofsoft.laio.laiovehiclegps.Config; import com.bofsoft.sdk.exception.BaseExceptionType; public class ExceptionType extends BaseExceptionType { public ExceptionType(int id, String name) { super(id, name); } }
package numberPgms; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SampleArrayList { public static void main(String[] args) { List<String> li= new ArrayList<String>(); li.add("Siva"); li.add("bupalem"); li.add("Sivapavan"); li.add("ManiKiran"); long ler=li.stream().filter(s->s.contains("a")).count(); // li.stream().filter(s->s.length()>4).forEach(s->System.out.println("Greater Than 4 letters in string:"+s)); // li.stream().filter(s->s.length()>4).forEach(s->System.out.println("Greater Than 4 letters in string:"+s)); System.out.println("Duplciates check:"+ler); li.stream().filter(s->s.endsWith("n")).sorted().map(s->s.toUpperCase()).forEach(s->System.out.println(s)); li.stream().filter(s->s.endsWith("n")).sorted().forEach(s->System.out.println(s)); //List<Integer> liint= Arrays.asList(3,2,9,4,55,888,33); //String str=liint.toString(); } }
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; /** * The path to a type argument, wildcard bound, array element type, or static inner type within an * enclosing type. * * @author Eric Bruneton */ public final class TypePath { /** A type path step that steps into the element type of an array type. See {@link #getStep}. */ public static final int ARRAY_ELEMENT = 0; /** A type path step that steps into the nested type of a class type. See {@link #getStep}. */ public static final int INNER_TYPE = 1; /** A type path step that steps into the bound of a wildcard type. See {@link #getStep}. */ public static final int WILDCARD_BOUND = 2; /** A type path step that steps into a type argument of a generic type. See {@link #getStep}. */ public static final int TYPE_ARGUMENT = 3; /** * The byte array where the 'type_path' structure - as defined in the Java Virtual Machine * Specification (JVMS) - corresponding to this TypePath is stored. The first byte of the * structure in this array is given by {@link #typePathOffset}. * * @see <a * href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.2">JVMS * 4.7.20.2</a> */ private final byte[] typePathContainer; /** The offset of the first byte of the type_path JVMS structure in {@link #typePathContainer}. */ private final int typePathOffset; /** * Constructs a new TypePath. * * @param typePathContainer a byte array containing a type_path JVMS structure. * @param typePathOffset the offset of the first byte of the type_path structure in * typePathContainer. */ TypePath(final byte[] typePathContainer, final int typePathOffset) { this.typePathContainer = typePathContainer; this.typePathOffset = typePathOffset; } /** * Returns the length of this path, i.e. its number of steps. * * @return the length of this path. */ public int getLength() { // path_length is stored in the first byte of a type_path. return typePathContainer[typePathOffset]; } /** * Returns the value of the given step of this path. * * @param index an index between 0 and {@link #getLength()}, exclusive. * @return one of {@link #ARRAY_ELEMENT}, {@link #INNER_TYPE}, {@link #WILDCARD_BOUND}, or {@link * #TYPE_ARGUMENT}. */ public int getStep(final int index) { // Returns the type_path_kind of the path element of the given index. return typePathContainer[typePathOffset + 2 * index + 1]; } /** * Returns the index of the type argument that the given step is stepping into. This method should * only be used for steps whose value is {@link #TYPE_ARGUMENT}. * * @param index an index between 0 and {@link #getLength()}, exclusive. * @return the index of the type argument that the given step is stepping into. */ public int getStepArgument(final int index) { // Returns the type_argument_index of the path element of the given index. return typePathContainer[typePathOffset + 2 * index + 2]; } /** * Converts a type path in string form, in the format used by {@link #toString()}, into a TypePath * object. * * @param typePath a type path in string form, in the format used by {@link #toString()}. May be * {@literal null} or empty. * @return the corresponding TypePath object, or {@literal null} if the path is empty. */ public static TypePath fromString(final String typePath) { if (typePath == null || typePath.length() == 0) { return null; } int typePathLength = typePath.length(); ByteVector output = new ByteVector(typePathLength); output.putByte(0); int typePathIndex = 0; while (typePathIndex < typePathLength) { char c = typePath.charAt(typePathIndex++); if (c == '[') { output.put11(ARRAY_ELEMENT, 0); } else if (c == '.') { output.put11(INNER_TYPE, 0); } else if (c == '*') { output.put11(WILDCARD_BOUND, 0); } else if (c >= '0' && c <= '9') { int typeArg = c - '0'; while (typePathIndex < typePathLength) { c = typePath.charAt(typePathIndex++); if (c >= '0' && c <= '9') { typeArg = typeArg * 10 + c - '0'; } else if (c == ';') { break; } else { throw new IllegalArgumentException(); } } output.put11(TYPE_ARGUMENT, typeArg); } else { throw new IllegalArgumentException(); } } output.data[0] = (byte) (output.length / 2); return new TypePath(output.data, 0); } /** * Returns a string representation of this type path. {@link #ARRAY_ELEMENT} steps are represented * with '[', {@link #INNER_TYPE} steps with '.', {@link #WILDCARD_BOUND} steps with '*' and {@link * #TYPE_ARGUMENT} steps with their type argument index in decimal form followed by ';'. */ @Override public String toString() { int length = getLength(); StringBuilder result = new StringBuilder(length * 2); for (int i = 0; i < length; ++i) { switch (getStep(i)) { case ARRAY_ELEMENT: result.append('['); break; case INNER_TYPE: result.append('.'); break; case WILDCARD_BOUND: result.append('*'); break; case TYPE_ARGUMENT: result.append(getStepArgument(i)).append(';'); break; default: throw new AssertionError(); } } return result.toString(); } /** * Puts the type_path JVMS structure corresponding to the given TypePath into the given * ByteVector. * * @param typePath a TypePath instance, or {@literal null} for empty paths. * @param output where the type path must be put. */ static void put(final TypePath typePath, final ByteVector output) { if (typePath == null) { output.putByte(0); } else { int length = typePath.typePathContainer[typePath.typePathOffset] * 2 + 1; output.putByteArray(typePath.typePathContainer, typePath.typePathOffset, length); } } }
/** * @author taylor */ package br.com.lucro.server.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import br.com.lucro.server.controller.dto.CompanyDTO; import br.com.lucro.server.model.Company; import br.com.lucro.server.model.WebResponse; import br.com.lucro.server.model.WebResponseException; import br.com.lucro.server.service.CompanyService; import br.com.lucro.server.util.Utils; import br.com.lucro.server.util.enums.EnumWebResponse; /** * @author taylor * */ @RestController @RequestMapping(value="/app/user") public class UserController { @Autowired private HttpSession session; @Autowired private HttpServletRequest request; private static final Logger logger = LoggerFactory.getLogger(UserController.class); @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public WebResponse createUser(@RequestBody CompanyDTO companyParameters) throws WebResponseException, Exception { logger.info(String.format("Request for '%s' - From: %s:%d - Parameters: %s", request.getServletPath(), request.getRemoteAddr(), request.getRemotePort(), Utils.getMapParam(new Object[]{companyParameters}))); //Get application context WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext()); //Create web response object WebResponse web = new WebResponse(); //Get bean service CompanyService companyService = ctx.getBean(CompanyService.class); //Create company Company company = companyService.saveCompany(companyParameters.toCompany()); //Create successful response web.setMessage(EnumWebResponse.OK.name()); web.setStatus(EnumWebResponse.OK); //Create map response Map<String, Object> mapResponse = new HashMap<String, Object>(); mapResponse.put("company", company); //Set map response web.setResponse(mapResponse); return web; } }
package com.evlj.searchmovie.network.factory; import com.evlj.searchmovie.BuildConfig; import com.evlj.searchmovie.base.BaseFactory; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.OkHttpClient.Builder; import okhttp3.logging.HttpLoggingInterceptor; public abstract class ServiceFactory<T> extends BaseFactory<T> { public ServiceFactory(Class<T> clazz) { super(clazz); } @Override() public Builder createOkHttpClient() { OkHttpClient.Builder httpClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS); if (BuildConfig.DEBUG) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(logging); } return httpClient; } }
package controller.student.registration; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import configuration.EncryptandDecrypt; import configuration.YearLevelUp; import connection.DBConfiguration; /** * Servlet implementation class AdmissionCurriculumItemViewController */ @WebServlet("/Registrar/Controller/Registrar/Application/ApplicationCurriculumItems2") public class ApplicationCurriculumItems2 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ApplicationCurriculumItems2() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("plain/text"); EncryptandDecrypt ec = new EncryptandDecrypt(); String curcode = request.getParameter("curcode"); // String semester = request.getParameter("semester"); DBConfiguration db = new DBConfiguration(); Connection conn = db.getConnection(); YearLevelUp ylu = new YearLevelUp(); Statement stmnt = null; Statement stmnt2 = null; Statement stmnt3 = null; Statement stmnt4 = null; try { stmnt = conn.createStatement(); stmnt2 = conn.createStatement(); stmnt3 = conn.createStatement(); stmnt4 = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = ""; String sql2 = ""; JSONArray arr = new JSONArray(); JSONArray grouplist = new JSONArray(); JSONArray sched = new JSONArray(); JSONArray schedlist = new JSONArray(); JSONArray schedlist2 = new JSONArray(); PrintWriter out = response.getWriter(); // HttpSession session = request.getSession(); // String username = session.getAttribute("username").toString(); try { ResultSet rs; String sem = ""; rs = stmnt.executeQuery("SELECT Semester_ID FROM `r_semester` where Semester_Active_Flag = 'Active' "); while(rs.next()) sem = rs.getString("Semester_ID"); // sem = ec.decrypt(ec.key, ec.initVector, sem); sql = "SELECT * FROM `r_curriculumitem` inner join r_curriculum on CurriculumItem_CurriculumID = Curriculum_ID INNER JOIN r_curriculumyear ON CurriculumYear_ID = Curriculum_CurriculumYearID INNER JOIN r_subject as t1 ON CurriculumItem_SubjectID = Subject_ID WHERE Curriculum_CourseID = (SELECT Course_ID from r_course where Course_Code = '"+ec.encrypt(ec.key, ec.initVector, curcode)+"') and Curriculum_SemesterID = '"+sem+"' and Curriculum_YearLevel = 'First Year' and CurriculumItem_Display_Status = 'Active' and CurriculumYear_ID = (SELECT CurriculumYear_ID FROM `r_curriculumyear` where CurriculumYear_Ative_Flag = 'Active') order by (select count(*) from r_subject as er where er.Subject_Group = t1.Subject_ID) asc "; //out.print(sql+"\n"); rs = stmnt.executeQuery(sql); ResultSet rs2,rs3,rs4; while(rs.next()){ JSONObject obj = new JSONObject(); JSONObject group = new JSONObject(); JSONObject section = new JSONObject(); JSONObject schedule = new JSONObject(); JSONObject section2 = new JSONObject(); JSONObject schedule2 = new JSONObject(); sched = new JSONArray(); grouplist = new JSONArray(); obj.put("code", ec.decrypt(ec.key, ec.initVector, rs.getString("Subject_Code"))); obj.put("desc", ec.decrypt(ec.key, ec.initVector, rs.getString("Subject_Description"))); //out.print(sql2+"\n"); obj.put("tuition", rs.getString("Subject_Tuition_Hours")); obj.put("lec", rs.getString("Subject_Lecture_Hours")); obj.put("lab", rs.getString("Subject_Laboratory_Hours")); obj.put("units", rs.getString("Subject_Credited_Units")); String subid = rs.getString("Subject_ID"); String acadyear = ""; rs2 = stmnt2.executeQuery("SELECT Academic_Year_ID FROM `r_academic_year` where Academic_Year_Active_Flag = 'Present' "); while(rs2.next()) acadyear = rs2.getString("Academic_Year_ID"); sql2 = "SELECT Section_Code,Schedule_ID from r_curriculumitem inner join t_schedule on CurriculumItem_ID = Schedule_CurriculumItemID inner join r_curriculum on CurriculumItem_CurriculumID = Curriculum_ID inner join r_section on Schedule_SectionID = Section_ID where Curriculum_CurriculumYearID = (SELECT CurriculumYear_ID FROM `r_curriculumyear` where CurriculumYear_Ative_Flag = 'Active' ) and Curriculum_SemesterID = (SELECT Semester_ID FROM `r_semester` where Semester_Active_Flag = 'Active') and Schedule_AcademicYearID = '"+acadyear+"' and Schedule_Display_Status = 'Active' and CurriculumItem_SubjectID = '"+subid+"' and CurriculumItem_Display_Status = 'Active' "; rs2 = stmnt2.executeQuery(sql2); //out.print(sql2+"\n"); String schedid = ""; String sec= ""; while(rs2.next()){ schedlist = new JSONArray(); section = new JSONObject(); section.put("section", rs2.getString("Section_Code")); sec = rs2.getString("Section_Code"); schedid = rs2.getString("Schedule_ID"); String sql3 = "SELECT Schedule_Items_Date ,TIME_FORMAT(Schedule_Items_Time_Start, '%H:%i') tstart,TIME_FORMAT(Schedule_Items_Time_End, '%H:%i') AS tend,IFNULL(Room_Code,'TBA') AS ROOM FROM `t_schedule_items` left join r_room on Room_ID = Schedule_Items_RoomID WHERE Schedule_Items_Display_Status = 'Active' and Schedule_Items_ScheduleID = '"+schedid+"'"; //out.print(sql3+"\n"); rs3 = stmnt3.executeQuery(sql3); while(rs3.next()){ schedule = new JSONObject(); // schedule.put("section", rs2.getString("Section_Code")); String day = rs3.getString("Schedule_Items_Date"); String tstart = rs3.getString("tstart"); String tend = rs3.getString("tend"); String room = ""; if(!rs3.getString("ROOM").equals("TBA")) room = ec.decrypt(ec.key, ec.initVector, rs3.getString("ROOM")) ; else room = "TBA" ; schedule.put("schedule", day + " " + tstart + " " + tend +" "+ room ); schedlist.add(schedule); } section.put("sched", schedlist); sched.add(section); } obj.put("section", sched); sql2 = "SELECT * FROM `r_subject` AS T1 WHERE T1.Subject_Group = (SELECT T2.Subject_ID FROM r_subject AS T2 where T2.Subject_Code = '"+rs.getString("Subject_Code")+"' )"; //out.print(sql2+"\n"); rs2 = stmnt2.executeQuery(sql2); while(rs2.next()){ group = new JSONObject(); group.put("code", ec.decrypt(ec.key, ec.initVector, rs2.getString("Subject_Code"))); group.put("desc", ec.decrypt(ec.key, ec.initVector, rs2.getString("Subject_Description"))); group.put("units", rs2.getString("Subject_Credited_Units")); group.put("lec", rs2.getString("Subject_Lecture_Hours")); group.put("lab", rs2.getString("Subject_Laboratory_Hours")); group.put("tuition", rs2.getString("Subject_Tuition_Hours")); String subid2 = rs2.getString("Subject_ID"); String sql3 = "SELECT Section_Code,Schedule_ID from r_curriculumitem inner join t_schedule on CurriculumItem_ID = Schedule_CurriculumItemID inner join r_curriculum on CurriculumItem_CurriculumID = Curriculum_ID inner join r_section on Schedule_SectionID = Section_ID inner join r_subject on Subject_Group = CurriculumItem_SubjectID where Curriculum_CurriculumYearID = (SELECT CurriculumYear_ID FROM `r_curriculumyear` where CurriculumYear_Ative_Flag = 'Active' ) and Curriculum_SemesterID = (SELECT Semester_ID FROM `r_semester` where Semester_Active_Flag = 'Active') and Schedule_AcademicYearID = '"+acadyear+"' and Schedule_Display_Status = 'Active' and CurriculumItem_SubjectID = '"+subid+"' and CurriculumItem_Display_Status = 'Active' and Schedule_ChildrenID = '"+subid2+"' group by Section_Code "; //out.print(sql3+"\n"); schedlist2 = new JSONArray(); section2 = new JSONObject(); rs3 = stmnt3.executeQuery(sql3); sec = ""; schedule2 = new JSONObject(); JSONArray finalsched = new JSONArray(); while(rs3.next()){ JSONObject schedholder = new JSONObject(); schedule2 = new JSONObject(); schedid = rs3.getString("Schedule_ID"); String sql4 = "SELECT Schedule_Items_Date ,TIME_FORMAT(Schedule_Items_Time_Start, '%H:%i') tstart,TIME_FORMAT(Schedule_Items_Time_End, '%H:%i') AS tend,IFNULL(Room_Code,'TBA') AS ROOM FROM `t_schedule_items` inner join t_schedule on Schedule_ID = Schedule_Items_ScheduleID left join r_room on Room_ID = Schedule_Items_RoomID inner join r_section on Schedule_SectionID = Section_ID WHERE Schedule_Items_Display_Status = 'Active' and Schedule_Items_ScheduleID = '"+schedid+"' and Schedule_ChildrenID = '"+subid2+"' "; rs4 = stmnt4.executeQuery(sql4); JSONArray grpsched = new JSONArray(); while(rs4.next()){ String day = rs4.getString("Schedule_Items_Date"); String tstart = rs4.getString("tstart"); String tend = rs4.getString("tend"); String room = ""; if(!rs4.getString("ROOM").equals("TBA")) room = ec.decrypt(ec.key, ec.initVector, rs4.getString("ROOM")) ; else room = "TBA" ; grpsched.add( day + " " + tstart + " " + tend +" "+ room ); } schedule2.put("datetime", grpsched); schedholder.put("section", rs3.getString("Section_Code")); schedholder.put("schedule", schedule2); finalsched.add(schedholder); //out.print(finalsched); } group.put("schedule", finalsched); grouplist.add(group); } obj.put("group", grouplist); arr.add(obj); } out.print(arr); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
// Generated from /Users/yurkiss/IdeaProjects/AntlrSample/src/org/yurkiss/antlr/Formulas.g4 by ANTLR 4.5.3 package org.yurkiss.antlr.formulas; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.ATN; import org.antlr.v4.runtime.atn.ATNDeserializer; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.tree.ParseTreeVisitor; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.List; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FormulasParser extends Parser { static { RuntimeMetaData.checkVersion("4.5.3", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int IDENTIFIER=1, STRING=2, QUOT=3, NUMBER=4, DIGIT=5, AMP=6, ADD=7, MINUS=8, MUL=9, DIV=10, POWER=11, PERCENT=12, ABS=13, EXCL=14, COLON=15, COMMA=16, DOT=17, SEMI=18, LPAR=19, RPAR=20, EQ=21, NEQ=22, LTEQ=23, GTEQ=24, GT=25, LT=26, AND_OP=27, OR_OP=28, WS=29; public static final int RULE_expr = 0, RULE_function = 1, RULE_qualifiedName = 2, RULE_literal = 3; public static final String[] ruleNames = { "expr", "function", "qualifiedName", "literal" }; private static final String[] _LITERAL_NAMES = { null, null, null, "'\"'", null, null, "'&'", "'+'", "'-'", "'*'", "'/'", "'^'", "'%'", "'$'", "'!'", "':'", "','", "'.'", "';'", "'('", "')'", null, null, "'<='", "'>='", "'>'", "'<'", "'&&'", "'||'" }; private static final String[] _SYMBOLIC_NAMES = { null, "IDENTIFIER", "STRING", "QUOT", "NUMBER", "DIGIT", "AMP", "ADD", "MINUS", "MUL", "DIV", "POWER", "PERCENT", "ABS", "EXCL", "COLON", "COMMA", "DOT", "SEMI", "LPAR", "RPAR", "EQ", "NEQ", "LTEQ", "GTEQ", "GT", "LT", "AND_OP", "OR_OP", "WS" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "Formulas.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public FormulasParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class ExprContext extends ParserRuleContext { public ExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expr; } public ExprContext() { } public void copyFrom(ExprContext ctx) { super.copyFrom(ctx); } } public static class UnarContext extends ExprContext { public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode MINUS() { return getToken(FormulasParser.MINUS, 0); } public UnarContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitUnar(this); else return visitor.visitChildren(this); } } public static class LiterContext extends ExprContext { public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public LiterContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitLiter(this); else return visitor.visitChildren(this); } } public static class MulDivContext extends ExprContext { public Token op; public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode MUL() { return getToken(FormulasParser.MUL, 0); } public TerminalNode DIV() { return getToken(FormulasParser.DIV, 0); } public MulDivContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitMulDiv(this); else return visitor.visitChildren(this); } } public static class AddSubContext extends ExprContext { public Token op; public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode ADD() { return getToken(FormulasParser.ADD, 0); } public TerminalNode MINUS() { return getToken(FormulasParser.MINUS, 0); } public AddSubContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitAddSub(this); else return visitor.visitChildren(this); } } public static class ParensContext extends ExprContext { public TerminalNode LPAR() { return getToken(FormulasParser.LPAR, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode RPAR() { return getToken(FormulasParser.RPAR, 0); } public ParensContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitParens(this); else return visitor.visitChildren(this); } } public static class ComparisonORContext extends ExprContext { public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode OR_OP() { return getToken(FormulasParser.OR_OP, 0); } public ComparisonORContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitComparisonOR(this); else return visitor.visitChildren(this); } } public static class NameContext extends ExprContext { public QualifiedNameContext qualifiedName() { return getRuleContext(QualifiedNameContext.class,0); } public NameContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitName(this); else return visitor.visitChildren(this); } } public static class ComparisonAndContext extends ExprContext { public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode AND_OP() { return getToken(FormulasParser.AND_OP, 0); } public ComparisonAndContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitComparisonAnd(this); else return visitor.visitChildren(this); } } public static class ConcatenationContext extends ExprContext { public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode AMP() { return getToken(FormulasParser.AMP, 0); } public ConcatenationContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitConcatenation(this); else return visitor.visitChildren(this); } } public static class ComparisonContext extends ExprContext { public Token op; public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode GT() { return getToken(FormulasParser.GT, 0); } public TerminalNode LT() { return getToken(FormulasParser.LT, 0); } public TerminalNode LTEQ() { return getToken(FormulasParser.LTEQ, 0); } public TerminalNode GTEQ() { return getToken(FormulasParser.GTEQ, 0); } public ComparisonContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitComparison(this); else return visitor.visitChildren(this); } } public static class FunctionCallContext extends ExprContext { public FunctionContext function() { return getRuleContext(FunctionContext.class,0); } public FunctionCallContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitFunctionCall(this); else return visitor.visitChildren(this); } } public static class ComparisonEqualsContext extends ExprContext { public Token op; public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode EQ() { return getToken(FormulasParser.EQ, 0); } public TerminalNode NEQ() { return getToken(FormulasParser.NEQ, 0); } public ComparisonEqualsContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitComparisonEquals(this); else return visitor.visitChildren(this); } } public static class PowerContext extends ExprContext { public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode POWER() { return getToken(FormulasParser.POWER, 0); } public PowerContext(ExprContext ctx) { copyFrom(ctx); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitPower(this); else return visitor.visitChildren(this); } } public final ExprContext expr() throws RecognitionException { return expr(0); } private ExprContext expr(int _p) throws RecognitionException { ParserRuleContext _parentctx = _ctx; int _parentState = getState(); ExprContext _localctx = new ExprContext(_ctx, _parentState); ExprContext _prevctx = _localctx; int _startState = 0; enterRecursionRule(_localctx, 0, RULE_expr, _p); int _la; try { int _alt; enterOuterAlt(_localctx, 1); { setState(18); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,0,_ctx) ) { case 1: { _localctx = new UnarContext(_localctx); _ctx = _localctx; _prevctx = _localctx; { setState(9); match(MINUS); } setState(10); expr(13); } break; case 2: { _localctx = new FunctionCallContext(_localctx); _ctx = _localctx; _prevctx = _localctx; setState(11); function(); } break; case 3: { _localctx = new NameContext(_localctx); _ctx = _localctx; _prevctx = _localctx; setState(12); qualifiedName(); } break; case 4: { _localctx = new LiterContext(_localctx); _ctx = _localctx; _prevctx = _localctx; setState(13); literal(); } break; case 5: { _localctx = new ParensContext(_localctx); _ctx = _localctx; _prevctx = _localctx; setState(14); match(LPAR); setState(15); expr(0); setState(16); match(RPAR); } break; } _ctx.stop = _input.LT(-1); setState(46); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,2,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( _parseListeners!=null ) triggerExitRuleEvent(); _prevctx = _localctx; { setState(44); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,1,_ctx) ) { case 1: { _localctx = new ConcatenationContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(20); if (!(precpred(_ctx, 12))) throw new FailedPredicateException(this, "precpred(_ctx, 12)"); setState(21); match(AMP); setState(22); expr(13); } break; case 2: { _localctx = new PowerContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(23); if (!(precpred(_ctx, 11))) throw new FailedPredicateException(this, "precpred(_ctx, 11)"); setState(24); match(POWER); setState(25); expr(12); } break; case 3: { _localctx = new MulDivContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(26); if (!(precpred(_ctx, 10))) throw new FailedPredicateException(this, "precpred(_ctx, 10)"); setState(27); ((MulDivContext)_localctx).op = _input.LT(1); _la = _input.LA(1); if ( !(_la==MUL || _la==DIV) ) { ((MulDivContext)_localctx).op = (Token)_errHandler.recoverInline(this); } else { consume(); } setState(28); expr(11); } break; case 4: { _localctx = new AddSubContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(29); if (!(precpred(_ctx, 9))) throw new FailedPredicateException(this, "precpred(_ctx, 9)"); setState(30); ((AddSubContext)_localctx).op = _input.LT(1); _la = _input.LA(1); if ( !(_la==ADD || _la==MINUS) ) { ((AddSubContext)_localctx).op = (Token)_errHandler.recoverInline(this); } else { consume(); } setState(31); expr(10); } break; case 5: { _localctx = new ComparisonContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(32); if (!(precpred(_ctx, 8))) throw new FailedPredicateException(this, "precpred(_ctx, 8)"); setState(33); ((ComparisonContext)_localctx).op = _input.LT(1); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << LTEQ) | (1L << GTEQ) | (1L << GT) | (1L << LT))) != 0)) ) { ((ComparisonContext)_localctx).op = (Token)_errHandler.recoverInline(this); } else { consume(); } setState(34); expr(9); } break; case 6: { _localctx = new ComparisonEqualsContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(35); if (!(precpred(_ctx, 7))) throw new FailedPredicateException(this, "precpred(_ctx, 7)"); setState(36); ((ComparisonEqualsContext)_localctx).op = _input.LT(1); _la = _input.LA(1); if ( !(_la==EQ || _la==NEQ) ) { ((ComparisonEqualsContext)_localctx).op = (Token)_errHandler.recoverInline(this); } else { consume(); } setState(37); expr(8); } break; case 7: { _localctx = new ComparisonAndContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(38); if (!(precpred(_ctx, 6))) throw new FailedPredicateException(this, "precpred(_ctx, 6)"); { setState(39); match(AND_OP); } setState(40); expr(7); } break; case 8: { _localctx = new ComparisonORContext(new ExprContext(_parentctx, _parentState)); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(41); if (!(precpred(_ctx, 5))) throw new FailedPredicateException(this, "precpred(_ctx, 5)"); { setState(42); match(OR_OP); } setState(43); expr(6); } break; } } } setState(48); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,2,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { unrollRecursionContexts(_parentctx); } return _localctx; } public static class FunctionContext extends ParserRuleContext { public TerminalNode IDENTIFIER() { return getToken(FormulasParser.IDENTIFIER, 0); } public TerminalNode LPAR() { return getToken(FormulasParser.LPAR, 0); } public TerminalNode RPAR() { return getToken(FormulasParser.RPAR, 0); } public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public List<TerminalNode> COMMA() { return getTokens(FormulasParser.COMMA); } public TerminalNode COMMA(int i) { return getToken(FormulasParser.COMMA, i); } public FunctionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_function; } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitFunction(this); else return visitor.visitChildren(this); } } public final FunctionContext function() throws RecognitionException { FunctionContext _localctx = new FunctionContext(_ctx, getState()); enterRule(_localctx, 2, RULE_function); int _la; try { enterOuterAlt(_localctx, 1); { setState(49); match(IDENTIFIER); setState(50); match(LPAR); setState(59); _la = _input.LA(1); if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << IDENTIFIER) | (1L << STRING) | (1L << NUMBER) | (1L << MINUS) | (1L << ABS) | (1L << LPAR))) != 0)) { { setState(51); expr(0); setState(56); _errHandler.sync(this); _la = _input.LA(1); while (_la==COMMA) { { { setState(52); match(COMMA); setState(53); expr(0); } } setState(58); _errHandler.sync(this); _la = _input.LA(1); } } } setState(61); match(RPAR); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class QualifiedNameContext extends ParserRuleContext { public List<TerminalNode> IDENTIFIER() { return getTokens(FormulasParser.IDENTIFIER); } public TerminalNode IDENTIFIER(int i) { return getToken(FormulasParser.IDENTIFIER, i); } public QualifiedNameContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_qualifiedName; } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitQualifiedName(this); else return visitor.visitChildren(this); } } public final QualifiedNameContext qualifiedName() throws RecognitionException { QualifiedNameContext _localctx = new QualifiedNameContext(_ctx, getState()); enterRule(_localctx, 4, RULE_qualifiedName); int _la; try { int _alt; enterOuterAlt(_localctx, 1); { setState(64); _la = _input.LA(1); if (_la==ABS) { { setState(63); match(ABS); } } setState(66); match(IDENTIFIER); setState(71); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,6,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { { { setState(67); match(DOT); setState(68); match(IDENTIFIER); } } } setState(73); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,6,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LiteralContext extends ParserRuleContext { public TerminalNode STRING() { return getToken(FormulasParser.STRING, 0); } public TerminalNode NUMBER() { return getToken(FormulasParser.NUMBER, 0); } public LiteralContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_literal; } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof FormulasVisitor ) return ((FormulasVisitor<? extends T>)visitor).visitLiteral(this); else return visitor.visitChildren(this); } } public final LiteralContext literal() throws RecognitionException { LiteralContext _localctx = new LiteralContext(_ctx, getState()); enterRule(_localctx, 6, RULE_literal); int _la; try { enterOuterAlt(_localctx, 1); { setState(74); _la = _input.LA(1); if ( !(_la==STRING || _la==NUMBER) ) { _errHandler.recoverInline(this); } else { consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 0: return expr_sempred((ExprContext)_localctx, predIndex); } return true; } private boolean expr_sempred(ExprContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 12); case 1: return precpred(_ctx, 11); case 2: return precpred(_ctx, 10); case 3: return precpred(_ctx, 9); case 4: return precpred(_ctx, 8); case 5: return precpred(_ctx, 7); case 6: return precpred(_ctx, 6); case 7: return precpred(_ctx, 5); } return true; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\37O\4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\5\2\25\n\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2/\n\2\f\2\16\2\62\13\2\3\3\3\3\3\3\3\3\3"+ "\3\7\39\n\3\f\3\16\3<\13\3\5\3>\n\3\3\3\3\3\3\4\5\4C\n\4\3\4\3\4\3\4\7"+ "\4H\n\4\f\4\16\4K\13\4\3\5\3\5\3\5\2\3\2\6\2\4\6\b\2\7\3\2\13\f\3\2\t"+ "\n\3\2\31\34\3\2\27\30\4\2\4\4\6\6Z\2\24\3\2\2\2\4\63\3\2\2\2\6B\3\2\2"+ "\2\bL\3\2\2\2\n\13\b\2\1\2\13\f\7\n\2\2\f\25\5\2\2\17\r\25\5\4\3\2\16"+ "\25\5\6\4\2\17\25\5\b\5\2\20\21\7\25\2\2\21\22\5\2\2\2\22\23\7\26\2\2"+ "\23\25\3\2\2\2\24\n\3\2\2\2\24\r\3\2\2\2\24\16\3\2\2\2\24\17\3\2\2\2\24"+ "\20\3\2\2\2\25\60\3\2\2\2\26\27\f\16\2\2\27\30\7\b\2\2\30/\5\2\2\17\31"+ "\32\f\r\2\2\32\33\7\r\2\2\33/\5\2\2\16\34\35\f\f\2\2\35\36\t\2\2\2\36"+ "/\5\2\2\r\37 \f\13\2\2 !\t\3\2\2!/\5\2\2\f\"#\f\n\2\2#$\t\4\2\2$/\5\2"+ "\2\13%&\f\t\2\2&\'\t\5\2\2\'/\5\2\2\n()\f\b\2\2)*\7\35\2\2*/\5\2\2\t+"+ ",\f\7\2\2,-\7\36\2\2-/\5\2\2\b.\26\3\2\2\2.\31\3\2\2\2.\34\3\2\2\2.\37"+ "\3\2\2\2.\"\3\2\2\2.%\3\2\2\2.(\3\2\2\2.+\3\2\2\2/\62\3\2\2\2\60.\3\2"+ "\2\2\60\61\3\2\2\2\61\3\3\2\2\2\62\60\3\2\2\2\63\64\7\3\2\2\64=\7\25\2"+ "\2\65:\5\2\2\2\66\67\7\22\2\2\679\5\2\2\28\66\3\2\2\29<\3\2\2\2:8\3\2"+ "\2\2:;\3\2\2\2;>\3\2\2\2<:\3\2\2\2=\65\3\2\2\2=>\3\2\2\2>?\3\2\2\2?@\7"+ "\26\2\2@\5\3\2\2\2AC\7\17\2\2BA\3\2\2\2BC\3\2\2\2CD\3\2\2\2DI\7\3\2\2"+ "EF\7\23\2\2FH\7\3\2\2GE\3\2\2\2HK\3\2\2\2IG\3\2\2\2IJ\3\2\2\2J\7\3\2\2"+ "\2KI\3\2\2\2LM\t\6\2\2M\t\3\2\2\2\t\24.\60:=BI"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
/* * Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 2016, 2017-2020 Peter G. Horvath, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.blausql; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public final class Version { public static final String VERSION_STRING; private static final String VERSION_PROPERTIES_FILE = "version.properties"; private static final String VERSION_STRING_KEY = "version"; private static final String UNKNOWN_VERSION_STRING = "(unknown)"; private static final Logger LOGGER = Logger.getLogger(Version.class.getName()); static { Properties properties = new Properties(); try (InputStream is = Version.class.getResourceAsStream(VERSION_PROPERTIES_FILE)) { if (is != null) { properties.load(is); } else { LOGGER.log(Level.SEVERE, "Cannot establish version. File not found on classpath: " + VERSION_PROPERTIES_FILE); } } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Cannot establish version. Could not load properties file from classpath: " + VERSION_PROPERTIES_FILE, t); } VERSION_STRING = properties.getProperty(Version.VERSION_STRING_KEY, UNKNOWN_VERSION_STRING); } private Version() { // static utility class -- no instances allowed } }
package com.example.front_end_of_clean_up_the_camera_app.UserFragment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.support.design.widget.TabLayout; import com.example.front_end_of_clean_up_the_camera_app.Adapter.CUHOrderFragmentAdapter; import com.example.front_end_of_clean_up_the_camera_app.R; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class CUHOrderFragment extends Fragment { @BindView(R.id.cuh_order_tabLayout) TabLayout tabLayout; @BindView(R.id.cuh_order_viewPager) ViewPager viewPager; private CUHOrderFragmentAdapter adapter; private List<String> titles; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initTitles(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_user_home_order_layout,container, false); ButterKnife.bind(this, view); adapter = new CUHOrderFragmentAdapter(getChildFragmentManager()); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); adapter.setList(titles); tabLayout.getTabAt(0).setIcon(R.drawable.waiting_pay_icon); tabLayout.getTabAt(1).setIcon(R.drawable.waiting_server_icon); tabLayout.getTabAt(2).setIcon(R.drawable.had_send_icon); tabLayout.getTabAt(3).setIcon(R.drawable.order_history_icon); return view; } private void initTitles(){ titles = new ArrayList<>(); titles.add("待付款"); titles.add("待接单"); titles.add("进行中"); titles.add("所有订单"); } }
package com.example.olawr.assignment1; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { ImageButton im; Button add1, add2, add3, add4; Button remove1, remove2, remove3, remove4; Button cal; boolean changed = false; RelativeLayout layout; TextView tv1, tv2, tv3, tv4, tv5, totalcost; int fullcount = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0; double vat = 1, cost; RadioButton r1, r2, r3; CheckBox cb1; EditText et1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); add1 = (Button) findViewById(R.id.button1); add2 = (Button) findViewById(R.id.button3); add3 = (Button) findViewById(R.id.button5); add4 = (Button) findViewById(R.id.button7); remove1 = (Button) findViewById(R.id.button2); remove2 = (Button) findViewById(R.id.button4); remove3 = (Button) findViewById(R.id.button6); remove4 = (Button) findViewById(R.id.button8); cal = (Button) findViewById(R.id.button9); layout = (RelativeLayout) findViewById(R.id.screen1); im = (ImageButton) findViewById(R.id.imageButton); tv1 = (TextView) findViewById(R.id.textview6); tv2 = (TextView) findViewById(R.id.textview7); tv3 = (TextView) findViewById(R.id.textview8); tv4 = (TextView) findViewById(R.id.textview9); tv5 = (TextView) findViewById(R.id.textview12); r1 = (RadioButton) findViewById(R.id.radiobutton1); r1.setChecked(true); tv5.setTextColor(Color.RED); im.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!changed) { layout.setBackgroundColor(Color.GREEN); changed = true; } else { layout.setBackgroundColor(Color.WHITE); changed = false; } } }); } public void addclick1(View v) { if (fullcount < 5) { fullcount++; count1++; tv1.setText("" + count1); } else { tv5.setVisibility(View.VISIBLE); } } public void addclick2(View v) { if (fullcount < 5) { fullcount++; count2++; tv2.setText("" + count2); } else { tv5.setVisibility(View.VISIBLE); } } public void addclick3(View v) { if (fullcount < 5) { fullcount++; count3++; tv3.setText("" + count3); } else { tv5.setVisibility(View.VISIBLE); } } public void addclick4(View v) { if (fullcount < 5) { fullcount++; count4++; tv4.setText("" + count4); } else { tv5.setVisibility(View.VISIBLE); } } public void removeclick1(View v) { if (fullcount > 0 && count1 > 0) { fullcount--; count1--; tv1.setText("" + count1); tv5.setVisibility(View.INVISIBLE); } } public void removeclick2(View v) { if (fullcount > 0 && count2 > 0) { fullcount--; count2--; tv2.setText("" + count2); tv5.setVisibility(View.INVISIBLE); } } public void removeclick3(View v) { if (fullcount > 0 && count3 > 0) { fullcount--; count3--; tv3.setText("" + count3); tv5.setVisibility(View.INVISIBLE); } } public void removeclick4(View v) { if (fullcount > 0 && count4 > 0) { fullcount--; count4--; tv4.setText("" + count4); tv5.setVisibility(View.INVISIBLE); } } public void calculate(View v) { r2 = (RadioButton) findViewById(R.id.radiobutton2); r3 = (RadioButton) findViewById(R.id.radiobutton3); cb1 = (CheckBox) findViewById(R.id.checkbox1); et1 = (EditText) findViewById(R.id.edittext1); totalcost = (TextView) findViewById(R.id.textview13); if (cb1.isChecked()) { vat = 0.2; } else { vat = 0; } cost = (count1 * 50) + (count2 * 100) + (count3 * 150) + (count4 * 200); cost = cost + (cost * vat); String cc = et1.getText().toString(); if (cc.equals("COMP3606DISC005")) { cost = cost - (cost * 0.05); } else if (cc.equals("COMP3606DISC010")) { cost = cost - (cost * 0.1); } if (cost != 0) { if (r1.isChecked()) { cost += 4.95; } else if (r2.isChecked()) { cost += 5.95; } else { cost++; } } totalcost.setText("" + cost); } }
package org.kiworkshop.jdbcapi; import org.kiworkshop.dao.MemberDao; import org.kiworkshop.domain.Member; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class MemberDaoJdbcApiImpl implements MemberDao { private DataSource dataSource; public MemberDaoJdbcApiImpl(DataSource dataSource) { this.dataSource = dataSource; } @Override public void insert(Member member) { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO member (id, name, point) VALUES (?, ?, ?)") ) { preparedStatement.setLong(1, member.getId()); preparedStatement.setString(2, member.getName()); preparedStatement.setDouble(3, member.getPoint()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public void update(Member member) { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE member SET name=?, point=? WHERE id=?") ) { preparedStatement.setString(1, member.getName()); preparedStatement.setDouble(2, member.getPoint()); preparedStatement.setLong(3, member.getId()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public void delete(Member member) { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM member WHERE id=?") ) { preparedStatement.setLong(1, member.getId()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public void deleteAll() { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM member") ) { preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public Member findById(Long id) { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM member WHERE id=?") ) { preparedStatement.setLong(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Long idFromDB = resultSet.getLong(1); String name = resultSet.getString(2); Double point = resultSet.getDouble(3); return new Member(idFromDB, name, point); } throw new RuntimeException("멤버가 존재하지 않습니다"); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public List<Member> findAll() { try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM member") ) { ResultSet resultSet = preparedStatement.executeQuery(); List<Member> members = new ArrayList<>(); while (resultSet.next()) { Long id = resultSet.getLong(1); String name = resultSet.getString(2); Double point = resultSet.getDouble(3); members.add(new Member(id, name, point)); } return members; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); } } private Connection getConnection() { return DataSourceUtils.getConnection(dataSource); } }
package be.mxs.common.util.pdf.general; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.pdf.PDFBasic; import be.mxs.common.util.system.Pointer; import be.mxs.common.util.system.ScreenHelper; import be.openclinic.pharmacy.ProductStock; import be.openclinic.pharmacy.ServiceStock; import be.openclinic.pharmacy.Batch; import be.openclinic.pharmacy.Product; import net.admin.User; import com.itextpdf.text.*; import com.itextpdf.text.Font; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfPCell; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayOutputStream; import java.util.*; import java.awt.*; import java.text.DecimalFormat; import java.text.SimpleDateFormat; /** * User: stijn smets * Date: 24-jan-2007 */ public class PDFInventoryUpdateGenerator extends PDFBasic { // declarations private final int pageWidth = 90; private boolean bPrintAll = false; //--- CONSTRUCTOR -------------------------------------------------------------------------------------------------- public PDFInventoryUpdateGenerator(User user, String sProject){ this.user = user; this.sProject = sProject; doc = new Document(); } //--- GENERATE PDF DOCUMENT BYTES ---------------------------------------------------------------------------------- public ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, ServiceStock serviceStock, String printLanguage) throws Exception { ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter docWriter = PdfWriter.getInstance(doc,baosPDF); this.req = req; this.sPrintLanguage = printLanguage; this.bPrintAll = ("1".equalsIgnoreCase(ScreenHelper.checkString(req.getParameter("printall")))); try{ doc.addProducer(); doc.addAuthor(user.person.firstname+" "+user.person.lastname); doc.addCreationDate(); doc.addCreator("OpenClinic Software"); doc.setPageSize(PageSize.A4); doc.open(); // add content to document addPageHeader(serviceStock); printInventoryUpdate(serviceStock); } catch(Exception e){ baosPDF.reset(); e.printStackTrace(); } finally{ if(doc!=null) doc.close(); if(docWriter!=null) docWriter.close(); } if(baosPDF.size() < 1){ throw new DocumentException("document has no bytes"); } return baosPDF; } //############################################# PRIVATE METHODS #################################################### //--- ADD PAGE HEADER ---------------------------------------------------------------------------------------------- private void addPageHeader(ServiceStock serviceStock) throws Exception { table = new PdfPTable(4); table.setWidthPercentage(pageWidth); // page title table.addCell(createTitle(ScreenHelper.getTranNoLink("web","inventoryupdatelist",sPrintLanguage),4)); // service stock cell = createValueCell(ScreenHelper.getTranNoLink("web","serviceStock",sPrintLanguage),1); cell.setBackgroundColor(new BaseColor(245,245,245)); // light grey table.addCell(cell); table.addCell(createValueCell(serviceStock.getName(),3)); // print date cell = createValueCell(ScreenHelper.getTranNoLink("web","printdate",sPrintLanguage),1); cell.setBackgroundColor(new BaseColor(245,245,245)); // light grey table.addCell(cell); table.addCell(createValueCell(ScreenHelper.fullDateFormat.format(new java.util.Date()),3)); doc.add(table); addBlankRow(); } //--- PRINT PRODUCT STOCK FICHE ------------------------------------------------------------------------------------ private void printInventoryUpdate(ServiceStock serviceStock){ try{ PdfPTable ficheTable = new PdfPTable(67); ficheTable.setWidthPercentage(pageWidth); //*** HEADER *** ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","code",sPrintLanguage),10)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","product",sPrintLanguage),22)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","batch",sPrintLanguage),7)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","theoretical",sPrintLanguage),7)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","physical",sPrintLanguage),7)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","difference",sPrintLanguage),7)); ficheTable.addCell(createTitleCell(ScreenHelper.getTranNoLink("web","value",sPrintLanguage),7)); String sClass = "1", sStockUid = "", sProductUid = "", sProductName = "", sStockBegin = ""; Product product; long day=24*3600*1000; double totalDiffVal=0; Hashtable productnames = Product.getProductNames(); Vector productstocks=serviceStock.getProductStocks(); for(int i=0; i<productstocks.size(); i++){ ProductStock productStock = (ProductStock)productstocks.elementAt(i); sStockUid = productStock.getUid(); if(productnames.get(productStock.getProductUid()) != null) { sProductName = (String)productnames.get(productStock.getProductUid()); sProductUid = productStock.getProductUid(); } else{ sProductName = getTran("web","nonexistingproduct"); } int stocklevel = productStock.getLevel(); boolean bHasNegative=false; //We must write a row for each batch with a level<>0 Vector batches = Batch.getAllBatches(productStock.getUid()); for(int n=0;n<batches.size();n++){ Batch batch = (Batch)batches.elementAt(n); String sPhysical=Pointer.getPointer("physical."+productStock.getUid()+"."+batch.getUid()); if(sPhysical.length()==0){ sPhysical=batch.getLevel()+""; } if((!sPhysical.equalsIgnoreCase(batch.getLevel()+"") || bPrintAll) && batch.getLevel()!=0){ stocklevel-=batch.getLevel(); cell = createValueCell(productStock.getProduct().getCode()+"",10); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(sProductName,22); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(batch.getBatchNumber(),7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(batch.getLevel()+"",7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(sPhysical,7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell((Double.parseDouble(sPhysical)-batch.getLevel())+"",7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); double value=productStock.getProduct().getLastYearsAveragePrice(); double difval=(Double.parseDouble(sPhysical)-batch.getLevel())*value; totalDiffVal+=difval; cell = createValueCell(new DecimalFormat(MedwanQuery.getInstance().getConfigString("priceFormat","#")).format(difval),7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); } } if(stocklevel!=0){ String sPhysical=Pointer.getPointer("physical."+productStock.getUid()); if(sPhysical.length()==0){ sPhysical=stocklevel+""; } if((!sPhysical.equalsIgnoreCase(stocklevel+"") || bPrintAll)){ cell = createValueCell(productStock.getProduct().getCode()+"",10); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(sProductName,22); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell("?",7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(stocklevel+"",7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell(sPhysical,7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); cell = createValueCell((Double.parseDouble(sPhysical)-stocklevel)+"",7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); double value=productStock.getProduct().getLastYearsAveragePrice(); double difval=(Double.parseDouble(sPhysical)-stocklevel)*value; totalDiffVal+=difval; cell = createValueCell(new DecimalFormat(MedwanQuery.getInstance().getConfigString("priceFormat","#")).format(difval),7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); } } } cell = emptyCell(60); cell.setBorder(PdfPCell.NO_BORDER); ficheTable.addCell(cell); cell = createValueCell(new DecimalFormat(MedwanQuery.getInstance().getConfigString("priceFormat","#")).format(totalDiffVal),7); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); ficheTable.addCell(cell); doc.add(ficheTable); } catch(Exception e){ e.printStackTrace(); } } //################################### UTILITY FUNCTIONS ############################################################ //--- CREATE TITLE ------------------------------------------------------------------------------------------------- protected PdfPCell createTitle(String msg, int colspan){ cell = new PdfPCell(new Paragraph(msg,FontFactory.getFont(FontFactory.HELVETICA,10,Font.UNDERLINE))); cell.setColspan(colspan); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setPaddingBottom(20); return cell; } //--- CREATE BORDERLESS CELL --------------------------------------------------------------------------------------- protected PdfPCell createBorderlessCell(String value, int height, int colspan){ cell = new PdfPCell(new Paragraph(value,FontFactory.getFont(FontFactory.HELVETICA,7,Font.NORMAL))); cell.setPaddingTop(height); // cell.setColspan(colspan); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_TOP); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); return cell; } protected PdfPCell createBorderlessCell(String value, int colspan){ return createBorderlessCell(value,3,colspan); } protected PdfPCell createBorderlessCell(int colspan){ cell = new PdfPCell(); cell.setColspan(colspan); cell.setBorder(PdfPCell.NO_BORDER); return cell; } }
package ru.mcfr.oxygen.framework.operations.highlight; import ro.sync.ecss.extensions.api.*; import ro.sync.ecss.extensions.api.highlights.AuthorPersistentHighlighter; /** * Operation used to remove all persistent highlights. */ public class RemoveAllHighlightsOperation implements AuthorOperation { /** * @see ro.sync.ecss.extensions.api.AuthorOperation#doOperation(ro.sync.ecss.extensions.api.AuthorAccess, ro.sync.ecss.extensions.api.ArgumentsMap) */ public void doOperation(AuthorAccess authorAccess, ArgumentsMap args) throws IllegalArgumentException, AuthorOperationException { AuthorPersistentHighlighter highlighter = authorAccess.getEditorAccess().getPersistentHighlighter(); int highlights = highlighter.getHighlights().length; // Remove all highlights highlighter.removeAllHighlights(); authorAccess.getWorkspaceAccess().showInformationMessage(highlights == 1 ? "1 highlight removed" : highlights + " highlights removed"); } /** * @see ro.sync.ecss.extensions.api.AuthorOperation#getArguments() */ public ArgumentDescriptor[] getArguments() { return null; } /** * @see ro.sync.ecss.extensions.api.Extension#getDescription() */ public String getDescription() { return "Remove all persistent highlights"; } }
package com.yuan.library.bannerdialog; /** * yuan * 2020/2/23 **/ public interface OnImageClickListener { void onImageClick(int index); }
package com.legaoyi.protocol.down.messagebody; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.common.util.JsonUtil; import com.legaoyi.protocol.exception.IllegalMessageException; import com.legaoyi.protocol.message.MessageBody; import com.legaoyi.protocol.util.SpringBeanUtil; /** * 行驶记录采集命令 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8700_2013" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT808_8700_2013_MessageBody extends MessageBody { private static final long serialVersionUID = -3928873466655778218L; public static final String MESSAGE_ID = "8700"; public static final String HEAD_FLAG = "AA75"; /** 命令字,见GB/T19056中的相关定义的命令字,如01H、02H **/ @JsonProperty("commandWord") private String commandWord; public final String getCommandWord() { return commandWord; } public final void setCommandWord(String commandWord) { this.commandWord = commandWord; } @Override public MessageBody invoke(Object o) throws Exception { JTT808_8700_2013_MessageBody messageBody = null; if (o instanceof String) { messageBody = JsonUtil.convertStringToObject((String) o, JTT808_8700_2013_MessageBody.class); } else if (o instanceof Map) { messageBody = JsonUtil.convertStringToObject(JsonUtil.covertObjectToString(o), JTT808_8700_2013_MessageBody.class); } try { String messageId = MESSAGE_ID.concat("_").concat(messageBody.getCommandWord()); messageBody = (JTT808_8700_2013_MessageBody) SpringBeanUtil.getMessageBody(messageId, "2013"); if (o instanceof String) { messageBody = JsonUtil.convertStringToObject((String) o, messageBody.getClass()); } else if (o instanceof Map) { messageBody = JsonUtil.convertStringToObject(JsonUtil.covertObjectToString(o), messageBody.getClass()); } } catch (IllegalMessageException e) { } return messageBody; } }
package bcg.common.entity; import java.util.Date; public class BookInfo implements java.io.Serializable { private static final long serialVersionUID = 1L; // DB에서 불러올 부분 private String bookCode; private String title; private Double totalScore; private String imgurl; private int genreCode; private String wordCloud; private String graph; // api에서 불러올 부분 private String author; private String publisher; private String description; private int price; private Date pubdate; private Double satisfactionScore; private Double impressionScore; private Double legibilityScore; private Double compositionScore; private Double authorScore; private Double designScore; private Double usefulnessScore; // wordcloud와 graph는 resource에 저장해 놓고 불러오기(wordcloud_xxx, graph_xxx) // mapkey: classcode, mapvalue: classscore public BookInfo() { } public String getBookCode() { return bookCode; } public void setBookCode(String bookCode) { this.bookCode = bookCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Double getTotalScore() { return totalScore; } public void setTotalScore(Double totalScore) { this.totalScore = totalScore; } public String getImgurl() { return imgurl; } public void setImgurl(String imgurl) { this.imgurl = imgurl; } public int getGenreCode() { return genreCode; } public void setGenreCode(int genreCode) { this.genreCode = genreCode; } public String getWordCloud() { return wordCloud; } public void setWordCloud(String wordCloud) { this.wordCloud = wordCloud; } public String getGraph() { return graph; } public void setGraph(String graph) { this.graph = graph; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Date getPubdate() { return pubdate; } public void setPubdate(Date pubdate) { this.pubdate = pubdate; } public Double getSatisfactionScore() { return satisfactionScore; } public void setSatisfactionScore(Double satisfactionScore) { this.satisfactionScore = satisfactionScore; } public Double getImpressionScore() { return impressionScore; } public void setImpressionScore(Double impressionScore) { this.impressionScore = impressionScore; } public Double getLegibilityScore() { return legibilityScore; } public void setLegibilityScore(Double legibilityScore) { this.legibilityScore = legibilityScore; } public Double getCompositionScore() { return compositionScore; } public void setCompositionScore(Double compositionScore) { this.compositionScore = compositionScore; } public Double getAuthorScore() { return authorScore; } public void setAuthorScore(Double authorScore) { this.authorScore = authorScore; } public Double getDesignScore() { return designScore; } public void setDesignScore(Double designScore) { this.designScore = designScore; } public Double getUsefulnessScore() { return usefulnessScore; } public void setUsefulnessScore(Double usefulnessScore) { this.usefulnessScore = usefulnessScore; } @Override public String toString() { return "BookInfo [bookCode=" + bookCode + ", title=" + title + ", totalScore=" + totalScore + ", imgurl=" + imgurl + ", genreCode=" + genreCode + ", wordCloud=" + wordCloud + ", graph=" + graph + ", author=" + author + ", publisher=" + publisher + ", description=" + description + ", price=" + price + ", pubdate=" + pubdate + ", satisfactionScore=" + satisfactionScore + ", impressionScore=" + impressionScore + ", legibilityScore=" + legibilityScore + ", compositionScore=" + compositionScore + ", authorScore=" + authorScore + ", designScore=" + designScore + ", usefulnessScore=" + usefulnessScore + "]"; } }
/* * 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.beans.factory.support; import java.lang.reflect.Method; import org.junit.jupiter.api.Test; import org.springframework.util.function.ThrowingBiFunction; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link InstanceSupplier}. * * @author Phillip Webb */ class InstanceSupplierTests { private final RegisteredBean registeredBean = RegisteredBean .of(new DefaultListableBeanFactory(), "test"); @Test void getWithoutRegisteredBeanThrowsException() { InstanceSupplier<String> supplier = registeredBean -> "test"; assertThatIllegalStateException().isThrownBy(() -> supplier.get()) .withMessage("No RegisteredBean parameter provided"); } @Test void getWithExceptionWithoutRegisteredBeanThrowsException() { InstanceSupplier<String> supplier = registeredBean -> "test"; assertThatIllegalStateException().isThrownBy(() -> supplier.getWithException()) .withMessage("No RegisteredBean parameter provided"); } @Test void getReturnsResult() throws Exception { InstanceSupplier<String> supplier = registeredBean -> "test"; assertThat(supplier.get(this.registeredBean)).isEqualTo("test"); } @Test void andThenWhenFunctionIsNullThrowsException() { InstanceSupplier<String> supplier = registeredBean -> "test"; ThrowingBiFunction<RegisteredBean, String, String> after = null; assertThatIllegalArgumentException().isThrownBy(() -> supplier.andThen(after)) .withMessage("'after' function must not be null"); } @Test void andThenAppliesFunctionToObtainResult() throws Exception { InstanceSupplier<String> supplier = registeredBean -> "bean"; supplier = supplier.andThen( (registeredBean, string) -> registeredBean.getBeanName() + "-" + string); assertThat(supplier.get(this.registeredBean)).isEqualTo("test-bean"); } @Test void andThenWhenInstanceSupplierHasFactoryMethod() throws Exception { Method factoryMethod = getClass().getDeclaredMethod("andThenWhenInstanceSupplierHasFactoryMethod"); InstanceSupplier<String> supplier = InstanceSupplier.using(factoryMethod, () -> "bean"); supplier = supplier.andThen( (registeredBean, string) -> registeredBean.getBeanName() + "-" + string); assertThat(supplier.get(this.registeredBean)).isEqualTo("test-bean"); assertThat(supplier.getFactoryMethod()).isSameAs(factoryMethod); } @Test void ofSupplierWhenInstanceSupplierReturnsSameInstance() { InstanceSupplier<String> supplier = registeredBean -> "test"; assertThat(InstanceSupplier.of(supplier)).isSameAs(supplier); } @Test void usingSupplierAdaptsToInstanceSupplier() throws Exception { InstanceSupplier<String> instanceSupplier = InstanceSupplier.using(() -> "test"); assertThat(instanceSupplier.get(this.registeredBean)).isEqualTo("test"); } @Test void ofInstanceSupplierAdaptsToInstanceSupplier() throws Exception { InstanceSupplier<String> instanceSupplier = InstanceSupplier .of(registeredBean -> "test"); assertThat(instanceSupplier.get(this.registeredBean)).isEqualTo("test"); } }
package com.android.myvirtualnutritionist.ui.diary.nutrition; public class NutrientsTableDataModel { private String nutrientsName; private String total; private String goal; private String left; public NutrientsTableDataModel(String nutrientsName, String total, String goal, String left) { this.nutrientsName = nutrientsName; this.total = total; this.goal = goal; this.left = left; } public String getNutrientsName() { return nutrientsName; } public String getTotal() { return total; } public String getGoal() { return goal; } public String getLeft() { return left; } }
package cafe.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import cafe.interfaces.iOrmMethods; import cafe.model.dao.CafeOrm; import cafe.model.entities.Supplier; @RestController @EnableAutoConfiguration @ImportResource("classpath:beans.xml") public class CafeWebController { @Autowired iOrmMethods cafe; // what is this for static RestTemplate restTemplate = new RestTemplate(); static String url = "http://localhost:8080/"; @RequestMapping(value = "getSupplier/{id}", method = RequestMethod.GET) public Supplier getSupplierById(@PathVariable int id) { return cafe.getSupplierById(id); } public static void main(String[] args) { SpringApplication.run(CafeWebController.class, args); } }
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.contrib.mqtt.impl; import com.hazelcast.function.FunctionEx; import com.hazelcast.function.SupplierEx; import com.hazelcast.jet.core.Processor; import com.hazelcast.jet.retry.IntervalFunction; import com.hazelcast.jet.retry.RetryStrategy; import com.hazelcast.logging.ILogger; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class SinkContext<T> { private static final long WAIT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(5); private final ILogger logger; private final String topic; private final IMqttAsyncClient client; private final RetryStrategy retryStrategy; private final FunctionEx<T, MqttMessage> messageFn; public SinkContext( Processor.Context context, String broker, String clientId, String topic, SupplierEx<MqttConnectOptions> connectOpsFn, RetryStrategy retryStrategy, FunctionEx<T, MqttMessage> messageFn ) throws MqttException { this.logger = context.logger(); this.topic = topic; this.retryStrategy = retryStrategy; this.messageFn = messageFn; this.client = client(context, broker, clientId, connectOpsFn.get()); } public void publish(T item) throws MqttException, InterruptedException { MqttMessage message = messageFn.apply(item); int maxAttempts = retryStrategy.getMaxAttempts(); IntervalFunction intervalFunction = retryStrategy.getIntervalFunction(); if (maxAttempts < 0) { // try indefinitely maxAttempts = Integer.MAX_VALUE; } else if (maxAttempts < Integer.MAX_VALUE) { // maxAttempts=0 means try once and don't retry again // so we add the actual try to maxAttempts maxAttempts++; } MqttException lastException = null; for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { client.publish(topic, message).waitForCompletion(WAIT_TIMEOUT_MILLIS); return; } catch (MqttException exception) { lastException = exception; logger.warning(String.format("Exception while publishing %s to %s, current attempt: %d", item, topic, attempt), exception); MILLISECONDS.sleep(intervalFunction.waitAfterAttempt(attempt)); } } throw lastException; } public void close() throws MqttException { try { client.disconnect().waitForCompletion(); } catch (MqttException exception) { logger.warning("Exception when disconnecting", exception); } client.close(); } private IMqttAsyncClient client(Processor.Context context, String broker, String clientId, MqttConnectOptions connectOptions) throws MqttException { clientId = clientId + "-" + context.globalProcessorIndex(); IMqttAsyncClient client = new MqttAsyncClient(broker, clientId, new ConcurrentMemoryPersistence()); client.connect(connectOptions).waitForCompletion(); return client; } }
package org.shazhi.businessEnglishMicroCourse.repository; import org.shazhi.businessEnglishMicroCourse.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.io.Serializable; import java.util.List; public interface UserRepository extends JpaRepository<UserEntity, Integer>, JpaSpecificationExecutor<UserEntity>, Serializable { UserEntity getUserEntityByUserName(String userName); @Query("select user from UserEntity user where user.userName = :username") UserEntity getProfileByUsername(@Param("username") String username); List<UserEntity> findUserEntitiesByUserEmail(String userEmail); List<UserEntity> findUserEntitiesByUserName(String userName); }
package Lab4; import java.util.Scanner; /** * 4th task - how many times repeat some symbol * * @author anri6a * */ public class RepeatSymb { private static Scanner workString; public static void main(String[] args) { workString = new Scanner(System.in); System.out.println("Enter String for Work"); String enterStr = workString.nextLine(); workString.close(); int symbArr[] = new int[255]; for (int i = 0; i < enterStr.length(); i++) { symbArr[enterStr.charAt(i)]++; } for (int i = 0; i < 255; i++) { if (symbArr[i] > 1) { System.out.println((char) i + " - repeat " + symbArr[i] + " times"); } } } }
package com.springboot.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.springboot.demo.model.Mathang; public interface MathangRepository extends JpaRepository<Mathang, Long> { }
package com.sobev.OpLock.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @ToString @AllArgsConstructor @NoArgsConstructor public class Person { private String id; private String name; private Integer gender; private String addr; }
package com.example.myapplication.Database; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "task_table") public class Task { @PrimaryKey(autoGenerate = true) int id; String task_name; String task_desc; int hour; int min; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTask_name() { return task_name; } public void setTask_name(String task_name) { this.task_name = task_name; } public String getTask_desc() { return task_desc; } public void setTask_desc(String task_desc) { this.task_desc = task_desc; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } public int getMin() { return min; } public void setMin(int min) { this.min = min; } }
package proeza.sah.desktop.listener.light; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.digi.xbee.api.exceptions.XBeeException; import com.guiBuilder.api.component.listener.GBEventListener; import com.guiBuilder.app.main.GBBeanFactory; import com.guiBuilder.core.GuiManager; import proeza.sah.radio.ILocalRadio; public class LightsSwitchListener extends GBEventListener implements ActionListener { private ILocalRadio radio = GBBeanFactory.getInstance().getBean(ILocalRadio.class); private static final String ON = "ON"; private static final String OFF = "OFF"; private boolean isOn; public LightsSwitchListener(GuiManager manager) { super(manager); } @Override public void actionPerformed(ActionEvent event) { try { if (this.isOn) { this.isOn = false; this.radio.sendBroadcast(OFF.getBytes()); } else { this.isOn = true; this.radio.sendBroadcast(ON.getBytes()); } } catch (XBeeException e) { e.printStackTrace(); } } public boolean isOn() { return this.isOn; } public void setOn(boolean isOn) { this.isOn = isOn; } }
package com.nuvu.backendtarjetas.rest; import com.nuvu.backendtarjetas.rest.security.entity.UsuarioPrincipal; import com.nuvu.backendtarjetas.rest.security.entity.Usuario; import com.nuvu.backendtarjetas.dtos.TarjetaDto; import com.nuvu.backendtarjetas.model.Tarjeta; import com.nuvu.backendtarjetas.repositories.TarjetaRepository; import com.nuvu.backendtarjetas.rest.security.repository.UsuarioRepository; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import org.slf4j.Logger; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/tarjetas") @CrossOrigin(origins = "*") //@PreAuthorize("permitAll()") @PreAuthorize("hasRole ('ROLE_USER')") public class TarjetaRest { private final static Logger logger = LoggerFactory.getLogger(TarjetaRest.class); @Autowired private TarjetaRepository tarjetaRepository; @Autowired UsuarioRepository usuarioRepository; @GetMapping // @PreAuthorize("permitAll()") @PreAuthorize("hasRole ('ROLE_USER')") public ResponseEntity<List<Tarjeta>> tarjetaResponseEntity(Authentication authentication) { List<Tarjeta> tarjetaList = tarjetaRepository.findAll(); return ResponseEntity.ok(tarjetaList); } @RequestMapping(value = "{tarjetaId}") // public ResponseEntity<Tarjeta> getTarjetaByIdPersona(@PathVariable("tarjetaId") Long id, Authentication authentication) { UsuarioPrincipal usuarioPrincipal = (UsuarioPrincipal) authentication.getPrincipal(); usuarioPrincipal.getUsuario(); Optional<Tarjeta> optionalTarjeta = tarjetaRepository.findById(id); return ResponseEntity.ok(optionalTarjeta.get()); } @PostMapping @PreAuthorize("hasRole ('ROLE_USER')") public ResponseEntity<Tarjeta> createTarjeta(@RequestBody TarjetaDto tarjetaDto, Authentication authentication) { System.out.println(authentication.getName()); Optional<Usuario> optionalUsuario = usuarioRepository.findByNombreUsuario(authentication.getName()); Optional<Tarjeta> optionalTarjeta = tarjetaRepository.findById(tarjetaDto.getNumeroTarjeta()); if (optionalTarjeta.isPresent()){ return ResponseEntity.noContent().build(); }else { Tarjeta tarjeta = new Tarjeta( tarjetaDto.getNumeroTarjeta(), tarjetaDto.getCvn(), tarjetaDto.getAñoVencimiento(), tarjetaDto.getMesVencimiento(), optionalUsuario.get()); System.out.println("Creando Tarjeta"); Tarjeta tarjetaNueva = tarjetaRepository.save(tarjeta); return ResponseEntity.ok(tarjetaNueva); } } @PutMapping @PreAuthorize("hasRole ('ROLE_USER')") public ResponseEntity<Tarjeta> updateTarjetaResponseEntity(@RequestBody TarjetaDto tarjetaDto, Authentication authentication) { Optional<Usuario> optionalUsuario = usuarioRepository.findByNombreUsuario(authentication.getName()); Optional<Tarjeta> optionalTarjeta = tarjetaRepository.findById(tarjetaDto.getNumeroTarjeta()); if (optionalTarjeta.isPresent()) { Tarjeta tarjeta = new Tarjeta( tarjetaDto.getNumeroTarjeta(), tarjetaDto.getCvn(), tarjetaDto.getAñoVencimiento(), tarjetaDto.getMesVencimiento(), optionalUsuario.get()); Tarjeta tarjetaUpdate = tarjetaRepository.save(tarjeta); System.out.println("Tarjeta Modificada"); return ResponseEntity.ok(tarjetaUpdate); } else { System.out.println("Tarjeta no Modificado"); return ResponseEntity.noContent().build(); } } @DeleteMapping(value = "{tarjetaId}") @PreAuthorize("hasRole ('ROLE_USER')") public ResponseEntity<Void> deleteLugar(@PathVariable("tarjetaId") Long id, Authentication authentication) { tarjetaRepository.deleteById(id); System.out.println("Eliminando Tarjeta"); return ResponseEntity.ok(null); } }
package com.nipaibao.config; import com.nipaibao.BuildConfig; public class Config { public static final long ONE_HOUR_MS = 60 * 60 * 1000; public static final long ONE_DAY_MS = 24 * ONE_HOUR_MS; public static final String SERVER_URL = "http://47.99.93.72/shop/"; public static final String GET_FILE_PARAMS = "eop/upload/getFile.do?fileName="; public static final String SPLASH_PARAMS = GET_FILE_PARAMS + "splash.dat"; }
package leetcode.HotLeetcode; /** * 翻转数字 * eg:1230 输出:321 * -12345 输出:-54321 */ public class ReverseInteger { public static void main(String[] args) { int n = 123405; // reverseInteger(n); System.out.println(reverseInteger(n)); System.out.println("数字翻转"); } public static int reverseInteger(int x){ int result = 0; while(x != 0){ int tail = x % 10; result = result * 10 + tail; x = x / 10; } return result; } }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-29 * Time: 上午9:54 * To change this template use File | Settings | File Templates. */ public class TestLazyPrimMST { public static void main(String[] args) { EdgeWeightedGraph G = new EdgeWeightedGraph(new In("mediumEWG.txt")); StdOut.println(G); MyLazyPrimMST mst = new MyLazyPrimMST(G); for(Edge e : mst.edges()) { StdOut.println(e); } StdOut.println(mst.weight()); } }
/** * © Copyright IBM Corporation 2020. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ import com.ibm.cloud.cloudant.v1.Cloudant; import com.ibm.cloud.cloudant.v1.model.DatabaseInformation; import com.ibm.cloud.cloudant.v1.model.Document; import com.ibm.cloud.cloudant.v1.model.GetDatabaseInformationOptions; import com.ibm.cloud.cloudant.v1.model.GetDocumentOptions; import com.ibm.cloud.cloudant.v1.model.ServerInformation; public class GetInfoFromExistingDatabase { public static void main(String[] args) { // 1. Create a Cloudant client with "EXAMPLES" service name =========== Cloudant client = Cloudant.newInstance("EXAMPLES"); // 2. Get server information ========================================== ServerInformation serverInformation = client .getServerInformation() .execute() .getResult(); System.out.println("Server Version: " + serverInformation.getVersion()); // 3. Get database information for "animaldb" ========================= String dbName = "animaldb"; GetDatabaseInformationOptions dbInformationOptions = new GetDatabaseInformationOptions.Builder(dbName).build(); DatabaseInformation dbInformationResponse = client .getDatabaseInformation(dbInformationOptions) .execute() .getResult(); // 4. Show document count in database ================================= Long documentCount = dbInformationResponse.getDocCount(); System.out.println("Document count in \"" + dbInformationResponse.getDbName() + "\" database is " + documentCount + "."); // 5. Get zebra document out of the database by document id =========== GetDocumentOptions getDocOptions = new GetDocumentOptions.Builder() .db(dbName) .docId("zebra") .build(); Document documentAboutZebra = client .getDocument(getDocOptions) .execute() .getResult(); System.out.println("Document retrieved from database:\n" + documentAboutZebra); } }
/* * 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 br.edu.ifpb.sd.task; import java.util.Scanner; /** * * @author natan */ public class EndTask implements Runnable { @Override public void run() { Scanner toRead = new Scanner(System.in); int n = toRead.nextInt(); System.exit(0); } }
package de.digitalstreich.Manufact.model; import de.digitalstreich.Manufact.model.auth.User; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import javax.persistence.*; import java.sql.Date; import java.util.List; @Entity @Table(name = "retailers") public class Retailer { @Id @Column(name = "user_id") private Long id; @OneToOne @MapsId @JoinColumn( name = "user_id", foreignKey = @ForeignKey(name = "fk_retailer_user") ) private User user; @Column(name = "name") private String name; @Column(name = "url", columnDefinition = "TEXT") private String url; @CreatedDate @Column(name = "created_at", columnDefinition = "DATETIME default CURRENT_TIMESTAMP") private Date createdAt; @LastModifiedDate @Column(name = "updated_at", columnDefinition = "DATETIME default CURRENT_TIMESTAMP") private Date updatedAt; @ManyToMany(mappedBy = "retailerList") private List<Productgroup> productgroupList; }
package com.qst.dms.gather; import java.util.ArrayList; import com.qst.dms.data.LogRecStore; import com.qst.dms.data.MatchedLogRecStore; import com.qst.dms.entity.DataBase; import com.qst.dms.entity.LogRec; import com.qst.dms.entity.MatchedLogRec; import com.qst.dms.exception.DataAnalyseException; /** * @author 陌意随影 TODO :日志分析类,继承DataFilter抽象类,实现数据分析接口 *2019年11月7日 下午7:05:42 */ public class LogRecAnalyse extends DataFilter implements IDataAnalyse { /**“登入”集合*/ private ArrayList<LogRec> logIns = new ArrayList<>(); /**“登出”集合*/ private ArrayList<LogRec> logOuts = new ArrayList<>(); @SuppressWarnings("javadoc") public LogRecAnalyse() { } @SuppressWarnings("javadoc") public LogRecAnalyse(ArrayList<LogRec> logRecs) { super(logRecs); } /** 实现DataFilter抽象类中的过滤抽象方法*/ public void doFilter() { // 获取数据集合 @SuppressWarnings("unchecked") ArrayList<LogRec> logs = (ArrayList<LogRec>) this.getDatas(); // 遍历,对日志数据进行过滤,根据日志登录状态分别放在不同的数组中 for (LogRec rec : logs) { if (rec.getLogType() == LogRec.LOG_IN) { // 添加到“登入”日志集合中 logIns.add(rec); } else if (rec.getLogType() == LogRec.LOG_OUT) { // 添加到“登出”日志集合中 logOuts.add(rec); } } } // 实现IDataAnalyse接口中数据分析方法 public ArrayList<MatchedLogRec> matchData() { // 创建日志匹配集合 ArrayList<MatchedLogRec> matchLogs = new ArrayList<>(); // 数据匹配分析 for (LogRec in : logIns) { for (LogRec out : logOuts) { if ((in.getUserName().equals(out.getUserName())) && (in.getIp().equals(out.getIp()))) { // 修改in和out日志状态类型为“匹配” in.setType(DataBase.MATHCH); out.setType(DataBase.MATHCH); // 添加到匹配集合中 matchLogs.add(new MatchedLogRec(in, out)); } } } //将暂时存储的记录清空 LogRecStore.getLogs().clear(); return matchLogs; } }
package JAVA9_EXERCISE1; public class Q2 implements AutoCloseable { public void display(){ System.out.println("displaying"); } @Override public void close() throws Exception { System.out.println("closing"); } public static void main(String[] args) throws Exception { try(Q2 obj=new Q2()){ obj.display(); } } }
package cn.jcera.fileservice.core.entity; import lombok.Data; @Data public class FastDFSFile { private String name; private byte[] content; private String ext; private String md5; private String author; private String height; }
package sop.web.management; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import dwz.framework.config.Constants; import dwz.framework.sys.exception.ServiceException; import dwz.framework.user.User; import dwz.framework.vo.Checker; import dwz.persistence.BaseConditionVO; import dwz.persistence.mapper.ItemMapper; import dwz.web.BaseController; import it.sauronsoftware.base64.Base64; import sop.persistence.beans.ItemType; import sop.persistence.beans.ItemDoc; import sop.services.ItemServiceMgr; import sop.util.DateUtils; import sop.util.Sys; import sop.utils.Common; import sop.services.ItemDocServiceMgr; /** * @Author: LCF * @Date: 2020/1/9 12:51 * @Package: sop.web.management */ @Controller("management.itemdocController") @RequestMapping(value = "/management/itemdoc") public class ItemDocController extends BaseController { @Autowired private ItemMapper itemMapper; @Autowired private ItemDocServiceMgr itemDocMgr; @RequestMapping("/list") public String index(BaseConditionVO vo, Model model) { List<ItemDoc> list = itemDocMgr.getItemDocListByCondition(vo); itemDocMgr.getItemDocListNum(vo); model.addAttribute("totalCount", vo.getTotalCount()); model.addAttribute("pageSize", vo.getPageSize()); model.addAttribute("vo", vo); model.addAttribute("list", list); model.addAttribute("itemTypes", itemMapper.getAllItemTypes()); return "/management/itemdoc/list"; } @RequestMapping("/uploadpicindex/{id}/{docNo}") public String uploadpicindex(@PathVariable("id") String id, @PathVariable("docNo") String docNo, Model model, HttpServletRequest request) { model.addAttribute("id", id); model.addAttribute("docNo", docNo); return "/management/itemdoc/uploadpic"; } @RequestMapping("/upload") public void upload(Model model, HttpServletRequest request, HttpServletResponse respone, @RequestParam(value = "myfile") MultipartFile multipartFile, @RequestParam(value = "docNo") String docNo) throws IOException { PrintWriter out = respone.getWriter(); if (multipartFile.getSize() > 0) { Map<String, String> ftpPropertiesMap = Common.getProperties("/ftpclient.properties"); String baselocation = ftpPropertiesMap.get("baselocation"); String picdir = ftpPropertiesMap.get("picdir"); InputStream fis = multipartFile.getInputStream(); String fileName = multipartFile.getOriginalFilename(); Checker checker = Common.down(fileName, fis, baselocation + "/" + picdir + "/" + docNo); out.println("<script>parent.callback(" + checker.isSuccess() + ", '" + checker.getReturnStr() + "')</script>"); } else { out.println("<script>parent.callback(false, '请选择图片')</script>"); } } @RequestMapping("/add") public String add(Model model) { model.addAttribute("itemTypes", itemMapper.getAllItemTypes()); ItemDoc pb = new ItemDoc(); pb.setDocNo("DN" + DateUtils.formatDateTime("yyMMddHHmmSS", Sys.getDate())); model.addAttribute("itemDoc", pb); return "/management/itemdoc/add"; } @RequestMapping(value = "/insert", method = RequestMethod.POST) public ModelAndView insert(ItemDoc itemDoc, HttpServletRequest request) { Checker checker = itemDocMgr.checkItemDoc(itemDoc); if (checker.isSuccess()) { User user = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY); if (user != null) { itemDoc.setCrtUsr(user.getUsrId()); itemDoc.setModUsr(user.getUsrId()); } else { itemDoc.setCrtUsr("test"); itemDoc.setModUsr("test"); } try { itemDocMgr.addItemDoc(itemDoc); } catch (ServiceException e) { //e.printStackTrace(); //return ajaxDoneError("Code 重复"); return this.update(itemDoc, request); } return ajaxDoneSuccess(getMessage("msg.operation.success")); } else { return ajaxDoneError(checker.getReturnStr()); } } @RequestMapping("/edit/{docNo}") public String edit(@PathVariable("docNo") String docNo, Model model) { //docNo = Base64.decode(docNo, "utf-8"); model.addAttribute("itemTypes", itemMapper.getAllItemTypes()); ItemDoc itemDoc = itemDocMgr.getItemDocByNo(docNo); model.addAttribute("itemDoc", itemDoc); return "/management/itemdoc/add"; } @RequestMapping("/delete/{docNo}") public ModelAndView delete(@PathVariable("docNo") String docNo, Model model) throws ServiceException { //docNo = Base64.decode(docNo, "utf-8"); itemDocMgr.deleteItemDoc(docNo); return ajaxDoneSuccess(getMessage("msg.operation.success")); } @RequestMapping("/update") public ModelAndView update(ItemDoc itemDoc, HttpServletRequest request) { User user = (User) request.getSession().getAttribute(Constants.AUTHENTICATION_KEY); if (user != null) { itemDoc.setModUsr(user.getUsrId()); } else { itemDoc.setModUsr("test"); } try { itemDocMgr.updateItemDoc(itemDoc); } catch (ServiceException e) { e.printStackTrace(); return ajaxDoneError(e.getMessage()); } return ajaxDoneSuccess(getMessage("msg.operation.success")); } }
package com.haku.light.input.mapping; public class EventScale { public final String name; public final float scale; public EventScale(String name, float scale) { this.name = name; this.scale = scale; } @Override public String toString() { return this.name + ' ' + this.scale; } }
package generator.util; public class Operators { private static String[] ARITHEMTIC_OPERATORS = {"+", "-", "/", "*"}; private static String[] RELATIONAL_OPERATORS = {">", "<", ">=", "<="}; private static String[] COMBINATIONAL_OPERATORS = {"and", "or"}; public static String randomArithmeticOperator() { return ARITHEMTIC_OPERATORS[(int) (Math.floor(Math.random() * ARITHEMTIC_OPERATORS.length))]; } public static String randomRelationalOperator() { return RELATIONAL_OPERATORS[(int) (Math.floor(Math.random() * RELATIONAL_OPERATORS.length))]; } public static String randomCombinationalOperator() { return COMBINATIONAL_OPERATORS[(int) (Math.floor(Math.random() * COMBINATIONAL_OPERATORS.length))]; } }
package com.lemon.controller; import com.lemon.entity.AppVersionEntity; import com.lemon.entity.CommonResult; import com.lemon.entity.UpdateAppBean; import com.lemon.service.AppVersionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @author LyuBo * @create 2021/8/26 21:12 */ @RestController public class VersionController { private static final Logger log = LoggerFactory.getLogger(VersionController.class); @Autowired private AppVersionService appVersionService; /** * 请求更新 * * @param versionCode * @return */ @GetMapping("/version/update") public CommonResult update(@RequestParam String versionCode) { // version只保留一条记录 UpdateAppBean updateAppBean = new UpdateAppBean(); if (appVersionService.findAll().size() == 0) { updateAppBean.setUpdate("No"); return new CommonResult(400, "还没发布新版本", updateAppBean); } else { if (appVersionService.findAll().get(0).getVersionCode() <= Integer.parseInt(versionCode)) { return new CommonResult(400, "已经是最新版本", updateAppBean); } else { AppVersionEntity appVersionEntity = appVersionService.findAll().get(0); updateAppBean.setUpdate("Yes"); updateAppBean.setUpdate_log(appVersionEntity.getChangeLog()); updateAppBean.setApk_file_url(appVersionEntity.getFileUrl()); updateAppBean.setNew_version(appVersionEntity.getVersionName()); return new CommonResult(200, "更新的版本", updateAppBean); } } } /** * 更新App版本信息 * * @param appVersionEntity * @return */ @PostMapping("/version/update") public CommonResult register(@RequestBody AppVersionEntity appVersionEntity) { log.info(appVersionEntity.toString()); if (appVersionService.findAll().size() == 0) { // 保存 appVersionService.saveVersion(appVersionEntity); return new CommonResult(400, "已插入", appVersionEntity); } else { // 更新 AppVersionEntity oldAppVersionEntity = appVersionService.findAll().get(0); if (appVersionEntity.getChangeLog() != null) { oldAppVersionEntity.setChangeLog(appVersionEntity.getChangeLog()); } oldAppVersionEntity.setVersionCode(appVersionEntity.getVersionCode()); oldAppVersionEntity.setVersionName(appVersionEntity.getVersionName()); if (appVersionEntity.getFileUrl() != null) { oldAppVersionEntity.setFileUrl(appVersionEntity.getFileUrl()); } appVersionService.saveVersion(oldAppVersionEntity); return new CommonResult(200, "已更新", oldAppVersionEntity); } } }
package com.maxkuzmenchuk.new_releases_bot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; @SpringBootApplication(scanBasePackages={"com.maxkuzmenchuk.new_releases_bot"}) public class NewReleasesBotApplication { private static final Logger logger = LoggerFactory.getLogger(NewReleasesBotApplication.class); public static void main(String[] args) { SpringApplication.run(NewReleasesBotApplication.class, args); } @Bean public void bot() { ApiContextInitializer.init(); TelegramBotsApi telegram = new TelegramBotsApi(); try { telegram.registerBot(new Bot()); logger.info("Bot initialized!"); } catch ( TelegramApiRequestException e) { e.printStackTrace(); } } }
package com.pronix.android.apssaataudit.services; import android.content.Context; import com.pronix.android.apssaataudit.common.Constants; import com.pronix.android.apssaataudit.models.WebServiceDO; /** * Created by ravi on 1/11/2018. */ public class AsyncTask extends android.os.AsyncTask<WebServiceDO, WebServiceDO, WebServiceDO> { OnTaskCompleted onTaskCompleted; String url; String requestType; String parameters; public AsyncTask(Context context, OnTaskCompleted onTaskCompleted, String url, String requestType, String parameres) { this.onTaskCompleted = onTaskCompleted; this.url = url; this.requestType = requestType; this.parameters = parameres; } @Override protected WebServiceDO doInBackground(WebServiceDO... webServiceDOS) { WebServiceDO webServiceDO = webServiceDOS[0]; try { webServiceDO = WebService.callWebService(url, requestType, parameters, webServiceDOS[0]); } catch (Exception e) { e.getMessage(); webServiceDO.result = Constants.EXCEPTION; webServiceDO.responseContent = "Error: " + e.getMessage(); } return webServiceDO; } @Override protected void onPostExecute(WebServiceDO webServiceDO) { super.onPostExecute(webServiceDO); onTaskCompleted.onTaskCompletes(webServiceDO); } }
public class NoSuchAccountException extends Exception { /** * */ private static final long serialVersionUID = 1L; public NoSuchAccountException() { super("Account not found! Check your userID and password!"); } }
package com.bruce.singleton.type2_ehanshi2; public class SingletonTest02 { public static void main(String[] args) { //todo more logics Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); System.out.println(s1==s2); System.out.println(s1.hashCode()+".."+s2.hashCode()); } } class Singleton{ //构造器私有化 private Singleton() { } private static Singleton instance; //在静态代码块 创建单例对象 static { instance=new Singleton(); } public static Singleton getInstance() { return instance; } }
import java.io.IOException; public class enemyShip1 extends ship{ public enemyShip1() throws IOException{ this.assetPath="sprites/Tank1.jpg"; this.defaultImage=this.get_image(this.assetPath); this.centerx=50; this.centery=40; this.width=230; this.height=250; this.showrooms=true; this.useCoords=false; this.tilesize=10; Room r1=new Room(0,1,5,8); this.addRoom(r1); Room r2=new Room(2,9,7,4); this.addRoom(r2); Room r3=new Room(8,3,4,6); this.addRoom(r3); Room r4=new Room(5,-1,5,4); this.addRoom(r4); system shield=new shieldSystem(1,5,1); } }
package myLabs; public class DelFixLengthWordStartWithConsonant { public static void main(String args[]) { String testStr = "sgfskj erty sfghksjv Gkjhsksvj cvbn jHjhkjvksv"; int siseOfWord = 4; /*Scanner enterString = new Scanner(System.in); System.out.println("Enter sentence for work"); String enterStr = enterString.nextLine(); enterString.close(); System.out.println("\nNew clear sentence will be"); System.out.println(enterStr.replaceAll("\\b[qwrtpsdfghjklzxcvbnm]{1}.{1}\\b", ""));*/ String[] wordsStr = testStr.split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < wordsStr.length; i++) { char firstLatter = wordsStr[i].charAt(0); if (!((wordsStr[i].length() == siseOfWord) && ((firstLatter != 'a') && (firstLatter != 'e') && (firstLatter != 'i') && (firstLatter != 'o') && (firstLatter != 'u') && (firstLatter != 'y')))) { sb.append(wordsStr[i]).append(" "); } } String outputStr = sb.toString().trim(); System.out.println(outputStr); } }
package ir.madreseplus.data.model.res; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class TicketDictRes { @SerializedName("clusters") @Expose private List<ClusterRes> clusters = null; @SerializedName("priority") @Expose private List<PriorityRes> priority = null; public List<ClusterRes> getClusters() { return clusters; } public void setClusters(List<ClusterRes> clusters) { this.clusters = clusters; } public List<PriorityRes> getPriority() { return priority; } public void setPriority(List<PriorityRes> priority) { this.priority = priority; } }
package net.MindTree.spring.boot.example.pojo; /** * @author prasa * */ public class Transaction { private Integer id; private String arrangementId; private String externalId; private String externalArrangementId; private String productId; private String reference; private String description; private String category; private String bookingDate; private String valueDate; private String currency; private String creditDebitIndicator; private String counterPartyName; private String instructedCurrency; private String counterPartyAccountNumber; private String status; private Float amount; private Float currencyExchangeRate; private Float instructedAmount; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getArrangementId() { return arrangementId; } public void setArrangementId(String arrangementId) { this.arrangementId = arrangementId; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getExternalArrangementId() { return externalArrangementId; } public void setExternalArrangementId(String externalArrangementId) { this.externalArrangementId = externalArrangementId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getBookingDate() { return bookingDate; } public void setBookingDate(String bookingDate) { this.bookingDate = bookingDate; } public String getValueDate() { return valueDate; } public void setValueDate(String valueDate) { this.valueDate = valueDate; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getCreditDebitIndicator() { return creditDebitIndicator; } public void setCreditDebitIndicator(String creditDebitIndicator) { this.creditDebitIndicator = creditDebitIndicator; } public String getCounterPartyName() { return counterPartyName; } public void setCounterPartyName(String counterPartyName) { this.counterPartyName = counterPartyName; } public String getInstructedCurrency() { return instructedCurrency; } public void setInstructedCurrency(String instructedCurrency) { this.instructedCurrency = instructedCurrency; } public String getCounterPartyAccountNumber() { return counterPartyAccountNumber; } public void setCounterPartyAccountNumber(String counterPartyAccountNumber) { this.counterPartyAccountNumber = counterPartyAccountNumber; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } public Float getCurrencyExchangeRate() { return currencyExchangeRate; } public void setCurrencyExchangeRate(Float currencyExchangeRate) { this.currencyExchangeRate = currencyExchangeRate; } public Float getInstructedAmount() { return instructedAmount; } public void setInstructedAmount(Float instructedAmount) { this.instructedAmount = instructedAmount; } }
package page.objects; import org.openqa.selenium.*; import org.openqa.selenium.WebDriver; public class LoginPage { /* Defining of final values for web paths */ private static final String LOGUSERNAME = "//input[@placeholder='korisničko ime']"; private static final String LOGPASSWORD = "//input[@placeholder='lozinka']"; private static final String LOGINBUTTON = "//input[@value='Uloguj se']"; private static final String LOGOUTBUTTON = "//a[@id='logoutBtn']"; /* User Login */ public static WebElement getLogUsername(WebDriver driver) { WebElement wb = driver.findElement(By.xpath(LOGUSERNAME)); return wb; } public static void clickLogUsername(WebDriver driver) { getLogUsername(driver).click(); } public static void SendKeysLogUsername(WebDriver driver, String str) { getLogUsername(driver).sendKeys(str); } /* User Password */ public static WebElement getLogPassword(WebDriver driver) { WebElement wb = driver.findElement(By.xpath(LOGPASSWORD)); return wb; } public static void clickLogPassword(WebDriver driver) { getLogPassword(driver).click(); } public static void SendKeysLogPassword(WebDriver driver, String str) { getLogPassword(driver).sendKeys(str); } /* Login Confirm */ public static WebElement getLoginButton(WebDriver driver) { WebElement wb = driver.findElement(By.xpath(LOGINBUTTON)); return wb; } public static void clickLoginButton(WebDriver driver) { getLoginButton(driver).click(); } /* User Logout */ public static WebElement getLogoutButton(WebDriver driver) { WebElement wb = driver.findElement(By.xpath(LOGOUTBUTTON)); return wb; } public static void clickLogoutButton(WebDriver driver) { getLogoutButton(driver).click(); } }
package com.messagesender.messagesender; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements Callback<DataModel> { private RecyclerView list; private TextView title; private TextView url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getRecipe(); list = findViewById(R.id.list); title = findViewById(R.id.title); url = findViewById(R.id.url); } private void getRecipe(){ Call<DataModel> call = Service.getApi().getRecipe(); call.enqueue(new Callback<DataModel>() { @Override public void onResponse(Call<DataModel> call, Response<DataModel> response) { DataModel dataModel = response.body(); title.setText(dataModel.getTitle()); url.setText(dataModel.getHref()); list.setLayoutManager(new LinearLayoutManager(getBaseContext())); RecipeAdapter adapter = new RecipeAdapter(); adapter.setList(dataModel.getResults()); list.setAdapter(adapter); list.getAdapter().notifyDataSetChanged(); } @Override public void onFailure(Call<DataModel> call, Throwable t) { t.getMessage(); } }); } @Override public void onResponse(Call<DataModel> call, Response<DataModel> response) { response.body(); } @Override public void onFailure(Call<DataModel> call, Throwable t) { } }
package com.springtraining.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class KintaiListEntity implements Serializable { private static final long serialVersionUID = 1L; @Id private String userId; private String userName; private String workHours; private String overTime; private String workingDay; private String lateDays; private String leaveEarlyDays; public static long getSerialversionuid() { return serialVersionUID; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getWorkHours() { return workHours; } public void setWorkHours(String workHours) { this.workHours = workHours; } public String getOverTime() { return overTime; } public void setOverTime(String overTime) { this.overTime = overTime; } public String getWorkingDay() { return workingDay; } public void setWorkingDay(String workingDay) { this.workingDay = workingDay; } public String getLateDays() { return lateDays; } public void setLateDays(String lateDays) { this.lateDays = lateDays; } public String getLeaveEarlyDays() { return leaveEarlyDays; } public void setLeaveEarlyDays(String leaveEarlyDays) { this.leaveEarlyDays = leaveEarlyDays; } }
package com.eshop.model.dao.impl; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.ArrayList; import com.eshop.model.dao.SQL; import com.eshop.model.dao.DBException; import com.eshop.model.dao.UsersDao; import com.eshop.model.dao.mapper.UserMapper; import com.eshop.model.dao.mapper.OrderMapper; import com.eshop.model.entity.User; import com.eshop.model.entity.Order; import java.util.logging.Logger; import java.util.logging.Level; public class JDBCUsersDao implements UsersDao { Logger logger = Logger.getLogger(JDBCUsersDao.class.getName()); Connection connection; public JDBCUsersDao (Connection connection) { this.connection = connection; } @Override public void create (User u) throws DBException { try (PreparedStatement stmt = connection.prepareStatement(SQL.INSERT_USER, Statement.RETURN_GENERATED_KEYS)) { int k = 1; stmt.setString(k++, u.getLogin()); stmt.setString(k++, u.getPassword()); stmt.setString(k++, u.getRole().toString()); stmt.execute(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { u.setId(rs.getLong(1)); } } } catch (SQLException sqle) { if (sqle.getErrorCode() == 1062) throw new DBException (DBException.NOT_UNIQUE_LOGIN, sqle); throw new DBException (DBException.CREATE_USER, sqle); } } @Override public User findById (long id) throws DBException { try (PreparedStatement stmt = connection.prepareStatement(SQL.SELECT_USER_BY_ID)) { stmt.setString(1, Long.toString(id)); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { User u = new UserMapper().extractFromResultSet(rs); return u; } else throw new DBException (DBException.USER_NOT_FOUND); } } catch (SQLException sqle) { logger.log(Level.WARNING, DBException.FIND_USER, sqle); throw new DBException (DBException.FIND_USER, sqle); } } @Override public User findByLogin (String login) throws DBException { try (PreparedStatement stmt = connection.prepareStatement(SQL.SELECT_USER_BY_LOGIN)) { stmt.setString(1, login); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { User u = new UserMapper().extractFromResultSet(rs); return u; } else throw new DBException (DBException.USER_NOT_FOUND); } } catch (SQLException sqle) { logger.log(Level.WARNING, DBException.FIND_USER, sqle); throw new DBException (DBException.FIND_USER, sqle); } } @Override public List <User> findAll () throws DBException { try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(SQL.SELECT_ALL_USERS)) { List <User> users = new ArrayList <> (); UserMapper mapper = new UserMapper (); while (rs.next()) { User u = mapper.extractFromResultSet(rs); users.add(u); } return users; } catch (SQLException sqle) { logger.log(Level.WARNING, DBException.FIND_USERS, sqle); throw new DBException (DBException.FIND_USERS, sqle); } } @Override public void update (User u) throws DBException { try (PreparedStatement stmt = connection.prepareStatement(SQL.UPDATE_USER)) { int k = 1; stmt.setString(k++, u.getLogin()); stmt.setString(k++, u.getPassword()); stmt.setString(k++, u.getState().toString()); stmt.setString(k++, u.getRole().toString()); stmt.setString(k++, Long.toString(u.getId())); stmt.execute(); } catch (SQLException sqle) { logger.log(Level.WARNING, DBException.UPDATE_USER, sqle); throw new DBException (DBException.UPDATE_USER, sqle); } } @Override public void delete (User u) throws DBException { try (PreparedStatement stmt = connection.prepareStatement(SQL.DELETE_USER)) { stmt.setString(1, Long.toString(u.getId())); stmt.execute(); } catch (SQLException sqle) { logger.log(Level.WARNING, DBException.DELETE_USER, sqle); throw new DBException (DBException.DELETE_USER, sqle); } } @Override public void close () { try { connection.close(); } catch (Exception e) { logger.log(Level.WARNING, DBException.CLOSE_CONNECTION, e); } } }
package com.codingchili.instance.controller; import com.codingchili.core.logging.Logger; import com.codingchili.core.protocol.Api; import com.codingchili.core.protocol.Serializer; import com.codingchili.instance.context.GameContext; import com.codingchili.instance.model.admin.AuthorizationException; import com.codingchili.instance.model.designer.DesignerRequest; import com.codingchili.instance.model.entity.PlayerCreature; import com.codingchili.instance.model.npc.SpawnEngine; import com.codingchili.instance.transport.InstanceRequest; import java.util.function.Consumer; /** * apply permissions * filter by inventory, no filter for admin :)) * use inventory "blueprints" or "sandbags " * add to configuration + persist async */ public class DesignHandler implements GameHandler { private GameContext game; private SpawnEngine spawner; public DesignHandler(GameContext game) { this.game = game; spawner = game.spawner(); } @Api public void modify(InstanceRequest request) { authorize(request, () -> { DesignerRequest designer = request.raw(DesignerRequest.class); switch (designer.getType()) { case SPAWN: spawner.add(designer); break; case DESPAWN: spawner.remove(designer); break; } }); } @Api public void npc_registry(InstanceRequest request) { authorize(request, () -> request.write(spawner.npcs().toBuffer())); } @Api public void structure_registry(InstanceRequest request) { authorize(request, () -> request.write(spawner.entities().toBuffer())); } private void authorize(InstanceRequest request, Runnable authorized) { if (game.instance().realm().isAdmin(request.account())) { authorized.run(); } else { request.error(new AuthorizationException()); } } }
package haircutter.bussinessmodel; import lombok.Getter; import lombok.Setter; import haircutter.bussinessmodel.*; public class UserModel { @Getter @Setter private Long id; @Getter @Setter private String email; @Getter @Setter private String password; @Getter @Setter private String firstName; @Getter @Setter private String lastName; }
package org.levelup.web.controllers; import org.levelup.dao.CategoryDao; import org.levelup.model.Article; import org.levelup.model.Category; import org.levelup.repositories.ArticleRepository; import org.levelup.repositories.CategoryRepository; import org.levelup.web.forms.CategoriesForm; import org.levelup.web.forms.VisibilityList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.levelup.web.AppConstants.*; @Controller public class AdminController { @Autowired private CategoryDao dao; @Autowired private CategoryRepository repository; @Autowired private ArticleRepository articleRepository; /* @ModelAttribute(CATEGORIES_FORM_ATTRIBUTE) public CategoriesForm createCategoriesForm() { return new CategoriesForm("", VisibilityType.PUBLIC); }*/ public VisibilityList createVisibilityList() { return new VisibilityList(); } @GetMapping(path = CRUD_CATEGORIES_PAGE) public String categories(ModelMap model) { List<Category> categories = dao.findAll(); model.addAttribute(CATEGORIES, categories); return CATEGORIES; } @GetMapping(path = CREATE_CATEGORY_PAGE) public String createCategoryPage(ModelMap model, @ModelAttribute(CATEGORIES_FORM_ATTRIBUTE) CategoriesForm form) { model.addAttribute(VISIBILITY_ATTRIBUTE, createVisibilityList()); return CREATE_CATEGORY; } @GetMapping("/admin/create-random-articles") public String createArticles(Model model) { Map<Category, List<Article>> catalog = new HashMap<>(); String text = "\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."; for (Category category : repository.findAll()) { for (int i = 1; i <= 3; i++) { articleRepository.save(new Article("Article-" + i, text, category)); catalog.put(category, null); } } catalog.replaceAll((c, v) -> articleRepository.findByCategory(c)); model.addAttribute("catalog", catalog); return ALL_ARTICLES; } @PostMapping(path = CREATE_CATEGORY_PAGE) public String create(ModelMap model, @ModelAttribute(CATEGORIES_FORM_ATTRIBUTE) CategoriesForm form, BindingResult validationResult) { model.addAttribute(VISIBILITY_ATTRIBUTE, createVisibilityList()); Category newCategory = new Category(); newCategory.setName(form.getName()); newCategory.setVisibility(form.getVisible()); try { dao.create(newCategory); } catch (Exception e) { validationResult.addError( new FieldError(CATEGORIES_FORM_ATTRIBUTE, "category name", "Category with name " + form.getName() + " is already registered.")); return CREATE_CATEGORY; } return REDIRECT + CATEGORIES; } }
package com.zaiou.web.controller.system; import com.zaiou.common.enums.ResultInfo; import com.zaiou.web.annotation.CurrentUserSeession; import com.zaiou.web.common.bean.CurrentUser; import com.zaiou.web.common.bean.RespBody; import com.zaiou.web.common.utils.R; import com.zaiou.web.service.system.UserService; import com.zaiou.web.validate.group.SaveValidate; import com.zaiou.web.vo.system.SysUserReq; import com.zaiou.web.vo.system.UserLoginReq; import com.zaiou.web.vo.system.UserLoginResp; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * @Description: 用户管理 * @auther: LB 2018/9/18 16:37 * @modify: LB 2018/9/18 16:37 */ @RestController @Slf4j @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 添加用户 * @param user * @param httpServletRequest * @param sysUserReq * @param result * @return */ @RequestMapping(value = "/addUser", method = { RequestMethod.POST }) public @ResponseBody RespBody addUser(@CurrentUserSeession CurrentUser user,HttpServletRequest httpServletRequest, @RequestBody @Validated(value = { SaveValidate.class }) SysUserReq sysUserReq, BindingResult result) { try { log.info("========用户添加开始========"); // req.setRoleName(SysRoleEnum.getMsgByCode(req.getRoleCode())); userService.addUser(sysUserReq, user); return R.info(ResultInfo.SUCCESS); } finally { log.info("========用户添加结束========"); } } /** * 用户登录 * @param httpServletRequest * @param result * @return * @throws Exception */ @RequestMapping(value = "/login", method = { RequestMethod.POST }) public @ResponseBody RespBody login(HttpServletRequest httpServletRequest, @RequestBody @Validated UserLoginReq userLoginReq, BindingResult result) { try { log.info("========用户登录开始========"); UserLoginResp loginResp = userService.login(userLoginReq); httpServletRequest.setAttribute("token", loginResp.getToken()); return R.success(loginResp); } finally { log.info("========用户登录结束========"); } } }
package PA165.language_school_manager.sample; /** * @author Viktor Slany */ public interface SampleDataLoadingFacade { void loadData(); }
package io.github.satr.aws.lambda.bookstore.repositories.localdatabase; // Copyright © 2020, github.com/satr, MIT License import io.github.satr.aws.lambda.bookstore.common.TestHelper; import io.github.satr.aws.lambda.bookstore.entity.Book; import io.github.satr.aws.lambda.bookstore.repositories.database.tableentity.BookSearchResultItem; import io.github.satr.aws.lambda.bookstore.test.ObjectMother; import org.junit.After; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /* * For each running test - the table "BookSearchResult" is created in the local DynamoDb instance and deleted afterwards * */ public class CustomerBooksRepositoryImplBookSearchResultForLocalDatabaseTest extends AbstractCustomerBooksRepositoryImplForLocalDatabaseTest { public void customSetUp() { LocalDatabaseTableHelper.createTableBookSearchResult(dynamoDbClient); } @After public void tearDown() throws Exception { LocalDatabaseTableHelper.deleteTableBookSearchResult(dynamoDbClient); } @Test public void putToBookSearchResult() { List<BookSearchResultItem> books = ObjectMother.getRandomBookSearchResultItemList(3); repository.putToBookSearchResult(books); } @Test public void getBookSearchResult() { List<BookSearchResultItem> repBooks = ObjectMother.getRandomBookSearchResultItemList(3); repository.putToBookSearchResult(repBooks); List<Book> searchResult = repository.getBookSearchResult(); assertNotNull(searchResult); assertEquals(repBooks.size(), searchResult.size()); BookSearchResultItem oneItem = repBooks.stream().filter(b -> b.getIsbn().equals(searchResult.get(0).getIsbn())).findFirst().orElse(null); assertNotNull(oneItem); assertEquals(oneItem.getAuthor(), searchResult.get(0).getAuthor()); assertEquals(oneItem.getTitle(), searchResult.get(0).getTitle()); assertEquals(oneItem.getIssueYear(), searchResult.get(0).getIssueYear()); assertEquals(oneItem.getPrice(), searchResult.get(0).getPrice(), 0.0001f); assertTrue(searchResult.stream().allMatch(resBook -> repBooks.stream().anyMatch(repBook -> TestHelper.isEqual(resBook, repBook)))); } }
package revolt.backend.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import revolt.backend.entity.Liquid; @Repository public interface LiquidRepository extends JpaRepository<Liquid, Long> { }
package com.company.game; import xyz.noark.core.annotation.Component; import xyz.noark.core.annotation.Order; import xyz.noark.core.annotation.Service; /** * @author 小流氓[176543888@qq.com] * @since 3.4 */ @Component(name = "test") @Order(1) public class TestService1 implements TestService { }
package com.github.colinjeremie.justpickafilm.database; import com.github.colinjeremie.justpickafilm.models.Genres; import com.raizlabs.android.dbflow.converter.TypeConverter; import java.util.Arrays; /** * * JustPickAFilm * Created by jerem_000 on 3/2/2016. */ @com.raizlabs.android.dbflow.annotation.TypeConverter public class GenresConverter extends TypeConverter<String, Genres> { @Override public String getDBValue(Genres model) { if (model != null){ StringBuilder stringBuilder = new StringBuilder(""); int size = model.size(); for (int i = 0; i < size; i++){ String tmp = model.get(i); stringBuilder.append(tmp); if (i != size - 1){ stringBuilder.append(" "); } } return stringBuilder.toString(); } return null; } @Override public Genres getModelValue(String data) { if (data != null){ Genres genres = new Genres(); genres.addAll(Arrays.asList(data.split(" "))); return genres; } return null; } }
package com.gxtc.huchuan.helper; import android.app.Activity; import android.app.Application; import android.content.Context; import android.net.Uri; import com.gxtc.commlibrary.utils.SpUtil; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.bean.dao.User; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.im.extension.MyRongExtensionModule; import com.gxtc.huchuan.im.provide.MyGroupInfoProvider; import com.gxtc.huchuan.im.provide.MyUserInfoProvider; import com.gxtc.huchuan.ui.mine.personalhomepage.personalinfo.PersonalInfoActivity; import com.gxtc.huchuan.ui.mine.setting.MessageSettingActivity; import com.gxtc.huchuan.ui.mine.setting.SettingActivity; import com.gxtc.huchuan.utils.JPushUtil; import com.gxtc.huchuan.utils.RIMSoundHandler; import java.util.List; import io.rong.callkit.RongCallKit; import io.rong.calllib.RongCallClient; import io.rong.calllib.RongCallCommon; import io.rong.imkit.DefaultExtensionModule; import io.rong.imkit.IExtensionModule; import io.rong.imkit.RongExtensionManager; import io.rong.imkit.RongIM; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.UserInfo; import io.rong.push.RongPushClient; /** * Created by Steven on 16/12/30. * 融云帮助类 */ public class RongImHelper { //客服id public static final String ID_KEFU_DEBUG = "KEFU149455996053212"; public static final String ID_KEFU = "KEFU149455997594652"; /** * 初始化 */ public static void init(Context context){ RongIM.init(context); } /** * 连接融云 * @param app * @param token * @param callback */ public static void connect(Application app, String token , RongIMClient.ConnectCallback callback){ if (app.getApplicationInfo().packageName.equals(MyApplication.getCurProcessName(app)) && RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED) { RongIM.connect(token, callback); } } public static void initDefaultConfig(){ RongIM.setUserInfoProvider(new MyUserInfoProvider(), true); //设置用户信息提供者 RongIM.setGroupInfoProvider(new MyGroupInfoProvider(), true); //设置用户信息提供者 initExtension(); //自定义输入区域拓展功能,加个红包功能 //初始化融云消息状态 SettingActivity.sound = SpUtil.getBoolean(MyApplication.getInstance(), SettingActivity.SP_SOUND(), true); RIMSoundHandler.INSTANCE.setRongIMSounds(MyApplication.getInstance(),SettingActivity.sound); // 设置融云会话提示的声音是否打开 boolean notifi = SpUtil.getBoolean(MyApplication.getInstance(), MessageSettingActivity.SP_NEW_MESSAGE(), true); JPushUtil.setSoundAndVibrate(MyApplication.getInstance(), notifi, notifi); User user = UserManager.getInstance().getUser(); if(user != null){ RongIM.getInstance().setCurrentUserInfo(RongImHelper.createUserInfo(user.getUserCode(), user.getName(), user.getHeadPic())); } RongIM.getInstance().enableNewComingMessageIcon(true); //显示新消息提醒 RongIM.getInstance().enableUnreadMessageIcon(true); //显示未读消息数目 RongCallClient.getInstance().setVideoProfile(RongCallCommon.CallVideoProfile.VIDEO_PROFILE_240P); } /** * 创建一个userInfo对象 * @param userId 用户id * @param name 用户名字 * @param avatar 用户头像 */ public static UserInfo createUserInfo(String userId, String name, String avatar){ return new UserInfo(userId, name, Uri.parse(avatar)); } public static void startCustomerServices(Activity activity,String title){ //首先需要构造使用客服者的用户信息 /*CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder(); CSCustomServiceInfo csInfo = csBuilder.nickName("在线客服").build(); RongIM.getInstance().startCustomerServiceChat(activity, ID_KEFU, title,csInfo);*/ //暂时使用聊天客服 //RongIM.getInstance().startPrivateChat(activity,"00006 ","小袁"); PersonalInfoActivity.startActivity(activity,"00006"); } public static void startCustomerServices(Activity activity,String title,String userCode){ //暂时使用聊天客服 RongIM.getInstance().startPrivateChat(activity,userCode,title); } private static void initExtension(){ List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules(); IExtensionModule defaultModule = null; if (moduleList != null) { for (IExtensionModule module : moduleList) { if (module instanceof DefaultExtensionModule) { defaultModule = module; break; } } if (defaultModule != null) { RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule); RongExtensionManager.getInstance().registerExtensionModule(new MyRongExtensionModule()); } } } }
package ru.telepnev.dmitriy.SmsSender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; import ru.telepnev.dmitriy.SmsSender.beans.MessageList; import ru.telepnev.dmitriy.SmsSender.properties.AppProps; @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); @Autowired private SmsReader reader; @Autowired private SmsSender sender; @Autowired private SmsUpdater updater; @Autowired private BalanceReader balanceReader; @Autowired private AppProps props; public static void main(String args[]) throws Exception { SpringApplication app = new SpringApplication( Application.class ); ConfigurableApplicationContext ctx = app.run( args ); Application smsSender = ctx.getBean( Application.class ); smsSender.sendMessages(); } private void sendMessages() throws InterruptedException { updater.start(); while( !Thread.currentThread().isInterrupted() ) { balanceReader.read(); MessageList messages = reader.getMessages( props.getChunkLimit() ); sender.sendMessages( messages ); updater.addIntoQueue( messages ); if( messages.size() == 0 ) { Thread.sleep( props.getSleepMs() ); } } updater.interrupt(); } }
package com.sky.design.strategy; public class Test { //简单工厂模式 public static void main(String[] args) { CashSuper cashSuper; cashSuper=CashFactory.createCashAccept("正常收费"); System.out.println(cashSuper.acceptCash(800)); cashSuper=CashFactory.createCashAccept("满300返100"); System.out.println(cashSuper.acceptCash(800)); cashSuper=CashFactory.createCashAccept("打8折"); System.out.println(cashSuper.acceptCash(800)); cashSuper=CashFactory.createCashAccept(""); System.out.println(cashSuper.acceptCash(800)); } public static void main2(String[] args) { CashContext cashContext; //策略与简单工厂结合 cashContext=new CashContext("正常收费"); System.out.println(cashContext.GetResult(800)); cashContext=new CashContext("满300返100"); System.out.println(cashContext.GetResult(800)); cashContext=new CashContext("打8折"); System.out.println(cashContext.GetResult(800)); cashContext=new CashContext(""); System.out.println(cashContext.GetResult(80000)); } public static void main1(String[] args) { CashContext cashContext; //策略 cashContext=new CashContext(new CashNormal()); System.out.println(cashContext.GetResult(800)); cashContext=new CashContext(new CashRebate(0.8)); System.out.println(cashContext.GetResult(800)); cashContext=new CashContext(new CashReturn(700,200)); System.out.println(cashContext.GetResult(800)); } }
public class RockPaperScissorsMagicEasy { long MOD = 1000000007; public int count(int[] card, int score) { if(card.length < score) { return 0; } long result = modPow(2, card.length - score); long n = 1; long k = 1; long nk = 1; for(long i = 1; i <= card.length; ++i) { n *= i; n %= MOD; if(i == score) { k = n; } if(i == card.length - score) { nk = n; } } result *= n; result %= MOD; result *= modPow((k * nk)%MOD, MOD - 2); result %= MOD; return (int)result; } private long modPow(long base, long pow) { long result = 1; long b = base; while(pow != 0) { if(pow%2 == 1) { result *= b; result %= MOD; } pow /= 2; b *= b; b %= MOD; } return result; } }
package com.codecool.stampcollection.exception; public class CurrencyNotExistsException extends RuntimeException{ public CurrencyNotExistsException(String currency) { super("Currency does not exists with code: " + currency); } }
package com.radauer.mathrix; import static com.radauer.mathrix.MathrixTestHelper.getGroupKey; import static com.radauer.mathrix.MathrixTestHelper.getRowKey; import java.math.BigDecimal; import org.junit.Test; import com.radauer.mathrix.tasks.SumTask; /** * Performance Test for the Mathrix */ public class MathrixMassTest { private Mathrix mat; private static int TEST_RUNS = 10; private static int GROUPS = 25; private static int ROWS = 200; @Test public void testMass() { long t = System.currentTimeMillis(); System.out.println("start"); for (int i = 0; i < TEST_RUNS; i++) { mat = new Mathrix(new TestCalcContext()); for (int group = 0; group < GROUPS; group++) { for (int row = 0; row < ROWS; row++) { mat.insert( new Position(getGroupKey("G" + group), getRowKey("R" + row), new BigDecimal(group * row))); } } for (int group = 0; group < GROUPS; group++) { new SumTask(getGroupKey("G" + group), null, getRowKey("SUM")).calc(mat); } } System.out.println("fertig " + mat.getSize()); System.out.println("T: " + (System.currentTimeMillis() - t) / TEST_RUNS); } }
// Jesus Rodriguez // 1/28/2020 // ITC 115 Winter 2020 /* Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0 (1) * up to that maximum power,inclusive. For example, consider the following calls: * printPowerOfN(4, 3); * printPowerOfN(5, 6); * printPowerOfN(-2, 8); * These calls should produce the following output: * 1 4 16 54 * 1 5 25 125 625 3125 15625 * 1 -2 4 -8 16 -32 64 -128 256 * You may assume that the exponent passed to printPowerOfN has a value of 0 or greater. (The math class may help you with this problem. * If you see it, you may need to cast its result from double to int so that you don't see a .0 after each number in your output * Also try to write this program without using Math class.) */ package chapter3; public class Power { //The main method calls the printPowerOfN with two arguments public static void main(String[] args) { printPowerOfN(4, 3); //Call of the method printPowerOfN with its actual parameters. System.out.println(); //Print the separation within lines of output. printPowerOfN(5,6); //Call of the method printPowerOfN with its actual parameters. System.out.println(); //Print the separation within lines of output. printPowerOfN(-2, 8); //Call of the method printPowerOfN with its actual parameters. } public static void printPowerOfN(int num1, int num2) { //This is the method that I was required to build with to parameters //One parameter (num1) is the base and num2 is the power exponent. for (int i = 0; i<= num2; i++) { //In this loop I start in 0, stops in the value of num2, and increase by one each time. double power = Math.pow(num1, i); //Here the variable "power" gets the value of num1 that goes to the i exponential. System.out.print((int) power + " "); //Prints the value of power plus a space to separate each value.Also, I had to cast power to "int". } } }
package farmerline.com.dev.farmerserviceapp.dashboard.home.mapLocation; import android.content.SharedPreferences; import com.google.android.gms.maps.model.LatLng; import com.google.gson.Gson; import farmerline.com.dev.farmerserviceapp.login.UserModel; import farmerline.com.dev.farmerserviceapp.root.App; import farmerline.com.dev.farmerserviceapp.utils.Constant; public class MapFragmentModel implements MapFragmentMVP.Model { public MapFragmentModel() { } @Override public void saveLocation(LatLng latLng) { LocationModel locationModel=new LocationModel(latLng.latitude,latLng.longitude); SharedPreferences.Editor editor= App.getSharedPrefs().edit(); String location= new Gson().toJson(locationModel); editor.putString(Constant.location,location); editor.apply(); } @Override public LocationModel getLatLng() { String location= App.getSharedPrefs().getString(Constant.location,null); if (location !=null) { return new Gson().fromJson(location,LocationModel.class); }else { return new LocationModel(); } } }
package cc.ipotato.jdbc.basic; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.sql.*; import java.util.Properties; /** * Created by haohao on 2018/5/25. */ public class JDBCUtils { public static String DBDRIVER; public static String DBURL; public static String DBUSER; public static String DBPASS; static { try { readConfig(); Class.forName(DBDRIVER); } catch (ClassNotFoundException e) { throw new RuntimeException(e + "数据库驱动注册失败!"); } catch (FileNotFoundException e) { throw new RuntimeException(e + "读取配置文件失败!"); } catch (IOException e) { throw new RuntimeException(e + "加载配置文件失败!"); } } private JDBCUtils(){} private static void readConfig() throws IOException{ Properties properties = new Properties(); Reader reader = new FileReader("db.properties"); properties.load(reader); DBDRIVER = properties.getProperty("driver"); DBURL = properties.getProperty("url"); DBUSER = properties.getProperty("user"); DBPASS = properties.getProperty("password"); } public static Connection getConnection() { try { return DriverManager.getConnection(DBURL, DBUSER, DBPASS); } catch (SQLException e) { throw new RuntimeException(e + "获取数据库连接失败"); } } public static void close(Connection conn, Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } public static void close(Connection conn, Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } }
package com.pibs.bo; import java.util.HashMap; import java.util.Map; public interface ReportBo { Map<String, Object> generateReport(HashMap<String, Object> criteriaMap) throws Exception; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Business.MunicipalCorporation; import Business.Architecture.ArchitectureDirectory; import Business.Email.EmailManagementSystem; import Business.Organization.Organization; import Business.Organization.OrganizationDirectory; import Business.StructuralHealthMonitor.StructuralHealthHistory; /** * * @author raunak */ public abstract class MunicipalCorporation extends Organization{ private DepartmentType departmentType; private OrganizationDirectory organizationDirectory; private ArchitectureDirectory buildingDirectory; private EmailManagementSystem email; public MunicipalCorporation(String name, DepartmentType type) { super(name); this.departmentType = type; organizationDirectory = new OrganizationDirectory(); buildingDirectory=new ArchitectureDirectory(); email=new EmailManagementSystem(); } /** * @return the buildingDirectory */ public ArchitectureDirectory getBuildingDirectory() { return buildingDirectory; } /** * @param buildingDirectory the buildingDirectory to set */ public void setBuildingDirectory(ArchitectureDirectory buildingDirectory) { this.buildingDirectory = buildingDirectory; } /** * @return the contract */ /** * @return the email */ public EmailManagementSystem getEmail() { return email; } /** * @param email the email to set */ public void setEmail(EmailManagementSystem email) { this.email = email; } public enum DepartmentType{ BBR("Board of Building Regulation"); private String value; private DepartmentType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value; } } public DepartmentType getDepartmentType() { return departmentType; } public OrganizationDirectory getOrganizationDirectory() { return organizationDirectory; } }
package com.leetcode; public class PostOrderTree { private static class Node { private Node left; private Node right; private Object value; } public void traversal(Node node) { if(node == null) return; if(node.left != null) traversal(node.left); if(node.right != null) traversal(node.right); System.out.println(node.value); } }
package com.poly.dotsave.adapter; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.poly.dotsave.R; public class HistoryHolder extends RecyclerView.ViewHolder { public ImageView imageView; public Button btnPlay, btnDel; public TextView textView; public HistoryHolder(View view) { super(view); imageView = view.findViewById(R.id.imageView); btnPlay = view.findViewById(R.id.btnPlay); btnDel = view.findViewById(R.id.btnDelete); textView = view.findViewById(R.id.textView); } }
package com.getkhaki.api.bff.web; import com.getkhaki.api.bff.domain.models.GoalDm; import com.getkhaki.api.bff.domain.services.GoalService; import com.getkhaki.api.bff.web.models.*; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class GoalsControllerUnitTests { private GoalsController underTest; @Mock private GoalService goalService; @Mock private ModelMapper modelMapper; @BeforeEach public void setup() { underTest = new GoalsController( this.goalService, this.modelMapper ); } @Test public void getGoals() { List<GoalDm> goalList = Lists.list( new GoalDm().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.AttendeesPerMeeting).setGreaterThanOrEqualTo(10), new GoalDm().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.AverageMeetingLength).setLessThanOrEqualTo(1000), new GoalDm().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.StaffTimeInMeetings).setLessThanOrEqualTo(10000)); when(goalService.getGoals()).thenReturn(goalList); List<GoalDto> goalDtos = Lists.list( new GoalDto().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.AttendeesPerMeeting).setGreaterThanOrEqualTo(10), new GoalDto().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.AverageMeetingLength).setLessThanOrEqualTo(1000), new GoalDto().setId(UUID.randomUUID()).setMeasure(GoalMeasureDte.StaffTimeInMeetings).setLessThanOrEqualTo(10000) ); when(modelMapper.map(goalList.get(0), GoalDto.class)).thenReturn(goalDtos.get(0)); when(modelMapper.map(goalList.get(1), GoalDto.class)).thenReturn(goalDtos.get(1)); when(modelMapper.map(goalList.get(2), GoalDto.class)).thenReturn(goalDtos.get(2)); GoalsResponseDto result = this.underTest.getGoals(); GoalsResponseDto expectedResult = new GoalsResponseDto().setGoals(goalDtos); assertThat(result.getGoals().size()).isEqualTo(expectedResult.getGoals().size()); assertThat(result.getGoals().get(0).getMeasure()).isEqualTo(expectedResult.getGoals().get(0).getMeasure()); assertThat(result.getGoals().get(0).getLessThanOrEqualTo()).isEqualTo(expectedResult.getGoals().get(0).getLessThanOrEqualTo()); assertThat(result.getGoals().get(0).getGreaterThanOrEqualTo()).isEqualTo(expectedResult.getGoals().get(0).getGreaterThanOrEqualTo()); } }
package com.example.kuno.actionbarex; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /* Context(컨텍스트) 객체의 상태 정보를 표현 액티비티 정보 저장/제공 안드로이드에서는 UI구성요소인 뷰의 정보를 확인하거나 설정하기 위해 컨텍스트 객체를 사용합니다. 액티비티 클래스 안에서는 this를 컨텍스트 객체로 사용할 수 있습니다. Activity 는 Context클래스를 상속하기 때문에 가능합니다. */ public class MainActivity extends AppCompatActivity { ActionBar actionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionBar = this.getSupportActionBar(); //현재 있는 액션바 가져오기 /* actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME);*/ actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP|ActionBar.DISPLAY_SHOW_HOME); actionBar.setDisplayShowTitleEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { //return super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //return super.onOptionsItemSelected(item); switch(item.getItemId()){ case R.id.itSearch: Toast.makeText(this, "검색으로", Toast.LENGTH_SHORT).show(); return true; case R.id.itChat: Toast.makeText(this, "채팅으로", Toast.LENGTH_SHORT).show(); return true; case R.id.itEmail: Toast.makeText(this, "이메일로", Toast.LENGTH_SHORT).show(); return true; case R.id.itRefresh: Toast.makeText(this, "새로고침", Toast.LENGTH_SHORT).show(); return true; case R.id.itSettings: Toast.makeText(this, "설정으로", Toast.LENGTH_SHORT).show(); return true; case android.R.id.home: Toast.makeText(this, "뒤로", Toast.LENGTH_SHORT).show(); return true; } return false; } }
package com.daexsys.automata; public enum GameSide { CLIENT, // multiplayer client SERVER, // multiplayer server BOTH // singleplayer }
package com.salesfloors.client.controller; import java.io.File; import java.io.IOException; import java.util.List; import javax.inject.Inject; import org.apache.commons.io.FileUtils; import org.springframework.social.connect.ConnectionRepository; import org.springframework.social.facebook.api.Facebook; import org.springframework.social.facebook.api.Reference; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.salesfloors.aws.AwsClient; @Controller public class FacebookController { public static final String fbTokenBucket = "FacebookToken"; @Inject private ConnectionRepository connectionRepository; @Inject private Facebook facebook; @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Model model) throws IOException, AmazonServiceException, AmazonClientException, InterruptedException { List<Reference> friends = facebook.friendOperations().getFriends(); storeTokenInS3(); model.addAttribute("friends", friends); return "home"; } private void storeTokenInS3() throws IOException, AmazonServiceException, AmazonClientException, InterruptedException { String token = connectionRepository.getPrimaryConnection(Facebook.class).createData().getAccessToken(); AwsClient aws = new AwsClient(); File file = new File("target/facebook_token"); FileUtils.write(file, token); aws.uploadFileToS3(file, CannedAccessControlList.Private, fbTokenBucket); } }
package slimeknights.tconstruct.debug; import com.google.common.eventbus.Subscribe; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import org.apache.logging.log4j.Logger; import java.util.Map; import slimeknights.mantle.pulsar.pulse.Pulse; import slimeknights.tconstruct.common.config.Config; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.modifiers.IModifier; import slimeknights.tconstruct.library.utils.ListUtil; @Pulse(id = TinkerDebug.PulseId, description = "Debug utilities", defaultEnable = false) public class TinkerDebug { public static final String PulseId = "TinkerDebug"; static final Logger log = Util.getLogger(PulseId); @Subscribe public void preInit(FMLPreInitializationEvent event) { if(Config.dumpTextureMap) { MinecraftForge.EVENT_BUS.register(new TextureDump()); } } @Subscribe public void postInit(FMLPostInitializationEvent event) { if(event.getSide().isClient()) { ClientCommandHandler.instance.registerCommand(new ReloadResources()); } } @Subscribe public void serverStart(FMLServerStartingEvent event) { event.registerServerCommand(new DamageTool()); event.registerServerCommand(new TestTool()); event.registerServerCommand(new GenValidModifiers()); if(event.getSide().isClient()) { ClientCommandHandler.instance.registerCommand(new LocalizationCheckCommand()); ClientCommandHandler.instance.registerCommand(new DumpMaterialTest()); ClientCommandHandler.instance.registerCommand(new FindBestTool()); ClientCommandHandler.instance.registerCommand(new GetToolGrowth()); ClientCommandHandler.instance.registerCommand(new CompareVanilla()); ClientCommandHandler.instance.registerCommand(new ListValidModifiers()); } sanityCheck(); } public static void sanityCheck() { // check all modifiers if they can be applied for(IModifier modifier : TinkerRegistry.getAllModifiers()) { try { modifier.matches(ListUtil.getListFrom(new ItemStack(Items.STICK))); modifier.matches(NonNullList.withSize(1, ItemStack.EMPTY)); } catch(Exception e) { log.error("Caught exception in modifier " + modifier.getIdentifier(), e); } } // check all blocks if all metadatas are supported for(ResourceLocation identifier : Block.REGISTRY.getKeys()) { // only our own stuff if(!identifier.getResourceDomain().equals(Util.RESOURCE)) { continue; } Block block = Block.REGISTRY.getObject(identifier); for(int i = 0; i < 16; i++) { try { IBlockState state = block.getStateFromMeta(i); state.getBlock().getMetaFromState(state); } catch(Exception e) { log.error("Caught exception when checking block " + identifier + ":" + i, e); } } } // same for items for(ResourceLocation identifier : Item.REGISTRY.getKeys()) { // only our own stuff if(!identifier.getResourceDomain().equals(Util.RESOURCE)) { continue; } Item item = Item.REGISTRY.getObject(identifier); for(int i = 0; i < 0x7FFF; i++) { try { item.getMetadata(i); } catch(Exception e) { log.error("Caught exception when checking item " + identifier + ":" + i, e); } } } // check for broken unsavable fluids for(Map.Entry<String, Fluid> entry : FluidRegistry.getRegisteredFluids().entrySet()) { if(entry.getKey() == null || entry.getKey().isEmpty()) { log.error("Fluid " + entry.getValue().getUnlocalizedName() + " has an empty name registered!"); } String name = FluidRegistry.getFluidName(entry.getValue()); if(name == null || name.isEmpty()) { log.error("Fluid " + entry.getValue().getUnlocalizedName() + " is registered with an empty name!"); } } log.info("Sanity Check Complete"); } }
package com.example.csvJsonParser; import com.example.csvJsonParser.model.Order; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; @Slf4j @Component("json") public class JSONParser implements Parser { @Autowired ObjectMapper mapper; @Override public Order parseLine(String s) throws ParseException { try { return mapper.readValue(s, Order.class); } catch (IOException e) { throw new ParseException("JSON parse exception", e); } } }
package kg13; /** * Created by C0116289 on 2017/07/10. */ public class Ex01 { public static void main(String[] args) { Triangle t1 = new Triangle(2, 5); Triangle t2 = new Triangle(3, 7); System.out.println("t1の面積 : " + t1.toArea()); System.out.println("t2の面積 : " + t2.toArea()); System.out.println("t1の底辺と高さを2倍にします"); System.out.println("t2の底辺と高さを3倍にします"); t1.enlarge(2); t2.enlarge(3); System.out.println("t1の面積 : " + t1.toArea()); System.out.println("t2の面積 : " + t2.toArea()); } }
package net.edzard.kinetic; /** * A circular shape. * @author Ed */ public class Circle extends Shape { /** Protected default Ctor keeps GWT happy */ protected Circle() {} /** * Retrieve this circle's radius. * @return The radius */ public final native double getRadius() /*-{ return this.getRadius(); }-*/; /** * Assign a radius. * @param radius The new radius value */ public final native void setRadius(double radius) /*-{ this.setRadius(radius); }-*/; /** * Animate a linear transition of this circle. * @param target Another circle shape - defines the characteristics that the current circle will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @return An object for controlling the transition. */ public final Transition transitionTo(Circle target, int duration) { return transitionTo(target, duration, null, null); } /** * Animate a transition of this circle. * @param target Another circle shape - defines the characteristics that the current circle will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @param ease An easing function that defines how the transition will take place * @param callback A function that will be called at the end of the animation * @return An object for controlling the transition. */ public final Transition transitionTo(Circle target, int duration, EasingFunction ease, Runnable callback) { StringBuffer sb = new StringBuffer(); if (this.getRadius() != target.getRadius()) sb.append("radius:").append(target.getRadius()).append(","); return transitionToShape(target, sb, duration, ease, callback); } }
package com.example.mav_mr_fpv_osu_2020.old; import android.view.TextureView; import android.widget.FrameLayout; import com.example.vfsmav_osu20_fpv.mavdata.MAVRepo; public class FPVFullAdapter extends FrameLayout.Adapter<FPVFullAdapter.telemetryViewHolder> { private MAVRepo mTelemetry; private TextureView textureView; @Override protected void getItemCount() { setContentView(R.layout.activity_fpv_full); textureView = (TextureView) findViewById(R.id.textureView); assert textureView != null; textureView.setSurfaceTexture(new TextureView.SurfaceTextureListener() { }); } public FPVFullAdapter() { } }
package com.uav.rof.bo; import com.uav.rof.activity.ConnectionVO; import java.io.Serializable; import java.util.HashMap; public class PaymentTypeBO implements Serializable { public static ConnectionVO getPaymentType(){ ConnectionVO connectionVO = new ConnectionVO(); connectionVO.setMethodName("getPaymentTypeListCache"); connectionVO.setRequestType(ConnectionVO.REQUEST_GET); return connectionVO; } }
import java.util.Scanner; public class MovieTicket { public static void main(String[] args) { int ticket; String refreshment,coupanCode,circle; int ref=0; float dis=0; float TotalCost=0; float coupanDis=0; Scanner sc =new Scanner(System.in); System.out.println("Enter the no.of ticket"); ticket=sc.nextInt(); //30 if(ticket>=5 && ticket<=40) { System.out.print("Do you want refreshment"); //y refreshment=sc.next(); sc.nextLine(); System.out.println("Do you have coupon code"); //y coupanCode=sc.nextLine(); //sc.nextLine(); System.out.println("Enter the circle"); //q circle=sc.nextLine(); if(circle.equals("q")) { System.out.println("we selected q and value of ticket"+ticket); int ticketTotal=ticket*150; if(ticket>20) { dis=ticketTotal*10/100; dis=ticketTotal-dis; System.out.println("ticketTotal : "+ticketTotal+"dis:"+dis); System.out.println("refreshment: "+refreshment); }else { dis=ticketTotal; } if(refreshment.equals("y")) { ref=50*ticket; System.out.println("Refreshment:"+ref); } if(coupanCode.equals("y")) { coupanDis= dis*2/100; coupanDis=dis-coupanDis; System.out.println("Coupan Discounted:"+coupanDis); }else { coupanDis= dis; } TotalCost= coupanDis+ref; System.out.println("Toatal cost of movie ticket is "+TotalCost); }else if(circle.equals("k")) { int ticketTotal=ticket*75; if(ticket>20) { dis=ticketTotal*10/100; }else { dis=ticketTotal; } if(refreshment.equals("y")) { ref=50*ticket; } if(coupanCode.equals("y")) { coupanDis= dis*2/100; }else { coupanDis= dis; } TotalCost= coupanDis+ref; System.out.println("Toatal cost of movie ticket is "+TotalCost); } else { System.out.println("Invalid Input"); } }else { System.out.println("Minimum of 5 and Maximum of 40 Tickets"); } } }
/** * Package for delegates used by database child classes. */ package lib.Databases.Delegates; // Date Created: 2012-12-31 05:45
package com.example.fuemi.eisbaer.Activitys; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.ViewFlipper; import com.example.fuemi.eisbaer.R; import java.util.ArrayList; import Items.Order; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { ViewFlipper vf; FloatingActionButton fab; SharedPreferences sd; boolean guest = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Neues Spiel starten", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); sd = getSharedPreferences("Login", Context.MODE_PRIVATE); System.out.println(sd.getString("Gast", "")); System.out.println(sd.getBoolean("LoggedIn", true)); guest = sd.getString("Gast", "").equals("Gast"); System.out.println(guest); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.getMenu().clear(); if(guest){ navigationView.inflateMenu(R.menu.activity_main_drawer_guest); }else{ navigationView.inflateMenu(R.menu.activity_main_drawer_no_guest); } navigationView.setNavigationItemSelectedListener(this); vf = (ViewFlipper) findViewById(R.id.viewFlipper); Intent i = getIntent(); //Funktioniert bei offline starten noch nicht if(i.hasExtra("OrderOfMerrit")){ Bundle bundle = i.getBundleExtra("OrderOfMerrit"); ArrayList<Order> orderOfMerrit = (ArrayList<Order>) bundle.getSerializable("OrderOfMerrit"); TextView helloWorld = (TextView) findViewById(R.id.main); System.out.print(orderOfMerrit.size()); helloWorld.setText(orderOfMerrit.get(0).getPosition() + " - " + orderOfMerrit.get(0).getName() + " - " + orderOfMerrit.get(0).getPreisgeld()); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_newGame) { // Handle the camera action //vf.setDisplayedChild(1); //fab.setVisibility(View.INVISIBLE); newGame(); } else if (id == R.id.nav_friends) { vf.setDisplayedChild(2); fab.setVisibility(View.VISIBLE); } else if (id == R.id.nav_news) { vf.setDisplayedChild(0); fab.setVisibility(View.VISIBLE); } else if (id == R.id.nav_statistiken) { vf.setDisplayedChild(3); fab.setVisibility(View.VISIBLE); } else if (id == R.id.nav_einstellungen) { vf.setDisplayedChild(4); fab.setVisibility(View.VISIBLE); } else if (id == R.id.nav_ausloggen) { logOut(); } else if (id == R.id.nav_einloggen) { logIn(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private void logIn() { sd = getSharedPreferences("Login", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sd.edit(); editor.putString("Gast", "NoGast"); editor.putBoolean("LoggedIn", false); editor.apply(); Intent i = new Intent(MainActivity.this, LadescreenActivity.class); startActivity(i); finish(); } private void logOut() { sd = getSharedPreferences("Login", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sd.edit(); editor.putBoolean("LoggedIn", false); editor.putString("Gast", "NoGast"); editor.apply(); Intent i = new Intent(MainActivity.this, LadescreenActivity.class); startActivity(i); finish(); } private void newGame(){ Intent i = new Intent(MainActivity.this, GameConfigurationActivity.class); startActivity(i); } }
package Services.InfoService; import DB.DBHandler; import DB.Job; import DB.Orchestration; import DB.Rule; import Services.StatusCodes; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @WebService(serviceName = "InfoService") public class InfoService { private DBHandler handler = new DBHandler(); @WebMethod @XmlElement(name = "getJob") public JobResponse getJob(@WebParam(name = "jobID") @XmlElement(required = true) Integer jobId) throws Exception { Job job = handler.getJob(jobId.intValue()); JobResponse info = new JobResponse(); info.setDescription(job.getDescription()); info.setDestination(job.getDestination()); info.setFileUrl(job.getFileUrl()); info.setId(job.getId()); info.setInsertDateTime(job.getInsertDateTime_Date()); info.setOwner(job.getOwner()); info.setRelatives(job.getRelatives()); info.setRuleId(job.getRuleId()); info.setStatus(job.getStatus()); info.setUpdateDateTime(job.getUpdateDateTime_Date()); return info; } @WebMethod @XmlElement(name = "getJobFromOwner") public ArrayList<JobResponse> getJobsFromOwner(@WebParam(name = "ownerID") @XmlElement(required = true) Integer ownerId) throws Exception { ArrayList<Job> jobSet = handler.getJobSet(ownerId); ArrayList<JobResponse> jobList = new ArrayList<>(); for(Job job : jobSet){ if (job.getStatus() != StatusCodes.REMOVED) { JobResponse info = new JobResponse(); info.setDescription(job.getDescription()); info.setDestination(job.getDestination()); info.setFileUrl(job.getFileUrl()); info.setId(job.getId()); info.setInsertDateTime(job.getInsertDateTime_Date()); info.setOwner(job.getOwner()); info.setRelatives(job.getRelatives()); info.setRuleId(job.getRuleId()); info.setStatus(job.getStatus()); info.setUpdateDateTime(job.getUpdateDateTime_Date()); jobList.add(info); } } return jobList; } @WebMethod @XmlElement(name = "getOrchestration") public ArrayList<OrchestrationResponse> getOrchestration(@WebParam(name = "ownerID") @XmlElement(required = true) Integer ownerId) throws Exception { ArrayList<Orchestration> orc = handler.getOrchestration(ownerId); ArrayList<OrchestrationResponse> orcList = new ArrayList<>(); for (Orchestration temp : orc) { OrchestrationResponse res = new OrchestrationResponse(); res.setId(temp.getId()); res.setInsertDateTime(temp.getInsertDateTime_Date()); res.setOwnerID(temp.getOwnerID()); res.setStartJobID(temp.getStartJobID()); res.setStatus(temp.getStatus()); res.setUpdateDateTime(temp.getUpdateDateTime_Date()); orcList.add(res); } return orcList; } @WebMethod @XmlElement(name = "getRule") public RuleResponse getRule(@WebParam(name = "ruleID") @XmlElement(required = true)Integer ruleId) throws Exception { Rule rule = handler.getRule(ruleId.intValue()); RuleResponse info = new RuleResponse(); info.setId(rule.getId()); info.setNoEdge(rule.getNoEdge()); info.setOwnerID(rule.getOwnerID()); info.setQuery(rule.getQuery()); info.setRelativeResults(rule.getRelativeResults()); info.setYesEdge(rule.getYesEdge()); return info; } @WebMethod @XmlElement(name = "getJobFromRelative") public ArrayList<JobResponse> getJobsFromRelative(@WebParam(name = "relativeID") @XmlElement(required = true) Integer relativeId) throws Exception { ArrayList<Job> jobSet = handler.getAllJobs(); ArrayList<JobResponse> jobList = new ArrayList<>(); for(Job job : jobSet){ String relatives = job.getRelatives(); List<String> reList = Arrays.asList(relatives.split("\\s*,\\s*")); if(job.getStatus() != StatusCodes.REMOVED && reList.contains(Integer.toString(relativeId))){ JobResponse info = new JobResponse(); info.setDescription(job.getDescription()); info.setDestination(job.getDestination()); info.setFileUrl(job.getFileUrl()); info.setId(job.getId()); info.setInsertDateTime(job.getInsertDateTime_Date()); info.setOwner(job.getOwner()); info.setRelatives(job.getRelatives()); info.setRuleId(job.getRuleId()); info.setStatus(job.getStatus()); info.setUpdateDateTime(job.getUpdateDateTime_Date()); jobList.add(info); } } return jobList; } /** Added a new method for gettin all job from admin panel. MUST CHANGE LATER. **/ @WebMethod @XmlElement(name = "getAllJobs") public ArrayList<JobResponse> getAllJobs() throws Exception { ArrayList<Job> jobSet = handler.getUnorchestrainedJobs(); ArrayList<JobResponse> jobList = new ArrayList<>(); for(Job job : jobSet){ JobResponse info = new JobResponse(); info.setDescription(job.getDescription()); info.setDestination(job.getDestination()); info.setFileUrl(job.getFileUrl()); info.setId(job.getId()); info.setInsertDateTime(job.getInsertDateTime_Date()); info.setOwner(job.getOwner()); info.setRelatives(job.getRelatives()); info.setRuleId(job.getRuleId()); info.setStatus(job.getStatus()); info.setUpdateDateTime(job.getUpdateDateTime_Date()); jobList.add(info); } return jobList; } }
package com.virtusa.project.books; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import com.virtusa.project.users.Member; @Entity @Table(name = "books") public class Book { @Id @GeneratedValue( generator = "generatorB",strategy = GenerationType.AUTO) @SequenceGenerator(name="generatorB",sequenceName="BOOK_SEQ") private int bookId; private String bookName; private String author; private int edition; private double rating; @ManyToOne @JoinColumn(name="memberId") private Member member; public Member getMember() { return member; } public void setMember(Member member){ this.member = member; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getEdition() { return edition; } public void setEdition(int edition) { this.edition = edition; } public double getRating() { return rating; } public void setRating(double rating) { this.rating = rating; } @Override public String toString() { return "Book [bookId=" + bookId + ", bookName=" + bookName + ", author=" + author + ", edition=" + edition + ", rating=" + rating + ", member=" + member + "]"; } }
package com.sky.design.factory.base; public class Test { public static void main(String[] args) throws Exception { IFactory operFacory=new AddFactory(); Operation operation=operFacory.CreateOperation(); operation.setNumberA(12); operation.setNumberB(156); System.out.println(operation.GetResult()); operation=new SubFactory().CreateOperation(); operation.setNumberA(12); operation.setNumberB(156); System.out.println(operation.GetResult()); } }
package controllers.records; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import services.ActorService; import services.BrotherhoodService; import services.InceptionRecordService; import services.LegalRecordService; import services.LinkRecordService; import services.MiscRecordService; import services.PeriodRecordService; import controllers.AbstractController; import datatype.Url; import domain.Actor; import domain.Brotherhood; import domain.InceptionRecord; import domain.LegalRecord; import domain.LinkRecord; import domain.MiscRecord; import domain.PeriodRecord; import forms.InceptionRecordForm; import forms.LegalRecordForm; import forms.PeriodRecordForm; @Controller @RequestMapping("/records") public class RecordsController extends AbstractController { @Autowired private InceptionRecordService inceptionRecordService; @Autowired private LegalRecordService legalRecordService; @Autowired private MiscRecordService miscRecordService; @Autowired private PeriodRecordService periodRecordService; @Autowired private LinkRecordService linkRecordService; @Autowired private BrotherhoodService brotherhoodService; @Autowired private ActorService actorService; //********************************************************************************** //** //** ALL RECORDS LIST //** //********************************************************************************** @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView list(@RequestParam final int brotherhoodId) { ModelAndView result; try { Assert.isTrue(this.brotherhoodService.findAll().contains(this.brotherhoodService.findOne(brotherhoodId))); Assert.notNull(brotherhoodId); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } final Collection<InceptionRecord> inceptions = this.inceptionRecordService.getInceptionRecordByBrotherhood(brotherhoodId); final Collection<LegalRecord> legals = this.legalRecordService.getLegalRecordByBrotherhood(brotherhoodId); final Collection<MiscRecord> miscs = this.miscRecordService.getMiscRecordByBrotherhood(brotherhoodId); final Collection<PeriodRecord> periods = this.periodRecordService.getPeriodRecordByBrotherhood(brotherhoodId); final Collection<LinkRecord> links = this.linkRecordService.getLinkRecordByBrotherhood(brotherhoodId); result = new ModelAndView("records/list"); result.addObject("InceptionRecord", inceptions); result.addObject("LegalRecord", legals); result.addObject("LinkRecord", links); result.addObject("MiscRecord", miscs); result.addObject("PeriodRecord", periods); //Comprueba si el usuario logeado es la brotherhood de los records if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(this.brotherhoodService.findOne(brotherhoodId))) result.addObject("isBrotherhood", true); } return result; } @RequestMapping(value = "/history", method = RequestMethod.GET) public ModelAndView history() { ModelAndView result; Brotherhood bh; try { bh = (Brotherhood) this.actorService.getActorLogged(); Assert.isTrue(this.brotherhoodService.findAll().contains(this.brotherhoodService.findOne(bh.getId()))); Assert.notNull(bh); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } final Collection<InceptionRecord> inceptions = this.inceptionRecordService.getInceptionRecordByBrotherhood(bh.getId()); final Collection<LegalRecord> legals = this.legalRecordService.getLegalRecordByBrotherhood(bh.getId()); final Collection<MiscRecord> miscs = this.miscRecordService.getMiscRecordByBrotherhood(bh.getId()); final Collection<PeriodRecord> periods = this.periodRecordService.getPeriodRecordByBrotherhood(bh.getId()); final Collection<LinkRecord> links = this.linkRecordService.getLinkRecordByBrotherhood(bh.getId()); result = new ModelAndView("records/list"); result.addObject("InceptionRecord", inceptions); result.addObject("LegalRecord", legals); result.addObject("LinkRecord", links); result.addObject("MiscRecord", miscs); result.addObject("PeriodRecord", periods); //Comprueba si el usuario logeado es la brotherhood de los records if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) if (bh != null) if (bh.equals(this.brotherhoodService.findOne(bh.getId()))) result.addObject("isBrotherhood", true); return result; } //********************************************************************************** //** //** ALL RECORDS CREATES GET AND POST //** //********************************************************************************** //INCEPTION RECORD CREATE @RequestMapping(value = "/inceptionRecord/create", method = RequestMethod.GET) public ModelAndView createInception() { ModelAndView result; final InceptionRecord iR = this.inceptionRecordService.create(); result = this.createModelAndView(iR); return result; } @RequestMapping(value = "/inceptionRecord/create", method = RequestMethod.POST, params = "create") public ModelAndView createInception(@ModelAttribute("iRF") @Valid final InceptionRecordForm iRF, final BindingResult binding) { ModelAndView result; InceptionRecord iR; iR = this.inceptionRecordService.reconstructCreate(iRF, binding); if (binding.hasErrors()) result = this.createModelAndView(iRF, null); else try { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); iR.setBrotherhood(bh); this.inceptionRecordService.save(iR); result = this.list(iR.getBrotherhood().getId()); } catch (final Throwable oops) { result = this.createModelAndView(iRF, "record.edit.error"); } return result; } //LEGAL RECORD CREATE @RequestMapping(value = "/legalRecord/create", method = RequestMethod.GET) public ModelAndView createLegal() { ModelAndView result; final LegalRecord lR = this.legalRecordService.create(); result = this.createModelAndView(lR); return result; } @RequestMapping(value = "/legalRecord/create", method = RequestMethod.POST, params = "create") public ModelAndView createLegal(@ModelAttribute("lRF") @Valid final LegalRecordForm lRF, final BindingResult binding) { ModelAndView result; LegalRecord lR; if (!lRF.getLaw().equals("")) { final List<String> laws = new ArrayList<String>(); laws.add(lRF.getLaw()); lRF.setApplicableLaws(laws); } lR = this.legalRecordService.reconstructCreate(lRF, binding); if (binding.hasErrors()) { result = this.createModelAndView(lRF, null); if (lRF.getLaw().equals("")) result.addObject("customErrorMessage", "record.error.oneLaw"); } else try { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); lR.setBrotherhood(bh); this.legalRecordService.save(lR); result = this.list(lR.getBrotherhood().getId()); } catch (final Throwable oops) { result = this.createModelAndView(lRF, "record.edit.error"); } return result; } //MISC RECORD CREATE @RequestMapping(value = "/miscRecord/create", method = RequestMethod.GET) public ModelAndView createMisc() { ModelAndView result; final MiscRecord mR = this.miscRecordService.create(); result = this.createModelAndView(mR); return result; } @RequestMapping(value = "/miscRecord/create", method = RequestMethod.POST, params = "create") public ModelAndView createMisc(@ModelAttribute("mRF") final MiscRecord mRF, final BindingResult binding) { ModelAndView result; MiscRecord mR; mR = this.miscRecordService.reconstructCreate(mRF, binding); if (binding.hasErrors()) result = this.createModelAndView(mRF, null); else try { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); mR.setBrotherhood(bh); this.miscRecordService.save(mR); result = this.list(mR.getBrotherhood().getId()); } catch (final Throwable oops) { result = this.createModelAndView(mRF, "record.edit.error"); } return result; } //PERIOD RECORD CREATE @RequestMapping(value = "/periodRecord/create", method = RequestMethod.GET) public ModelAndView createPeriod() { ModelAndView result; final PeriodRecord pR = this.periodRecordService.create(); result = this.createModelAndView(pR); return result; } @RequestMapping(value = "/periodRecord/create", method = RequestMethod.POST, params = "create") public ModelAndView createPeriod(@ModelAttribute("pRF") @Valid final PeriodRecordForm pRF, final BindingResult binding) { ModelAndView result; PeriodRecord pR; if (!pRF.getLink().equals("")) { final List<Url> photos = new ArrayList<Url>(); final Url photo = new Url(); photo.setLink(pRF.getLink()); photos.add(photo); pRF.setPhoto(photos); } if (pRF.getStartYear() > pRF.getEndYear()) { result = this.createModelAndView(pRF, null); result.addObject("error", "record.error.1"); } else { pR = this.periodRecordService.reconstructCreate(pRF, binding); if (binding.hasErrors()) { result = this.createModelAndView(pRF, null); if (pRF.getLink().equals("")) { result.addObject("customErrorMessage", "record.error.onePhoto"); result.addObject("error", "record.error.1"); } } else try { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); pR.setBrotherhood(bh); this.periodRecordService.save(pR); result = this.list(pR.getBrotherhood().getId()); } catch (final Throwable oops) { result = this.createModelAndView(pRF, "record.edit.error"); } } return result; } //LINK RECORD CREATE @RequestMapping(value = "/linkRecord/create", method = RequestMethod.GET) public ModelAndView createLink() { ModelAndView result; final LinkRecord lR = this.linkRecordService.create(); result = this.createModelAndView(lR); return result; } @RequestMapping(value = "/linkRecord/create", method = RequestMethod.POST, params = "create") public ModelAndView createLink(@ModelAttribute("lRF") final LinkRecord lRF, final BindingResult binding) { ModelAndView result; LinkRecord lR; lR = this.linkRecordService.reconstructCreate(lRF, binding); if (binding.hasErrors()) result = this.createModelAndView(lRF, null); else try { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); lR.setBrotherhood(bh); this.linkRecordService.save(lR); result = this.list(lR.getBrotherhood().getId()); } catch (final Throwable oops) { result = this.createModelAndView(lRF, "record.edit.error"); } return result; } //********************************************************************************** //** //** ALL RECORDS SHOWS //** //********************************************************************************** //INCEPTION RECORD SHOW @RequestMapping(value = "/inceptionRecord/show", method = RequestMethod.GET) public ModelAndView showInception(@RequestParam final int id) { ModelAndView result; final InceptionRecord iR; try { Assert.notNull(id); iR = this.inceptionRecordService.findOne(id); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } result = new ModelAndView("records/inceptionRecord/show"); result.addObject("record", iR); //Comprueba si el record pertenece al usuario logeado if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(iR.getBrotherhood())) result.addObject("isBrotherhood", true); } return result; } //LEGAL RECORD SHOW @RequestMapping(value = "/legalRecord/show", method = RequestMethod.GET) public ModelAndView showLegal(@RequestParam final int id) { ModelAndView result; final LegalRecord lR; try { Assert.notNull(id); lR = this.legalRecordService.findOne(id); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } result = new ModelAndView("records/legalRecord/show"); result.addObject("record", lR); //Comprueba si el record pertenece al usuario logeado if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(lR.getBrotherhood())) result.addObject("isBrotherhood", true); } return result; } //LINK RECORD SHOW @RequestMapping(value = "/linkRecord/show", method = RequestMethod.GET) public ModelAndView showLink(@RequestParam final int id) { ModelAndView result; final LinkRecord lR; try { Assert.notNull(id); lR = this.linkRecordService.findOne(id); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } result = new ModelAndView("records/linkRecord/show"); result.addObject("record", lR); //Comprueba si el record pertenece al usuario logeado if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(lR.getBrotherhood())) result.addObject("isBrotherhood", true); } return result; } //PERIOD RECORD SHOW @RequestMapping(value = "/periodRecord/show", method = RequestMethod.GET) public ModelAndView showPeriod(@RequestParam final int id) { ModelAndView result; final PeriodRecord pR; try { Assert.notNull(id); pR = this.periodRecordService.findOne(id); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } result = new ModelAndView("records/periodRecord/show"); result.addObject("record", pR); //Comprueba si el record pertenece al usuario logeado if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(pR.getBrotherhood())) result.addObject("isBrotherhood", true); } return result; } //MISC RECORD SHOW @RequestMapping(value = "/miscRecord/show", method = RequestMethod.GET) public ModelAndView showMisc(@RequestParam final int id) { ModelAndView result; final MiscRecord mR; try { Assert.notNull(id); mR = this.miscRecordService.findOne(id); } catch (final Exception e) { result = this.forbiddenOperation(); return result; } result = new ModelAndView("records/miscRecord/show"); result.addObject("record", mR); //Comprueba si el record pertenece al usuario logeado if (!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")) { final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh != null) if (bh.equals(mR.getBrotherhood())) result.addObject("isBrotherhood", true); } return result; } //********************************************************************************** //** //** ALL RECORDS EDITS //** //********************************************************************************** //INCEPTION RECORD EDIT GET AND POST @RequestMapping(value = "/inceptionRecord/edit", method = RequestMethod.GET) public ModelAndView editInception(@RequestParam final int id) { ModelAndView result; try { final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); result = this.editModelAndView(this.inceptionRecordService.findOne(id)); } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } @RequestMapping(value = "/inceptionRecord/edit", method = RequestMethod.POST, params = "save") public ModelAndView saveInception(@ModelAttribute("iRF") @Valid final InceptionRecordForm iRF, final BindingResult binding) { ModelAndView result; InceptionRecord iR; iR = this.inceptionRecordService.reconstructEdit(iRF, binding); iRF.setPhoto(iR.getPhoto()); if (binding.hasErrors()) result = this.editModelAndView(iRF, null); else try { this.inceptionRecordService.save(iR); result = new ModelAndView("redirect:/records/inceptionRecord/show.do?id=" + iR.getId()); } catch (final Throwable oops) { result = this.editModelAndView(iRF, "record.edit.error"); } return result; } //LEGAL RECORD EDIT GET AND POST @RequestMapping(value = "/legalRecord/edit", method = RequestMethod.GET) public ModelAndView editLegal(@RequestParam final int id) { ModelAndView result; try { final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); result = this.editModelAndView(this.legalRecordService.findOne(id)); } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } @RequestMapping(value = "/legalRecord/edit", method = RequestMethod.POST, params = "save") public ModelAndView saveLegal(@ModelAttribute("lRF") @Valid final LegalRecordForm lRF, final BindingResult binding) { ModelAndView result; LegalRecord lR; lR = this.legalRecordService.reconstructEdit(lRF, binding); lRF.setApplicableLaws(lR.getApplicableLaws()); if (binding.hasErrors()) result = this.editModelAndView(lRF, null); else try { this.legalRecordService.save(lR); result = new ModelAndView("redirect:/records/legalRecord/show.do?id=" + lR.getId()); } catch (final Throwable oops) { result = this.editModelAndView(lRF, "record.edit.error"); } return result; } //MISC RECORD EDIT GET AND POST @RequestMapping(value = "/miscRecord/edit", method = RequestMethod.GET) public ModelAndView editMisc(@RequestParam final int id) { ModelAndView result; try { final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); result = this.editModelAndView(this.miscRecordService.findOne(id)); } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } @RequestMapping(value = "/miscRecord/edit", method = RequestMethod.POST, params = "save") public ModelAndView saveMisc(@ModelAttribute("mRF") final MiscRecord mRF, final BindingResult binding) { ModelAndView result; MiscRecord mR; mR = this.miscRecordService.reconstructEdit(mRF, binding); if (binding.hasErrors()) result = this.editModelAndView(mRF, null); else try { this.miscRecordService.save(mR); result = new ModelAndView("redirect:/records/miscRecord/show.do?id=" + mR.getId()); } catch (final Throwable oops) { result = this.editModelAndView(mRF, "record.edit.error"); } return result; } //PERIOD RECORD EDIT GET AND POST @RequestMapping(value = "/periodRecord/edit", method = RequestMethod.GET) public ModelAndView editPeriod(@RequestParam final int id) { ModelAndView result; try { final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); result = this.editModelAndView(this.periodRecordService.findOne(id)); } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } @RequestMapping(value = "/periodRecord/edit", method = RequestMethod.POST, params = "save") public ModelAndView savePeriod(@ModelAttribute("pRF") @Valid final PeriodRecordForm pRF, final BindingResult binding) { ModelAndView result; PeriodRecord pR; pR = this.periodRecordService.reconstructEdit(pRF, binding); pRF.setPhoto(pR.getPhoto()); if (pRF.getStartYear() > pRF.getEndYear()) { result = this.editModelAndView(pRF, null); result.addObject("error", "record.error.1"); } else if (binding.hasErrors()) { result = this.editModelAndView(pRF, null); if (pR.getStartYear() > pR.getEndYear()) result.addObject("error", "record.error.1"); } else try { this.periodRecordService.save(pR); result = new ModelAndView("redirect:/records/periodRecord/show.do?id=" + pR.getId()); } catch (final Throwable oops) { result = this.editModelAndView(pRF, "record.edit.error"); } return result; } //LINK RECORD EDIT GET AND POST @RequestMapping(value = "/linkRecord/edit", method = RequestMethod.GET) public ModelAndView editLink(@RequestParam final int id) { ModelAndView result; try { final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); result = this.editModelAndView(this.linkRecordService.findOne(id)); } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } @RequestMapping(value = "/linkRecord/edit", method = RequestMethod.POST, params = "save") public ModelAndView saveLink(@ModelAttribute("lRF") final LinkRecord lRF, final BindingResult binding) { ModelAndView result; LinkRecord lR; lR = this.linkRecordService.reconstructEdit(lRF, binding); if (binding.hasErrors()) result = this.editModelAndView(lRF, null); else try { this.linkRecordService.save(lR); result = new ModelAndView("redirect:/records/linkRecord/show.do?id=" + lR.getId()); } catch (final Throwable oops) { result = this.editModelAndView(lRF, "record.edit.error"); } return result; } //********************************************************************************** //** //** ALL RECORDS DELETE //** //********************************************************************************** //INCEPTION RECORD DELETE @RequestMapping(value = "/inceptionRecord/delete", method = RequestMethod.GET) public ModelAndView deleteInception(@RequestParam final int id) { ModelAndView result = null; final InceptionRecord iR; try { Assert.notNull(id); iR = this.inceptionRecordService.findOne(id); final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh.equals(iR.getBrotherhood())) { this.inceptionRecordService.delete(iR); result = this.list(bh.getId()); } } catch (final Exception e) { result = this.forbiddenOperation(); return result; } return result; } //LEGAL RECORD DELETE @RequestMapping(value = "/legalRecord/delete", method = RequestMethod.GET) public ModelAndView deleteLegal(@RequestParam final int id) { ModelAndView result = null; final LegalRecord lR; try { Assert.notNull(id); lR = this.legalRecordService.findOne(id); final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh.equals(lR.getBrotherhood())) { this.legalRecordService.delete(lR); result = this.list(bh.getId()); } } catch (final Exception e) { result = this.forbiddenOperation(); return result; } return result; } //MISC RECORD DELETE @RequestMapping(value = "/miscRecord/delete", method = RequestMethod.GET) public ModelAndView deleteMisc(@RequestParam final int id) { ModelAndView result = null; final MiscRecord mR; try { Assert.notNull(id); mR = this.miscRecordService.findOne(id); final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh.equals(mR.getBrotherhood())) { this.miscRecordService.delete(mR); result = this.list(bh.getId()); } } catch (final Exception e) { result = this.forbiddenOperation(); return result; } return result; } //PERIOD RECORD DELETE @RequestMapping(value = "/periodRecord/delete", method = RequestMethod.GET) public ModelAndView deletePeriod(@RequestParam final int id) { ModelAndView result = null; final PeriodRecord pR; try { Assert.notNull(id); pR = this.periodRecordService.findOne(id); final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh.equals(pR.getBrotherhood())) { this.periodRecordService.delete(pR); result = this.list(bh.getId()); } } catch (final Exception e) { result = this.forbiddenOperation(); return result; } return result; } //LINK RECORD DELETE @RequestMapping(value = "/linkRecord/delete", method = RequestMethod.GET) public ModelAndView deleteLink(@RequestParam final int id) { ModelAndView result = null; final LinkRecord lR; try { Assert.notNull(id); lR = this.linkRecordService.findOne(id); final Brotherhood bh = this.brotherhoodService.findOne(this.actorService.getActorLogged().getId()); if (bh.equals(lR.getBrotherhood())) { this.linkRecordService.delete(lR); result = this.list(bh.getId()); } } catch (final Exception e) { result = this.forbiddenOperation(); return result; } return result; } //********************************************************************************** //** //** RECORDS ADD/DELETE PHOTOS AND LAWS //** //********************************************************************************** //INCEPTION RECORD ADD PHOTO @RequestMapping(value = "/inceptionRecord/edit", method = RequestMethod.POST, params = "addPhoto") public ModelAndView addPhoto(@ModelAttribute("iRF") @Valid final InceptionRecordForm iRF, final BindingResult binding) { ModelAndView result; InceptionRecord iR; final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); iR = this.inceptionRecordService.reconstructAddPhoto(iRF, binding); if (binding.hasErrors()) { iR = this.inceptionRecordService.findOne(iRF.getId()); iRF.setPhoto(iR.getPhoto()); result = this.editModelAndView(iRF, null); } else try { this.inceptionRecordService.save(iR); result = this.editModelAndView(iR); ; } catch (final Throwable oops) { result = this.editModelAndView(iRF, "record.edit.error"); } return result; } //INCEPTION RECORD DELETE PHOTO @RequestMapping(value = "/inceptionRecord/deletePhoto", method = RequestMethod.GET) public ModelAndView deleteInceptionPhoto(@RequestParam("id") final int id, @RequestParam("pos") final int pos) { ModelAndView result; try { final InceptionRecord iR = this.inceptionRecordService.findOne(id); final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); final List<Url> photos = (List<Url>) iR.getPhoto(); if (!(iR.getBrotherhood().equals(bh)) || pos >= photos.size() || (photos.size() == 1)) result = this.editModelAndView(iR); else { photos.remove(photos.get(pos)); iR.setPhoto(photos); this.inceptionRecordService.save(iR); result = this.editModelAndView(iR); } } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } //PERIOD RECORD ADD PHOTO @RequestMapping(value = "/periodRecord/edit", method = RequestMethod.POST, params = "addPhoto") public ModelAndView addPhoto(@ModelAttribute("pRF") @Valid final PeriodRecordForm pRF, final BindingResult binding) { ModelAndView result; PeriodRecord pR; final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); pR = this.periodRecordService.reconstructAddPhoto(pRF, binding); if (binding.hasErrors()) { pR = this.periodRecordService.findOne(pRF.getId()); pRF.setPhoto(pR.getPhoto()); result = this.editModelAndView(pRF, null); } else try { this.periodRecordService.save(pR); result = this.editModelAndView(pR); ; } catch (final Throwable oops) { result = this.editModelAndView(pRF, "record.edit.error"); } return result; } //PERIOD RECORD DELETE PHOTO @RequestMapping(value = "/periodRecord/deletePhoto", method = RequestMethod.GET) public ModelAndView deletePeriodPhoto(@RequestParam("id") final int id, @RequestParam("pos") final int pos) { ModelAndView result; try { final PeriodRecord pR = this.periodRecordService.findOne(id); final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); final List<Url> photos = (List<Url>) pR.getPhoto(); if (!(pR.getBrotherhood().equals(bh)) || pos >= photos.size() || (photos.size() == 1)) result = this.editModelAndView(pR); else { photos.remove(photos.get(pos)); pR.setPhoto(photos); this.periodRecordService.save(pR); result = this.editModelAndView(pR); } } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } //LEGAL RECORD ADD LAW @RequestMapping(value = "/legalRecord/edit", method = RequestMethod.POST, params = "addLaw") public ModelAndView addLaw(@ModelAttribute("lRF") @Valid final LegalRecordForm lRF, final BindingResult binding) { ModelAndView result; LegalRecord lR; final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); lR = this.legalRecordService.reconstructAddLaw(lRF, binding); if (binding.hasErrors()) { lR = this.legalRecordService.findOne(lRF.getId()); lRF.setApplicableLaws(lR.getApplicableLaws()); result = this.editModelAndView(lRF, null); } else try { this.legalRecordService.save(lR); result = this.editModelAndView(lR); ; } catch (final Throwable oops) { result = this.editModelAndView(lRF, "record.edit.error"); } return result; } //LEGAL RECORD DELETE LAW @RequestMapping(value = "/legalRecord/deleteLaw", method = RequestMethod.GET) public ModelAndView deleteLaw(@RequestParam("id") final int id, @RequestParam("law") final String law) { ModelAndView result; try { final LegalRecord lR = this.legalRecordService.findOne(id); final Actor user = this.actorService.getActorLogged(); final Brotherhood bh = this.brotherhoodService.findOne(user.getId()); Assert.notNull(bh); final List<String> laws = (List<String>) lR.getApplicableLaws(); if (!(lR.getBrotherhood().equals(bh)) || (lR.getApplicableLaws().size() == 1)) result = this.editModelAndView(lR); else { laws.remove(law); lR.setApplicableLaws(laws); this.legalRecordService.save(lR); result = this.editModelAndView(lR); } } catch (final Throwable oops) { result = this.forbiddenOperation(); } return result; } //********************************************************************************** //** //** MODELS AND VIEWS //** //********************************************************************************** //INCEPTION RECORD M&V protected ModelAndView editModelAndView(final InceptionRecord iR) { ModelAndView result; final InceptionRecordForm iRF = new InceptionRecordForm(iR); result = this.editModelAndView(iRF, null); return result; } protected ModelAndView editModelAndView(final InceptionRecordForm iRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/inceptionRecord/edit"); result.addObject("iRF", iRF); result.addObject("size", iRF.getPhoto().size()); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } protected ModelAndView createModelAndView(final InceptionRecord iR) { ModelAndView result; final InceptionRecordForm iRF = new InceptionRecordForm(iR); result = this.createModelAndView(iRF, null); return result; } protected ModelAndView createModelAndView(final InceptionRecordForm iRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/inceptionRecord/create"); result.addObject("iRF", iRF); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } //PERIOD RECORD M&V protected ModelAndView editModelAndView(final PeriodRecord pR) { ModelAndView result; final PeriodRecordForm pRF = new PeriodRecordForm(pR); result = this.editModelAndView(pRF, null); return result; } protected ModelAndView editModelAndView(final PeriodRecordForm pRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/periodRecord/edit"); result.addObject("pRF", pRF); result.addObject("cont", 0); result.addObject("size", pRF.getPhoto().size()); result.addObject("messageCode", messageCode); return result; } protected ModelAndView createModelAndView(final PeriodRecord pR) { ModelAndView result; final PeriodRecordForm pRF = new PeriodRecordForm(pR); result = this.createModelAndView(pRF, null); return result; } protected ModelAndView createModelAndView(final PeriodRecordForm pRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/periodRecord/create"); result.addObject("pRF", pRF); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } //LEGAL RECORD M&V protected ModelAndView editModelAndView(final LegalRecord lR) { ModelAndView result; final LegalRecordForm lRF = new LegalRecordForm(lR); result = this.editModelAndView(lRF, null); return result; } protected ModelAndView editModelAndView(final LegalRecordForm lRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/legalRecord/edit"); result.addObject("lRF", lRF); result.addObject("size", lRF.getApplicableLaws().size()); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } protected ModelAndView createModelAndView(final LegalRecord lR) { ModelAndView result; final LegalRecordForm lRF = new LegalRecordForm(lR); result = this.createModelAndView(lRF, null); return result; } protected ModelAndView createModelAndView(final LegalRecordForm lRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/legalRecord/create"); result.addObject("lRF", lRF); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } //MISC RECORD M&V protected ModelAndView editModelAndView(final MiscRecord mR) { ModelAndView result; result = this.editModelAndView(mR, null); return result; } protected ModelAndView editModelAndView(final MiscRecord mRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/miscRecord/edit"); result.addObject("mRF", mRF); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } protected ModelAndView createModelAndView(final MiscRecord mR) { ModelAndView result; result = this.createModelAndView(mR, null); return result; } protected ModelAndView createModelAndView(final MiscRecord mRF, final String messageCode) { ModelAndView result; result = new ModelAndView("records/miscRecord/create"); result.addObject("mRF", mRF); result.addObject("cont", 0); result.addObject("messageCode", messageCode); return result; } //LINK RECORD M&V protected ModelAndView editModelAndView(final LinkRecord lR) { ModelAndView result; result = this.editModelAndView(lR, null); return result; } protected ModelAndView editModelAndView(final LinkRecord lRF, final String messageCode) { ModelAndView result; final Collection<Brotherhood> brotherhoods = this.brotherhoodService.findAll(); brotherhoods.remove(this.brotherhoodService.findOne(this.actorService.getActorLogged().getId())); result = new ModelAndView("records/linkRecord/edit"); result.addObject("lRF", lRF); result.addObject("cont", 0); result.addObject("brotherhoods", brotherhoods); result.addObject("messageCode", messageCode); return result; } protected ModelAndView createModelAndView(final LinkRecord lR) { ModelAndView result; result = this.createModelAndView(lR, null); return result; } protected ModelAndView createModelAndView(final LinkRecord lRF, final String messageCode) { ModelAndView result; final Collection<Brotherhood> brotherhoods = this.brotherhoodService.findAll(); brotherhoods.remove(this.brotherhoodService.findOne(this.actorService.getActorLogged().getId())); result = new ModelAndView("records/linkRecord/create"); result.addObject("lRF", lRF); result.addObject("cont", 0); result.addObject("brotherhoods", brotherhoods); result.addObject("messageCode", messageCode); return result; } //********************************************************************************** //** //** MISC //** //********************************************************************************** private ModelAndView forbiddenOperation() { return new ModelAndView("redirect:/"); } }
package com.thomson.dp.principle.zen.lsp; import com.thomson.dp.principle.zen.lsp.domain.Son; import java.util.HashMap; import java.util.Map; /** * 父类子类场景类 * * @author Thomson Tang */ public class FatherSonClient { public static void invoker() { // Father father = new Father(); Son f = new Son(); //父类出现的地方,子类就应该能够出现 HashMap hashMap = new HashMap(); f.doSomething(hashMap); } public static void main(String[] args) { invoker(); } }