text
stringlengths
10
2.72M
import java.sql.Blob; import java.util.Date; /** Assignment class @StephenCole19 **/ public class Assignment { public int assignmentId; public String assignmentName; public Blob assignmentFile; public Date dueDate; //public Set<AssignmentSubmission> assignmentSubmission; public int courseOfferingId; //public Account account; public Assignment() {} public Assignment(String name, int id, Date due) { assignmentName = name; assignmentId = id; dueDate = due; } public String toString() { return "ID: " + assignmentId + " | " + assignmentName; } public Date getDate() { return dueDate; } public String getAssignmentName() { return assignmentName; } public int getAssignmentId() { return assignmentId; } }
/** * Copyright (c) Jason Brophy 2016 */ package edu.jbrophypdx.idsolitaire; import android.widget.ImageView; class Card { protected int value; protected int suit; protected ImageView img; Card(int value, int suit, ImageView img) { this.value = value; this.suit = suit; this.img = img; } Card(Card toCopy) { this.value = toCopy.value; this.suit = toCopy.suit; this.img = toCopy.img; } //Used to set the removable value. If the test against card makes this removable, return true. public boolean canRemove(Card testAgainst) { return testAgainst != null && this.value < testAgainst.getValue() && this.suit == testAgainst.getSuit(); } public int getValue() { return this.value; } public int getSuit() { return this.suit; } public ImageView getImageView() { return this.img; } }
/** * Package providing integration of * <a href="https://hibernate.org/">Hibernate 5.x</a> * with Spring concepts. * * <p>Contains an implementation of Spring's transaction SPI for local Hibernate transactions. * This package is intentionally rather minimal, with no template classes or the like, * in order to follow Hibernate recommendations as closely as possible. We recommend * using Hibernate's native <code>sessionFactory.getCurrentSession()</code> style. * * <p><b>This package supports Hibernate 5.x only.</b> */ @NonNullApi @NonNullFields package org.springframework.orm.hibernate5; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package br.com.welson.clinic.security; import br.com.welson.clinic.annotations.Transactional; import br.com.welson.clinic.errors.UsernameOrPasswordError; import br.com.welson.clinic.persistence.dao.DAO; import br.com.welson.clinic.persistence.model.AccessToken; import br.com.welson.clinic.persistence.model.ApplicationUser; import io.jsonwebtoken.SignatureAlgorithm; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.core.Response; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import static br.com.welson.clinic.security.SecurityConstants.*; import static io.jsonwebtoken.Jwts.builder; import static java.time.ZonedDateTime.now; import static java.util.Date.from; @RequestScoped public class Authentication { @Inject private DAO<ApplicationUser> applicationUserDAO; public Response authenticate(String username, String password) { ApplicationUser applicationUser = getApplicationUserByUsernameAndPassword(username, password); if (applicationUser == null) { return Response.status(Response.Status.FORBIDDEN).entity(new UsernameOrPasswordError()).build(); } applicationUser.setAccessToken(generateToken(applicationUser)); return Response.ok(applicationUser).build(); } private AccessToken generateToken(ApplicationUser applicationUser) { ZonedDateTime expirationTime = now(ZoneOffset.UTC).plus(EXPIRATION_TIME_IN_HOURS, ChronoUnit.HOURS); String token = PREFIX + builder().setSubject(applicationUser.getUsername()).setExpiration(from(expirationTime.toInstant())).signWith(SignatureAlgorithm.HS256, SECRET).compact(); return new AccessToken(token, expirationTime.toLocalDateTime()); } private ApplicationUser getApplicationUserByUsernameAndPassword(String username, String password) { List<ApplicationUser> applicationUsers = applicationUserDAO.findByHQLQuery(0, "applicationUserByUsernameAndPassword", username, password); return applicationUsers.size() == 1 ? applicationUsers.get(0) : null; } }
open module modmain { // allow reflective access, currently used in the example_jerry-mouse requires commons.lang3; }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.sql.oracle.select; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.visitor.SchemaStatVisitor; import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.wall.WallUtils; import java.util.List; public class OracleSelectTest117_bigunion extends MysqlTest { public void test_small_10() throws Exception { StringBuilder buf = new StringBuilder(); { buf.append("select * from (\n"); for (int i = 0; i < 10; ++i) { if (i != 0) { buf.append("union all\n"); } buf.append("select :").append(i).append(" as sid from dual\n"); } buf.append("\n) ux_x"); } String sql = buf.toString(); List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM (\n" + "\tSELECT :0 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :1 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :2 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :3 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :4 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :5 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :6 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :7 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :8 AS sid\n" + "\tFROM dual\n" + "\tUNION ALL\n" + "\tSELECT :9 AS sid\n" + "\tFROM dual\n" + ") ux_x", stmt.toString()); } public void test_big_100000() throws Exception { StringBuilder buf = new StringBuilder(); { buf.append("select * from (\n"); for (int i = 0; i < 1000 * 100; ++i) { if (i != 0) { buf.append("union all\n"); } buf.append("select :").append(i).append(" as sid from dual\n"); } buf.append("\n) ux_x"); } String sql = buf.toString(); List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); stmt.toString(); WallUtils.isValidateOracle(sql); SchemaStatVisitor statVisitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); stmt.accept(statVisitor); } }
package com.pd.security.shiro.security; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.Realm; /** * @author peramdy on 2018/10/23. */ public class PdSecurityManager extends DefaultSecurityManager { @Override public void setRealm(Realm realm) { super.setRealm(realm); } }
package com.ma.pluginframework.domain; import android.os.Parcel; import android.os.Parcelable; import java.util.List; /** * 主程序数据 */ public class HostData implements Parcelable { /** * 当前主程序界面使用的QQ */ private long activeUin; /** * 所有登录的QQ数据 */ private List<AccountData> accountDataList; /** * 附加数据 */ private String extra; public HostData(long activeUin, List<AccountData> accountDataList, String extra) { this.activeUin = activeUin; this.accountDataList = accountDataList; this.extra = extra; } protected HostData(Parcel in) { activeUin = in.readLong(); accountDataList = in.createTypedArrayList(AccountData.CREATOR); extra = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(activeUin); dest.writeTypedList(accountDataList); dest.writeString(extra); } @Override public int describeContents() { return 0; } public static final Creator<HostData> CREATOR = new Creator<HostData>() { @Override public HostData createFromParcel(Parcel in) { return new HostData(in); } @Override public HostData[] newArray(int size) { return new HostData[size]; } }; public long getActiveUin() { return activeUin; } public void setActiveUin(long activeUin) { this.activeUin = activeUin; } public List<AccountData> getAccountDataList() { return accountDataList; } public void setAccountDataList(List<AccountData> accountDataList) { this.accountDataList = accountDataList; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } @Override public String toString() { return "HostData{" + "activeUin=" + activeUin + ", accountDataList=" + accountDataList + ", extra='" + extra + '\'' + '}'; } }
package utils; /** * Work with JVM memory (only read). * Project: importBaseFoxPro * * @author Sergey B. (Prof0Soft@gmail.com) on 05.04.2019 */ public final class MemoryUtils { /** * Default constructor. */ private MemoryUtils() { } /** * Get description of using memory. * * @return string about using memory. */ public static String getMemory() { return "Memory total/use/free >>> " + Runtime.getRuntime().totalMemory() / 1048576 + "M / " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576 + "M / " + Runtime.getRuntime().freeMemory() / 1048576 + "M"; } }
package com.example.firstproject.entity; import lombok.AllArgsConstructor; import lombok.ToString; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity // DB가 해당 객체를 인식가능하게 한다. @AllArgsConstructor // 모든 변수에 대한 생성자를 생성해주는 lombok 코드 @ToString // 모든 변수에 대한 toString()을 만들어주는 annotation public class Article { @Id // primary key @GeneratedValue // 자동으로 Primary key값 설정 private Long id; // DB에서 알아볼 수 있게 Column이라고 해준다. @Column private String title; @Column private String content; }
package lab01; public interface GraphInterface { public void addVertex(Vertex vertex); public void removeVertex(Vertex vertex); public void addEdge(Vertex initialVertex, Vertex finalVertex, Edge edge); public void removeEdge(Edge edge); public int getVertexCount(); public boolean vertexExists(Vertex vertex); public boolean edgeExists(Vertex initialVertex, Vertex finalVertex); public Edge getEdge(Vertex initialVertex, Vertex finalVertex); }
package com.devgabriel.dglearn.repositories; import com.devgabriel.dglearn.entities.Topic; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TopicRepository extends JpaRepository<Topic, Long> { }
package com.dokyme.alg4.sorting.merge; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import static com.dokyme.alg4.sorting.merge.LinkedListNaturalMerge.LinkedList; /** * Created by intellij IDEA.But customed by hand of Dokyme. * 2.2.18 * * @author dokym * @date 2018/4/23-17:43 * Description: */ public class DisorderLinkedList { private LinkedList.Node middleNode(LinkedList.Node start, LinkedList.Node end) { //快慢指针查找链表中点(中点或中间靠前的一个节点) LinkedList.Node fast = start, slow = start; while (fast != end && fast.next != end) { fast = fast.next.next; slow = slow.next; } return slow; } private void shuffleMerge(LinkedList.Node lo, LinkedList.Node hi) { LinkedList.Node mi = middleNode(lo, hi); //乱序归并a[lo+1...mi]和a[mi+1...hi] LinkedList.Node i = lo.next, j = mi.next; final LinkedList.Node leftEnd = mi.next, rightEnd = hi.next; while (i != leftEnd || j != rightEnd) { if (i == leftEnd) { lo.next = j; j = j.next; } else if (j == rightEnd) { lo.next = i; i = i.next; } else if (StdRandom.bernoulli()) { lo.next = j; j = j.next; } else { lo.next = i; i = i.next; } lo = lo.next; } lo.next = rightEnd; } public void shuffle(LinkedList a) { shuffle(a.first, a.last); } private void shuffle(LinkedList.Node start, LinkedList.Node end) { if (start == end || start.next == end) { return; } LinkedList.Node mid = middleNode(start, end); LinkedList.Node midNext = mid.next; shuffle(start, mid); shuffle(midNext, end); shuffleMerge(start, end); } public static void main(String[] args) { LinkedList<Integer> list = new LinkedList(); for (int i = 0; i < 19; i++) { list.add(i); } new DisorderLinkedList().shuffle(list); for (int i = 0; i < 16; i++) { StdOut.print(list.poll() + "\n"); } } }
import java.io.*; import java.util.*; class baek__12906 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] start = new String[3]; Arrays.fill(start, ""); String[] temp = br.readLine().split(" "); if (!temp[0].equals("0")) start[0] = temp[1]; temp = br.readLine().split(" "); if (!temp[0].equals("0")) start[1] = temp[1]; temp = br.readLine().split(" "); if (!temp[0].equals("0")) start[2] = temp[1]; char[] arr = (start[0] + start[1] + start[2]).toCharArray(); String[] target = new String[3]; Arrays.fill(target, ""); for (int idx = 0; idx < 3; idx++) { for (int i = 0; i < arr.length; i++) { if (arr[i] == 'A' + idx) { target[idx] += arr[i]; } } } // for (int i = 0; i < 3; i++) { // System.out.print(target[i] + " "); // } HashMap<List<String>, Integer> map = new HashMap<>(); Queue<List<String>> q = new LinkedList<>(); q.add(Arrays.asList(start)); map.put(Arrays.asList(start), 0); while (!q.isEmpty()) { String[] cur = q.poll().toArray(new String[3]); int d = map.get(Arrays.asList(cur)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == j) continue; if (cur[i].equals("")) continue; String[] now = cur.clone(); char moved = now[i].charAt(now[i].length() - 1); now[i] = now[i].substring(0, now[i].length() - 1); now[j] = now[j] + moved; if (map.containsKey(Arrays.asList(now))) continue; map.put(Arrays.asList(now), d + 1); q.add(Arrays.asList(now)); } } } System.out.print(map.get(Arrays.asList(target))); } }
package org.abrahamalarcon.datastream.util; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; @Component public class ErrorCodeMapping { @Autowired protected MessageSource errorCodeMessageSource; public String getMessage(ErrorCode errorCode) { return getMessage(errorCode, null); } public String getMessage(ErrorCode errorCode, String[] params) { String message = null; if(errorCode != null) { message = errorCodeMessageSource.getMessage(errorCode.toString(), params, Locale.getDefault()); } return message; } }
package com.sohu.live56.view.main.square; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.sohu.kurento.bean.RoomBean; import com.sohu.kurento.netClient.KWWebSocketClient; import com.sohu.kurento.util.LooperExecutor; import com.sohu.live56.R; import com.sohu.live56.bean.Room; import com.sohu.live56.util.Constants; import com.sohu.live56.util.LogCat; import com.sohu.live56.view.main.player.ObserverActivity; import com.sohu.live56.view.main.player.ObserverFrag; import java.util.ArrayList; import pl.droidsonroids.gif.GifImageView; /** * 广场 fragment . * <p/> * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * to handle interaction events. * Use the {@link SquareFrag#newInstance} factory method to * create an instance of this fragment. */ public class SquareFrag extends Fragment implements AdapterView.OnItemClickListener { private TextView titletv; private ListView squarelv; private LinearLayout squarenodatefl; private SquareAdapter squareAdapter; private KWWebSocketClient socketClient = null; private boolean webSocketOk = false; private GifImageView progressImg = null; public static final String MASTER_KEY = "masterId"; // TODO: Rename parameter arguments, choose names that match public static SquareFrag newInstance() { SquareFrag fragment = new SquareFrag(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public SquareFrag() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } LogCat.debug("squareFragment create()----"); socketClient = KWWebSocketClient.init(); socketClient.setExecutor(new LooperExecutor()); socketClient.setListListener(new ListListener()); socketClient.connect(Constants.HOST_URL); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_square, container, false); initialize(view); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } @Override public void onDestroy() { super.onDestroy(); socketClient.close(); } private void initialize(View view) { titletv = (TextView) view.findViewById(R.id.title_tv); squarelv = (ListView) view.findViewById(R.id.square_lv); squarelv.setSelector(new BitmapDrawable()); squarelv.setOnItemClickListener(this); squarenodatefl = (LinearLayout) view.findViewById(R.id.square_nodate_fl); progressImg = (GifImageView) view.findViewById(R.id.wifi_progress); squareAdapter = new SquareAdapter(getActivity().getApplicationContext()); squarelv.setAdapter(squareAdapter); requestData(); } /** * init data to listview. * * @param rooms */ private void initData(ArrayList<Room> rooms) { if (rooms != null && rooms.size() > 0) { hasData(); squareAdapter.notifyDataSetChanged(rooms); } else noData(); } /** * get list data. Show progress icon if websocket is connecttiong. * Show no data if websocket connected failed. */ private void requestData() { if (webSocketOk) { socketClient.sendListerRequest(); } else { noData(); } } private void noData() { squarelv.setVisibility(View.GONE); squarenodatefl.setVisibility(View.VISIBLE); } private void progressWifi() { squarenodatefl.setVisibility(View.VISIBLE); } private void hasData() { squarelv.setVisibility(View.VISIBLE); squarenodatefl.setVisibility(View.GONE); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getActivity(), ObserverActivity.class); SquareAdapter adapter = (SquareAdapter) parent.getAdapter(); Room room = (Room) adapter.getItem(position); intent.putExtra(MASTER_KEY, String.valueOf(room.getName())); LogCat.debug("start room Id : " + room.getSessionId()); getActivity().startActivity(intent); } private class ListListener implements KWWebSocketClient.OnListListener { @Override public void onListListener(final ArrayList<RoomBean> rooms) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (rooms == null) return; ArrayList<Room> viewRooms = new ArrayList<Room>(); for (RoomBean roomBean : rooms) { Room room = new Room(); room.setSessionId(roomBean.getSessionId()); room.setName(roomBean.getName()); room.setState(Room.State.LIVING); viewRooms.add(room); } initData(viewRooms); } }); } @Override public void onConnectionOpened() { webSocketOk = true; requestData(); } @Override public void onError(final String msg) { // webSocketOk = false; getActivity().runOnUiThread(new Runnable() { @Override public void run() { initData(null); // Toast.makeText(getActivity().getApplicationContext(), "websocket connect failed : " + msg, Toast.LENGTH_SHORT).show(); } }); } @Override public void onClose(String msg) { // webSocketOk = false; LogCat.debug("websocket colsed...." + msg); } } }
package cttd.cryptography.demo; import org.junit.Test; import static org.junit.Assert.*; public class AesTests { private String plaintext = "Nguyễn Anh Tuấn"; private String ciphertext = "YlBfisYuEUlt/JBGQYWaMa7EKg=="; @Test public void encryptTest() { assertEquals(ciphertext, Aes.encrypt(plaintext)); } @Test public void decryptTest() { assertEquals(plaintext, Aes.decrypt(ciphertext)); } }
package com.atguigu.test; import static org.junit.Assert.*; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.atguigu.entity.User; import com.atguigu.mvc.UserController; public class SpringTest { /* * 容器中的对象是创建容器时创建; * */ @Test public void test1() throws Exception { ApplicationContext Context = new ClassPathXmlApplicationContext("helloword.xml"); UserController bean = Context.getBean(UserController.class); User user = bean.getUserById(); System.out.println(user); } }
package com.perfect.web.service.impl; import com.perfect.core.base.BaseServiceImpl; import com.perfect.entity.RolePermission; import com.perfect.entity.mapper.RolePermissionMapper; import com.perfect.web.service.RolePermissionService; import org.springframework.stereotype.Service; /** * <p> * 角色权限表 服务实现类 * </p> * * @author Ben. * @since 2017-03-15 */ @Service public class RolePermissionServiceImpl extends BaseServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService { }
package com.saechimdaeki.chap05; import org.springframework.data.repository.query.ReactiveQueryByExampleExecutor; public interface ItemByExampleRepository extends ReactiveQueryByExampleExecutor<Item> { }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.captcha.util; import java.io.Serializable; import java.util.Collections; import java.util.Map; /** * Enabled Security Mechanism. */ public class EnabledSecurityMechanism implements Serializable { private static final long serialVersionUID = -4123547888178387354L; private String mechanism; private Map<String, String> properties; public String getMechanism() { return mechanism; } public void setMechanism(String mechanism) { this.mechanism = mechanism; } public Map<String, String> getProperties() { if (properties == null) { return Collections.emptyMap(); } return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } }
package com.yma.week_of_code; import java.util.Scanner; /** * Created by Yoshan Amarathunga on 3/13/2017. */ public class CandyReplenishingRobot { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int t = in.nextInt(); int[] c = new int[t]; for(int c_i=0; c_i < t; c_i++){ c[c_i] = in.nextInt(); } int bowl = n; int inc = 0; for (int i = 0; i < t; i++) { bowl = bowl - c[i]; if(i != (t-1)){ if(bowl < 5){ int incres = (n - bowl); inc += incres; bowl += incres; } } } System.out.println(inc); } }
package de.cuuky.varo.command.essentials; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import de.cuuky.varo.Main; import de.cuuky.varo.config.messages.ConfigMessages; import de.cuuky.varo.version.BukkitVersion; import de.cuuky.varo.version.VersionUtils; import de.cuuky.varo.version.types.Sounds; import de.cuuky.varo.world.border.VaroBorder; public class BorderCommand implements CommandExecutor { /* * OLD CODE */ @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { if(VersionUtils.getVersion() == BukkitVersion.ONE_7) { sender.sendMessage(Main.getPrefix() + "Nicht verfügbar in der 1.7!"); return false; } if(args.length == 0) { sender.sendMessage(Main.getPrefix() + "§7Die Border ist " + Main.getColorCode() + (sender instanceof Player ? new VaroBorder(((Player) sender).getWorld()).getSize() : Main.getDataManager().getWorldHandler().getBorder().getSize()) + " §7Blöcke groß!"); if(sender instanceof Player) sender.sendMessage(Main.getPrefix() + "§7Du bist " + Main.getColorCode() + (int) Main.getDataManager().getWorldHandler().getBorder().getDistanceTo((Player) sender) + "§7 Blöcke von der Border entfernt!"); if(sender.hasPermission("varo.setup")) sender.sendMessage(Main.getPrefix() + "§7Du kannst die Größe der Border mit " + Main.getColorCode() + "/border <Größe> §7setzen!"); return false; } else if(args.length >= 1 && sender.hasPermission("varo.setup")) { Player p = sender instanceof Player ? (Player) sender : null; int border1; int inSeconds = -1; try { border1 = Integer.parseInt(args[0]); } catch(NumberFormatException e) { p.sendMessage(Main.getPrefix() + "§7Das ist keine Zahl!"); return false; } VaroBorder border = p != null ? new VaroBorder(p.getWorld()) : Main.getDataManager().getWorldHandler().getBorder(); try { inSeconds = Integer.parseInt(args[1]); border.setSize(border1, inSeconds); } catch(ArrayIndexOutOfBoundsException e) { border.setSize(border1); } if(p != null) border.setCenter(p.getLocation()); sender.sendMessage(Main.getPrefix() + ConfigMessages.COMMAND_SET_BORDER.getValue().replace("%zahl%", String.valueOf(border1))); if(p != null) p.playSound(p.getLocation(), Sounds.NOTE_BASS_DRUM.bukkitSound(), 1, 1); } else sender.sendMessage(Main.getPrefix() + "§7/border"); return false; } }
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import java.math.BigDecimal; /** * ExpensePenson * * @author ZhangJP * @date 2020/10/30 */ @Data public class ExpenseVO { @TableField("user_id") private String userId; @TableField("user_name") private String userName; @TableField("dept_id") private String deptId; @TableField("sub_dept_id") private String subDeptId; @TableField("amount") private BigDecimal amount; }
/* * Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.translation.form.action; import org.apache.log4j.Logger; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.translation.form.RegistrationTranslationAction; import pl.edu.icm.unity.server.translation.form.TranslatedRegistrationRequest; import pl.edu.icm.unity.server.utils.Log; import pl.edu.icm.unity.types.translation.TranslationActionType; /** * Action used instead of a real action when it is misconfigured. * @author K. Benedyczak */ public class BlindStopperRegistrationAction extends RegistrationTranslationAction { private static final Logger log = Log.getLogger(Log.U_SERVER_TRANSLATION, BlindStopperRegistrationAction.class); public BlindStopperRegistrationAction(TranslationActionType description, String[] params) { super(description, params); } @Override protected void invokeWrapped(TranslatedRegistrationRequest state, Object mvelCtx, String currentProfile) throws EngineException { log.warn("Skipping invocation of a invalid action " + getName()); } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; public class Main { public static void main(String[] args) { Motorcycle motorcycle1 = new Motorcycle("WE23"); Motorcycle motorcycle2 = new Motorcycle("R666"); Car car1 = new Car("T123PH"); Car car2 = new Car("X666XX"); Byke byke1 = new Byke("12D"); Byke byke2 = new Byke("14S"); ParkingPlace place = new ParkingPlace(); place.Parking(car1); place.Parking(motorcycle1); place.Parking(byke2); place.Unparking("WE23"); } }
package com.base.demo; import com.base.demo.enums.City; import com.base.demo.interfaces.Behavior; import com.base.demo.interfaces.Dog; /** * 接口细节,枚举类 * @author Cherry * 2020年4月2日 */ public class DemoF extends Base{ @SuppressWarnings("static-access") public static void main(String[] args) { Man n = new Man(); n.watch(); show(n.TIME); show(n.name); Behavior b = new Behavior() { @Override public void watch() { System.out.println("watch method"); } @Override public void say() { System.out.println("say method"); } }; b.say(); show(b.name); show(City.Beijin); Dog g = new Dog() { @Override public void watch() { } @Override public void say() { } @Override public void eat() { } }; show(g.c); } }
package msip.go.kr.organ.service.impl; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import msip.go.kr.common.entity.Tree; import msip.go.kr.organ.entity.HeadDprt; /** * 본부 조직도 데이터 처리를 위한 DAO 클래스 정의 * * @author 정승철 * @since 2015.07.09 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * --------------------------------------------------------------------------------- * 2015.07.09 정승철 최초생성 * * </pre> */ @Repository("headDprtDAO") public class HeadDprtDAO { /** * @PersistenceContext 어노테이션을 이용하여 컨테이너로부터 EntityManger DI * @param EntityManager em */ @PersistenceContext private EntityManager em; /** * 선택된 id 에 따라 본부 조직도 정보를 데이터베이스에서 삭제 * @param HeadDprtTemp entity * @throws Exception */ public void remove(HeadDprt entity) throws Exception { em.remove(em.merge(entity)); } /** * 새로운 본부 조직 정보를 입력받아 데이터베이스에 저장 * @param HeadDprtTemp entity * @throws Exception */ public void persist(HeadDprt entity) throws Exception { this.em.persist(entity); } /** * 본부 조직도의 전체 목록을 데이터베이스에서 읽어와 화면에 출력 * @return List<HeadDprt> 본부 조직도 목록 * @throws Exception */ public List<HeadDprt> findAll() throws Exception { String hql = "from HeadDprt order by c.id"; List<HeadDprt> categories = em.createQuery(hql, HeadDprt.class).getResultList(); return categories; } /** * 본부 조직도의 전체 목록을 데이터베이스에서 읽어와 화면에 출력 * @return List<HeadDprt> 본부 조직도 목록 * @throws Exception */ @SuppressWarnings("unchecked") public List<Tree> tree() throws Exception { StringBuffer hql = new StringBuffer(); hql.append("SELECT TO_CHAR(id), DECODE(pid, 0, '#', TO_CHAR(pid)), name "); hql.append("FROM head_dprt WHERE isvisb = 1 START WITH dprtid=1000 CONNECT BY PRIOR id = pid ORDER SIBLINGS BY sort, trns_key"); Query query = em.createNativeQuery(hql.toString()); List<Tree> list = new ArrayList<Tree>(); List<Object[]> result = query.getResultList(); for(Object[] row : result) { String id = (String) row[0]; String parent = (String) row[1]; String text = (String) row[2]; boolean opened = false; if("#".equals(parent)) opened = true; Tree t = new Tree(id, parent, text, opened); list.add(t); } return list; } /** * 수정된 조직도 정보를 데이터베이스에 반영 * @param HeadDprtTemp entity * @throws Exception */ public void merge(HeadDprt entity) throws Exception { em.merge(entity); } /** * 선택된 id에 따라 데이터베이스에서 조직도 정보를 읽어와 화면에 출력 * @param Long id * @return HeadDprt entity * @throws Exception */ public HeadDprt findById(Long id) throws Exception{ return em.find(HeadDprt.class, id); } }
package fileManager; public class BinaryTree { Node root; BinaryTree(String key){ root = new Node(key); } BinaryTree(){ root = null; } // public Node createnewNode(String key) { // Node a = new Node(); // a.key = key; // a.left = null; // a.right = null; // return a; // // } // // public Node insert(Node node, String key) { // if(node == null) { // return createnewNode(key); // } // // if(key < node.key) { // node. // } // // return node; // } public void printtree(Node node, int level) { if(node == null) { return; } if(level == 1) { System.out.print(node.key + " "); } printtree(node.left,level-1); printtree(node.right,level-1); } }
package String_Level1.Programming_Questions; import java.util.Scanner; public class P5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int count=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)>='A' && s.charAt(i)<='Z') { count++; } } for(int i=0;i<s.length();i++) { if(s.charAt(i)==' ') { count++; } } System.out.println(count); } }
package sign.com.biz.role.service.impl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import sign.com.biz.base.service.impl.BaseServiceImpl; import sign.com.biz.role.dto.ResourceDto; import sign.com.biz.role.mapper.ResourceMapper; import sign.com.biz.role.service.ResourceService; import sign.com.biz.user.dto.UserRoleDto; import tk.mybatis.mapper.entity.Example; import java.util.List; /** * create by luolong on 2018/5/14 */ @Service public class ResourceServiceImpl extends BaseServiceImpl<ResourceDto> implements ResourceService { Logger log = Logger.getLogger(getClass()); @Autowired ResourceMapper resourceMapper; @Override public List<ResourceDto> findViewResourceAll() { /*Example resourceExample = new Example(ResourceDto.class); resourceExample.createCriteria() .andEqualTo("enabled",false) .andEqualTo("isConfig",true); return resourceMapper.selectByExample(resourceExample); */ ResourceDto resourceDto = new ResourceDto() {{ setEnabled(true); setConfig(true); }}; return resourceMapper.select(resourceDto); } @Override public List<ResourceDto> findUserResourceAll(UserRoleDto userRoleDto) { if (userRoleDto != null && userRoleDto.getIdUserGroup() > 0 && userRoleDto.getIdUser() > 0) { return resourceMapper.selectAllResourceOnUser(userRoleDto); } return null; } @Override public List<ResourceDto> findAbledResourceAll() { Example example = new Example(ResourceDto.class); example.createCriteria().andEqualTo("enabled",true); return resourceMapper.selectByExample(example); } }
/* * 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 ru.sfedu.booklibhibernate.dao; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author sergey */ public class HibernateDataProviderTest { public HibernateDataProviderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getDatabaseSize method, of class HibernateDataProvider. */ @Test public void testGetDatabaseSize() { System.out.println("getDatabaseSize"); HibernateDataProvider instance = new HibernateDataProvider(); String expResult = ""; String result = instance.getDatabaseSize(); System.out.println(result); } /** * Test of getDatabaseTableList method, of class HibernateDataProvider. */ //@Test public void testGetDatabaseTableList() { System.out.println("getDatabaseTableList"); HibernateDataProvider instance = new HibernateDataProvider(); String[] expResult = null; String[] result = instance.getDatabaseTableList(); assertArrayEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getDatabaseUserList method, of class HibernateDataProvider. */ //@Test public void testGetDatabaseUserList() { System.out.println("getDatabaseUserList"); HibernateDataProvider instance = new HibernateDataProvider(); String[] expResult = null; String[] result = instance.getDatabaseUserList(); assertArrayEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getDatabaseDataTypesList method, of class HibernateDataProvider. */ // @Test public void testGetDatabaseDataTypesList() { System.out.println("getDatabaseDataTypesList"); HibernateDataProvider instance = new HibernateDataProvider(); String[] expResult = null; String[] result = instance.getDatabaseDataTypesList(); assertArrayEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getDatabaseFunctionList method, of class HibernateDataProvider. */ //@Test public void testGetDatabaseFunctionList() { System.out.println("getDatabaseFunctionList"); HibernateDataProvider instance = new HibernateDataProvider(); String[] expResult = null; String[] result = instance.getDatabaseFunctionList(); assertArrayEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
// 2021-08-04 import java.util.*; // 마이너스 부호가 숫자 앞에 있을 경우 재고려해야함. // ex ) [ 5 , - , 2 , * , 3 , *, 5] // [ 5 , - , 6 , *, 5] => (o) // [ 5 , -6 , *, 5] => (x) - 현재 이렇게 구현되어 있음 class AddParentheses { // solution // dfs 로 풀이 시 중복 문제 발생 // 분할정복으로 풀이 public List<Integer> diffWaysToCompute(String expression) { List<Integer> res = new ArrayList<>(); if ( expression == null || expression.length() == 0 ) { return res; } for(int i=0; i<expression.length(); i++) { char chr = expression.charAt(i); if ( chr == '+' || chr == '-' || chr == '*' ) { String part1 = expression.substring(0, i); String part2 = expression.substring(i+1); List<Integer> part1Res = diffWaysToCompute(part1); List<Integer> part2Res = diffWaysToCompute(part2); for(Integer p1: part1Res) { for(Integer p2 : part2Res) { if ( chr == '+' ) { res.add(p1+p2); } else if ( chr == '-' ) { res.add(p1-p2); } else { res.add(p1*p2); } } } } } if ( res.size() == 0 ) { res.add(Integer.valueOf(expression)); } return res; } /// List<Integer> list = new ArrayList<>(); public int operate ( int idx, List<String> l ) { int first = l.get(idx).charAt(0)-'0'; int second = l.get(idx+2).charAt(0)-'0'; String operand = l.get(idx+1); int operated; if ( operand.charAt(0) == '*' ) { operated = first*second; } else if ( operand.charAt(0) == '+' ) { operated = first + second; } else { operated = first - second; } return operated; } public void dfs( List<String> strList ) { System.out.println( "dfs : " + strList.toString()); if ( strList.size() == 3 ) { int cal = operate( 0, strList ); list.add( cal ); System.out.println( " finish : " + cal ); return; } List<String> tmp = new ArrayList<>(); for( int i=0; i<strList.size()-3; i+=2 ) { System.out.println( i ); tmp.clear(); for( int j=0; j<i; j++) { tmp.add( strList.get(j) ); } int cal = operate( i, strList ); tmp.add( Integer.toString(cal) ); for( int k=i+3; k<strList.size(); k++ ) { tmp.add( strList.get(k) ); } dfs( tmp ); } } public List<Integer> diffWaysToCompute1(String expression) { String[] arr = expression.split(""); List<String> arrAsList = Arrays.asList(arr); dfs(arrAsList); return list; } public static void main(String[] args) { AddParentheses add = new AddParentheses(); String str = "2*3-4*5"; List<Integer> result = add.diffWaysToCompute( str ); System.out.println("================"); for( int ans : result ) { System.out.println( ans ); } System.out.println(); } }
package algorithms.chap1; import java.util.Iterator; public class LinkedListQueue<Item> implements Iterable<Item> { Node first; Node last; int size = 0; public void push(Item item) { if (last != null) { Node old = last; last = new Node(); last.item = item; old.next = last; }else { first = last = new Node(); last.item = item; } size++; } public Item pop() { Item result = first.item; if (first != last) { first = first.next; }else { first = last = null; } size--; return result; } public int size() { return size; } @Override public Iterator iterator() { return new LinkedListIterator(); } class Node { Node next; Item item; } private class LinkedListIterator implements Iterator<Item> { Node head = first; @Override public boolean hasNext() { return head != null; } @Override public Item next() { Item item = head.item; head = head.next; return item; } } }
/** * Custom JUnit 4 {@code Rules} used in the <em>Spring TestContext Framework</em>. */ @NonNullApi @NonNullFields package org.springframework.test.context.junit4.rules; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package cn.okay.page.officialwebsite.secondpage; import cn.okay.testbase.AbstractPage; import cn.okay.tools.WaitTool; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * Created by yutz on 2017/10/17. * 公司简介页 */ public class CompanyProfilePage extends AbstractPage { @FindBy(id="nav") public WebElement pageContent; public CompanyProfilePage(WebDriver driver) { super(driver); WaitTool.waitFor(driver,DefaultWaitElementTime4Page,pageContent); } }
/*********************************************************** * @Description : 测试开闭原则的类 * @author : 梁山广(Laing Shan Guang) * @date : 2019/3/10 17:58 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第3章_软件设计七大原则.S01_开闭原则OpenClose; public class Test { public static void main(String[] args) { // 实现接口,面向接口编程,接口是不能变地 ICourse iCourse1 = new JavaCourse(96, "Java编程思想", 348.00); System.out.println(iCourse1); // 利用类继承实现"课程打折"需求从而不改变ICourse和JavaCourse两个既有的类和接口 ICourse iCourse2 = new JavaCourseDiscount(96, "Java编程思想", 348.00); System.out.println(iCourse2); // 如果想要调用JavaCourseDiscount中的getOriginalPrice()方法必须先把javaCourseDiscount强转换成JavaCourseDiscount类 JavaCourseDiscount javaCourseDiscount = (JavaCourseDiscount) iCourse2; System.out.println((javaCourseDiscount).getOriginalPrice()); } }
package com.example.ayuth.androidpresentationremoteclient; import android.net.Uri; import android.util.Log; import com.github.nkzawa.socketio.client.IO; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import java.net.URISyntaxException; public class RemoteSocket { private static volatile RemoteSocket remoteSocketInstance; private Socket mSocket; private boolean isConnected; private RemoteSocket() { if (remoteSocketInstance != null) { throw new RuntimeException("Use getInstance() method to get the single instance of this class."); } isConnected = false; } // private constructor. public static RemoteSocket getInstance() { if (remoteSocketInstance == null) { // if there is no instance available... create new one synchronized (RemoteSocket.class) { // Check for the second time. if (remoteSocketInstance == null) remoteSocketInstance = new RemoteSocket(); } } return remoteSocketInstance; } public void connect(String uri) throws URISyntaxException { mSocket = IO.socket(uri); mSocket.connect(); } public void sendCommand(RemoteCommand remoteCommand) { JSONObject command = new JSONObject(); try { command.put("command", remoteCommand.toString()); Log.i("RemoteSocket", remoteCommand.toString()); } catch (JSONException ex) { Log.e("RemoteSocket", ex.getMessage()); } if (remoteCommand == RemoteCommand.START_PRESENTATION) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.STOP_PRESENTATION) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.GOTO_FIRST_SLIDE) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.GOTO_FIRST_SLIDE) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.GOTO_PREVIOUS_SLIDE) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.GOTO_NEXT_SLIDE) { mSocket.emit("command", command); } else if (remoteCommand == RemoteCommand.GOTO_LAST_SLIDE) { mSocket.emit("command", command); } } public Socket getSocket() { return this.mSocket; } // Make singleton from serialize and deserialize operation. protected RemoteSocket readResolve() { return getInstance(); } }
package creational.factory_method; public class Test { public static void main(String[] args){ IProduct product = FactoryMethod.getProductY(); product.doA(); } }
package com.yoga.controller; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.yoga.dao.TbStaffDAO; import com.yoga.dao.TbStaffDetailDAO; import com.yoga.entity.TbMember; import com.yoga.entity.TbStaff; import com.yoga.entity.TbStaffDetail; import com.yoga.util.Constants; import com.yoga.util.DateUtil; import com.yoga.util.JsonResponse; import com.yoga.util.Page; /** * action * * @author wwb * */ @Controller @RequestMapping("/") public class TbStaffController { /** * 获取dao */ private TbStaffDAO dao = new TbStaffDAO(); private TbStaffDetailDAO staffDetailDAO= new TbStaffDetailDAO(); /** * 添加信息 * @param id * @param name * @param price * @return */ @RequestMapping(value = "staffDetail/add", method = RequestMethod.GET) @ResponseBody public JsonResponse<TbStaffDetail> add(final String id, final String name, final String sex, final String age,final String post,final String phone, final String card,final String address, String email, final String time,final String staffDetailId) { JsonResponse<TbStaffDetail> jsonResponse = new JsonResponse<TbStaffDetail>(); try { TbStaffDetail entity = getBean(id, name, sex, age, post, phone, card, address, email, time, staffDetailId); dao.save(entity.getTbStaff()); staffDetailDAO.save(entity); jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.STAFF, Constants.SUCCESS)); jsonResponse.setSuccess(true); } catch (Exception e) { e.printStackTrace(); jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.STAFF, Constants.FAILURE)); } return jsonResponse; } /** * 获取所有用户列表 * @return */ @RequestMapping(value = "staff/alllist.html", method = RequestMethod.GET) @ResponseBody public JsonResponse<TbStaff> alllist() { JsonResponse<TbStaff> jsonResponse = new JsonResponse<TbStaff>(); try { List<TbStaff> findAll = dao.findAll(); jsonResponse.setSuccess(true); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.MEMBER, Constants.SUCCESS)); jsonResponse.setList(findAll); } catch (Exception e) { jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.MEMBER, Constants.FAILURE)); } return jsonResponse; } /** * 编辑信息 * @param id * @param name * @param price * @return */ @RequestMapping(value = "staffDetail/edit", method = RequestMethod.GET) @ResponseBody public JsonResponse<TbStaffDetail> edit(final String id, final String name, final String sex, final String age,final String post,final String phone, final String card,final String address, String email, final String time,final String staffDetailId) { JsonResponse<TbStaffDetail> jsonResponse = new JsonResponse<TbStaffDetail>(); try { TbStaffDetail entity = getBean(id, name, sex, age, post, phone, card, address, email, time,staffDetailId); //更新员工表 dao.update(entity.getTbStaff()); //更新员工详细表 staffDetailDAO.update(entity); jsonResponse.setMsg(Constants.getTip(Constants.EDIT, Constants.STAFF, Constants.SUCCESS)); jsonResponse.setSuccess(true); } catch (Exception e) { e.printStackTrace(); jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.EDIT, Constants.STAFF, Constants.FAILURE)); } return jsonResponse; } /** * 删除信息 * @param id * @param name * @param price * @return */ @RequestMapping(value = "staffDetail/delete", method = RequestMethod.GET) public ModelAndView delete(final String id, final String name, final String sex, final String age,final String post,final String phone, final String card,final String address, String email, final String time,final String staffDetailId) { try { TbStaffDetail entity = getBean(id, name, sex, age, post, phone, card, address, email, null,staffDetailId); //更新员工表 dao.update(entity.getTbStaff()); //更新员工详细表 staffDetailDAO.update(entity); dao.delete(entity.getTbStaff()); staffDetailDAO.delete(entity); } catch (Exception e) { e.printStackTrace(); } return new ModelAndView("staff/index"); } /** * 获取列表 * @param page * @param size * @param id * @param name * @param price * @return */ @RequestMapping(value = "staffDetail/list.html", method = RequestMethod.GET) @ResponseBody public JsonResponse<TbStaffDetail> list(@RequestParam(required = true, defaultValue = "1") int page, @RequestParam(required = true, defaultValue = "10") int size, @RequestParam(required = false) final String id, @RequestParam(required = false) final String name, @RequestParam(required = false) final String post) { JsonResponse<TbStaffDetail> jsonResponse = new JsonResponse<TbStaffDetail>(); //获取对应的参数 String[] params = new String[]{id,name,post}; try { if (params != null) { for (int i = 0; i < params.length; i++) { // 编码有问题,get传过来的参数 if(params[i] != null && !"".equals(params[i])){ String newStr = new String(params[i].getBytes("iso8859-1"), "UTF-8"); params[i] = newStr; } } } //xml文件修改lazy=false Page<TbStaffDetail> findAll = staffDetailDAO.findAll(page, size, params); jsonResponse.setSuccess(true); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.STAFF, Constants.SUCCESS)); jsonResponse.setPage(findAll); } catch (Exception e) { e.printStackTrace(); jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.STAFF, Constants.FAILURE)); } return jsonResponse; } /** * 获取其中一个信息,并跳转页面 * @param id * @param modelMap * @return */ @RequestMapping(value = "staffDetail/showOne.html", method = RequestMethod.GET) public ModelAndView showOne(@RequestParam final String id,ModelMap modelMap) { TbStaffDetail tbStaffDetail = new TbStaffDetail(); try { tbStaffDetail = staffDetailDAO.findById(Integer.parseInt(id)); modelMap.put("update", "update"); modelMap.put("tbStaffDetail", tbStaffDetail); }catch(Exception exception){ exception.printStackTrace(); } return new ModelAndView("staff/add"); } /** * 重构代码 * @param id * @param name * @param price * @return */ private TbStaffDetail getBean(final String id, final String name, final String sex, final String age,final String post,final String phone, final String card,final String address, String email, final String time,final String staffDetailId) { TbStaffDetail detail = null; TbStaff entity = null; try { String newId = new String(id.getBytes("iso8859-1"), "UTF-8"); String newname = new String(name.getBytes("iso8859-1"), "UTF-8"); String newsex = new String(sex.getBytes("iso8859-1"), "UTF-8"); String newage = new String(age.getBytes("iso8859-1"), "UTF-8"); String newpost = new String(post.getBytes("iso8859-1"), "UTF-8"); String newcard = new String(card.getBytes("iso8859-1"), "UTF-8"); String newphone = new String(phone.getBytes("iso8859-1"), "UTF-8"); String newaddress = new String(address.getBytes("iso8859-1"), "UTF-8"); String newemail = new String(email.getBytes("iso8859-1"), "UTF-8"); String newtime = null; if(time != null){ newtime = new String(time.getBytes("iso8859-1"), "UTF-8"); } detail = new TbStaffDetail(); entity = new TbStaff(); entity.setStaffId(newId); entity.setStaffName(newname); entity.setStaffAge(Short.parseShort(newage)); entity.setStaffPost(newpost); //预定0为男,1为女 entity.setStaffSex("1".equals(newsex) ? true : false); entity.setStaffPhone(newphone); if("".equals(staffDetailId)){ detail.setId(null); }else{ detail.setId(Integer.parseInt(staffDetailId)); } detail.setStaffAddress(newaddress); detail.setStaffCard(newcard); detail.setStaffEmail(newemail); System.out.println(newtime); if(newtime != null){ //时间这里会异常 // Date str2Date = DateUtil.str2Date(newtime, "yyyy-MM-dd"); String[] split = newtime.split(" "); split[0]+=" 00:00:00"; detail.setStaffTime(Timestamp.valueOf(split[0])); } detail.setTbStaff(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return detail; } }
package com.anonymous9495.mashit; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.net.URLDecoder; /** * Created by staffonechristian on 2017-09-22. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG="MyGcmListenerService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { String image = remoteMessage.getNotification().getIcon(); String title = remoteMessage.getNotification().getTitle(); String text = remoteMessage.getNotification().getBody(); String sound = remoteMessage.getNotification().getSound(); System.out.print("----->"+text+title); int id=0; Object obj = remoteMessage.getData().get("id"); if(obj!=null) { id = Integer.valueOf(obj.toString()); } this.sendNotification(new NotificationData(image,id,title,text,sound) ); super.onMessageReceived(remoteMessage); } private void sendNotification(NotificationData notificationData) { Intent intent = new Intent(this,MainActivity.class); MainActivity.flag=true; intent.putExtra(NotificationData.TEXT,notificationData.getTextMessage()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this,0/*Request Code*/,intent,PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder = null; try{ notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.flame_icon) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.flame_icon)) .setContentTitle(URLDecoder.decode(notificationData.getTitle(),"UTF-8")) .setColor((getColor(R.color.colorAccent))) .setContentText(URLDecoder.decode(notificationData.getTextMessage(),"UTF-8")) .setAutoCancel(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentIntent(pendingIntent); }catch (Exception e) { e.printStackTrace(); } if (notificationBuilder != null) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationData.getId(), notificationBuilder.build()); } else { Log.d(TAG, "notificationBuilder is null"); } } }
package com.galaksiya.education.rss.interaction; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.galaksiya.education.rss.common.Info; /** * show all news source.. * * @author galaksiya * */ public class MenuPrinter { private List<String> sourceNames; public MenuPrinter() throws FileNotFoundException, IOException { sourceNames = readSourceNames(); } public int getSourceCount() { return sourceNames.size(); } public int showMenu() throws IOException { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); int newsNumber = 0; do { print(); newsNumber = scanner.nextInt(); scanner.nextLine(); } while (newsNumber + 1 > getSourceCount() || newsNumber < 1); return newsNumber; } /** * show all news sources name into console * * @throws IOException */ public void print() { printSourceNames(sourceNames); } private void printSourceNames(List<String> sourceNames) { for (int i = 0; i < sourceNames.size(); i++) { System.out.println(sourceNames.get(i) + " news ---> " + (i + 1) + "\n"); } } private List<String> readSourceNames() throws IOException, FileNotFoundException { List<String> sourceNames = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(Info.RSS_FILE));) { String line = ""; String csvSplitBy = ","; while ((line = br.readLine()) != null) { // use comma as separator String[] sourcedata = line.split(csvSplitBy); if (sourcedata.length > 0) { sourceNames.add(sourcedata[0]); } } } return sourceNames; } }
package tiles.inner; import game.Hand; public abstract class Resource_Port extends Port { public abstract Hand cost(); }
package cn.wq.kgdxkj.service.impl; import cn.wq.kgdxkj.dao.UserDao; import cn.wq.kgdxkj.model.User; import cn.wq.kgdxkj.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @program: SpringBoot_Demo * @description: 用户service实现类 * @author: Mr.Wu * @create: 2019-02-13 09:48 **/ @Service public class UserServiceImpl implements UserService{ @Autowired public UserDao userDao; //这里会报错,但是并不会影响 public List<User> findAllUser(){ List<User> list=userDao.findAll(); return list; } @Override //@Transactional //事务 public int addUser(User user) { try{ userDao.addUser(user); int a = 1/0; user.setUserid(999); user.setUsername("中国"); user.setPassword("4444444"); user.setPhone("110"); userDao.addUser(user); }catch (Exception e){ e.printStackTrace(); } return 1; } }
package com.stk123.spring.control; import com.stk123.model.RequestResult; import com.stk123.model.Index; import com.stk123.model.K; import com.stk123.spring.dto.StkDto; import com.stk123.spring.service.IndexService; import com.stk123.spring.service.IndustryService; import com.stk123.util.ServiceUtils; import com.stk123.service.XueqiuService; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import javax.servlet.http.HttpServletRequest; import javax.sql.DataSource; import java.sql.Connection; import java.util.*; @Controller("kControl") @RequestMapping("/k") @CommonsLog public class KControl { //private static final Log log = LogFactory.getLog(KControl.class); @Autowired private IndustryService industryService; @Autowired private IndexService indexService; @Autowired private ApplicationContext applicationContext; @Autowired protected DataSource ds; @RequestMapping("") public String index(HttpServletRequest request){ //log.info("id="+id); //ServletContext servletContext = request.getSession().getServletContext(); //WebApplicationContext context = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); /*StkIndustryTypeEntity industryTypeEntity = industryService.findStkIndustryType(124618); log.info(industryTypeEntity.getName()); viewAllRequestMapping(request);*/ return "k"; } /** * http://webquoteklinepic.eastmoney.com/GetPic.aspx?token=&nid=1.600000&type=D&unitWidth=-6&ef=&formula=MACD&imageType=KXL&_=1599294174363 */ @RequestMapping("/show/{codes}") @ResponseBody public RequestResult<List<StkDto>> show(@PathVariable("codes")String codes){ //log.info("codes:"+codes); List<StkDto> list = new ArrayList<StkDto>(); if(!StringUtils.isEmpty(codes)) { String[] cs = StringUtils.split(StringUtils.replace(codes," ", ""), ","); List<StkDto> stks = indexService.findStkByCode(Arrays.asList(cs)); for(StkDto stk : stks){ String url = null; if(StringUtils.length(stk.getCode()) == 5){ url = "http://webquoteklinepic.eastmoney.com/GetPic.aspx?imageType=KXL&nid=116."+stk.getCode()+"&token=&type=%s&unitWidth=-6&ef=&formula=MACD"; }else { String code = (Index.getLocation(stk.getCode()) == Index.SH ? 1 : 0) + "." + stk.getCode(); url = "http://webquoteklinepic.eastmoney.com/GetPic.aspx?token=&nid=" + code + "&type=%s&unitWidth=-6&ef=&formula=MACD&imageType=KXL&_=" + ServiceUtils.now.getTime(); } stk.setDailyUrl(String.format(url, "D")); stk.setWeekUrl(String.format(url, "W")); stk.setMonthUrl(String.format(url, "M")); stk.setNameAndCodeLink(ServiceUtils.wrapCodeAndName(stk.getCode(), stk.getName())); list.add(stk); } } return RequestResult.success(list); } @RequestMapping("/xueqiu/{name}") @ResponseBody public RequestResult<List<StkDto>> xueqiu(@PathVariable("name")String name) throws Exception { Set<String> codes = XueqiuService.getFollowStks(name); return show(StringUtils.join(codes, ",")); } /** * fromDate must after toDate */ @RequestMapping("/{code}") @ResponseBody public List<K> getKs(@PathVariable("code")String code, @RequestParam(value = "type", required = false, defaultValue = "1")int type, @RequestParam(value = "days", required = false, defaultValue = "0")int days, @RequestParam(value = "fromDate", required = false)String fromDate, @RequestParam(value = "toDate", required = false)String toDate) throws Exception { Connection conn = null; try { conn = ds.getConnection(); Index index = new Index(conn, code); List<K> ks = null; switch (type){ case 1: ks = index.getKs(); break; case 2: ks = index.getKsWeekly(true); break; case 3: ks = index.getKsMonthly(true); break; } if(StringUtils.isEmpty(fromDate)) { return ks.subList(0, days); }else{ int fromIndex = index.indexOf(fromDate); int toIndex = fromIndex + days; if(!StringUtils.isEmpty(toDate)) { toIndex = index.indexOf(toDate); } return ks.subList(fromIndex, toIndex); } }finally { conn.close(); } } public void viewAllRequestMapping(HttpServletRequest request) { Set<String> noLoginUrlSet = new HashSet<String>(); RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();// 就是这个 for (RequestMappingInfo rmi : handlerMethods.keySet()) { HandlerMethod handlerMethod = handlerMethods.get(rmi); //if (handlerMethod.hasMethodAnnotation(NoLogin.class)) { PatternsRequestCondition prc = rmi.getPatternsCondition(); Set<String> patterns = prc.getPatterns(); noLoginUrlSet.addAll(patterns); //} } for(String s : noLoginUrlSet){ System.out.println(s); } } }
package com.example.axonssejavascript.api; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(as = PackageRecord.class) public interface PackageRecord { String getId(); String getType(); String getDescription(); }
package headlessTests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.ParseException; import java.time.DayOfWeek; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import logic.Course; public class CourseTests { Course tester; @BeforeAll public static void setup() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { MockGlobals.setup(); } @BeforeEach public void reset() throws ParseException { tester = new Course("4", "FA", "20", true, Arrays.asList(48d), "Yang Gang", "MWR", "4:00 am-6:00 pm", "2", "Gang, Yang", "01/18-01/17|2020", 47000); } @ParameterizedTest(name = "Test TBA no conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void TBANoConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "TBA", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "TBA", "12", "No one", "01/12-01/13|2019", 500); assertFalse(first.conflicts(second), "Courses at exact same times should be conflicting!"); } @ParameterizedTest(name = "Test exact course conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void exactCourseConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses at exact same times should be conflicting!"); } @ParameterizedTest(name = "Test overlapping course conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void overlapCourseConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:35 pm-2:35 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses at overlapping same times should be conflicting!"); } @ParameterizedTest(name = "Test super overlapping course conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void superOverlapCourseConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "12:35 pm-3:35 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses at super overlapping same times should be conflicting!"); } @ParameterizedTest(name = "Test start/end course conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void startEndCourseConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "2:15 pm-3:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses at end when one starts should be conflicting!"); } @ParameterizedTest(name = "Test start/end walk time course conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void startEnd5CourseConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "2:20 pm-3:20 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses at end without 5 minutes in between should be conflicting!"); } @ParameterizedTest(name = "Test different dates no conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void differentDatesNoConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "2:15 pm-3:15 pm", "12", "No one", "01/14-01/15|2019", 500); assertFalse(first.conflicts(second), "Courses should not be conflicting if on different dates!"); } @ParameterizedTest(name = "Test different days no conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void differentDaysNoConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", invert(days), "2:15 pm-3:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertFalse(first.conflicts(second), "Courses should not be conflicting if on different days!"); } @ParameterizedTest(name = "Test same day no conflict with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void sameDaysNoConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "3:15 pm-4:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertFalse(first.conflicts(second), "Courses should not be conflicting if on same days with no conflicts!"); } @ParameterizedTest(name = "Test same day no conflict multiple times with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void sameDaysMultipleTimesNoConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); first.addDayandTime(days + "|5:15 pm-6:15 pm"); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "3:15 pm-4:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertFalse(first.conflicts(second), "Courses should not be conflicting if on same days with multiple times and no conflicts!"); } @ParameterizedTest(name = "Test same day conflict multiple times with [{arguments}]") @ValueSource(strings = { "M", "T", "MT", "W", "MW", "TW", "MTW", "R", "MR", "TR", "MTR", "WR", "MWR", "TWR", "MTWR", "F", "MF", "TF", "MTF", "WF", "MWF", "TWF", "MTWF", "RF", "MRF", "TRF", "MTRF", "WRF", "MWRF", "TWRF", "MTWRF" }) public void sameDaysMultipleTimesConflict(String days) throws ParseException { Course first = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "1:15 pm-2:15 pm", "12", "No one", "01/12-01/13|2019", 500); first.addDayandTime(days + "|4:15 pm-6:15 pm"); Course second = new Course("0", "EV", "0", false, Arrays.asList(1d), "Test", days, "3:15 pm-4:15 pm", "12", "No one", "01/12-01/13|2019", 500); assertTrue(first.conflicts(second), "Courses should be conflicting if on same days with multiple times and conflicts!"); } @Test public void courseCRN() { assertEquals(4, tester.getCRN(), "Course CRN is not correct!"); } @Test public void getCredits() { assertEquals(48, tester.getCredits()[0], 0, "Course credits is not correct!"); } @Test public void getDays() { List<String> results = tester.getDays(); assertTrue(results.containsAll(Arrays.asList("MO", "WE", "TH")), "Course getDays does not return all days!"); } @Test public void getRemaining() { assertEquals(2, tester.getRemaining(), "Course getRemaining doesn't return the correct value"); } @Test public void getInstructor() { assertEquals("Gang, Yang", tester.getInstructor(), "Course getInstructor doesn't return the correct value"); } @Test public void getStartDate() { assertEquals("2020-01-18", tester.getStartDate().toString(), "Course getStartDate doesn't return the correct value"); } @Test public void getEndDate() { assertEquals("2020-01-17", tester.getEndDate().toString(), "Course getEndDate doesn't return the correct value"); } @Test public void getFee() { assertEquals(47000, tester.getFee(), 0, "Course getFee doesn't return the correct value"); } @Test public void tostring() { assertEquals("FA20 - Yang Gang Lab", tester.toString(), "Course toString doesn't return correct representation!"); } @Test public void firstDay() { assertEquals(DayOfWeek.MONDAY, tester.firstDay(), "First day is not the Monday enum!"); } @Test public void isSplitClass() { assertFalse(tester.isSplitClass(), "The tester is not a split class yet!"); tester.addDayandTime("T|1:05 am-1:06 pm"); assertTrue(tester.isSplitClass(), "The tester is supposed to be a split class now!"); } @Test public void iterator() { ArrayList<DayOfWeek> days = new ArrayList<>(); ArrayList<String> daysRRule = new ArrayList<>(); for (Course.CourseTimeIterator it = (Course.CourseTimeIterator) tester.iterator(); it.hasNext(); it.next()) { days.add(it.getDayEnum()); daysRRule.add(it.getRRuleDay()); } assertTrue(days.contains(DayOfWeek.THURSDAY)); assertTrue(daysRRule.contains("TH")); } private String invert(String input) { String result = "MTWRF"; for (String s : input.split("")) { result = result.replaceAll(s, ""); } return result; } }
package Domain; import Resources.Product; import java.sql.SQLException; public class Controller{ CustomerListInterface customerList = new CustomerList(); ProductList productList = new ProductList(); PackageList packageList = new PackageList(); OrderList orderList = new OrderList(); TruckList truckList = new TruckList(); PickUpList pickupList = new PickUpList(); UserList userlist = new UserList(); public Controller() { } /* * methods for PickUpList() */ public boolean addPickUp(int orderID, int customerID, String startDate, String finishDate){ return pickupList.addPickUp(orderID, customerID, startDate, finishDate); } /* * methods for ProductList() */ public void clearProductList(){ productList.clearProductList(); } public int getProductId(int i){ productList.getCurrentProduct(i); return productList.getProdID(); } public String getProductName(int i){ productList.getCurrentProduct(i); return productList.getProdName(); } public int getProductVolume(int i){ productList.getCurrentProduct(i); return productList.getProdVol(); } public int getProductQuantiy(int i){ productList.getCurrentProduct(i); return productList.getProdQTY(); } public String getProductDescription(int i){ productList.getCurrentProduct(i); return productList.getProdDisc(); } public int getProductPrice(int i){ productList.getCurrentProduct(i); return productList.getProdPrice(); } public int getProductListSize() { return productList.getProductListsize(); } public boolean buildProductList() { return productList.buildProductList(productList); } public boolean addProduct(String prodName, int prodVol, int prodQTY, String prodDisc, int prodPrice) { return productList.addProduct(prodName, prodVol, prodQTY, prodDisc, prodPrice); } public boolean saveEditedProduct(int prodID, String prodName, int prodVol, int prodQTY, String prodDisc, int prodPrice) { return productList.saveEditedProduct(prodID, prodName, prodVol, prodQTY, prodDisc, prodPrice); } public boolean deleteProduct(int cusID) { return productList.deleteProduct(cusID); } public boolean searchProdByNameinArray(String name){ return productList.searchProdByNameinArray(name); } public int searchProdByIDinArray(int ID){ return productList.searchProdByIDinArray(ID); } public int getProductSearchListsize() { return productList.getProductSearchListsize(); } public int getSearchProductId(int i){ productList.getCurrentSearchProduct(i); return productList.getProdID(); } public String getSearchProductName(int i){ productList.getCurrentSearchProduct(i); return productList.getProdName(); } /* * Methods for OrderList() */ public int getOrderID(int i){ orderList.getCurrentOrder(i); return orderList.getOrderID(); } public String getOrderStartDate(int i){ orderList.getCurrentOrder(i); return orderList.getOrderStartDate(); } public String getOrderFinishDate(int i){ orderList.getCurrentOrder(i); return orderList.getOrderFinishDate(); } public int getOrderCutomerID(int i){ orderList.getCurrentOrder(i); return orderList.getCustomerID(); } public int getOrderBalance(){ return orderList.getOrderBalance(); } public void setOrderBalance(int balance){ orderList.setOrderBalance(balance); } public Product getOrderProductList(int i){ return orderList.getProductList(i); } public int getCurrentOrderProductListSize(){ return orderList.getCurrentOrderProductListSize(); } public int getOrderListSize(){ return orderList.getOrderListSize(); } public boolean addItemToOrderList(int prodID, String name, int vol, int quantity, String descrip, int price, int availableQuantity){ return orderList.addItemToOrderList(prodID, name, vol, quantity, descrip, price, availableQuantity); } public void removeFromOrderList(int index){ orderList.removeProductFromOrderList(index); } public boolean checkProdForOrderQuantity(int quantityForOrder, int existingQuantity){ return orderList.checkProdForOrderQuantity(quantityForOrder, existingQuantity); } public boolean buildOrderList(){ return orderList.buildOrderList(orderList); } public boolean addOrder(int orderid){ return orderList.addOrder(orderid, orderList); } public boolean addCustomerOrder(int customerID, String startDate, String finishDate){ return orderList.addCustomerOrder(customerID, startDate, finishDate); } public boolean editCustomerOrder(int customerID, String startdate, String finishdate, int balance){ return orderList.editCustomerOrder(customerID, startdate, finishdate, balance); } public int getNewOrderID(int custID, String startDate, String endDate){ return orderList.getNewOrderID(custID, startDate, endDate); } public int getOrderProductID(int i){ return orderList.getOrderProductID(i); } public String getOrderProductName(int i){ return orderList.getOrderProductName(i); } public int getOrderProductQTY(int i){ return orderList.getOrderProductQTY(i); } public int getOrderProductPrice(int i){ return orderList.getOrderProductPrice(i); } public int searchOrderProdByIDinArray(int ID){ return orderList.searchOrderProdByIDinArray(ID); } //Methods for TruckList() public void getcurrTruck(int i){ truckList.getcurrTruck(i); } public void clearTruckOrderList(){ truckList.clearTruckOrderList(); } public int getTruckID(int i){ truckList.getcurrTruck(i); return truckList.getTruckID(); } public int getTruckCapacity(int i){ truckList.getcurrTruck(i); return truckList.getTruckCapacity(); } public String getTruckModel(int i){ truckList.getcurrTruck(i); return truckList.getTruckmodel(); } public int getTruckOrderID(int i){ truckList.getcurrTruckOrder(i); return truckList.getTruckOrderID(); } public int getTruckOrderTruckID(int i){ truckList.getcurrTruckOrder(i); return truckList.getTruckOrderTruckID(); } public int getAvailableTruckListSize(){ return truckList.getAvailableTruckListSize(); } public String getTruckOrderStatus(int i){ truckList.getcurrTruckOrder(i); return truckList.getTruckOrderStatus(); } public String getTruckOrderDate(int i){ truckList.getcurrTruckOrder(i); return truckList.getTruckOrderDate(); } public int getAvailableTruck(int index){ return truckList.getAvailableTruck(index); } public int getTrucksRequired(int totalVolume){ return truckList.getTrucksRequired(totalVolume); } public void checkFreeTrucks(String date){ truckList.checkFreeTrucks(date); } public boolean buildTruckList(){ return truckList.buildTruckList(truckList); } public boolean buildTruckOrderList(){ return truckList.buildTruckOrderList(truckList); } public boolean addTruckOrder(int orderid, int truckid, String status, String date){ return truckList.addTruckOrder(orderid,truckid,status,date); } public boolean addTruck(int truckid, String model, int capacity, String bookeddate){ return truckList.addTruck(truckid, model, capacity, bookeddate); } //Methods for CustomerList() public void clearCustomerList(){ customerList.clearCustomerList(); } public int getCustomerID(int i){ customerList.getCurrentCustomer(i); return customerList.getCusID(); } public String getCustomerName(int i){ customerList.getCurrentCustomer(i); return customerList.getCusName(); } public String getCustomerAddress(int i){ customerList.getCurrentCustomer(i); return customerList.getCusAddress(); } public String getCustomerEmail(int i){ customerList.getCurrentCustomer(i); return customerList.getCusEmail(); } public int getCustomerListSize() { return customerList.getCustomerListSize(); } public boolean buildCustomerList() { return customerList.buildCustomerList(customerList); } public boolean addCustomer(String name, String address, String email) { return customerList.addCustomer(name, address, email); } public boolean saveEditedCustomer(int cusID, String cusName, String cusAddress, String cusEmail) throws SQLException { return customerList.saveEditedCustomer(cusID, cusName, cusAddress, cusEmail); } public boolean deleteCustomer(int cusID) { return customerList.deleteCustomer(cusID); } public boolean lockCustomer(int cusID){ return customerList.lockCustomer(cusID); } /* * Methods for PackageList() */ public void clearPackageList(){ packageList.clearPackageList(); } public int getPackageListSize() { return packageList.getPackageListSize(); } public int getPackageID(int i){ packageList.getCurrentPackage(i); return packageList.getPackID(); } public String getPackageName(int i){ packageList.getCurrentPackage(i); return packageList.getPackName(); } public String getPackageDiscription(int i){ packageList.getCurrentPackage(i); return packageList.getPackDisc(); } public int getPackagePrice(int i){ packageList.getCurrentPackage(i); return packageList.getPackPrice(); } public Product getPackageProductList(int i) { return packageList.getPackageProductList(i); } public int getPackageProductListSize() { return packageList.getPackageProductListSize(); } public boolean buildPackageList(){ return packageList.buildPackageList(packageList); } public boolean addPackage(String name, String description, int price){ return packageList.addPackage(name, description, price); } public boolean addItemToPackageList(int prodID, String name, int vol, int quantity, String descrip, int price){ return packageList.addItemToPackageList(prodID, name, vol, quantity, descrip, price); } public void removeFromPackageList(int index){ packageList.removeFromPackageList(index); } public boolean addProductsToPackageInDB(){ return packageList.addProductsToPackageInDB(packageList); } public boolean loadPackageProducts(int packID){ return packageList.loadPackageProducts(packID, packageList); } public boolean deletePackageProducts(int packID){ return packageList.deletePackageProducts(packID); } public boolean deletePackage(int packID){ return packageList.deletePackage(packID); } public int getNewPackageID(String packName, String packDis, int packPrice){ return packageList.getNewPackageID(packName, packDis, packPrice); } public int getPackageProductID(int i){ return packageList.getPackageProductID(i); } public String getPackageProductName(int i){ return packageList.getPackageProductName(i); } public int getPackageProductQTY(int i){ return packageList.getPackageProductQTY(i); } public int searchPackProdByIDinArray(int ID){ return packageList.searchPackProdByIDinArray(ID); } //UserList functionality public boolean buildUserList(){ return userlist.buildUserListFromDB(userlist); }//end of buildUserList, added by Andrew public boolean addUserToDB(String id, String pw, int pou ){ boolean succes = false; if(userlist.addUserToDB(id, pw, pou)){ userlist.buildUserListFromDB(userlist); succes = true; } return succes; }//end of addUserToDB, added by Andrew public boolean editUserInDB(String id, String pw, int pou){ boolean succes = false; if(userlist.editUserInDB(id, pw, pou)){ userlist.buildUserListFromDB(userlist); succes = true; } return succes; }//end of editUserInDB, added by Andrew public String getCurrUserName(int i){ userlist.getCurrentUser(i); return userlist.getUserName(); }//end of gerCurrUserName, added by Andrew public String getCurrUserPw(int i){ userlist.getCurrentUser(i); return userlist.getUserPassword(); }//end of getCurrUserPw, added by Andrew public int getCurrUserRank(){ return userlist.getUserPowerOfUser(); }//end of buildgetCurrUserRank, added by Andrew public boolean checkUserNPw(String id, String pw){ return userlist.checkUserNPw(id,pw); } }
package br.com.candleanalyser.engine; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CandleSequence { private int maxCandles; private List<Candle> candles; public CandleSequence(int maxCandles) { this.maxCandles = maxCandles; this.candles = new ArrayList<Candle>(); } public CandleSequence(int maxCandles, List<Candle> candles) { this(maxCandles); for (Candle candle : candles) { add(candle); } } public void add(Candle candle) { candles.add(candle); if(candles.size()>maxCandles) { candles.remove(0); } } public List<Candle> getCandles() { return candles; } public Candle getLast(int n) { int p = candles.size()-n-1; if(p<0) throw new IllegalArgumentException("'n' is greater than values.size()"); return candles.get(p); } public int getSize() { return candles.size(); } public int getMaxCandles() { return maxCandles; } public double[] getOpens() { double[] result = new double[candles.size()]; for (int i=0; i<candles.size(); i++) { result[i] = candles.get(i).getOpen(); } return result; } public double[] getCloses() { double[] result = new double[candles.size()]; for (int i=0; i<candles.size(); i++) { result[i] = candles.get(i).getClose(); } return result; } public double[] getMaxes() { double[] result = new double[candles.size()]; for (int i=0; i<candles.size(); i++) { result[i] = candles.get(i).getMax(); } return result; } public double[] getMins() { double[] result = new double[candles.size()]; for (int i=0; i<candles.size(); i++) { result[i] = candles.get(i).getMin(); } return result; } public double[] getVolumes() { double[] result = new double[candles.size()]; for (int i=0; i<candles.size(); i++) { result[i] = candles.get(i).getVolume(); } return result; } public Date[] getDates() { List<Date> result = new ArrayList<Date>(); for (Candle candle : candles) { result.add(candle.getDate()); } return result.toArray(new Date[0]); } public List<Candle> getLastCandles(int lastCandle) { int p = candles.size()-lastCandle-1; if(p<0) throw new IllegalArgumentException("'lastCandle' is greater than values.size()"); return new ArrayList<Candle>(candles.subList(0, p+1)); } }
package CallCenterDesign; public enum Rank { Representative(0), Senior(1), Manager(2); private final int rank; Rank(final int rank){ this.rank = rank; } public int value(){ return rank; } }
package strategy; // Strategy public interface Animal { public String attack(String target); }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.server; import java.net.URI; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.http.CacheControl; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseCookie; import org.springframework.http.codec.HttpMessageWriter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Arjen Poutsma */ class DefaultServerResponseBuilderTests { static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() { @Override public List<HttpMessageWriter<?>> messageWriters() { return Collections.emptyList(); } @Override public List<ViewResolver> viewResolvers() { return Collections.emptyList(); } }; @Test void from() { ResponseCookie cookie = ResponseCookie.from("foo", "bar").build(); ServerResponse other = ServerResponse.ok().header("foo", "bar") .cookie(cookie) .hint("foo", "bar") .build().block(); Mono<ServerResponse> result = ServerResponse.from(other).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.OK.equals(response.statusCode()) && "bar".equals(response.headers().getFirst("foo")) && cookie.equals(response.cookies().getFirst("foo"))) .expectComplete() .verify(); } @Test @SuppressWarnings("deprecation") void status() { Mono<ServerResponse> result = ServerResponse.status(HttpStatus.CREATED).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.CREATED.equals(response.statusCode()) && response.rawStatusCode() == 201) .expectComplete() .verify(); } @Test void ok() { Mono<ServerResponse> result = ServerResponse.ok().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.OK.equals(response.statusCode())) .expectComplete() .verify(); } @Test void created() { URI location = URI.create("https://example.com"); Mono<ServerResponse> result = ServerResponse.created(location).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.CREATED.equals(response.statusCode()) && location.equals(response.headers().getLocation())) .expectComplete() .verify(); } @Test void accepted() { Mono<ServerResponse> result = ServerResponse.accepted().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.ACCEPTED.equals(response.statusCode())) .expectComplete() .verify(); } @Test void noContent() { Mono<ServerResponse> result = ServerResponse.noContent().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.NO_CONTENT.equals(response.statusCode())) .expectComplete() .verify(); } @Test void seeOther() { URI location = URI.create("https://example.com"); Mono<ServerResponse> result = ServerResponse.seeOther(location).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.SEE_OTHER.equals(response.statusCode()) && location.equals(response.headers().getLocation())) .expectComplete() .verify(); } @Test void temporaryRedirect() { URI location = URI.create("https://example.com"); Mono<ServerResponse> result = ServerResponse.temporaryRedirect(location).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.TEMPORARY_REDIRECT.equals(response.statusCode()) && location.equals(response.headers().getLocation())) .expectComplete() .verify(); } @Test void permanentRedirect() { URI location = URI.create("https://example.com"); Mono<ServerResponse> result = ServerResponse.permanentRedirect(location).build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.PERMANENT_REDIRECT.equals(response.statusCode()) && location.equals(response.headers().getLocation())) .expectComplete() .verify(); } @Test void badRequest() { Mono<ServerResponse> result = ServerResponse.badRequest().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.BAD_REQUEST.equals(response.statusCode())) .expectComplete() .verify(); } @Test void notFound() { Mono<ServerResponse> result = ServerResponse.notFound().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.NOT_FOUND.equals(response.statusCode())) .expectComplete() .verify(); } @Test void unprocessableEntity() { Mono<ServerResponse> result = ServerResponse.unprocessableEntity().build(); StepVerifier.create(result) .expectNextMatches(response -> HttpStatus.UNPROCESSABLE_ENTITY.equals(response.statusCode())) .expectComplete() .verify(); } @Test void allow() { Mono<ServerResponse> result = ServerResponse.ok().allow(HttpMethod.GET).build(); Set<HttpMethod> expected = Set.of(HttpMethod.GET); StepVerifier.create(result) .expectNextMatches(response -> expected.equals(response.headers().getAllow())) .expectComplete() .verify(); } @Test void contentLength() { Mono<ServerResponse> result = ServerResponse.ok().contentLength(42).build(); StepVerifier.create(result) .expectNextMatches(response -> Long.valueOf(42).equals(response.headers().getContentLength())) .expectComplete() .verify(); } @Test void contentType() { Mono<ServerResponse> result = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).build(); StepVerifier.create(result) .expectNextMatches(response -> MediaType.APPLICATION_JSON.equals(response.headers().getContentType())) .expectComplete() .verify(); } @Test void eTag() { Mono<ServerResponse> result = ServerResponse.ok().eTag("foo").build(); StepVerifier.create(result) .expectNextMatches(response -> "\"foo\"".equals(response.headers().getETag())) .expectComplete() .verify(); } @Test void lastModified() { ZonedDateTime now = ZonedDateTime.now(); Mono<ServerResponse> result = ServerResponse.ok().lastModified(now).build(); Long expected = now.toInstant().toEpochMilli() / 1000; StepVerifier.create(result) .expectNextMatches(response -> expected.equals(response.headers().getLastModified() / 1000)) .expectComplete() .verify(); } @Test void cacheControlTag() { Mono<ServerResponse> result = ServerResponse.ok().cacheControl(CacheControl.noCache()).build(); StepVerifier.create(result) .expectNextMatches(response -> "no-cache".equals(response.headers().getCacheControl())) .expectComplete() .verify(); } @Test void varyBy() { Mono<ServerResponse> result = ServerResponse.ok().varyBy("foo").build(); List<String> expected = Collections.singletonList("foo"); StepVerifier.create(result) .expectNextMatches(response -> expected.equals(response.headers().getVary())) .expectComplete() .verify(); } @Test void statusCode() { HttpStatus statusCode = HttpStatus.ACCEPTED; Mono<ServerResponse> result = ServerResponse.status(statusCode).build(); StepVerifier.create(result) .expectNextMatches(response -> statusCode.equals(response.statusCode())) .expectComplete() .verify(); } @Test void headers() { HttpHeaders newHeaders = new HttpHeaders(); newHeaders.set("foo", "bar"); Mono<ServerResponse> result = ServerResponse.ok().headers(headers -> headers.addAll(newHeaders)).build(); StepVerifier.create(result) .expectNextMatches(response -> newHeaders.equals(response.headers())) .expectComplete() .verify(); } @Test void cookies() { MultiValueMap<String, ResponseCookie> newCookies = new LinkedMultiValueMap<>(); newCookies.add("name", ResponseCookie.from("name", "value").build()); Mono<ServerResponse> result = ServerResponse.ok().cookies(cookies -> cookies.addAll(newCookies)).build(); StepVerifier.create(result) .expectNextMatches(response -> newCookies.equals(response.cookies())) .expectComplete() .verify(); } @Test void copyCookies() { Mono<ServerResponse> serverResponse = ServerResponse.ok() .cookie(ResponseCookie.from("foo", "bar").build()) .bodyValue("body"); assertThat(serverResponse.block().cookies().isEmpty()).isFalse(); serverResponse = ServerResponse.ok() .cookie(ResponseCookie.from("foo", "bar").build()) .bodyValue("body"); assertThat(serverResponse.block().cookies().isEmpty()).isFalse(); } @Test void overwriteHeaders() { ServerResponse serverResponse = ServerResponse.ok().headers(headers -> headers.set("Foo", "Bar")).build().block(); assertThat(serverResponse).isNotNull(); MockServerWebExchange mockExchange = MockServerWebExchange .builder(MockServerHttpRequest.get("https://example.org")) .build(); MockServerHttpResponse response = mockExchange.getResponse(); response.getHeaders().set("Foo", "Baz"); serverResponse.writeTo(mockExchange, EMPTY_CONTEXT).block(); assertThat(response.getHeaders().getFirst("Foo")).isEqualTo("Bar"); } @Test void build() { ResponseCookie cookie = ResponseCookie.from("name", "value").build(); Mono<ServerResponse> result = ServerResponse.status(HttpStatus.CREATED) .header("MyKey", "MyValue") .cookie(cookie).build(); MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block(); MockServerHttpResponse response = exchange.getResponse(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(response.getHeaders().getFirst("MyKey")).isEqualTo("MyValue"); assertThat(response.getCookies().getFirst("name").getValue()).isEqualTo("value"); StepVerifier.create(response.getBody()).expectComplete().verify(); } @Test void buildVoidPublisher() { Mono<Void> mono = Mono.empty(); Mono<ServerResponse> result = ServerResponse.ok().build(mono); MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block(); MockServerHttpResponse response = exchange.getResponse(); StepVerifier.create(response.getBody()).expectComplete().verify(); } @Test void bodyObjectPublisher() { Mono<Void> mono = Mono.empty(); assertThatIllegalArgumentException().isThrownBy(() -> ServerResponse.ok().bodyValue(mono)); } @Test void notModifiedEtag() { String etag = "\"foo\""; ServerResponse responseMono = ServerResponse.ok() .eTag(etag) .bodyValue("bar") .block(); MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com") .header(HttpHeaders.IF_NONE_MATCH, etag) .build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); responseMono.writeTo(exchange, EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); } @Test void notModifiedLastModified() { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES); ServerResponse responseMono = ServerResponse.ok() .lastModified(oneMinuteBeforeNow) .bodyValue("bar") .block(); MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com") .header(HttpHeaders.IF_MODIFIED_SINCE, DateTimeFormatter.RFC_1123_DATE_TIME.format(now)) .build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); responseMono.writeTo(exchange, EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); } }
package com.library.source; import java.io.File; import java.nio.file.Paths; public class ClassSignature { static String pathlib = Paths.get(".").toAbsolutePath().normalize().toString() + "/librariesClasses/jar"; public static void main(String[] args) { File folder = new File(pathlib); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { new ClassSignature().buildTFfiles(listOfFiles[i].getName()); } } } void buildTFfiles(String libraryName) { try { String cmdStr = "jar -tf " + pathlib + "/" + libraryName + ">>" + pathlib + "/tfs/" + libraryName + ".txt"; System.out.println("Run command " + cmdStr); Process p = Runtime.getRuntime().exec(new String[] { "bash", "-c", cmdStr }); p.waitFor(); System.out.println("Process completed: "); } catch (Exception e) { // TODO: handle exception } } }
package io.jrevolt.sysmon.zabbix; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> */ public enum GetMode { GET, CREATE, UPDATE, ; public boolean isGet() { return equals(GET); } public boolean isCreate() { return equals(CREATE) || equals(UPDATE); } public boolean isUpdate() { return equals(UPDATE); } }
package com.example.rayhardi.medimind; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by rayhardi on 10/15/2017. */ public class Medication { private String Name; private int Quantity; private Date dateToTake; public Medication(JSONObject medication) { try { Name = medication.getString("mediName"); Quantity = medication.getInt("mediQuantity"); DateFormat formatter = new SimpleDateFormat("HH:mm"); dateToTake = formatter.parse (medication.getString("time_to_take")); } catch (JSONException e) {} catch (ParseException ex){} } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JFrameHome.java * * Created on Oct 30, 2013, 10:26:38 PM */ package instance; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; import instance.*; /** * * @author user */ @SuppressWarnings({ "unused", "serial" }) public class JFrameHome extends javax.swing.JFrame { private static class jframeTitle { public jframeTitle() { } } /** Creates new form JFrameHome */ public JFrameHome() { JPanel contentPane = new JPanel() { public void paintComponent(Graphics g) { Image img = Toolkit.getDefaultToolkit().getImage( JFrameHome.class.getResource("BG.jpg")); g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this); } }; contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jButtonList = new javax.swing.JButton(); jButtonCreate = new javax.swing.JButton(); jButtonTerminate = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenuFile = new javax.swing.JMenu(); jMenuItemExit = new javax.swing.JMenuItem(); jMenuView = new javax.swing.JMenu(); jMenuItemList = new javax.swing.JMenuItem(); jMenuItemCreate = new javax.swing.JMenuItem(); jMenuItemTerminate = new javax.swing.JMenuItem(); setIconImage(Toolkit.getDefaultToolkit().getImage("Cloud.png")); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("ALL OPERATIONS"); setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N setBackground(Color.lightGray); jButtonList.setBackground(new java.awt.Color(0, 153, 153)); jButtonList.setForeground(new java.awt.Color(255, 255, 255)); jButtonList.setText("LIST ALL INSTANCES"); jButtonList.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonListActionPerformed(evt); } }); jButtonCreate.setBackground(new java.awt.Color(0, 153, 153)); jButtonCreate.setForeground(new java.awt.Color(255, 255, 255)); jButtonCreate.setText("CREATE A NEW INSTANCE"); jButtonCreate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCreateActionPerformed(evt); } }); jButtonTerminate.setBackground(new java.awt.Color(0, 153, 153)); jButtonTerminate.setForeground(new java.awt.Color(255, 255, 255)); jButtonTerminate.setText("TERMINATE A INSTANCE"); jButtonTerminate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTerminateActionPerformed(evt); } }); jMenuFile.setBackground(new java.awt.Color(255, 255, 255)); jMenuFile.setText("FILE"); jMenuFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuFileActionPerformed(evt); } }); jMenuItemExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0)); jMenuItemExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/instance/twitter-20x20.png"))); // NOI18N jMenuItemExit.setText("Exit"); jMenuItemExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemExitActionPerformed(evt); } }); jMenuFile.add(jMenuItemExit); jMenuBar1.add(jMenuFile); jMenuView.setBackground(new java.awt.Color(255, 255, 255)); jMenuView.setText("VIEW"); jMenuView.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuViewActionPerformed(evt); } }); jMenuItemList.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK)); jMenuItemList.setIcon(new javax.swing.ImageIcon(getClass().getResource("/instance/twitter-20x20.png"))); // NOI18N jMenuItemList.setText("LIST"); jMenuItemList.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemListActionPerformed(evt); } }); jMenuView.add(jMenuItemList); jMenuItemCreate.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItemCreate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/instance/twitter-20x20.png"))); // NOI18N jMenuItemCreate.setText("CREATE"); jMenuItemCreate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemCreateActionPerformed(evt); } }); jMenuView.add(jMenuItemCreate); jMenuItemTerminate.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); jMenuItemTerminate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/instance/twitter-20x20.png"))); // NOI18N jMenuItemTerminate.setText("TERMINATE"); jMenuItemTerminate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemTerminateActionPerformed(evt); } }); jMenuView.add(jMenuItemTerminate); jMenuBar1.add(jMenuView); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(206, 206, 206) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonTerminate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE) .addComponent(jButtonCreate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE) .addComponent(jButtonList, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)) .addGap(224, 224, 224)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jButtonList) .addGap(40, 40, 40) .addComponent(jButtonCreate) .addGap(41, 41, 41) .addComponent(jButtonTerminate) .addContainerGap(94, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private static void jButtonListActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //new JFrameHome().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // JFrameList jFrameList = new JFrameList(); //dispose(); JFrameList.main(null); } private void jButtonCreateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFrameScale.main(null); } private void jButtonTerminateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFrameTerminate.main(null); } private void jMenuFileActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: System.exit(0); } private void jMenuViewActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jMenuItemListActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFrameList.main(null); } private void jMenuItemCreateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFrameScale.main(null); } private void jMenuItemTerminateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: JFrameTerminate.main(null); } /** * @param args the command line arguments */ public static void main(String args[]) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception ex) { ex.printStackTrace(); } //JFrameList frame =new JFrameList(); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new JFrameHome().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButtonCreate; private javax.swing.JButton jButtonList; private javax.swing.JButton jButtonTerminate; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenu jMenuFile; private javax.swing.JMenuItem jMenuItemCreate; private javax.swing.JMenuItem jMenuItemExit; private javax.swing.JMenuItem jMenuItemList; private javax.swing.JMenuItem jMenuItemTerminate; private javax.swing.JMenu jMenuView; // End of variables declaration }
package items; import java.util.Map; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class Misc extends Item{ public Misc(Map<String, String> itm, Image sprite, int xPos, int yPos) throws SlickException { super(itm,sprite,xPos,yPos); } public void equip(){ // add AC remove item from person } public void unequip(){ } public void use(){ } }
/* * 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 psa.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author TALGAT */ public class SQL_Update { private PreparedStatement update = null; public void query(String owner, String checkIn, String checkOut, String comments, String path, String status, int id){ SQL_Connection sqlConnection = new SQL_Connection(); Connection connection = sqlConnection.getConnection(); try{ update = connection.prepareStatement("UPDATE PSA_CONTAINERS " + "SET CONTAINER_OWNER = ?, CONTAINER_CHECK_IN = ?, CONTAINER_CHECK_OUT = ?, COMMENTS = ?, PATH_TO_IMAGES = ?, PAYMENT_STATUS = ? " + "WHERE CONTAINER_ID = ?"); update.setString(1, owner); update.setString(2, checkIn); update.setString(3, checkOut); update.setString(4, comments); update.setString(5, path); update.setString(6, status); update.setInt(7, id); int result = update.executeUpdate(); System.out.println("updated "+result+" line"); update.close(); connection.close(); }catch(SQLException exception){ exception.printStackTrace(); } } }
package com.hcl.dctm.data; import java.util.List; import java.util.Map; import com.documentum.fc.client.IDfSession; import com.documentum.fc.client.IDfSysObject; import com.documentum.fc.common.DfException; import com.hcl.dctm.data.exceptions.DctmException; import com.hcl.dctm.data.params.AddNoteParams; import com.hcl.dctm.data.params.ApplyAclParam; import com.hcl.dctm.data.params.CheckinContentParams; import com.hcl.dctm.data.params.Content; import com.hcl.dctm.data.params.CopyObjectParam; import com.hcl.dctm.data.params.CreateObjectParam; import com.hcl.dctm.data.params.CreateVirtualDocParams; import com.hcl.dctm.data.params.DctmSessionParams; import com.hcl.dctm.data.params.DeleteMetadataParam; import com.hcl.dctm.data.params.DeleteObjectParam; import com.hcl.dctm.data.params.ExportContentParams; import com.hcl.dctm.data.params.ImportContentParams; import com.hcl.dctm.data.params.LinkObjectParam; import com.hcl.dctm.data.params.MoveObjectParam; import com.hcl.dctm.data.params.ObjectIdentity; import com.hcl.dctm.data.params.OperationStatus; import com.hcl.dctm.data.params.SearchObjectParam; import com.hcl.dctm.data.params.UpdateObjectParam; /** * Documentum data access object */ public interface DctmDao { /** * get IDfSession object * @return DctmSessionManager */ public IDfSession getSession() throws DctmException; /** * Set params to create documentum session * @param DctmSessionParams * @throws DctmException */ public void setSessionParams(DctmSessionParams sessionParams); /** * Authenticate user credentials * @param DctmSessionParams * @throws DctmException */ public void authenticate(DctmSessionParams sessionParams) throws DctmException; /** * Release session * @throws DctmException */ public void releaseSession(); /** * Create a new sysobject, set properties and link to destination folder. * @param CreateObjectParam * @return String r_object_id of new object * @throws DctmException */ public String createObject(CreateObjectParam params) throws DctmException; /** * Copy object * @param CopyObjectParam * @return String r_object_id of new object * @throws DctmException */ public String copyObject(CopyObjectParam params) throws DctmException; /** * Update properties of existing object * @param UpdateObjectParam * @return boolean true, if successfully updated, false otherwise * @throws DctmException */ public boolean updateObjectProps(UpdateObjectParam params) throws DctmException; /** * Move object from one location to another (link and unlink) * @param MoveObjectParam * @return boolean true, if successfully updated, false otherwise * @throws DctmException */ public boolean moveObject(MoveObjectParam params) throws DctmException; /** * Delete given object * @param DeleteObjectParam * @return boolean true, if successfully updated, false otherwise * @throws DctmException */ public boolean deleteObject(DeleteObjectParam params) throws DctmException; /** * Delete given metadata of an object * @param params * @return * @throws DctmException */ public boolean deleteObjectMetadata(DeleteMetadataParam params) throws DctmException; /** * Create new acl (if doesn't exist), add user permissions (if supplied) and apply on object. * @param ApplyAclParam * @return boolean true, if successfully updated, false otherwise * @throws DctmException */ public boolean applyAcl(ApplyAclParam params) throws DctmException; /** * Fetch IDfSysObject from given qualification. * @param String * @return IDfSysObject * @throws DctmException */ public IDfSysObject getObjectByQualification(String qualification) throws DctmException; /** * Fetch IDfSysObject from given Identity. * @param Identity * @return IDfSysObject * @throws DctmException */ public IDfSysObject getObjectByIdentity(ObjectIdentity identity) throws DctmException; /** * Fetch persistent object properties(all) from given qualification. * @param String - Qualification * @return Map<String,Object> * @throws DctmException */ public Map<String,Object> getPropertiesByQualification(String qualification) throws DctmException; /** * Fetch persistent object properties(all) from given identity. * @param ObjectIdentity identity of object * @return Map<String,Object> * @throws DctmException */ public Map<String,String> getPropertiesByIdentity(ObjectIdentity identity) throws DctmException; /** * Fetch query(dql) results. * @param String - query(dql) * @return List<Map<String,String>> * @throws DctmException */ public List<Map<String,String>> execSelect(String query) throws DctmException; /** * Exec update query * @param String - Qualification * @return List<Map<String,String>> * @throws DctmException */ public int execUpdate(String query) throws DctmException; /** * Copy Content * @param CopyObjectParam * @return * @throws DctmException */ public boolean copyContent(CopyObjectParam params) throws DctmException; /** * Add note to a sysobject * @param AddNoteParams * @throws DctmException */ public boolean addNote(AddNoteParams params) throws DctmException; /** * Create virtual document * @param CreateVirtualDocParams * @return boolean * @throws DctmException */ public boolean createVirtualDocument(CreateVirtualDocParams params) throws DctmException; /** * Create virtual document * @param CreateVirtualDocParams * @return boolean * @throws DctmException */ public boolean deleteVirtualDocument(List<ObjectIdentity> identityList) throws DctmException; /** * Link object to a folder * @param LinkObjectParam * @return boolean * @throws DctmException */ public boolean linkObject(LinkObjectParam params) throws DctmException; /** * Get content of object as ByteArrayInputStream * @param ExportObjectParams * @return Content * @throws DctmException */ public Content getContentAsByteArray(ExportContentParams params) throws DctmException; /** * Get content url of object for acs server * @param ObjectIdentity * @return String * @throws DctmException */ public String getAcsUrlOfContent(ObjectIdentity identity) throws DctmException; /** * Checkin Content for object * @param CheckinContentParams * @return String, object id * @throws DctmException */ public String checkinContent(CheckinContentParams params) throws DctmException; /** * Get thumbnail url for object * @param identity * @return * @throws DfException * @throws DctmException */ public String getThumbnailUrl(ObjectIdentity identity) throws DctmException; /** * Get Search Result * @param identity * @return * @throws DctmException */ public List<Map<String, String>> getSearchResult(SearchObjectParam param) throws DctmException; /** * @param param * @return * @throws DctmException */ public OperationStatus importOperation(ImportContentParams param) throws DctmException; /** * @param param * @return * @throws DctmException */ public OperationStatus exportOperation(ExportContentParams param) throws DctmException; /** * @param identity * @return * @throws DctmException */ public String getObjectPaths(ObjectIdentity identity) throws DctmException; }
/* * Copyright 2017 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package gr.javapemp.vertxonspring.model; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * A book JPA entity. * * @author Thomas Segismont */ @Entity @Data @NoArgsConstructor @DataObject(generateConverter = true) public class Book { @Id @GeneratedValue private Long id; private String name; private String author; public Book(String name, String author) { this.name = name; this.author = author; } // Mandatory for data objects public Book(JsonObject jsonObject) { BookConverter.fromJson(jsonObject, this); } public JsonObject toJson() { JsonObject json = new JsonObject(); BookConverter.toJson(this, json); return json; } }
package com.example.lbyanBack.util; import java.util.Base64; import java.util.logging.Logger; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.digest.DigestUtils; /** * AES 加密方法,是对称的密码算法(加密与解密的密钥一致),这里使用最大的 256 位的密钥 */ public class AESUtil { /** logger */ private static final Logger logger = Logger.getAnonymousLogger(); /** * 加密 * @param content 原文 * @param key 密钥 * @param iv 偏移量 * @return 密文,使用base64编码 */ public static String aesCbcEncrypt(String content, String key, String iv) { try { SecretKeySpec secretKey = new SecretKeySpec(DigestUtils.md5(key), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes())); byte[] result = cipher.doFinal(content.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(result); } catch (Exception e) { logger.info("exception:" + e.toString()); return null; } } /** * 解密 * @param content 密文,使用base64编码 * @param key 密钥 * @param iv 偏移量 * @return 原文 */ public static String aesCbcDecrypt(String content, String key, String iv) { try { SecretKeySpec secretKey = new SecretKeySpec(DigestUtils.md5(key), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes())); byte[] result = cipher.doFinal(Base64.getDecoder().decode(content)); return new String(result); } catch (Exception e) { logger.info("exception:" + e.toString()); return null; } } /** * 测试方法 * @param args args */ public static void main(String[] args) { String content = "{\"csrq\":\"1980-01-01\",\"xyjb\":\"无现有疾病\",\"yyqk\":\"无用药\",\"dh\":\"01-20190315-2-01-0003\",\"qtzysx\":\"无其他注意事项\",\"xb\":\"1\",\"lzswbbh\":\"084\",\"barylxfs\":\"77889900\",\"mz\":\"1\",\"lzsh\":\"西六04\",\"khdj\":\"3\",\"bar\":\"办案人1\",\"qsrq\":\"2019-03-15\",\"lzsj\":\"2019-03-15\",\"rybh\":\"2-01-01-20190315-03-011\",\"lzjssj\":\"2019-03-15\",\"baryzjh\":\"789456123\",\"badw\":\"01\"}"; String key = "thunisoft320"; String iv = "0000000000000000"; logger.info("加密前:" + content); String encrypted = aesCbcEncrypt(content, key, iv); logger.info("加密后:" + encrypted); String decrypted = aesCbcDecrypt(encrypted, key, iv); logger.info("解密后:" + decrypted); } }
/* * 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 at.ac.tuwien.dsg.grphStorage; //import at.ac.tuwien.dsg.dataenrichment.Configuration; //import at.ac.tuwien.dsg.app.graphstorage.test.OperateProperty; import at.ac.tuwien.dsg.test.OperateProperty; //import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.NodeFactory; import com.hp.hpl.jena.graph.Triple; //import com.hp.hpl.jena.mem.ModelMem; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDFS; //import com.mkyoung.datamodel.OperateProperty; import java.io.File; import java.io.FileReader; import virtuoso.jena.driver.VirtGraph; /** * * @author Anindita */ public class RDFGraphStorage { private static String fileURI=null; public static RDFGraphStorage getInstance(String newFileURI) { fileURI=newFileURI; return new RDFGraphStorage(); } public void GraphStore(String fileName)throws Exception { //consider the rdf file File rdfFileName=new File(fileName); FileReader rdfFileRead=new FileReader(rdfFileName); Model model=ModelFactory.createDefaultModel(); model.read(rdfFileRead,RDFS.getURI()); StmtIterator iter=model.listStatements(); Statement stmt; String url="jdbc:virtuoso://"+new OperateProperty().getVirtuosoIP()+":1111"; VirtGraph virtgraph=new VirtGraph(fileURI,url,"dba","dba"); while (iter.hasNext()) { stmt=(Statement)iter.next(); System.out.println("subject="+stmt.getSubject().getURI()); System.out.println("Predicate="+stmt.getPredicate().getLocalName()); System.out.println("object="+stmt.getObject().toString()); virtgraph.add(new Triple(NodeFactory.createURI(stmt.getSubject().getURI()) ,NodeFactory.createURI(stmt.getPredicate().getLocalName()) ,NodeFactory.createLiteral(stmt.getObject().toString()))); } } }
package com.rupom.city; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import com.rupom.city.R; public class MainActivity extends Activity { Animation _translateAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.splash_activity); _translateAnimation = new TranslateAnimation(TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE, -300f, TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE, 0f); _translateAnimation.setDuration(4000); _translateAnimation.setRepeatCount(-1); _translateAnimation.setRepeatMode(Animation.REVERSE); _translateAnimation.setInterpolator(new LinearInterpolator()); ImageView img = (ImageView) findViewById(R.id.image); img.startAnimation(_translateAnimation); ImageView imageButton = (ImageView) findViewById(R.id.imageButton); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, DrawerActivity.class); startActivity(intent); finish(); } }); } }
package com.model; import javax.persistence.CascadeType; import javax.persistence.Column; 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.OneToOne; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; @Entity public class Customer { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="Cid") private int customerId; @Column(name="password") @NotEmpty(message="Name is mandatory") private String password; @Column(name="Email") @NotEmpty(message="Name is mandatory") private String email; @NotEmpty(message="First Name is mandatory") @Column(name="firstname") private String firstName; @NotEmpty(message="Last Name is mandatory") @Column(name="lastname") private String lastName; @Column(name="Mobile") @Size(min = 10) @NotEmpty(message="Mobile is mandatory") private String mobile; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="address_id") private Address delAdderss; private boolean enabled; private String role; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="cart_id") private Cart cart; public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Address getDelAdderss() { return delAdderss; } public void setDelAdderss(Address delAdderss) { this.delAdderss = delAdderss; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } }
package enshud.typeexpression; import java.util.ArrayList; import enshud.syntaxtree.AbstractSyntaxNode; import enshud.syntaxtree.TerminalNode; public class ProcedureType extends AbstractType { public class ProcedureArgument { public String name; public AbstractType type; public ProcedureArgument(String name, AbstractType type) { this.name = name; this.type = type; } @Override public boolean equals(Object other) { if(!(other instanceof ProcedureArgument)) return false; return name.equals(((ProcedureArgument)other).name) && type.equals(((ProcedureArgument)other).type); } @Override public int hashCode() { return name.hashCode() * 31 + type.hashCode(); } } public ArrayList<ProcedureArgument> arguments; public ProcedureType(ArrayList<ProcedureArgument> arguments) { this.arguments = arguments; } public ProcedureType(AbstractSyntaxNode node) { if(!node.variableName.equals("ProcedureHead")) throw new RuntimeException(""); arguments = new ArrayList<ProcedureArgument>(); var tempParameter = node.get(2); if(tempParameter.size() == 0) return; int argumentsCount = 0; var tempParameters = tempParameter.get(1); for(var child : tempParameters) if(child.variableName.equals("TempParameterNames")) { argumentsCount = arguments.size(); for(var tempParameterName : child) if(tempParameterName.variableName.equals("TempParameterName")) { this.arguments.add(new ProcedureArgument( ((TerminalNode)tempParameterName.get(0)).token.content, null)); } } else if(child.variableName.equals("SimpleType")) { for(int i = argumentsCount; i < arguments.size(); ++i) arguments.get(i).type = new SimpleType(child); argumentsCount = 0; } } @Override public boolean equals(AbstractType obj) { if(obj instanceof ProcedureType) { if(arguments.size() != ((ProcedureType)obj).arguments.size()) return false; for(int i = 0; i < arguments.size(); ++i) if(!arguments.get(i).equals(((ProcedureType)obj).arguments.get(i))) return false; return true; } else return false; } @Override public String toString() { String res = "procedure ("; for(var argument : arguments) res += String.format("%s: %s, ", argument.name, argument.type); return res + ")"; } }
package org.andrill.conop.analysis.legacy; import java.util.List; import java.util.Map; public interface Solution { /** * Get all events. * * @return the list of events. */ public List<Map<String, String>> getEvents(); /** * Gets the name of this dataset. * * @return the name. */ public String getName(); /** * Gets all sections. * * @return the list of sections. */ public List<Map<String, String>> getSections(); }
package io.nuls.consensus.v1.thread; import io.nuls.base.basic.AddressTool; import io.nuls.base.data.NulsHash; import io.nuls.base.signture.BlockSignature; import io.nuls.core.core.ioc.SpringLiteContext; import io.nuls.core.model.DoubleUtils; import io.nuls.consensus.constant.ConsensusConstant; import io.nuls.consensus.model.bo.Chain; import io.nuls.consensus.model.bo.round.MeetingRound; import io.nuls.consensus.rpc.call.CallMethodUtils; import io.nuls.consensus.v1.RoundController; import io.nuls.consensus.v1.entity.BasicRunnable; import io.nuls.consensus.v1.entity.VoteStageResult; import io.nuls.consensus.v1.message.VoteResultMessage; import io.nuls.consensus.v1.utils.HashSetDuplicateProcessor; import java.util.HashSet; import java.util.Set; /** * @author Eva */ public class VoteResultProcessor extends BasicRunnable { private RoundController roundController; private HashSetDuplicateProcessor<NulsHash> duplicateProcessor = new HashSetDuplicateProcessor<>(1024); public VoteResultProcessor(Chain chain) { super(chain); } @Override public void run() { while (this.running) { try { if (null == roundController) { this.roundController = SpringLiteContext.getBean(RoundController.class); } doit(); } catch (Exception e) { log.error(e); } } } private void doit() throws Exception { VoteResultMessage resultMessage = chain.getConsensusCache().getVoteResultQueue().take(); if (null == resultMessage) { return; } if (resultMessage.getSignList() == null || resultMessage.getSignList().isEmpty()) { return; } if (resultMessage.getHeight() != chain.getBestHeader().getHeight() + 1) { return; } if (resultMessage.getBlockHash() == null || resultMessage.getBlockHash().equals(NulsHash.EMPTY_NULS_HASH)) { return; } if (resultMessage.getVoteStage() != ConsensusConstant.VOTE_STAGE_TWO) { return; } Set<String> set = new HashSet<>(); MeetingRound round = this.roundController.getRound(resultMessage.getRoundIndex(), resultMessage.getRoundStartTime()); for (byte[] sign : resultMessage.getSignList()) { BlockSignature signature = new BlockSignature(); signature.parse(sign, 0); byte[] addressBytes = AddressTool.getAddress(signature.getPublicKey(), chain.getChainId()); String address = AddressTool.getStringAddressByBytes(addressBytes); if (!round.getMemberAddressSet().contains(address)) { log.info("==========地址不对={}========", address); return; } boolean result = signature.verifySignature(resultMessage.getHash()).isSuccess(); if (!result) { log.info("==========签名不对=from:{}========", resultMessage.getNodeId()); return; } set.add(address); } double rate = DoubleUtils.div(set.size(), round.getMemberCount()) * 100; if (rate <= chain.getConfig().getByzantineRate()) { log.info("==========签名数量不足=={}%=from:{}========", rate, resultMessage.getNodeId()); return; } if (!duplicateProcessor.insertAndCheck(resultMessage.getBlockHash())) { //这里只处理一次就够了 return; } chain.getConsensusCache().cacheSignResult(resultMessage); if (!chain.isConsonsusNode() || !chain.isNetworkStateOk() || !chain.isSynchronizedHeight()) { log.info("通知区块模块,拜占庭验证通过:" + resultMessage.getHeight() + "-" + resultMessage.getBlockHash().toHex()); CallMethodUtils.noticeByzantineResult(chain, resultMessage.getHeight(), false, resultMessage.getBlockHash(), null); return; } //如果本地还没有收到 VoteStageResult result = new VoteStageResult(); result.setResultMessage(resultMessage); result.setBlockHash(resultMessage.getBlockHash()); result.setHeight(resultMessage.getHeight()); result.setVoteRoundIndex(resultMessage.getVoteRoundIndex()); result.setStage(ConsensusConstant.VOTE_STAGE_TWO); result.setRoundStartTime(resultMessage.getRoundStartTime()); result.setRoundIndex(resultMessage.getRoundIndex()); result.setPackingIndexOfRound(resultMessage.getPackingIndexOfRound()); chain.getConsensusCache().getStageTwoQueue().offer(result); } }
public class HeavyBox { private double width; private double height; private double depth; private String color; private double weight; private String name; public HeavyBox(String name, double width, double height, double depth, String color, double weight) { this.name = name; this.width = width; this.height = height; this.depth = depth; this.color = color; this.weight = weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getDepth() { return depth; } public void setDepth(double depth) { this.depth = depth; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } }
package com.junkStash.util; import java.io.File; import java.io.InputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; public class FileUtil { public static boolean saveLocal(String fileName, InputStream fileStream, String localDir){ try{ File uploadFile = new File(localDir+"/"+fileName); FileUtils.copyInputStreamToFile(fileStream, uploadFile); IOUtils.closeQuietly(fileStream); } catch(Exception e){ return false; } return true; } }
package br.com.maricamed.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.ResponseEntity; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import br.com.maricamed.entities.Clinica; import br.com.maricamed.entities.Endereco; import br.com.maricamed.entities.Perfil; import br.com.maricamed.entities.PerfilTipo; import br.com.maricamed.entities.Usuario; import br.com.maricamed.services.ClinicaService; import br.com.maricamed.services.EnderecoService; import br.com.maricamed.services.PerfilService; import br.com.maricamed.services.UsuarioService; import br.com.maricamed.utils.Utils; /** * <h1>Marica Med - controle de clinica!</h1> * Usuario Controller - * Tratamento do login / logout / cadastro do usuário * <p> * Controle de clinicas * * * @author Vitor Almeida * @version 1.0 * @since 2020-03-18 */ @Controller @RequestMapping("clinicas") public class ClinicaController { @Autowired private ClinicaService service; @Autowired private EnderecoService enderecoService; @Autowired private UsuarioService usuarioService; @Autowired private PerfilService perfilService; @GetMapping("/lista") public String listarClinicas() { return "clinica/lista"; } @GetMapping("/novo") public String telaCadastro(Clinica clinica) { return "clinica/cadastro"; } @GetMapping("/datatables/server/clinicas") public ResponseEntity<?> listarDatatables(HttpServletRequest request) { return ResponseEntity.ok(service.buscarTodos(request)); } @PostMapping("/salvar") public RedirectView salvarClinica(Clinica clinica, RedirectAttributes attr) { try { if(clinica.getUsuario() != null) { Usuario user = usuarioService.salvar(clinica.getUsuario()); List<Perfil> lpe = new ArrayList<Perfil>(); Perfil perf = perfilService.findById(PerfilTipo.CLINICA.getCod()); lpe.add(perf); user.setPerfis(lpe); clinica.setUsuario(user); } if(clinica.getEndereco() != null) { Endereco end = enderecoService.save(clinica.getEndereco()); clinica.setEndereco(end); } service.salvar(clinica); attr.addFlashAttribute("sucesso", "Operação realizada com sucesso!"); } catch (DataIntegrityViolationException ex) { attr.addFlashAttribute("falha", "Error: E-mail já existente!"); attr.addFlashAttribute("clinica", clinica); } RedirectView rv = new RedirectView (); rv.setUrl("/clinicas/novo/"); return rv; } @PostMapping("/editar") public RedirectView editarClinica(Clinica clinica, RedirectAttributes attr) { try { if(!clinica.hasNotId()) { Clinica cli = service.findById(clinica.getId()); if (cli.getEspecialidades() != null) { clinica.getEspecialidades().addAll(cli.getEspecialidades()); } if (!clinica.getEspecialidades().isEmpty()) { clinica.getEspecialidades().addAll(cli.getEspecialidades()); } if(clinica.getUsuario() != null) { Usuario usuario = updateUsuario(clinica.getUsuario()); usuarioService.salvar(usuario); //clinica.setUsuario(user); } if(clinica.getEndereco() != null) { Endereco end = enderecoService.save(clinica.getEndereco()); clinica.setEndereco(end); } service.salvar(clinica); attr.addFlashAttribute("sucesso", "Operação realizada com sucesso!"); } } catch (DataIntegrityViolationException ex) { attr.addFlashAttribute("falha", "Error: E-mail já existente!"); attr.addFlashAttribute("clinica", clinica); } RedirectView rv = new RedirectView (); if(!clinica.hasNotId()) { rv.setUrl("/clinicas/editar/dados/clinica/"+clinica.getId()); attr.addFlashAttribute("id", clinica.getId()); } else { rv.setUrl("/clinicas/novo/"); } return rv; } @GetMapping("/editar/dados/clinica/{id}") public ModelAndView preEditarCadastro(@PathVariable("id") Long id, HttpSession session) { Clinica clinica = service.findById(id); if (Utils.verificaSeUserSessionIgualUserParam(clinica.getUsuario().getId(), session)) { throw new UsernameNotFoundException(" "); } else { return new ModelAndView("clinica/cadastro", "clinica", service.findById(id)); } } // excluir especialidade @GetMapping({"/id/{idCli}/excluir/especializacao/{idEsp}"}) public RedirectView excluirEspecialidadePorClinica(@PathVariable("idCli") Long idCli, @PathVariable("idEsp") Long idEsp, RedirectAttributes attr, HttpSession session) { Clinica clinica = service.findById(idCli); if (Utils.verificaSeUserSessionIgualUserParam(clinica.getUsuario().getId(), session)) { throw new UsernameNotFoundException(" "); } else { service.excluirEspecialidadePorClinica(idCli, idEsp); attr.addFlashAttribute("sucesso", "Especialidade removida com sucesso."); RedirectView rv = new RedirectView (); rv.setUrl("/clinicas/editar/dados/clinica/"+idCli); attr.addFlashAttribute("id", idCli); return rv; } } public Usuario updateUsuario(Usuario usuario) { Usuario user = usuarioService.findById(usuario.getId()); user.setNome(usuario.getNome()); user.setTelefone1(usuario.getTelefone1()); user.setTelefone2(usuario.getTelefone2()); user.setCelular(usuario.getCelular()); user.setAtivo(usuario.isAtivo()); return user; } }
package com.legaoyi.protocol.server; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.legaoyi.common.message.ExchangeMessage; @Component("dataLimitAlarmHandler") public class DataLimitAlarmHandler { private static final Logger logger = LoggerFactory.getLogger(DataLimitAlarmHandler.class); @Autowired @Qualifier("commonUpstreamMessageHandler") private ServerMessageHandler commonUpstreamMessageHandler; @Autowired @Qualifier("gatewayCacheManager") private GatewayCacheManager gatewayCacheManager; /** * * @param ip * @param simCode * @param type 1:上行数据流量超频,2:消息条数超频 */ public void handleDataLimitAlarm(String ip, String simCode, int type) { try { Map<String, Object> data = new HashMap<String, Object>(); data.put("type", type); data.put("simCode", simCode); data.put("ip", ip); commonUpstreamMessageHandler.handle(new ExchangeMessage(ExchangeMessage.MESSAGEID_DATA_LIMIT_ALARM, data, null)); } catch (Exception e) { logger.error("******发送流量异常告警通知失败,handleDataLimitAlarm error", e); } if (ip != null) { Map<String, Object> info = gatewayCacheManager.getBlackListCache(ip); if (info == null) { info = new HashMap<String, Object>(); } Integer count = (Integer) info.get("count"); if (count == null) { count = 1; } // 加入黑名单,限制(count * 5)分钟 info.put("count", count); info.put("limitTime", count * 5 * 60 * 1000); info.put("startTime", System.currentTimeMillis()); try { gatewayCacheManager.addBlackListCache(ip, info); } catch (Exception e) { } } } public void handleDataLimitAlarm(Session session, int type) { String ip = null; String simCode = null; if (session != null) { ip = ((InetSocketAddress) session.getChannelHandlerContext().channel().remoteAddress()).getAddress().getHostAddress(); simCode = session.getSimCode(); } logger.warn("******设备流量异常,网关强制断开链接,data limit force offline,simCode={},ip={}", simCode, ip); session.getChannelHandlerContext().close(); handleDataLimitAlarm(ip, simCode, type); } }
/* * 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 jc.fog.data.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import jc.fog.exceptions.FogException; import jc.fog.logic.dto.MaterialDTO; import jc.fog.logic.dto.RooftypeDTO; /** * * @author Claus */ public class RooftypeDAO extends AbstractDAO { /** * Henter tupler i Rooftype og relateret data fra Materiale og Materialetype. * Tupler sorteres på Rooftype.id så ResultSet kan gennemløbes og liste af * MaterialDTO objekter dannes til hvert RooftypeDTO objekt. */ private static final String GET_ROOFTYPES_SQL = "SELECT rt.id, rt.type, m.id as materialId, m.materialtypeId, m.name, m.length, m.unit, m.price, mt.type as materialType " + "FROM Rooftypes rt INNER JOIN RooftypeMaterials rm ON rt.id = rm.rooftypeId " + "INNER JOIN Materials m ON rm.materialId = m.id " + "INNER JOIN Materialtypes mt ON m.materialtypeId = mt.id " + "ORDER BY rt.id ASC"; public RooftypeDAO(Connection connection) throws FogException { super(connection); } /** * Henter tagtyper fra databasen. * Findes ingen tagtyper, returneres en tom liste. * @return */ public List<RooftypeDTO> getRooftypes() throws FogException { List<RooftypeDTO> rooftypes = new ArrayList(); try ( // ResultSet og PreparedStatement implementerer AutoCloseable og lukkes automatisk. PreparedStatement pstm = connection.prepareStatement(GET_ROOFTYPES_SQL); ResultSet rs = pstm.executeQuery(); ) { rooftypes = mapRooftypes(rs); } catch(Exception e) { throw new FogException("Der er sket en fejl og systemet kan ikke hente tagtyper.", e.getMessage(), e); } return rooftypes; } /** * Mapper fra ResultSet til List af RooftypeDTO objekter. * Da metoden er privat, lader vi kaldende metode fange evt. SQLException. * @param rs * @return * @throws SQLException */ private List<RooftypeDTO> mapRooftypes(ResultSet rs) throws SQLException { RooftypeDTO rooftype = null; List<RooftypeDTO> rooftypes = new ArrayList<>(); List<MaterialDTO> materials = null; while(rs.next()) { // Opret rooftype hvis krævet, start med en tom liste af materialer. if (rooftype == null || rooftype.getId() != rs.getInt("id")) { materials = new ArrayList<>(); rooftype = new RooftypeDTO(rs.getInt("id"), rs.getString("type"), materials); rooftypes.add(rooftype); } // Tilføj materiale til listen i den aktuelle rooftype. materials.add(new MaterialDTO( rs.getInt("materialId"), rs.getInt("materialtypeId"), rs.getString("name"), rs.getInt("length"), rs.getString("unit"), rs.getString("materialType"), rs.getInt("id"), // rooftype id. rs.getFloat("price") )); } return rooftypes; } }
package pe.cibertec.excepciones; public class ExcepcionGeneral extends RuntimeException{ public ExcepcionGeneral(){ this("Ha ocurrido una excepcion"); } public ExcepcionGeneral(String mensaje){ super(mensaje); } }
package com.yhkx.core.errorcode; /** * @Author: uniqu * @Date: 2018-9-18 15:33 * @Description: */ public interface ErrorCode { int getNumber(); //ErrorLevel getErrorLevel(); }
package com.proyecto.dom; import java.util.Date; import javax.persistence.Column; 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 javax.validation.constraints.NotNull; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * * Tabla que contiene los datos correspondientes a usuarios de la aplicación. * * */ @Entity @Table(name = "USUARIO", schema = "PROYECTO") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "userCache") public class User extends AbstractEntity { /** * Constante LENGHT_255. */ private static final int LENGHT_250 = 250; private static final int LENGHT_150 = 150; private static final long serialVersionUID = -22100802440540807L; @Id @Column(name = "user_key") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userKey_generator") @SequenceGenerator(name = "userKey_generator", initialValue = 0, allocationSize = 0, sequenceName = "PROYECTO.USUARIO_SEQ") private Long userId; @Column(nullable = false, length = LENGHT_250) @NotNull private String name; @Column(unique = true, length = LENGHT_250) private String nickname; @Column(nullable = false, length = LENGHT_250) @NotNull private String surname1; @Column(length = LENGHT_250) private String surname2; @Column(length = LENGHT_250,name = "sextype_key") private String sexo; /** * email */ @Column(nullable = false, length = LENGHT_150, unique = true) @NotNull private String email; /** * Segundo apellido requerido */ @Column(length = LENGHT_250) private String surname3; /** * Fecha de nacimiento */ @javax.persistence.Column(nullable = false, name = "BIRTH_DATE") private Date birthDate; /** * The user password */ @Column(name = "PASSWORD") private String password; @ManyToOne(fetch = javax.persistence.FetchType.EAGER) @JoinColumn(referencedColumnName = "perfil_key", name = "Perfil_key") private Perfil perfil; @Column(name = "user_imagen") private byte[] imagen; public final Long getUserId() { return userId; } public final void setUserId(final Long userId) { this.userId = userId; } public final String getName() { return name; } public final void setName(final String name) { this.name = name; } public final String getSurname1() { return surname1; } public final void setSurname1(final String surname1) { this.surname1 = surname1; } public final String getSurname2() { return surname2; } public final void setSurname2(final String surname2) { this.surname2 = surname2; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public Date getBirthDate() { return (birthDate != null) ? new Date(birthDate.getTime()) : null; } public void setBirthDate(final Date birthDate) { this.birthDate = (birthDate != null) ? new Date(birthDate.getTime()) : null; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public byte[] getImagen() { return imagen; } public void setImagen(final byte[] imagen) { this.imagen = imagen; } public String getNickname() { return nickname; } public void setNickname(final String nickname) { this.nickname = nickname; } public String getSurname3() { return surname3; } public void setSurname3(final String surname3) { this.surname3 = surname3; } public Perfil getPerfil() { return perfil; } public void setPerfil(Perfil perfil) { this.perfil = perfil; } /** * @return the sexo */ public final String getSexo() { return sexo; } /** * @param sexo the sexo to set */ public final void setSexo(String sexo) { this.sexo = sexo; } }
package com.example.rubberyuzu.yugamiapp; /** * Created by reoy on 15/12/05. */ public class TimerTest { }
/* * Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.datumbox.common.utilities; import com.datumbox.configuration.TestConfiguration; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.regex.Pattern; import org.junit.Test; import static org.junit.Assert.*; /** * * @author bbriniotis */ public class PHPfunctionsTest { public PHPfunctionsTest() { } /** * Test of asort method, of class PHPfunctions. */ @Test public void testAsort() { System.out.println("asort"); Double[] array = {1.1, 1.2, 1.3, 1.4, 1.0}; Integer[] expResult = {4, 0, 1, 2, 3}; Integer[] result = PHPfunctions.<Double>asort(array); assertArrayEquals(expResult, result); } /** * Test of arsort method, of class PHPfunctions. */ @Test public void testArsort() { System.out.println("arsort"); Double[] array = {1.1, 1.2, 1.3, 1.4, 1.0}; Integer[] expResult = {3, 2, 1, 0, 4}; Integer[] result = PHPfunctions.<Double>arsort(array); assertArrayEquals(expResult, result); } /** * Test of ltrim method, of class PHPfunctions. */ @Test public void testLtrim() { System.out.println("ltrim"); String s = " test"; String expResult = "test"; String result = PHPfunctions.ltrim(s); assertEquals(expResult, result); } /** * Test of rtrim method, of class PHPfunctions. */ @Test public void testRtrim() { System.out.println("rtrim"); String s = "test "; String expResult = "test"; String result = PHPfunctions.rtrim(s); assertEquals(expResult, result); } /** * Test of substr_count method, of class PHPfunctions. */ @Test public void testSubstr_count_String_String() { System.out.println("substr_count"); String string = "test tester"; String substring = "test"; int expResult = 2; int result = PHPfunctions.substr_count(string, substring); assertEquals(expResult, result); } /** * Test of substr_count method, of class PHPfunctions. */ @Test public void testSubstr_count_String_char() { System.out.println("substr_count"); String string = "test test"; char character = 't'; int expResult = 4; int result = PHPfunctions.substr_count(string, character); assertEquals(expResult, result); } /** * Test of round method, of class PHPfunctions. */ @Test public void testRound() { System.out.println("round"); double d = 3.1415; int i = 2; double expResult = 3.14; double result = PHPfunctions.round(d, i); assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH); } /** * Test of round method, of class PHPfunctions. */ @Test public void testLog() { System.out.println("log"); double d = 100.0; double base = 10.0; double expResult = 2.0; double result = PHPfunctions.log(d, base); assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH); } /** * Test of mt_rand method, of class PHPfunctions. */ @Test public void testMt_rand_0args() { System.out.println("mt_rand"); RandomValue.randomGenerator = new Random(42); int expResult = -1562431105; int result = PHPfunctions.mt_rand(); assertEquals(expResult, result); } /** * Test of mt_rand method, of class PHPfunctions. */ @Test public void testMt_rand_int_int() { System.out.println("mt_rand"); RandomValue.randomGenerator = new Random(42); int min = 0; int max = 10; int expResult = 8; int result = PHPfunctions.mt_rand(min, max); assertEquals(expResult, result); } /** * Test of shuffle method, of class PHPfunctions. */ @Test public void testArray_flip() { System.out.println("array_flip"); Map<String, Integer> original = new HashMap<>(); original.put("1", 10); original.put("2", 11); original.put("3", 12); Map<Integer, String> expResult = new HashMap<>(); expResult.put(10, "1"); expResult.put(11, "2"); expResult.put(12, "3"); Map<Integer, String> result = PHPfunctions.array_flip(original); assertEquals(expResult, result); } /** * Test of shuffle method, of class PHPfunctions. */ @Test public void testShuffle() { System.out.println("shuffle"); RandomValue.randomGenerator = new Random(42); Integer[] result = {1,2,3,4,5}; Integer[] expResult = {2,3,4,5,1}; PHPfunctions.shuffle(result); assertArrayEquals(expResult, result); } /** * Test of preg_replace method, of class PHPfunctions. */ @Test public void testPreg_replace_3args_1() { System.out.println("preg_replace"); String regex = "\\s+"; String replacement = " "; String subject = "a a"; String expResult = "a a"; String result = PHPfunctions.preg_replace(regex, replacement, subject); assertEquals(expResult, result); } /** * Test of preg_replace method, of class PHPfunctions. */ @Test public void testPreg_replace_3args_2() { System.out.println("preg_replace"); Pattern pattern = Pattern.compile("\\s+"); String replacement = " "; String subject = "a a"; String expResult = "a a"; String result = PHPfunctions.preg_replace(pattern, replacement, subject); assertEquals(expResult, result); } /** * Test of preg_match method, of class PHPfunctions. */ @Test public void testPreg_match_String_String() { System.out.println("preg_match"); String regex = "\\s{2,}"; String subject = "a a a"; int expResult = 2; int result = PHPfunctions.preg_match(regex, subject); assertEquals(expResult, result); } /** * Test of preg_match method, of class PHPfunctions. */ @Test public void testPreg_match_Pattern_String() { System.out.println("preg_match"); Pattern pattern = Pattern.compile("\\s{2,}"); String subject = "a a a"; int expResult = 2; int result = PHPfunctions.preg_match(pattern, subject); assertEquals(expResult, result); } }
package com.cninnovatel.ev.utils; import java.util.TimeZone; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.CalendarContract; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.provider.CalendarContract.Reminders; import com.cninnovatel.ev.App; import com.cninnovatel.ev.R; import com.cninnovatel.ev.RuntimeData; import com.cninnovatel.ev.api.model.RestMeeting; public class CalendarUtil { private static ContentResolver cr = App.getContext().getContentResolver(); private static Logger log = Logger.getLogger(CalendarUtil.class); public static void addEvent(RestMeeting meeting) { try { String calendarId = getCalendarId(); deleteEvent(calendarId, meeting); addEvent(calendarId, meeting); } catch (Exception e) { log.error("CalendarUtil - add calendar event failed", e); } } public static void deleteEvent(RestMeeting meeting) { try { String calendarId = getCalendarId(); deleteEvent(calendarId, meeting); } catch (Exception e) { log.error("CalendarUtil - delete calendar event failed", e); } } private static String getCalendarId() { String email = "hexmeet@cninnovatel.com"; String type = "com.cninnovatel"; String[] projection = new String[] {Calendars._ID, Calendars.ACCOUNT_NAME, Calendars.ACCOUNT_TYPE }; String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?))"; String[] selectionArgs = new String[] {email, type}; Cursor cursor = cr.query(Calendars.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor.getCount() > 0) { cursor.moveToLast(); return cursor.getString(cursor.getColumnIndex("_id")); } // no cninnovatel calendar account, create one ContentValues value = new ContentValues(); value.put(Calendars.NAME, "hexmeet"); value.put(Calendars.ACCOUNT_NAME, email); value.put(Calendars.ACCOUNT_TYPE, type); value.put(Calendars.CALENDAR_DISPLAY_NAME,App.getContext().getResources().getString(R.string.app_name)); value.put(Calendars.VISIBLE, 1); value.put(Calendars.CALENDAR_COLOR, -9206951); value.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER); value.put(Calendars.SYNC_EVENTS, 1); value.put(Calendars.CALENDAR_TIME_ZONE, TimeZone.getDefault().getID()); value.put(Calendars.OWNER_ACCOUNT, email); value.put(Calendars.CAN_ORGANIZER_RESPOND, 0); Uri calendarUri = Calendars.CONTENT_URI; calendarUri = calendarUri.buildUpon() .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, email) .appendQueryParameter(Calendars.ACCOUNT_TYPE, type) .build(); Uri uri = cr.insert(calendarUri, value); return ContentUris.parseId(uri) + ""; } private static void addEvent(String calendarId, RestMeeting meeting) { ContentValues event = new ContentValues(); String htmlUrl = "/jymeeting.html"; if(App.isEnVersion()) { htmlUrl = "/enjymeeting.html"; } event.put(Events.TITLE, meeting.getName()); String remark = StringUtils.isEmpty(meeting.getRemarks()) ? "[" + App.getContext().getResources().getString(R.string.no) + "]" : meeting.getRemarks(); event.put(Events.DESCRIPTION, App.getContext().getResources().getString(R.string.no) + ": " + remark + "\n" + App.getContext().getResources().getString(R.string.click_it_to_join) + ": http://" + RuntimeData.getUcmServer() + htmlUrl + "?id=" + meeting.getId()); event.put(Events.CALENDAR_ID, calendarId); event.put(Events.EVENT_LOCATION, ""); event.put(Events.DTSTART, meeting.getStartTime()); event.put(Events.DTEND, meeting.getStartTime() + meeting.getDuration()); event.put(Events.HAS_ALARM, 1); event.put(Events.EVENT_COLOR, meeting.getId()); event.put(Events.EVENT_TIMEZONE, "Asia/Shanghai"); Uri uri = null; try { uri = cr.insert(Events.CONTENT_URI, event); } catch (Exception e) { log.error("CalendarUtil - add calendar event failed, calendarId=" + calendarId); e.printStackTrace(); return; } ContentValues values = new ContentValues(); values.put("event_id", ContentUris.parseId(uri)); values.put("minutes", 15); cr.insert(Reminders.CONTENT_URI, values); log.info("added calendar event, meetingId=" + meeting.getId()); } private static void deleteEvent(String calendarId, RestMeeting meeting) { String[] projection = new String[] { "calendar_id", "_id", "eventColor" }; String selection = "((calendar_id = ?) AND (eventColor = ?))"; String[] selectionArgs = new String[] {calendarId, meeting.getId() + ""}; Cursor cursor = cr.query(Events.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor != null) { while (cursor.moveToNext()) { cursor.moveToLast(); String eventId = cursor.getString(cursor.getColumnIndex("_id")); Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, Long.parseLong(eventId)); cr.delete(uri, null, null); log.info("deleted calendar event, meetingId=" + meeting.getId()); } } } }
package com.li.current; import java.util.concurrent.TimeUnit; public class ThreadMain { public static void main(String[] args) throws InterruptedException { MyThreadPool pool = new MyThreadPool(4, 20, 2L, TimeUnit.SECONDS); for (int i = 0; i < 10000; i++) { Task task = new Task(Integer.toString(i)); pool.execute(task); } Thread.sleep(10 * 1000); for (int i = 0; i < 16; i++) { Task task = new Task(Integer.toString(i)); pool.execute(task); } } private static class Task implements Runnable { private String name; public String getName() { return name; } public Task(String name) { super(); this.name = name; } @Override public void run() { // TODO Auto-generated method stub System.out.println("线程" + Thread.currentThread().getName() + "正在执行任务" + name); } } }
import java.util.ArrayList; /** * Created by mohammad on 5/19/17. */ public class DuplicateCourseChecker extends StudentPolicyChecker { @Override public boolean satisfy(Barnameh barnameh, StudentState studentState, History history) { ArrayList<Course> passedCourse = history.getPassedCourses(); for(Course course : passedCourse){ if(barnameh.hasCourse(course)) return false; } return true; } }
/** * This code find the median in two sorted arrays * Reference: * 1. https://github.com/mission-peace/interview/blob/master/src/com/interview/binarysearch/MedianOfTwoSortedArrayOfDifferentLength.java * Time complexity is O(log(min(x,y)) * Space complexity is O(1) */ public class MedianSortedArray { //function to find median in two sorted array public double findMedianSortedArray(int[] input1, int[] input2) { if(input1.length > input2.length) { return findMedianSortedArray(input2, input1); } int x = input1.length; int y = input2.length; int low = 0; int high = x; while(low <= high) { int partitionX = (low + high)/2; int partitionY = (x+y+1)/2 - partitionX; //if partitionX is 0 it means nothing is there on left side. Use -INF for maxLeftX //if partitionX is length of input then there is nothing on right side. Use +INF for minRightX int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : input1[partitionX - 1]; int minRightX = (partitionX == x) ? Integer.MAX_VALUE : input1[partitionX]; int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : input2[partitionY - 1]; int minRightY = (partitionY == y) ? Integer.MAX_VALUE : input2[partitionY]; if(maxLeftX <= minRightY && maxLeftY <= minRightX) { if((x+y) % 2 == 0) { return ((double)Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY))/2; } else { return (double)Math.max(maxLeftX, maxLeftY); } } else if(maxLeftX > minRightY) { high = partitionX - 1; } else { low = partitionX + 1; } } //Only we we can come here is if input arrays were not sorted. Throw in that scenario. throw new IllegalArgumentException(); } // main method public static void main(String args[]) { int[] x = {1, 3, 8, 9, 15}; int[] y = {7, 11, 19, 21, 18, 25}; MedianSortedArray mm = new MedianSortedArray(); double num = mm.findMedianSortedArray(x, y); System.out.println(num); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.appcloud.core.dto; import java.util.List; import java.util.Set; public class Container { private int id; private String imageName; private String imageVersion; private Set<ContainerServiceProxy> serviceProxies; private List<RuntimeProperty> runtimeProperties; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public String getImageVersion() { return imageVersion; } public void setImageVersion(String imageVersion) { this.imageVersion = imageVersion; } public Set<ContainerServiceProxy> getServiceProxies() { return serviceProxies; } public void setServiceProxies(Set<ContainerServiceProxy> serviceProxies) { this.serviceProxies = serviceProxies; } public void setRuntimeProperties(List<RuntimeProperty> runtimeProperties) { this.runtimeProperties = runtimeProperties; } public List<RuntimeProperty> getRuntimeProperties() { return runtimeProperties; } }
package com.test; import com.test.base.Solution; import com.test.base.TreeNode; /** * 普通 递归,没啥好说的 * @author YLine * * 2019年5月5日 下午7:12:04 */ public class SolutionA implements Solution { private int mTotal; @Override public int sumRootToLeaf(TreeNode root) { mTotal = 0; dfs(root, 0); return mTotal; } private void dfs(TreeNode node, int result) { // 节点为空,直接不处理 if (null == node) { return; } // 叶子结点 if (null == node.left && null == node.right) { // 总和 mTotal += ((result << 1) + node.val); System.out.println("result = " + result); return; } result = (result << 1) + node.val; if (null != node.left) { dfs(node.left, result); } if (null != node.right) { dfs(node.right, result); } } }
package be.odisee.pajotter.service; import be.odisee.pajotter.utilities.RolNotFoundException; import be.odisee.pajotter.domain.*; import java.util.List; public interface PajottersSessieService { //Partijen public Partij voegPartijToe(String voornaam, String familienaam, String emailadres, String paswoord, String rol); public Partij voegPartijToe(String voornaam, String familienaam, String emailadres, String paswoord); public Partij voegPartijToe(Partij partij); public Partij zoekPartijMetId(int id); public void verwijderPartij(int partijid); public void updatePartij(Partij partijid); public List<Partij> geefAllePartijen(); public Partij zoekPartijMetEmailadres(String username); //Toevoegen van rollen aan partijen public List<Rol> geefAlleRollen(int id); public Rol voegRolToe(String type, int partijId, String usernaam) throws RolNotFoundException; public Rol zoekRolMetId(int id); public Rol zoekRolMetUserid(String userid); public void verwijderRol(int id); //Productie aanbieden public Productie VoegProductieToe(String status, Partij partij, String tekst, int aantal); public Productie zoekProductieMetId(int productieId); public List<Productie> geefAlleProductie(int id); public void updateProductie(Productie productie); public void verwijderProductie(int productieID); //Aanbieding aanbieden public Aanbieding VoegAanbiedingToe(String status, Partij partij, String tekst, int aantal); public Aanbieding zoekAanbiedingMetId(int aanbiedingId); public List<Aanbieding> geefAlleAanbiedingen(int id); public void updateAanbieding(Aanbieding aanbieding); public void verwijderAanbieding(int aanbiedingID); //Bestelling aan leverancier public Bestelling VoegBestellingToe(String status, Partij partij, String tekst, int aantal, int LeverancierId); public Bestelling zoekBestellingMetId(int bestellingId); public List<Bestelling> geefAlleBestellingen(int id, String Columnname); public void updateBestelling(Bestelling bestelling); public void verwijderBestelling(int bestellingID); //Teler kan vraag stellen public Vraag VoegVraagToe(String status, Partij partij, String tekst); public Vraag zoekVraagMetId(int bestellingId); public List<Vraag> geefAlleVraagen(int id, String Columnname); public List<Vraag> geefAlleVraagen(); public void updateVraag(Vraag bestelling); public void verwijderVraag(int bestellingID); //Pajotter kan antwoorden op vraag public Antwoord VoegAntwoordToe(String status, Partij partij, Bericht reactieOp, String tekst); public Antwoord zoekAntwoordMetId(int bestellingId); public List<Antwoord> geefAlleAntwoorden(int id, String Columnname); public void updateAntwoord(Antwoord bestelling); public void verwijderAntwoord(int bestellingID); }
package pl.globallogic.qaa_academy.oop; public class GearBox { private String name; }
package view; import controller.ControllerClientes; import controller.ControllerProdutos; import controller.ControllerProdutosVendasProdutos; import controller.ControllerSection; import controller.ControllerUsuarios; import controller.ControllerVendas; import controller.ControllerVendasClientes; import controller.ControllerVendasProdutos; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.RowFilter; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import model.ModelClientes; import model.ModelProdutos; import model.ModelProdutosVendasProdutos; import model.ModelSection; import model.ModelVendas; import model.ModelVendasClientes; import model.ModelVendasProdutos; import util.Datas; public class ViewVenda extends javax.swing.JFrame { String salvarAlterar = "salvar"; ControllerUsuarios controllerUsuarios = new ControllerUsuarios(); // SECTION ControllerSection controllerSection = new ControllerSection(); ModelSection modelSection; ArrayList<ModelSection> listaModelSection = new ArrayList<>(); // CLIENTE ControllerClientes controllerClientes = new ControllerClientes(); ModelClientes modelClientes = new ModelClientes(); ArrayList<ModelClientes> listaModelClientes = new ArrayList<>(); // PRODUTO ControllerProdutos controllerProdutos = new ControllerProdutos(); ModelProdutos modelProdutos = new ModelProdutos(); ArrayList<ModelProdutos> listaModelProdutos = new ArrayList<>(); // VENDAS-CLIENTES ArrayList<ModelVendasClientes> listaModelVendasClientes = new ArrayList<>(); ControllerVendasClientes controllerVendasClientes = new ControllerVendasClientes(); // VENDAS-PRODUTOS ControllerVendasProdutos controllerVendasProdutos = new ControllerVendasProdutos(); ModelVendasProdutos modelVendasProdutos = new ModelVendasProdutos(); ArrayList<ModelVendasProdutos> listaModelVendasProdutos = new ArrayList<>(); // VENDAS ControllerVendas controllerVendas = new ControllerVendas(); ModelVendas modelVendas = new ModelVendas(); // VENDAS-PRODUTOS-VENDAS ControllerProdutosVendasProdutos controllerProdutosVendasProdutos = new ControllerProdutosVendasProdutos(); ModelProdutosVendasProdutos modelProdutosVendasProdutos = new ModelProdutosVendasProdutos(); ArrayList<ModelProdutosVendasProdutos> listaModelProdutosVendasProdutos = new ArrayList<>(); // Usado na conversão de datas para o padrão americano Datas datas = new Datas(); String nomeUsuario; int IdUsuario; public ViewVenda() { initComponents(); listarClientes(); listarProdutos(); setLocationRelativeTo(null); carregarVendas(); inicializarCodigosCliente(); inicilizarCodigoProduto(); // Desabilita o botão Salvar jbSalvar.setEnabled(false); jbSalvar.setForeground(Color.GRAY); // Seta os campos de desconto e valor com 0 jtfDesconto.setText("0"); jtfValorTotal.setText("0"); habilitarCampos(false); // Seta o ícone da aplicação URL url = this.getClass().getResource("/imagens/marca/appicon.png"); Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(imagemTitulo); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jtpPainel = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jtfCodCliente = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jtfCodVenda = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtfCodProduto = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jtfQuantidade = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jtCarrinho = new javax.swing.JTable(); jtfValorTotal = new javax.swing.JTextField(); jtfDesconto = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jcbProduto = new componentes.UJComboBox(); jcbCliente = new componentes.UJComboBox(); jPanel3 = new javax.swing.JPanel(); jbRemover = new javax.swing.JButton(); jbNovo = new javax.swing.JButton(); jbCancelar = new javax.swing.JButton(); jbSalvar = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jbAdicionar = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jtfNomeUsuario = new javax.swing.JTextField(); jtfCodUsuario = new javax.swing.JTextField(); jLabel18 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jtfPesquisar = new javax.swing.JTextField(); jScrollPane2 = new javax.swing.JScrollPane(); jtVendas = new javax.swing.JTable(); jLabel16 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); jbExcluir = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Vendas"); setResizable(false); jtpPainel.setBackground(new java.awt.Color(251, 245, 95)); jtpPainel.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jPanel1.setBackground(new java.awt.Color(251, 245, 95)); jLabel1.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel1.setText("Código do cliente"); jtfCodCliente.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfCodClienteFocusLost(evt); } }); jLabel2.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel2.setText("Cliente"); jtfCodVenda.setEditable(false); jLabel3.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel3.setText("Código da venda"); jLabel4.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel4.setText("Código do produto"); jtfCodProduto.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfCodProdutoFocusLost(evt); } }); jLabel5.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel5.setText("Produto"); jLabel6.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel6.setText("Quantidade"); jLabel7.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N jLabel7.setText("Carrinho"); jtCarrinho.getTableHeader().setFont(new java.awt.Font("Consolas", 0, 14)); jtCarrinho.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtCarrinho.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cód Prod", "Nome produto", "Quantidade", "Valor unitário", "Valor total" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jtCarrinho.setSelectionBackground(new java.awt.Color(251, 245, 95)); jtCarrinho.setSelectionForeground(new java.awt.Color(0, 0, 0)); jScrollPane1.setViewportView(jtCarrinho); jtfDesconto.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfDescontoFocusLost(evt); } }); jtfDesconto.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jtfDescontoKeyTyped(evt); } }); jLabel12.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel12.setText("Desconto"); jLabel13.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel13.setText("Valor total"); jLabel8.setText("R$"); jLabel9.setText("%"); jcbProduto.setAutocompletar(true); jcbProduto.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jcbProduto.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { jcbProdutoPopupMenuWillBecomeInvisible(evt); } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { } }); jcbCliente.setAutocompletar(true); jcbCliente.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jcbCliente.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { jcbClientePopupMenuWillBecomeInvisible(evt); } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { } }); jPanel3.setBackground(new java.awt.Color(0, 0, 0)); jPanel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jPanel3MouseEntered(evt); } }); jbRemover.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbRemover.setForeground(new java.awt.Color(251, 245, 95)); jbRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/delete.png"))); // NOI18N jbRemover.setText("REMOVER"); jbRemover.setBorder(null); jbRemover.setBorderPainted(false); jbRemover.setContentAreaFilled(false); jbRemover.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbRemoverMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbRemoverMouseExited(evt); } }); jbRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbRemoverActionPerformed(evt); } }); jbNovo.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbNovo.setForeground(new java.awt.Color(251, 245, 95)); jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/plus.png"))); // NOI18N jbNovo.setText("NOVO"); jbNovo.setBorder(null); jbNovo.setBorderPainted(false); jbNovo.setContentAreaFilled(false); jbNovo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbNovoMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbNovoMouseExited(evt); } }); jbNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbNovoActionPerformed(evt); } }); jbCancelar.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbCancelar.setForeground(new java.awt.Color(251, 245, 95)); jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/close.png"))); // NOI18N jbCancelar.setText("CANCELAR"); jbCancelar.setBorder(null); jbCancelar.setBorderPainted(false); jbCancelar.setContentAreaFilled(false); jbCancelar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbCancelarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbCancelarMouseExited(evt); } }); jbCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCancelarActionPerformed(evt); } }); jbSalvar.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbSalvar.setForeground(new java.awt.Color(251, 245, 95)); jbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/save.png"))); // NOI18N jbSalvar.setText("SALVAR"); jbSalvar.setBorder(null); jbSalvar.setBorderPainted(false); jbSalvar.setContentAreaFilled(false); jbSalvar.setEnabled(false); jbSalvar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbSalvarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbSalvarMouseExited(evt); } }); jbSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalvarActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(251, 245, 95)); jLabel10.setText("|"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(251, 245, 95)); jLabel11.setText("|"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jbRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jbSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11))) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel4.setBackground(new java.awt.Color(0, 0, 0)); jbAdicionar.setBackground(new java.awt.Color(251, 245, 95)); jbAdicionar.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbAdicionar.setForeground(new java.awt.Color(251, 245, 95)); jbAdicionar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jbAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/plus.png"))); // NOI18N jbAdicionar.setText("ADICIONAR"); jbAdicionar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jbAdicionarMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jbAdicionarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbAdicionarMouseExited(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbAdicionar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbAdicionar, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jLabel17.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel17.setText("Código do vendedor"); jtfNomeUsuario.setEditable(false); jtfNomeUsuario.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtfNomeUsuario.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfNomeUsuarioFocusLost(evt); } }); jtfCodUsuario.setEditable(false); jtfCodUsuario.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfCodUsuarioFocusLost(evt); } }); jLabel18.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jLabel18.setText("Nome do vendedor"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jtfCodProduto)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jcbProduto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jtfCodCliente, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(407, 407, 407)) .addComponent(jcbCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtfCodVenda, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE) .addComponent(jtfQuantidade)) .addComponent(jLabel6)) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(521, 521, 521) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel13)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jtfDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtfValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel17) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel18) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jtfCodUsuario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtfNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 564, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfCodCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfCodVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfCodProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcbProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(jLabel18)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfCodUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(jLabel12)) .addGap(4, 4, 4) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtfValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(jLabel9)) .addGap(30, 30, 30) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); jtpPainel.addTab("Cadastro", jPanel1); jPanel2.setBackground(new java.awt.Color(251, 245, 95)); jLabel14.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N jLabel14.setText("Pesquisa"); jtfPesquisar.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtfPesquisar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jtfPesquisarKeyTyped(evt); } }); jtVendas.getTableHeader().setFont(new java.awt.Font("Consolas", 0, 14)); jtVendas.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtVendas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Cliente", "Data" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jtVendas.setSelectionBackground(new java.awt.Color(251, 245, 95)); jtVendas.setSelectionForeground(new java.awt.Color(0, 0, 0)); jScrollPane2.setViewportView(jtVendas); if (jtVendas.getColumnModel().getColumnCount() > 0) { jtVendas.getColumnModel().getColumn(0).setMinWidth(50); jtVendas.getColumnModel().getColumn(0).setPreferredWidth(50); jtVendas.getColumnModel().getColumn(0).setMaxWidth(50); jtVendas.getColumnModel().getColumn(2).setMinWidth(80); jtVendas.getColumnModel().getColumn(2).setPreferredWidth(80); jtVendas.getColumnModel().getColumn(2).setMaxWidth(80); } jLabel16.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N jLabel16.setText("Vendas"); jPanel5.setBackground(new java.awt.Color(0, 0, 0)); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(251, 245, 95)); jLabel15.setText("|"); jbExcluir.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbExcluir.setForeground(new java.awt.Color(251, 245, 95)); jbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/delete.png"))); // NOI18N jbExcluir.setText("EXCLUIR"); jbExcluir.setBorder(null); jbExcluir.setBorderPainted(false); jbExcluir.setContentAreaFilled(false); jbExcluir.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbExcluirMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbExcluirMouseExited(evt); } }); jbExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbExcluirActionPerformed(evt); } }); jbAlterar.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbAlterar.setForeground(new java.awt.Color(251, 245, 95)); jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/edit.png"))); // NOI18N jbAlterar.setText("ALTERAR"); jbAlterar.setBorder(null); jbAlterar.setBorderPainted(false); jbAlterar.setContentAreaFilled(false); jbAlterar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbAlterarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbAlterarMouseExited(evt); } }); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jbAlterar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel16) .addComponent(jLabel14)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jtfPesquisar) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE)) .addContainerGap()) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jLabel16) .addGap(11, 11, 11) .addComponent(jLabel14) .addGap(6, 6, 6) .addComponent(jtfPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jtpPainel.addTab("Lista de vendas", jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtpPainel) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtpPainel, javax.swing.GroupLayout.Alignment.TRAILING) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jtfCodClienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCodClienteFocusLost // Seta o cliente correspodente quando insere o código modelClientes = controllerClientes.getClienteController(Integer.parseInt(jtfCodCliente.getText())); jcbCliente.setSelectedItem(modelClientes.getClienteNome()); }//GEN-LAST:event_jtfCodClienteFocusLost private void jtfCodProdutoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCodProdutoFocusLost // Seta o produto correspondente quando perde o foco modelProdutos = controllerProdutos.getProdutoController(Integer.parseInt(jtfCodProduto.getText())); jcbProduto.setSelectedItem(modelProdutos.getProdNome()); }//GEN-LAST:event_jtfCodProdutoFocusLost private void jbAdicionarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAdicionarMouseClicked // Checa se quantidade é vazia if (jtfQuantidade.getText().equals("")) { JOptionPane.showMessageDialog(this, "Todos os campos devem ser preenchidos", "Erro", JOptionPane.ERROR_MESSAGE); } else { modelProdutos = controllerProdutos.getProdutoController(Integer.parseInt(jtfCodProduto.getText())); // Adicionar linha na tabela DefaultTableModel modelo = (DefaultTableModel) jtCarrinho.getModel(); int cont = 0; double quantidade = 0.0; quantidade = Double.parseDouble(jtfQuantidade.getText()); for (int i = 0; i < cont; i++) { modelo.setNumRows(0); } // Adicionar nas colunas modelo.addRow(new Object[]{ modelProdutos.getProdId(), modelProdutos.getProdNome(), jtfQuantidade.getText(), modelProdutos.getProdPreco(), quantidade * modelProdutos.getProdPreco() }); somarValorTotal(); } }//GEN-LAST:event_jbAdicionarMouseClicked private void jtfDescontoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfDescontoFocusLost // Checa se desconto é menor que 100 e chama a função que calcula o valor total sobre o desconto if(Integer.parseInt(jtfDesconto.getText()) > 100) { System.out.println(jtfDesconto.getText()); System.out.println(modelVendas.getVendaDesconto()); JOptionPane.showMessageDialog(this, "O desconto não pode ser maior que 100%", "Erro", JOptionPane.ERROR_MESSAGE); jtfDesconto.setText("0"); } else { somarValorTotal(); } }//GEN-LAST:event_jtfDescontoFocusLost private void jcbProdutoPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jcbProdutoPopupMenuWillBecomeInvisible // Iniciar código correspondente ao primeiro cliente if (jcbProduto.isPopupVisible()) { inicilizarCodigoProduto(); } }//GEN-LAST:event_jcbProdutoPopupMenuWillBecomeInvisible private void jcbClientePopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jcbClientePopupMenuWillBecomeInvisible // Iniciar código correspondente ao primeiro produto if (jcbCliente.isPopupVisible()) { inicializarCodigosCliente(); } }//GEN-LAST:event_jcbClientePopupMenuWillBecomeInvisible private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed int codigoVenda = 0; int codigoProduto = 0; // Cria uma nova lista listaModelVendasProdutos = new ArrayList<>(); // Seta o cliente no objeto com o valor do text field modelVendas.setCliente(Integer.parseInt(jtfCodCliente.getText())); // Transforma o padrão da data para o padrão americano try { modelVendas.setVendaData(datas.converterDataParaDateUS(new java.util.Date(System.currentTimeMillis()))); } catch (Exception ex) { } // Seta os valores da venda modelVendas.setVendaValorLiquido(Double.parseDouble(jtfValorTotal.getText())); modelVendas.setVendaValorBruto(Double.parseDouble(jtfValorTotal.getText()) + calcularDesconto()); modelVendas.setVendaDesconto(calcularDesconto()); // Seta o código da venda caso não seja vazio if (!jtfCodVenda.getText().equals("")) { modelVendas.setVendaId(Integer.parseInt(jtfCodVenda.getText())); } // Seta o código do cliente modelVendas.setCliente(Integer.parseInt(jtfCodCliente.getText())); // Seta o código do usuário (funcionário logado) modelVendas.setUsuario(Integer.parseInt(jtfCodUsuario.getText())); // Checa a variável de controle SalvarAlterar if (salvarAlterar.equals("salvar")) { // Salvar a venda no bd codigoVenda = controllerVendas.salvarVendasController(modelVendas); // Checa se salvou if (codigoVenda > 0) { int cont = jtCarrinho.getRowCount(); for (int i = 0; i < cont; i++) { codigoProduto = (int) jtCarrinho.getValueAt(i, 0); modelProdutos = new ModelProdutos(); // Seta no objeto Vendas-Produtos modelVendasProdutos = new ModelVendasProdutos(); modelVendasProdutos.setProduto(codigoProduto); modelVendasProdutos.setVenda(codigoVenda); modelVendasProdutos.setVenProValor((double) jtCarrinho.getValueAt(i, 3)); modelVendasProdutos.setVenProQtd(Integer.parseInt(jtCarrinho.getValueAt(i, 2).toString())); // Refatorar estoque modelProdutos.setProdId(codigoProduto); modelProdutos.setProdEstoque( controllerProdutos.getProdutoController(codigoProduto).getProdEstoque() - Integer.parseInt(jtCarrinho.getValueAt(i, 2).toString())); listaModelVendasProdutos.add(modelVendasProdutos); listaModelProdutos.add(modelProdutos); } // Salva os produtos a partir de uma lista if (modelProdutos.getProdEstoque() <= 0) { JOptionPane.showMessageDialog(this, "Não há estoque suficiente", "Erro", JOptionPane.ERROR_MESSAGE); } else { if (controllerVendasProdutos.salvarVendasProdutosController(listaModelVendasProdutos)) { // Alterar o estoque de produtos controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos); JOptionPane.showMessageDialog(this, "Venda registrada!", "Pronto", JOptionPane.WARNING_MESSAGE); carregarVendas(); limparCampos(); habilitarCampos(false); jbSalvar.setEnabled(false); } else { JOptionPane.showMessageDialog(this, "Não foi possível registrar a venda", "Erro", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(this, "Não foi possível salvar a venda", "Erro", JOptionPane.ERROR_MESSAGE); } } else { // BEGIN // Retorna para o estoque e exclui os produtos da venda (não exclui a venda) int linha = jtVendas.getSelectedRow(); codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutos = new ArrayList<>(); listaModelProdutosVendasProdutos = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosController(codigoVenda); for (int i = 0; i < listaModelProdutosVendasProdutos.size(); i++) { modelProdutos = new ModelProdutos(); modelProdutos.setProdId(listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdId()); // Adiciona ao estoque a quantidade do produto que voltou do cancelamento da venda modelProdutos.setProdEstoque(listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdEstoque() + listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProQtd()); listaModelProdutos.add(modelProdutos); } if (controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos)) { if (controllerVendasProdutos.excluirVendasProdutosController(codigoVenda)) { //JOptionPane.showMessageDialog(this, "Venda excluída com sucesso", "Pronto!", JOptionPane.WARNING_MESSAGE); carregarVendas(); } else { JOptionPane.showMessageDialog(this, "Não foi possível excluir a vendas", "Erro", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Não foi possível excluir a venda", "Erro", JOptionPane.ERROR_MESSAGE); } // END // Atualiza as vendas if(controllerVendas.atualizarVendasController(modelVendas)) { //JOptionPane.showMessageDialog(this, "Venda alterada com sucesso", "Pronto!", JOptionPane.WARNING_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Não foi possível alterar a venda", "Erro", JOptionPane.ERROR_MESSAGE); } // Retorna os produtos para o carrinho int cont = jtCarrinho.getRowCount(); for (int i = 0; i < cont; i++) { codigoProduto = (int) jtCarrinho.getValueAt(i, 0); modelProdutos = new ModelProdutos(); // A partir daqui os procedimentos são os mesmos para salvar // Seta no objeto Vendas-Produtos modelVendasProdutos = new ModelVendasProdutos(); modelVendasProdutos.setProduto(codigoProduto); modelVendasProdutos.setVenda(codigoVenda); modelVendasProdutos.setVenProValor((double) jtCarrinho.getValueAt(i, 3)); modelVendasProdutos.setVenProQtd(Integer.parseInt(jtCarrinho.getValueAt(i, 2).toString())); // Refatorar estoque modelProdutos.setProdId(codigoProduto); modelProdutos.setProdEstoque( controllerProdutos.getProdutoController(codigoProduto).getProdEstoque() - Integer.parseInt(jtCarrinho.getValueAt(i, 2).toString())); listaModelVendasProdutos.add(modelVendasProdutos); listaModelProdutos.add(modelProdutos); } // Salvar os produtos da venda if(controllerVendasProdutos.salvarVendasProdutosController(listaModelVendasProdutos)) { JOptionPane.showMessageDialog(this, "Venda alterada com sucesso!", "Pronto!", JOptionPane.WARNING_MESSAGE); carregarVendas(); limparCampos(); habilitarCampos(false); } else { JOptionPane.showMessageDialog(this, "Não foi possível registrar a venda", "Erro", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_jbSalvarActionPerformed private void jbRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRemoverActionPerformed // Remove um produto do carrinho int linha = jtCarrinho.getSelectedRow(); DefaultTableModel modelo = (DefaultTableModel) jtCarrinho.getModel(); modelo.removeRow(linha); somarValorTotal(); }//GEN-LAST:event_jbRemoverActionPerformed private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed // TODO add your handling code here: salvarAlterar = "salvar"; jbSalvar.setEnabled(true); jbSalvar.setForeground(new java.awt.Color(251, 245, 95)); limparCampos(); setaUsuario(); habilitarCampos(true); }//GEN-LAST:event_jbNovoActionPerformed private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed // Exclui uma venda int linha = jtVendas.getSelectedRow(); int codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutos = new ArrayList<>(); listaModelProdutosVendasProdutos = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosController(codigoVenda); for (int i = 0; i < listaModelProdutosVendasProdutos.size(); i++) { modelProdutos = new ModelProdutos(); modelProdutos.setProdId(listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdId()); // Adiciona ao estoque a quantidade do produto que voltou do cancelamento da venda modelProdutos.setProdEstoque(listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdEstoque() + listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProQtd()); listaModelProdutos.add(modelProdutos); } if (controllerProdutos.alterarEstoqueProdutoController(listaModelProdutos)) { controllerVendasProdutos.excluirVendasProdutosController(codigoVenda); if (controllerVendas.excluirVendasController(codigoVenda)) { JOptionPane.showMessageDialog(this, "Venda excluída com sucesso", "Pronto!", JOptionPane.WARNING_MESSAGE); carregarVendas(); } else { JOptionPane.showMessageDialog(this, "Não foi possível excluir a vendas", "Erro", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Não foi possível excluir a vendas", "Erro", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jbExcluirActionPerformed private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed salvarAlterar = "alterar"; // Seta o usuário logado no formulário setaUsuario(); // Habilita o botão Salvar jbSalvar.setEnabled(true); jbSalvar.setForeground(new java.awt.Color(251, 245, 95)); habilitarCampos(true); System.out.println(jtVendas.getSelectedRow()); if(jtVendas.getSelectedRow() < 0) { JOptionPane.showMessageDialog(this, "Nenhuma linha selecionada", "Erro", JOptionPane.ERROR_MESSAGE); } else { int linha = jtVendas.getSelectedRow(); int codigoVenda = (int) jtVendas.getValueAt(linha, 0); listaModelProdutosVendasProdutos = controllerProdutosVendasProdutos.getListaProdutosVendasProdutosController(codigoVenda); DefaultTableModel modelo = (DefaultTableModel) jtCarrinho.getModel(); modelo.setNumRows(0); for (int i = 0; i < listaModelProdutosVendasProdutos.size(); i++) { jtfCodVenda.setText(String.valueOf(listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenda())); modelo.addRow(new Object[]{ listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdId(), listaModelProdutosVendasProdutos.get(i).getModelProdutos().getProdNome(), listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProQtd(), listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProValor(), listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProQtd() * listaModelProdutosVendasProdutos.get(i).getModelVendasProdutos().getVenProValor() }); } jtpPainel.setSelectedIndex(0); somarValorTotal(); } }//GEN-LAST:event_jbAlterarActionPerformed private void jbAdicionarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAdicionarMouseEntered jbAdicionar.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbAdicionarMouseEntered private void jbAdicionarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAdicionarMouseExited jbAdicionar.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbAdicionarMouseExited private void jbSalvarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbSalvarMouseEntered jbSalvar.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbSalvarMouseEntered private void jbSalvarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbSalvarMouseExited jbSalvar.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbSalvarMouseExited private void jbCancelarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbCancelarMouseEntered jbCancelar.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbCancelarMouseEntered private void jbCancelarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbCancelarMouseExited jbCancelar.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbCancelarMouseExited private void jbNovoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbNovoMouseEntered jbNovo.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbNovoMouseEntered private void jbNovoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbNovoMouseExited jbNovo.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbNovoMouseExited private void jPanel3MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jPanel3MouseEntered private void jbRemoverMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbRemoverMouseEntered jbRemover.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbRemoverMouseEntered private void jbRemoverMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbRemoverMouseExited jbRemover.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbRemoverMouseExited private void jbExcluirMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbExcluirMouseEntered jbExcluir.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbExcluirMouseEntered private void jbExcluirMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbExcluirMouseExited jbExcluir.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbExcluirMouseExited private void jbAlterarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAlterarMouseEntered jbAlterar.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbAlterarMouseEntered private void jbAlterarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAlterarMouseExited jbAlterar.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbAlterarMouseExited private void jtfPesquisarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPesquisarKeyTyped DefaultTableModel modelo = (DefaultTableModel) this.jtVendas.getModel(); final TableRowSorter<TableModel> classificador = new TableRowSorter<>(modelo); this.jtVendas.setRowSorter(classificador); String texto = jtfPesquisar.getText().toUpperCase();; classificador.setRowFilter(RowFilter.regexFilter(texto, 1)); }//GEN-LAST:event_jtfPesquisarKeyTyped private void jtfNomeUsuarioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNomeUsuarioFocusLost // TODO add your handling code here: }//GEN-LAST:event_jtfNomeUsuarioFocusLost private void jtfCodUsuarioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCodUsuarioFocusLost // TODO add your handling code here: }//GEN-LAST:event_jtfCodUsuarioFocusLost private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed limparCampos(); habilitarCampos(false); jbSalvar.setEnabled(false); jbSalvar.setForeground(Color.GRAY); }//GEN-LAST:event_jbCancelarActionPerformed private void jtfDescontoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescontoKeyTyped try {} catch(Exception e) {} }//GEN-LAST:event_jtfDescontoKeyTyped /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewVenda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewVenda().setVisible(true); } }); } /** * Lista todos os clientes no combobox */ private void listarClientes() { listaModelClientes = controllerClientes.getListaClientesController(); jcbCliente.removeAllItems(); for (int i = 0; i < listaModelClientes.size(); i++) { jcbCliente.addItem(listaModelClientes.get(i).getClienteNome()); } } /** * Lista todos os produtos no combobox */ private void listarProdutos() { listaModelProdutos = controllerProdutos.getListaProdutosController(); jcbProduto.removeAllItems(); for (int i = 0; i < listaModelProdutos.size(); i++) { jcbProduto.addItem(listaModelProdutos.get(i).getProdNome()); } } /** * Carrega vendas na tabela */ private void carregarVendas() { DefaultTableModel modelo = (DefaultTableModel) jtVendas.getModel(); listaModelVendasClientes = controllerVendasClientes.getListaVendasClienteController(); int cont = listaModelVendasClientes.size(); modelo.setNumRows(0); for (int i = 0; i < cont; i++) { modelo.addRow(new Object[]{ listaModelVendasClientes.get(i).getModelVendas().getVendaId(), listaModelVendasClientes.get(i).getModelClientes().getClienteNome(), listaModelVendasClientes.get(i).getModelVendas().getVendaData() }); } } /** * Soma os valores totais de cada produto e mostra o valor total da venda */ private void somarValorTotal() { double valor; double soma = 0; // Contador recebe a quantidade de linhas int contador = jtCarrinho.getRowCount(); for (int i = 0; i < contador; i++) { valor = (double) jtCarrinho.getValueAt(i, 4); soma = soma + valor; } System.out.println(soma); jtfValorTotal.setText(String.valueOf(soma)); aplicarDesconto(); } /** * Faz o calculo do valor total com o desconto */ private void aplicarDesconto() { jtfValorTotal.setText( String.valueOf(Double.parseDouble(jtfValorTotal.getText()) - calcularDesconto())); } /** * Calcula o desconto * @return */ private double calcularDesconto() { return (Double.parseDouble(jtfDesconto.getText()) / 100) * Double.parseDouble(jtfValorTotal.getText()); } /** * Inicializa código do cliente da combo box */ private void inicializarCodigosCliente() { modelClientes = controllerClientes.getClienteController(jcbCliente.getSelectedItem().toString()); jtfCodCliente.setText(String.valueOf(modelClientes.getClienteId())); } /** * Inicializa código do produto da combo box */ private void inicilizarCodigoProduto() { modelProdutos = controllerProdutos.getProdutoController(jcbProduto.getSelectedItem().toString()); jtfCodProduto.setText(String.valueOf(modelProdutos.getProdId())); } /** * Limpa os campos */ private void limparCampos() { jtfQuantidade.setText(""); jtfQuantidade.setText("0"); jtfValorTotal.setText("0"); DefaultTableModel modelo = (DefaultTableModel) jtCarrinho.getModel(); modelo.setNumRows(0); } /** * Seta os dados do usuário logado no formulário */ private void setaUsuario() { jtfNomeUsuario.setText(nomeUsuario); jtfCodUsuario.setText(String.valueOf(IdUsuario)); } /** * Habilita ou desabilta os campos * @param condicao */ private void habilitarCampos(boolean condicao) { jtfCodCliente.setEnabled(condicao); jtfCodProduto.setEnabled(condicao); jtfCodVenda.setEnabled(condicao); jtfDesconto.setEnabled(condicao); jtfNomeUsuario.setEnabled(condicao); jtfQuantidade.setEnabled(condicao); jtfValorTotal.setEnabled(condicao); jcbCliente.setEnabled(condicao); jcbProduto.setEnabled(condicao); jtfCodUsuario.setEnabled(condicao); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel jbAdicionar; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbCancelar; private javax.swing.JButton jbExcluir; private javax.swing.JButton jbNovo; private javax.swing.JButton jbRemover; private javax.swing.JButton jbSalvar; private componentes.UJComboBox jcbCliente; private componentes.UJComboBox jcbProduto; private javax.swing.JTable jtCarrinho; private javax.swing.JTable jtVendas; private javax.swing.JTextField jtfCodCliente; private javax.swing.JTextField jtfCodProduto; private javax.swing.JTextField jtfCodUsuario; private javax.swing.JTextField jtfCodVenda; private javax.swing.JTextField jtfDesconto; private javax.swing.JTextField jtfNomeUsuario; private javax.swing.JTextField jtfPesquisar; private javax.swing.JTextField jtfQuantidade; private javax.swing.JTextField jtfValorTotal; private javax.swing.JTabbedPane jtpPainel; // End of variables declaration//GEN-END:variables }
package mysql; import java.sql.*; import java.io.*; public class program { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/email","root","root"); System.out.print("Connected"); String q="insert into contacts(attachment) values(?) "; PreparedStatement pstmt = con.prepareStatement(q); FileInputStream fis = new FileInputStream("new.jpg"); pstmt.setBinaryStream(1, fis,fis.available()); pstmt.executeUpdate(); con.close(); }catch(Exception e) { System.out.println("Error"); } } }
package com.gsccs.sme.plat.auth.service; import java.util.List; import com.gsccs.sme.plat.auth.model.MsgT; /** * * @author x.d zhang * */ public interface MsgService { public void createMsg(MsgT param); public void updateMsg(MsgT param); public void deleteMsg(String appId); public MsgT findById(String appId); public List<MsgT> find(MsgT param, String order, int currPage, int pageSize); public Integer count(MsgT param); }
package com.cakemake.dao; import com.cakemake.model.Orders; import org.springframework.data.repository.CrudRepository; public interface OrdersRepository extends CrudRepository<Orders,Long> { }
package com.uit.huydaoduc.hieu.chi.hhapp.Main.Driver.v2; import android.net.Uri; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.uit.huydaoduc.hieu.chi.hhapp.Main.Driver.v2.RouteRequestManagerFragment; import com.uit.huydaoduc.hieu.chi.hhapp.R; import com.ogaclejapan.smarttablayout.SmartTabLayout; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems; import cn.bingoogolapple.titlebar.BGATitleBar; public class DriverActivity extends AppCompatActivity implements RouteRequestManagerFragment.OnRouteRequestManagerFragmentListener{ BGATitleBar titleBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_driver); FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter( getSupportFragmentManager(), FragmentPagerItems.with(this) .add("Your routes", RouteRequestManagerFragment.class) .create()); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(adapter); SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab); viewPagerTab.setViewPager(viewPager); Init(); Event(); } private void Init() { titleBar = (BGATitleBar) findViewById(R.id.titlebar); } private void Event() { titleBar.setDelegate(new BGATitleBar.Delegate() { @Override public void onClickLeftCtv() { } @Override public void onClickTitleCtv() { } @Override public void onClickRightCtv() { } @Override public void onClickRightSecondaryCtv() { } }); } @Override public void onFragmentInteraction(Uri uri) { } }
package com.worldtech.appupdateversion; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.widget.Toast; import com.tbruyelle.rxpermissions2.RxPermissions; import com.worldtech.appupdateversion.utils.CommonUtil; import com.worldtech.appupdateversion.utils.FileUtils; import com.worldtech.appupdateversion.utils.InstallUtils; import com.worldtech.appupdateversion.utils.NetWorkUtils; import java.math.BigDecimal; public class MainActivity extends AppCompatActivity { private RxPermissions rxPermissions; private String updateApkUrl; private boolean isInDownload = false; private UpdateDialog updateDialog; private String apkDownloadPath = null; private InstallUtils.DownloadCallBack downloadCallBack; private boolean isExsit; private boolean isMustUpdate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rxPermissions = new RxPermissions(this); initCallback(); updateApkUrl = "http://www.zhuoyou.com/upload/YouKaPlatForm-youka-Android.apk"; String versionName = "2.0.0"; String message = "I'm message"; long fileSize = 20; FileUtils.deleteDownOldFile(this, versionName); String apkDownloadPath = FileUtils.getApkDownloadPath(this, versionName); isExsit = FileUtils.isUpdateFileExist(apkDownloadPath, fileSize); // fileSize单位为b isMustUpdate = true; final int internalSetup = 1; //是否为内部更新 // 上面的参数,可依赖于服务器的接口具体返回 String positiveText = isExsit?getString(R.string.click_install):getString(R.string.dialog_notify_positive); UpdateDialog updateDialog = new UpdateDialog(this, getString(R.string.have_new_version) , getString(R.string.version_coode_number) + versionName , message, positiveText, getString(R.string.dialog_notify_negative), !isMustUpdate); updateDialog.setListener(new UpdateDialog.OnNormalDialogClickListener() { @SuppressLint("CheckResult") @Override public void onPositive(String desc) { if(internalSetup == 1){ if(!isExsit){ rxPermissions .request(Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(granted -> { if (granted) { // LogUtil.d("ttt","onPositive downloadApk updateApkUrl = "); downloadApk(); }else{ // CustomToast.showToast("您需要开启存储权限"); } }); }else { installApk(); } }else { // CommonUtil.openBrowser(SplashActivity.this, updateApkUrl); } } @Override public void onNegative() { negativeUpdateDialog(); } }); updateDialog.show(); } private void initCallback() { downloadCallBack = new InstallUtils.DownloadCallBack() { @Override public void onStart() { // LogUtil.d("ttt","InstallUtils onStart"); if(updateDialog != null){ updateDialog.setProgressCount("0"); updateDialog.setPositiveButtonDownloading(); isInDownload = true; } } @Override public void onComplete(String path) { // LogUtil.d("ttt","InstallUtils onComplete"); apkDownloadPath = path; updateDialog.setProgressCount("100"); updateDialog.setPositiveButtonDownloadingFinish(); isExsit = true; installApk(); isInDownload = false; } @Override public void onLoading(long total, long current) { int progress = (int)(div(current,total,2)*100); // LogUtil.d("ttt","InstallUtils onLoading current = " + current + ",total = " + total + ",progress = " + progress); updateDialog.setProgressCount(String.valueOf(progress)); } @Override public void onFail(Exception e) { isExsit = false; // LogUtil.d("ttt","InstallUtils onFail e" + e.getMessage()); Toast.makeText(MainActivity.this, R.string.download_fail, Toast.LENGTH_SHORT).show(); updateDialog.setPositiveButtonDownload(); FileUtils.deleteFile(apkDownloadPath); updateDialog.setProgressCount("0"); isInDownload = false; } @Override public void cancle() { isExsit = false; // LogUtil.d("ttt","InstallUtils cancle"); FileUtils.deleteFile(apkDownloadPath); updateDialog.setProgressCount("0"); isInDownload = false; } }; } private synchronized void downloadApk() { if(!TextUtils.isEmpty(updateApkUrl)){ // LogUtil.d("ttt","downloadApk updateApkUrl = " + updateApkUrl); if(NetWorkUtils.isNetworkConnected(this)){ if(!isInDownload){ isInDownload = true; updateDialog.setPositiveButtonDownloading(); InstallUtils.with(this) //必须-下载地址 .setApkUrl(updateApkUrl) //非必须-下载保存的文件的完整路径+name.apk .setApkPath(apkDownloadPath) //非必须-下载回调 .setCallBack(downloadCallBack) //开始下载 .startDownload(); } }else { isInDownload = false; // CustomToast.showToast(R.string.net_error); } } } private void installApk() { //先判断有没有安装权限 InstallUtils.checkInstallPermission(this, new InstallUtils.InstallPermissionCallBack() { @Override public void onGranted() { //去安装APK installApkFromPath(apkDownloadPath); } @Override public void onDenied() { //弹出弹框提醒用户 AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this) .setTitle("温馨提示") .setMessage("必须授权才能安装APK,请设置允许安装") .setNegativeButton("取消", null) .setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //打开设置页面 InstallUtils.openInstallPermissionSetting(MainActivity.this, new InstallUtils.InstallPermissionCallBack() { @Override public void onGranted() { //去安装APK installApkFromPath(apkDownloadPath); } @Override public void onDenied() { // LogSaveUtils.addLog("10006","未授权安装apk"); updateDialog.dismiss(); // if(isMustUpdate){ // ActivityQueueManager.getInstance().finishAllActivity(); // }else { // startMainActivity(); // } } }); } }) .create(); alertDialog.show(); } }); } public static float div(long v1, long v2, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Long.toString(v1)); BigDecimal b2 = new BigDecimal(Long.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue(); } private void installApkFromPath(String path) { InstallUtils.installAPK(this, path, new InstallUtils.InstallCallBack() { @Override public void onSuccess() { //onSuccess:表示系统的安装界面被打开 //防止用户取消安装,在这里可以关闭当前应用,以免出现安装被取消 // ActivityQueueManager.getInstance().finishAllActivity(); finish(); Toast.makeText(MainActivity.this, R.string.installing_apk, Toast.LENGTH_SHORT).show(); } @Override public void onFail(Exception e) { // LogSaveUtils.addLog("10006","安装失败"); // LogUtil.d("ttt","installApk onFail e = " + e.getMessage()); Toast.makeText(MainActivity.this, R.string.install_failed, Toast.LENGTH_SHORT).show(); CommonUtil.openBrowser(MainActivity.this, updateApkUrl); } }); } private void negativeUpdateDialog() { updateDialog.dismiss(); InstallUtils.cancleDownload(); FileUtils.deleteFile(apkDownloadPath); //根据自己的逻辑,强更:退出应用;非强更:跳主页面 // if(isMustUpdate){ // ActivityQueueManager.getInstance().finishAllActivity(); // }else { // startMainActivity(); // } } }
package com.ramirez.tarealabo7.Activitys; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.ramirez.tarealabo7.Activitys.ModificarActivity; import com.ramirez.tarealabo7.R; public class NotasActivity extends AppCompatActivity { Button buscar, modificar, eliminar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notas); buscar = findViewById(R.id.BuscarB); modificar = findViewById(R.id.modificarB); eliminar = findViewById(R.id.eliminarB); modificar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), ModificarActivity.class); startActivity(intent); } }); } }
package com.design.creational.singleton; import java.io.Serializable; public class SerializedSingleton implements Serializable { /** * */ private static final long serialVersionUID = -7601485207540493334L; protected Object readResolve() { return getInstance(); } private SerializedSingleton() { } private static class Helper { private static final SerializedSingleton instance = new SerializedSingleton(); } public SerializedSingleton getInstance() { return Helper.instance; } }
package com.zjf.myself.codebase.activity.ExerciseLibrary; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.util.CheckPermissionsActivity; import com.zjf.myself.codebase.util.LocUtils; /** * Created by Administrator on 2017/3/6. */ public class LocWordAct extends CheckPermissionsActivity implements View.OnClickListener{ private TextView tvResult; private TextView btLocation; private AMapLocationClient locationClient = null; private AMapLocationClientOption locationOption = new AMapLocationClientOption(); private TextView btnLoc,txtLoc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.win_word_loc); initView(); //初始化定位 initLocation(); } //初始化控件 private void initView(){ tvResult = (TextView) findViewById(R.id.txtLoc); btLocation = (TextView) findViewById(R.id.btnLoc); btLocation.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btnLoc) { if (btLocation.getText().equals(getResources().getString(R.string.startLocation))) { btLocation.setText(getResources().getString(R.string.stopLocation)); tvResult.setText("正在定位..."); startLocation(); } else { btLocation.setText(getResources().getString(R.string.startLocation)); stopLocation(); tvResult.setText("定位停止"); } } } private void initLocation(){ //初始化client locationClient = new AMapLocationClient(this.getApplicationContext()); //设置定位参数 locationClient.setLocationOption(getDefaultOption()); // 设置定位监听 locationClient.setLocationListener(locationListener); } /** * 默认的定位参数 * @since 2.8.0 * @author hongming.wang * */ private AMapLocationClientOption getDefaultOption(){ AMapLocationClientOption mOption = new AMapLocationClientOption(); mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式 mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭 mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效 mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒 mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true mOption.setOnceLocation(true);//可选,设置是否单次定位。默认是false mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用 AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差 mOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true return mOption; } /** * 定位监听 */ AMapLocationListener locationListener = new AMapLocationListener() { @Override public void onLocationChanged(AMapLocation loc) { if (null != loc) { //解析定位结果 String result = LocUtils.getLocationStr(loc); tvResult.setText(result); } else { tvResult.setText("定位失败,loc is null"); } } }; // 根据控件的选择,重新设置定位参数 private void resetOption() { // 设置是否需要显示地址信息 locationOption.setNeedAddress(true); /** * 设置是否优先返回GPS定位结果,如果30秒内GPS没有返回定位结果则进行网络定位 * 注意:只有在高精度模式下的单次定位有效,其他方式无效 */ locationOption.setGpsFirst(false); // 设置是否开启缓存 locationOption.setLocationCacheEnable(true); // 设置是否单次定位 locationOption.setOnceLocation(true); //设置是否等待设备wifi刷新,如果设置为true,会自动变为单次定位,持续定位时不要使用 locationOption.setOnceLocationLatest(true); //设置是否使用传感器 locationOption.setSensorEnable(true); //设置是否开启wifi扫描,如果设置为false时同时会停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差 String strInterval = "2000"; if (!TextUtils.isEmpty(strInterval)) { try{ // 设置发送定位请求的时间间隔,最小值为1000,如果小于1000,按照1000算 locationOption.setInterval(Long.valueOf(strInterval)); }catch(Throwable e){ e.printStackTrace(); } } String strTimeout = "50000"; if(!TextUtils.isEmpty(strTimeout)){ try{ // 设置网络请求超时时间 locationOption.setHttpTimeOut(Long.valueOf(strTimeout)); }catch(Throwable e){ e.printStackTrace(); } } } /** * 开始定位 * * @since 2.8.0 * @author hongming.wang * */ private void startLocation(){ //根据控件的选择,重新设置定位参数 resetOption(); // 设置定位参数 locationClient.setLocationOption(locationOption); // 启动定位 locationClient.startLocation(); } /** * 停止定位 * * @since 2.8.0 * @author hongming.wang * */ private void stopLocation(){ // 停止定位 locationClient.stopLocation(); } /** * 销毁定位 * * @since 2.8.0 * @author hongming.wang * */ @Override protected void onDestroy(){ super.onDestroy(); destroyLocation(); } private void destroyLocation(){ if (null != locationClient) { /** * 如果AMapLocationClient是在当前Activity实例化的, * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy */ locationClient.onDestroy(); locationClient = null; locationOption = null; } } }
package com.company; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Map<String, List>mapPersona = new HashMap<>(); } } class Persona { private Long id; private String dni; private String nombre; private Integer edad; public Persona(Long id, String dni, String nombre, Integer edad) { this.id = id; this.dni = dni; this.nombre = nombre; this.edad = edad; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDni(String dni) { return dni; } public void setDni(String dni) { this.dni = dni; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setEdad(Integer edad) { this.edad = edad; } public Integer getEdad() { return edad; } @Override public String toString() { return "id " + id + " dni " + dni + " nombre " + nombre + " edad " + edad + ""; } }
package com.esum.wp.ims.sftpinfo.struts.action; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.esum.appcommon.resource.application.Config; import com.esum.appcommon.session.SessionMgr; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.struts.action.BaseDelegateAction; import com.esum.appframework.struts.actionform.BeanUtilForm; import com.esum.framework.core.management.ManagementException; import com.esum.imsutil.util.ReloadXTrusAdmin; import com.esum.wp.ims.config.XtrusConfig; import com.esum.wp.ims.sftpinfo.SftpInfo; import com.esum.wp.ims.sftpinfo.service.ISftpInfoService; import com.esum.wp.ims.tld.XtrusLangTag; /** * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class SftpInfoAction extends BaseDelegateAction { protected ActionForward doService( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (method.equals("other method")) { /** */ return null; } else if (method.equals("selectPageList")) { SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } int itemCountPerPage = Config.getInt("Common", "LIST.COUNT_PER_PAGE"); if(inputObject == null) { sftpInfo = new SftpInfo(); sftpInfo.setCurrentPage(new Integer(1)); sftpInfo.setItemCountPerPage(new Integer(itemCountPerPage)); }else { sftpInfo = (SftpInfo)inputObject; if(sftpInfo.getCurrentPage() == null) { sftpInfo.setCurrentPage(new Integer(1)); } if(sftpInfo.getItemCountPerPage() == null) { sftpInfo.setItemCountPerPage(new Integer(itemCountPerPage)); } } // db SessionMgr sessMgr = new SessionMgr(request); sftpInfo.setDbType(sessMgr.getValue("dbType")); //search if(sftpInfo.getInterfaceId() != null){ if(sftpInfo.getInterfaceId().equals("null")){ sftpInfo.setInterfaceId(""); } }else if(sftpInfo.getInterfaceId() == null){ sftpInfo.setInterfaceId(""); } sftpInfo.setInterfaceId(sftpInfo.getInterfaceId() + "%"); if(sftpInfo.getNodeId() == null || sftpInfo.getNodeId().equals("null")) { sftpInfo.setNodeId(""); } sftpInfo.setNodeId(sftpInfo.getNodeId() + "%"); beanUtilForm.setBean(sftpInfo); request.setAttribute("inputObject", sftpInfo); return super.doService(mapping, beanUtilForm, request, response); } else if (method.equals("sftpInfoDetail")) { SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { sftpInfo = new SftpInfo(); }else { sftpInfo = (SftpInfo)inputObject; } beanUtilForm.setBean(sftpInfo); request.setAttribute("inputObject", sftpInfo); return super.doService(mapping, beanUtilForm, request, response); } else if (method.equals("delete")) { SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm) form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); } else { beanUtilForm = new BeanUtilForm(); } if (inputObject == null) { sftpInfo = new SftpInfo(); } else { sftpInfo = (SftpInfo) inputObject; } beanUtilForm.setBean(sftpInfo); request.setAttribute("inputObject", sftpInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[2]; ids[0] = XtrusConfig.SFTP_INFO_TABLE_ID; ids[1] = sftpInfo.getInterfaceId(); String configId = XtrusConfig.SFTP_COMPONENT_ID; ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance(); reload.reloadComponent(ids, configId); }catch (ManagementException me) { String errorMsg =XtrusLangTag.getMessage("error.management.exception"); ApplicationException are = new ApplicationException(me); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } catch (RuntimeException re) { String errorMsg = XtrusLangTag.getMessage("error.runtime.exception"); ApplicationException are = new ApplicationException(re); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); }catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if (method.equals("update")) { SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm) form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); } else { beanUtilForm = new BeanUtilForm(); } if (inputObject == null) { sftpInfo = new SftpInfo(); } else { sftpInfo = (SftpInfo) inputObject; } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); sftpInfo.setModDate(sdf.format(new Date())); beanUtilForm.setBean(sftpInfo); request.setAttribute("inputObject", sftpInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[2]; ids[0] = XtrusConfig.SFTP_INFO_TABLE_ID; ids[1] = sftpInfo.getInterfaceId(); String configId = XtrusConfig.SFTP_COMPONENT_ID; ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance(); reload.reloadComponent(ids, configId); }catch (ManagementException me) { String errorMsg = XtrusLangTag.getMessage("error.management.exception"); ApplicationException are = new ApplicationException(me); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } catch (RuntimeException re) { String errorMsg = XtrusLangTag.getMessage("error.runtime.exception"); ApplicationException are = new ApplicationException(re); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); }catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if (method.equals("insert")) { SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm) form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); } else { beanUtilForm = new BeanUtilForm(); } if (inputObject == null) { sftpInfo = new SftpInfo(); } else { sftpInfo = (SftpInfo) inputObject; } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); sftpInfo.setRegDate(sdf.format(new Date())); sftpInfo.setModDate(sdf.format(new Date())); beanUtilForm.setBean(sftpInfo); request.setAttribute("inputObject", sftpInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[2]; ids[0] = XtrusConfig.SFTP_INFO_TABLE_ID; ids[1] = sftpInfo.getInterfaceId(); String configId = XtrusConfig.SFTP_COMPONENT_ID; ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance(); reload.reloadComponent(ids, configId); }catch (ManagementException me) { String errorMsg = XtrusLangTag.getMessage("error.management.exception"); ApplicationException are = new ApplicationException(me); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } catch (RuntimeException re) { String errorMsg = XtrusLangTag.getMessage("error.runtime.exception"); ApplicationException are = new ApplicationException(re); ApplicationException ae = new ApplicationException(errorMsg); are.printException(""); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); }catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if(method.equals("saveSftpInfoExcel")){ SftpInfo sftpInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm) form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { sftpInfo = new SftpInfo(); } else { sftpInfo = (SftpInfo)inputObject; } SessionMgr sessMgr = new SessionMgr(request); sftpInfo.setDbType(sessMgr.getValue("dbType")); sftpInfo.setLangType(sessMgr.getValue("langType")); sftpInfo.setRootPath(getServlet().getServletContext().getRealPath("/")); ISftpInfoService service = (ISftpInfoService)iBaseService; service.saveSftpInfoExcel(sftpInfo, request, response); return null; } else { return super.doService(mapping, form, request, response); } } }
package com.nt.service; import com.nt.bo.UserDetails; import com.nt.dao.AuthenticateDAO; public class Authentication_manager { private ThreadLocal<UserDetails> th = new ThreadLocal<UserDetails>(); private AuthenticateDAO adao; public void setAdao(AuthenticateDAO adao) { this.adao = adao; } public void SignIn(String user, String pass) { UserDetails ud = null; ud = new UserDetails(); ud.setUname(user); ud.setPassword(pass); th.set(ud); } public void SignOut() { th.remove(); System.out.println("sign out......"); } public boolean isValidate() { int count; UserDetails ud = null; ud = th.get(); if (ud != null) { count = adao.Authenticate(ud); if (count == 0) return false; else return true; } return false; } }
package com.esum.framework.core.component.listener; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.core.component.channel.MessageChannel; import com.esum.framework.core.event.log.LoggingEvent; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.exception.SystemException; /** * Legacy Listener. */ public abstract class LegacyListener extends AbstractListener { private static final long serialVersionUID = 1L; private Logger log = LoggerFactory.getLogger(LegacyListener.class); private MessageChannel messageChannel; public void startup() throws SystemException { if (!isRunning()) { log.debug(traceId + "Starting Legacy Listener..."); if(messageChannel==null) messageChannel = new MessageChannel(getTraceId()); startupLegacy(); setRunning(true); log.info(traceId + "Started Legacy Listener."); } } public void shutdown() throws SystemException { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { public Void call() throws IOException { try { shutdownLegacy(); } catch (SystemException e) { log.warn(traceId+"Listener shutdown failed.", e); } return null; } }); try { future.get(5000, TimeUnit.MILLISECONDS); } catch (Exception e) { log.warn(traceId+"Listener shutdown failed.", e); } finally { if(executor!=null) executor.shutdown(); } setRunning(false); log.info(traceId + "Shutdowned Legacy Listener."); } public void sendLoggingEvent(LoggingEvent loggingEvent) throws SystemException { messageChannel.sendLoggingEvent(loggingEvent); } public MessageEvent sendNextComponent(String nextComponentId, String messageCtrlId, MessageEvent event, int priority) throws SystemException { return messageChannel.sendNextComponent(nextComponentId, messageCtrlId, event, priority); } /** * 주어진 MessageEvent를 특정 toChannel로 전송한다. * * @param toChannel 전송할 Channel * @param event 전송할 Event 객체 * @param priority 우선순위 * @throws SystemException */ public void sendToComponent(String toChannel, MessageEvent event, int priority) throws SystemException { messageChannel.sendToComponent(toChannel, event, priority); } /** * Start a legacy. */ protected abstract void startupLegacy() throws SystemException; /** * Shutdown a legacy. */ protected abstract void shutdownLegacy() throws SystemException; }
package net.gdsspt.app.ui.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import net.gdsspt.app.R; import net.gdsspt.app.SongShanApp; /** * Created by LittleHans on 2016/8/2. */ public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); } @Override protected void onStart() { super.onStart(); SongShanApp.getInstance().getHandler().postDelayed(new Runnable() { @Override public void run() { // TODO } }, 1000); } }
package org.mytvstream.converter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConverterFactory { /** * Logger definition */ private static final Logger logger = LoggerFactory.getLogger(ConverterFactory.class); /** * Singleton definition */ private ConverterFactory(){} private static ConverterFactory INSTANCE = new ConverterFactory(); public static ConverterFactory getInstance() { return INSTANCE; } // registering converters static HashMap<String, Class<?>>registeredConverter = new HashMap<String, Class<?>>(); static { registeredConverter.put("XugglerConverter", XugglerConverter.class); } /** * Factory method * @param inputUrl * @param inputFormat * @param outputUrl * @param outputFormat * @return * @throws ConverterException */ public Converter getConverter( String inputUrl, ConverterFormatEnum inputFormat, String outputUrl, ConverterFormatEnum outputFormat ) throws ConverterException { logger.debug("getting converter for " + inputUrl); Converter converter = null; Iterator<Entry<String, Class<?>>> it = registeredConverter.entrySet().iterator(); while (it.hasNext()) { Entry<String, Class<?>> pairs = it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); Class<?> converterClass = (Class<?>) pairs.getValue(); try { converter = (Converter)converterClass.newInstance(); if (converter.CanHandle(inputUrl, inputFormat, outputUrl, outputFormat)) { //converter.openMedia(inputUrl, inputFormat); //converter.openOutput(outputUrl, outputFormat); return converter; } } catch (InstantiationException e) { // TODO Auto-generated catch block throw new ConverterException("Error getting converter : " + e.getMessage()); } catch (IllegalAccessException e) { // TODO Auto-generated catch block throw new ConverterException("Error getting converter: " + e.getMessage()); } } throw new ConverterException("Can't find suitable converter"); } }