blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
204d29fd84acb2f1c57f52acf44f73f2d15cdf3d
Java
kmille/android-pwning
/apks/aldi/src/dagger/android/ContentProviderKey.java
UTF-8
587
1.609375
2
[]
no_license
package dagger.android; import android.content.ContentProvider; import dagger.MapKey; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.Target; @MapKey @Documented @Target({java.lang.annotation.ElementType.METHOD}) public @interface ContentProviderKey { Class<? extends ContentProvider> value(); } /* Location: /home/kmille/projects/android-pwning/apks/aldi/ALDI TALK_v6.2.1_apkpure.com-dex2jar.jar!/dagger/android/ContentProviderKey.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
f07908bdb3d71c8dd6ae56c15325758709afe6d2
Java
PerlaGCastillo/C2-Java-Testing
/Sesion-08/Reto-02/reto02/src/main/java/org/bedu/testing/demo/monitoreo/tools/SecurityContextHolderWrapper.java
UTF-8
758
2.078125
2
[]
no_license
package org.bedu.testing.demo.monitoreo.tools; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor(onConstructor_ = { @Autowired }) public class SecurityContextHolderWrapper { public String getAuthority() { SecurityContext context = SecurityContextHolder.getContext(); return context.getAuthentication().getAuthorities().iterator().next().getAuthority(); } public String getUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); } }
true
b30a7ed1c1bc28703c21876b5d25c81f1a751015
Java
yunzhaoGitHub/rmi-implements
/src/main/java/com/yunzhao/demo/client/TcpTransport.java
UTF-8
1,821
3.140625
3
[]
no_license
package com.yunzhao.demo.client; import java.io.*; import java.net.Socket; public class TcpTransport { private int port; private String host; public TcpTransport(int port, String host) { this.port = port; this.host = host; } public Object send(RpcRequest rpcRequest) { // 创建一个socket Socket clientSocket = null; // 写对象 ObjectOutputStream oops = null; // 读对象 ObjectInputStream oips = null; // 返回的Object Object obj = null; try { clientSocket = createClientSocket(); // 获取输出流,将客户端需要调用的远程方法发送 oops = new ObjectOutputStream(clientSocket.getOutputStream()); oops.writeObject(rpcRequest); oops.flush(); // 输入流 oips = new ObjectInputStream(clientSocket.getInputStream()); obj = oips.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (oips != null) { try { oips.close(); } catch (IOException e) { e.printStackTrace(); } } if (oops != null) { try { oops.close(); } catch (IOException e) { e.printStackTrace(); } } } return obj; } /** * 创建一个socket */ private Socket createClientSocket() { Socket socket; try { socket = new Socket(host, port); return socket; } catch (Exception e) { throw new RuntimeException("创建客户端socket失败"); } } }
true
d93244a306c806bfebdcbe174527fe36ea82be42
Java
uk-gov-mirror/hmcts.wa-case-event-handler
/src/test/java/uk/gov/hmcts/reform/wacaseeventhandler/domain/EventInformationTest.java
UTF-8
5,246
1.914063
2
[ "MIT" ]
permissive
package uk.gov.hmcts.reform.wacaseeventhandler.domain; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import org.assertj.core.util.Maps; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.JsonTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.boot.test.json.JsonContent; import org.springframework.boot.test.json.ObjectContent; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import pl.pojo.tester.api.assertion.Method; import uk.gov.hmcts.reform.wacaseeventhandler.domain.handlers.common.AdditionalData; import uk.gov.hmcts.reform.wacaseeventhandler.domain.handlers.common.EvaluateDmnResponse; import uk.gov.hmcts.reform.wacaseeventhandler.domain.handlers.common.EventInformation; import java.io.IOException; import java.time.LocalDateTime; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static pl.pojo.tester.api.assertion.Assertions.assertPojoMethodsFor; @RunWith(SpringRunner.class) @JsonTest @ActiveProfiles("local") public class EventInformationTest { private final Class classToTest = EvaluateDmnResponse.class; private static final JsonNodeFactory JSON_NODE_FACTORY = new JsonNodeFactory(false); @Autowired private JacksonTester<EventInformation> jacksonTester; private EventInformation eventInformation(AdditionalData additionalData) { return EventInformation.builder() .eventInstanceId("some event instance Id") .eventTimeStamp(LocalDateTime.parse("2020-12-07T17:39:22.232622")) .caseId("some case reference") .jurisdictionId("ia") .caseTypeId("asylum") .eventId("some event Id") .newStateId("some new state Id") .userId("some user Id") .additionalData(additionalData) .build(); } private AdditionalData additionalData() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String lastModifiedDirection = "{\"directionDueDate\": \"2021-04-08\"}"; JsonNode jsonNode = objectMapper.readTree(lastModifiedDirection); Map<String, JsonNode> dataMap = Maps.newHashMap("lastModifiedDirection", jsonNode); String definition = "{\n" + " \"type\": \"Complex\",\n" + " \"subtype\": \"lastModifiedDirection\",\n" + " \"typeDef\": {\n" + " \"directionDueDate\": {\n" + " \"type\": \"SimpleDate\",\n" + " \"subtype\": \"Date\",\n" + " \"typeDef\": null,\n" + " \"originalId\": \"directionDueDate\"\n" + " }\n" + " },\n" + " \"originalId\": \"lastModifiedDirection\"\n" + " }"; jsonNode = objectMapper.readTree(definition); Map<String, JsonNode> definitionMap = Maps.newHashMap("lastModifiedDirection", jsonNode); return AdditionalData.builder() .data(dataMap) .definition(definitionMap) .build(); } @Test public void deserialize_as_expected() throws IOException { ObjectContent<EventInformation> eventInformationObjectContent = jacksonTester.read("expected-event-information-from-ccd.json"); eventInformationObjectContent.assertThat().isEqualTo(eventInformation(null)); } @Test public void serialize_as_expected() throws IOException { EventInformation validEventInformation = eventInformation(null); JsonContent<EventInformation> eventInformationJsonContent = jacksonTester.write(validEventInformation); assertThat(eventInformationJsonContent).isEqualToJson("valid-event-information.json"); } @Test public void deserialize_as_expected_with_additional_data() throws IOException { ObjectContent<EventInformation> eventInformationObjectContent = jacksonTester.read("expected-event-information-additional-data.json"); eventInformationObjectContent.assertThat().isEqualTo(eventInformation(additionalData())); } @Test public void serialize_with_additional_data_as_expected() throws IOException { EventInformation validEventInformation = eventInformation(additionalData()); JsonContent<EventInformation> eventInformationJsonContent = jacksonTester.write(validEventInformation); assertThat(eventInformationJsonContent).isEqualToJson("valid-event-information-additional-data.json"); } @Test public void isWellImplemented() { assertPojoMethodsFor(classToTest) .testing(Method.GETTER) .testing(Method.CONSTRUCTOR) .testing(Method.EQUALS) .testing(Method.HASH_CODE) .testing(Method.TO_STRING) .areWellImplemented(); } }
true
5a49e6b79cd00c36ce1f1c915ae35abf04301361
Java
JanSei/Studium-AI
/AP II Vorlesung/VariantenJava/src/variante4/Tier.java
UTF-8
809
3.5625
4
[]
no_license
package variante4; final class Wald { public static void main(String[] args) { Tier[] tiere = { new Hase(), new Fuchs(), new Hase()}; for (Tier tier : tiere) { tier.hatHunger(); } } } interface Tier { void willFressen(); void hatHunger(); } class Hase implements Tier { public void hatHunger() { System.out.print("knurr.. "); this.willFressen(); } public void willFressen() { System.out.println("Wo ist das Möhrchen?"); } } class Fuchs implements Tier { public void hatHunger() { System.out.print("knurr.. "); willFressen(); } public void willFressen() { System.out.println("Wo ist der Hase?"); } }
true
07af026c6fb5eb51d1420edb4c827038dea73e21
Java
mirterious/PIvASTheSecond
/src/View/dialogs/panes/TravelTimePane.java
WINDOWS-1251
2,239
3.03125
3
[]
no_license
package view.dialogs.panes; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import view.ComponentCreator; public class TravelTimePane { private TextField years; private TextField months; private TextField days; private TextField hours; private TextField minutes; private ComponentCreator creator; private GridPane mainPane; public TravelTimePane() { creator = new ComponentCreator(); years = creator.getTextField(); months = creator.getTextField(); days = creator.getTextField(); hours = creator.getTextField(); minutes = creator.getTextField(); mainPane = new GridPane(); buildDialog(); } private void buildDialog() { mainPane.add(years, 0, 0); mainPane.add(creator.getLabel("- "), 1, 0); mainPane.add(months, 0, 1); mainPane.add(creator.getLabel("- "), 1, 1); mainPane.add(days, 0, 2); mainPane.add(creator.getLabel("- "), 1, 2); mainPane.add(hours, 0, 3); mainPane.add(creator.getLabel("- "), 1, 3); mainPane.add(minutes, 0, 4); mainPane.add(creator.getLabel("- "), 1, 4); } public Pane getPane() { return mainPane; } public int getYears() { int result = 0; if (!years.getText().isEmpty()) { result = Integer.parseInt(years.getText()); if (result < 0) { result = 0; } } return result; } public int getMonth() { int result = 0; if (!months.getText().isEmpty()) { result = Integer.parseInt(months.getText()); if (result < 0) { result = 0; } } return result; } public int getDays() { int result = 0; if (!days.getText().isEmpty()) { result = Integer.parseInt(days.getText()); if (result < 0) { result = 0; } } return result; } public int getHours() { int result = 0; if (!hours.getText().isEmpty()) { result = Integer.parseInt(hours.getText()); if (result < 0) { result = 0; } } return result; } public int getMinutes() { int result = 0; if (!minutes.getText().isEmpty()) { result = Integer.parseInt(minutes.getText()); if (result < 0) { result = 0; } } return result; } }
true
90174e2948fc6b5b16d73876271381df201bb403
Java
tangluochen/CoolMeeting
/src/servlet/FenYeServlet.java
UTF-8
2,192
2.0625
2
[]
no_license
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: FenYeServlet.java package servlet; import biz.FenYeBiz; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/FenYeServlet") public class FenYeServlet extends HttpServlet { public FenYeServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FenYeBiz biz = new FenYeBiz(); try { int currentPage = -999; String page = request.getParameter("page"); if(page == null) currentPage = 1; else currentPage = Integer.parseInt(page); if(currentPage < 1) currentPage = 1; int totalNum = biz.getCount(); int tiaoNum = 3; int totalPageNum = (totalNum - 1) / tiaoNum + 1; if(currentPage > totalPageNum) currentPage = totalPageNum; int startTiaoNum = (currentPage - 1) * tiaoNum + 1; int endTiaoNum = startTiaoNum + tiaoNum; request.setAttribute("currentPage", Integer.valueOf(currentPage)); request.setAttribute("totalNum", Integer.valueOf(totalNum)); request.setAttribute("totalPageNum", Integer.valueOf(totalPageNum)); request.setAttribute("staffList", biz.queryStaff(startTiaoNum, endTiaoNum, tiaoNum)); request.getRequestDispatcher("personnel_manage/searchemployees.jsp").forward(request, response); } catch(Exception e) { e.printStackTrace(); request.getRequestDispatcher("error.jsp").forward(request, response); } } private static final long serialVersionUID = 1L; }
true
06bd239f2c1c72aa35a57c6a761887bee69713ad
Java
linsen1983/adobe-pdf-library-samples
/Java/Sample_Source/Display/JavaViewer/src/com/datalogics/PDFL/JavaViewer/Views/Actions/TextSearchAction.java
UTF-8
1,330
2.234375
2
[]
no_license
/* * Copyright (C) 2011-2017, Datalogics, Inc. All rights reserved. * * For complete copyright information, refer to: * http://dev.datalogics.com/adobe-pdf-library/license-for-downloaded-pdf-samples/ * */ package com.datalogics.PDFL.JavaViewer.Views.Actions; import java.awt.event.ActionEvent; import javax.swing.JTextField; import com.datalogics.PDFL.JavaViewer.Document.JavaDocument; import com.datalogics.PDFL.JavaViewer.Document.Command.CommandType; import com.datalogics.PDFL.JavaViewer.Document.Command.DocumentCommand; import com.datalogics.PDFL.JavaViewer.Presentation.ApplicationController; public class TextSearchAction extends SimpleAction { public void actionPerformed(ActionEvent e) { if (textField != null) { final String seacrhPhrase = textField.getText(); ((ApplicationController) getApplication()).searchText(seacrhPhrase); } } public void setTextField(JTextField textField) { this.textField = textField; } @Override public boolean isPermitted() { return (textField != null) && JavaDocument.isCommandPermitted(getApplication().getActiveDocument(), CommandType.VIEW); } @Override protected Class<? extends DocumentCommand> getMainCommand() { return null; } private JTextField textField; }
true
e6dfe192d3317854b89011c8260f6ffd7a90465a
Java
SophiaPhelan/WheelHatchCommand
/src/main/java/frc/robot/OI.java
UTF-8
1,305
2.953125
3
[]
no_license
package frc.robot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import frc.robot.commands.ejectHatch; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { Joystick js = new Joystick(0); Button b1 = new JoystickButton( js, 1 ), b2 = new JoystickButton( js, 2 ), b3 = new JoystickButton( js, 3 ), b4 = new JoystickButton( js, 4 ); public OI () { b1.whenPressed(new ejectHatch(1)); } //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); }
true
e70e39d4dca3a8a3c45d3581c60b9e64134b98e2
Java
ssraul2000/FB-tecnicas-jogo-v2
/src/fbuni/User.java
UTF-8
614
2.78125
3
[]
no_license
package fbuni; import java.io.Serializable; public class User implements Serializable { private String nome; private int point; private int position; public User(String nome, int point, int position) { this.nome = nome; this.point = point; this.position = position; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getPoint() { return point; } public void setPoint(int point) { this.point = point; } }
true
825139ed91fc2051279bd970bb87640329bc1323
Java
zeroabyss/FinishProject
/app/src/main/java/com/example/aiy/finishproject/adapter/my_recycler_adapter/Wrapper/LoadMoreWrapper.java
UTF-8
3,883
2.40625
2
[]
no_license
package com.example.aiy.finishproject.adapter.my_recycler_adapter.Wrapper; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import com.example.aiy.finishproject.adapter.my_recycler_adapter.Base.ViewHolder; import com.example.aiy.finishproject.adapter.my_recycler_adapter.util.AdapterUtils; /** * <p>功能简述:加载更多内容,拉到底部的时候显示 * <p>Created by developer on 2017/12/13. */ public class LoadMoreWrapper extends RecyclerView.Adapter { //作为viewType private static final int ITEM_TYPE_LOAD_MORE=Integer.MAX_VALUE-2; //把需要包装的adapter传进来 private RecyclerView.Adapter mInnerAdapter; /** * 方法简述: 加载布局 */ private int mLayoutId; /** * 方法简述: 加载视图 */ private View mLoadMoreView; /** * 方法简述: 加载的回调 */ private OnLoadRequested onLoadRequested; public interface OnLoadRequested{ void requested(); } public void setOnLoadRequested(OnLoadRequested onLoadRequested) { this.onLoadRequested = onLoadRequested; } public LoadMoreWrapper(RecyclerView.Adapter mInnerAdapter) { this.mInnerAdapter = mInnerAdapter; } /** * 方法简述: 拥有布局或者视图其中一个 */ private boolean hasLoadMore(){ return mLoadMoreView != null || mLayoutId != 0; } private boolean isShowLoadMore(int position){ //位置要在最后 return hasLoadMore()&&position>=mInnerAdapter.getItemCount(); } @Override public int getItemViewType(int position) { //同理判断是不是最后位置 if (isShowLoadMore(position)) return ITEM_TYPE_LOAD_MORE; return mInnerAdapter.getItemViewType(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType==ITEM_TYPE_LOAD_MORE) { if (mLayoutId != 0) return ViewHolder.newInstance(parent.getContext(), parent, mLayoutId); else return ViewHolder.newInstance(parent.getContext(), mLoadMoreView); } return mInnerAdapter.onCreateViewHolder(parent,viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (isShowLoadMore(position)){ if (onLoadRequested!=null) { onLoadRequested.requested(); return; } } mInnerAdapter.onBindViewHolder(holder,position); } @Override public int getItemCount() { //有加载布局就+1 return mInnerAdapter.getItemCount()+(hasLoadMore()?1:0); } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { mInnerAdapter.onViewAttachedToWindow(holder); if (isShowLoadMore(holder.getLayoutPosition())) AdapterUtils.setFullSpan(holder); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { AdapterUtils.attach(mInnerAdapter, recyclerView, new AdapterUtils.UtilCallback() { @Override public int getSpanSize(GridLayoutManager layoutManager, GridLayoutManager.SpanSizeLookup lookup, int position) { if (isShowLoadMore(position)) return layoutManager.getSpanCount(); if (lookup!=null) return lookup.getSpanSize(position); return 1; } }); } public void setmLayoutId(int mLayoutId) { this.mLayoutId = mLayoutId; } public void setmLoadMoreView(View mLoadMoreView) { this.mLoadMoreView = mLoadMoreView; } }
true
88c5d87bfb83ac799eca5f900fb9c0cfa8f776b5
Java
Deepaksharma1995/Java--tutorials
/dynamic programming/src/MatrixChain.java
UTF-8
625
2.953125
3
[]
no_license
public class MatrixChain { static int MatrixChainOrder(int p[],int n){ int m[][] = new int[n][n]; int i,j,k,L,q; for(i=1;i<n;i++){ m[i][i] = 0; } for(L=2;L<n;L++){ for(i=1;i<n-L+1;i++){ j = i+L-1; if(j==n){ continue; } m[i][j] = Integer.MAX_VALUE; for(k=i;k<=j-1;k++){ q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]; if(q<m[i][j]){ m[i][j] = q; } } } } return m[1][n-1]; } public static void main(String[] args) { int arr[] = new int[]{1,2,3,4}; int size = arr.length; System.out.println(MatrixChainOrder(arr, size)); } }
true
01feec7e296fabe1184579b1cedcd3598f3c91ba
Java
Shekrba/InzenjeringZnanja
/iz/src/model/CBC.java
UTF-8
1,497
2.921875
3
[]
no_license
package model; public class CBC { private double redBloodCellCount; private double hemoglobin; private double hematocrit; private double whiteBloodCellCount; private double platelet; public CBC(){ } public CBC(double redBloodCellCount, double hemoglobin, double hematocrit, double whiteBloodCellCount, double platelet) { this.redBloodCellCount = redBloodCellCount; this.hemoglobin = hemoglobin; this.hematocrit = hematocrit; this.whiteBloodCellCount = whiteBloodCellCount; this.platelet = platelet; } public double getRedBloodCellCount() { return redBloodCellCount; } public void setRedBloodCellCount(double redBloodCellCount) { this.redBloodCellCount = redBloodCellCount; } public double getHemoglobin() { return hemoglobin; } public void setHemoglobin(double hemoglobin) { this.hemoglobin = hemoglobin; } public double getHematocrit() { return hematocrit; } public void setHematocrit(double hematocrit) { this.hematocrit = hematocrit; } public double getWhiteBloodCellCount() { return whiteBloodCellCount; } public void setWhiteBloodCellCount(double whiteBloodCellCount) { this.whiteBloodCellCount = whiteBloodCellCount; } public double getPlatelet() { return platelet; } public void setPlatelet(double platelet) { this.platelet = platelet; } }
true
8571caebfdead5164ad60cf0726ff5e6009602a7
Java
pooetitu/PPE2
/src/server/commands/ClientConnection.java
WINDOWS-1250
13,268
2.4375
2
[]
no_license
package server.commands; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import common.Compte; import common.Group; import server.Arene; public class ClientConnection implements Runnable { private Compte c; private Arene a; private Socket sock; private ObjectOutputStream oos, oos1; private ObjectInputStream ois, ois1; private boolean sending = false; public boolean isSending() { return sending; } public void setSending(boolean sending) { this.sending = sending; } public ClientConnection(Socket pSock) throws IOException { sock = pSock; oos = new ObjectOutputStream(sock.getOutputStream()); ois = new ObjectInputStream(sock.getInputStream()); } public Arene getA() { return a; } public void setA(Arene a) { this.a = a; } public void connectionCompte(String pseudo, String mdp) throws SQLException { if (GameServer.listClient.get(pseudo) == null) { SQL sql = new SQL(); if (sql.userExist(pseudo, mdp)) { int id = sql.userConnection(pseudo, mdp); try { File file = new File(String.valueOf(id)); FileInputStream fichier = new FileInputStream(file); ois1 = new ObjectInputStream(fichier); c = (Compte) ois1.readObject(); ois1.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final ClassNotFoundException e) { e.printStackTrace(); } } } } public void creationCompte(String pseudo, String mdp) throws SQLException { SQL sql = new SQL(); if (!sql.userExist(pseudo, mdp)) { this.c = new Compte(pseudo, mdp); try { File file = new File(String.valueOf(c.getId())); file.createNewFile(); FileOutputStream fichier = new FileOutputStream(file); oos1 = new ObjectOutputStream(fichier); oos1.writeObject(c); oos1.close(); fichier.close(); } catch (final IOException e) { e.printStackTrace(); } } } public void run() { Thread t = new Thread(new Runnable() { public void run() { try { while (!sock.isClosed()) { Thread.sleep(2000); if (sending = true) { Thread.sleep(50); } if (!sock.isClosed()) { ArrayList<String> keys = new ArrayList<String>(GameServer.listClient.keySet()); sendObject("USERS", keys); sendGroup(); } } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); System.err.println("Lancement du traitement de la connexion cliente"); while (!sock.isClosed()) { try { String request = null; request = (String) ois.readObject(); System.out.println(sock + " " + request); List<String> cmd = Arrays.asList(request.trim().split("\\s+")); // toSend = ""; if (cmd.size() >= 0) switch (cmd.get(0)) { case ("CONNECT"): { if (cmd.size() >= 1) switch (cmd.get(1)) { case ("SIGNIN"): { try { if (cmd.size() >= 3) creationCompte(cmd.get(2), cmd.get(3)); if (c != null) { GameServer.listClient.put(this.c.getPseudo(), this); sendObject("CONNECTED"); sendCompte(); } else { System.out.println("id used"); sendObject("ERROR INSCRIPTION"); } } catch (SQLException e) { sendObject("ERROR INSCRIPTION"); System.err.println("erreur connection signin"); } break; } case ("SIGNUP"): { try { if (cmd.size() > 3) connectionCompte(cmd.get(2), cmd.get(3)); if (c != null) { GameServer.listClient.put(String.valueOf(this.c.getPseudo()), this); sendObject("CONNECTED"); sendCompte(); } else { System.out.println("id eron"); sendObject("ERROR CONNECTION"); } } catch (SQLException e) { sendObject("ERROR CONNECTION"); System.err.println("erreur connection signup"); } break; } } break; } case ("MENU"): { if (cmd.size() >= 2) switch (cmd.get(1)) { case ("DELETE"): { if (c.getNbperso() > 0) { c.delPerso(); sendCompte(); sendGroup(); } break; } case ("COMP"): { c.getP(c.getSelection()).lvlUpComp(Integer.parseInt(cmd.get(2))); break; } case ("LEAVING"): { for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) || lg.getC2().equals(c.getPseudo())) { lg.setInSearch(false); GameServer.listGroup.remove(lg); break; } } break; } case ("CREATE"): { c.creePerso(cmd.get(2)); sendCompte(); sendGroup(); break; } case ("MESSAGE"): { String msg = this.c.getPseudo() + " : "; for (int i = 2; i < cmd.size(); i++) { msg += cmd.get(i); msg += " "; } for (Map.Entry<String, ?> me : GameServer.listClient.entrySet()) { ClientConnection c = (ClientConnection) me.getValue(); c.sendObject("MESSAGE", msg); } break; } case ("INVITE"): { GameServer.listClient.get(cmd.get(2)).sendObject("INVITE", this.c.getPseudo()); break; } case ("SELECT"): { this.c.setSelection(Integer.parseInt(cmd.get(2))); sendCompte(); sendGroup(); break; } case ("TARGETED"): { String msg = this.c.getPseudo() + " : "; for (int i = 4; i < cmd.size(); i++) { msg += cmd.get(i); msg += " "; } if (GameServer.listClient.get(cmd.get(3)) != null) { GameServer.listClient.get(cmd.get(3)).sendObject("MESSAGE", msg); } if (cmd.get(2).equals("Y")) { GameServer.listGroup.add(new Group(this.c.getP(this.c.getSelection()), GameServer.listClient.get(cmd.get(3)).getC() .getP(GameServer.listClient.get(cmd.get(3)).getC().getSelection()), c.getPseudo(), cmd.get(3))); sendGroup(); } break; } case ("SEARCHING"): { ClientConnection cc = this; Thread t1 = new Thread(new Runnable() { @Override public void run() { Group g = null; for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) || lg.getC2().equals(c.getPseudo())) { g = lg; break; } } if (g != null) { try { g.startSearch(); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { if (c.getP(c.getSelection()) != null) { c.getP(c.getSelection()).startGame(cc); } else { sendObject("ERROR PERSO"); } } catch (InterruptedException e) { e.printStackTrace(); } } } }); switch (cmd.get(2)) { case ("START"): { t1.start(); boolean found = false; for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) || lg.getC2().equals(c.getPseudo())) { GameServer.listClient.get(lg.getC1()).sendObject("SEARCH START", true); GameServer.listClient.get(lg.getC2()).sendObject("SEARCH START", true); found = true; break; } } if (!found) { sendObject("SEARCH START", true); } break; } case ("STOP"): { boolean found = false; for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) || lg.getC2().equals(c.getPseudo())) { GameServer.listClient.get(lg.getC1()).getC() .getP(GameServer.listClient.get(lg.getC1()).getC().getSelection()) .setSearching(false); GameServer.listClient.get(lg.getC2()).getC() .getP(GameServer.listClient.get(lg.getC2()).getC().getSelection()) .setSearching(false); GameServer.listClient.get(lg.getC1()).sendObject("SEARCH STOP", false); GameServer.listClient.get(lg.getC2()).sendObject("SEARCH STOP", false); found = true; break; } } if (!found) { if (c.getP(c.getSelection()) != null) { c.getP(c.getSelection()).setSearching(false); } sendObject("SEARCH STOP"); sendObject(false); } break; } } } break; } } case ("BATTLE"): { switch (cmd.get(1)) { case ("ACTION"): { c.getP(c.getSelection()).setCmd1(cmd.get(2)); if (cmd.size() > 3) c.getP(c.getSelection()).setCmd2(cmd.get(3)); } } break; } } } catch (ClassNotFoundException | IOException e) { System.err.println("Connection closed !"); try { oos.close(); ois.close(); sock.close(); if (c != null) { if (c.getP(0) != null) { c.getP(0).setSearching(false); } if (c.getP(c.getSelection()) != null) { c.getP(c.getSelection()).reset(); } c.save(); for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) || lg.getC2().equals(c.getPseudo())) { if (lg.isInSearch()) { lg.setInSearch(false); GameServer.listClient.get(lg.getC1()).getC() .getP(GameServer.listClient.get(lg.getC1()).getC().getSelection()) .setSearching(false); GameServer.listClient.get(lg.getC2()).getC() .getP(GameServer.listClient.get(lg.getC2()).getC().getSelection()) .setSearching(false); GameServer.listClient.get(lg.getC1()).sendObject("SEARCH STOP", false); GameServer.listClient.get(lg.getC2()).sendObject("SEARCH STOP", false); } if (!lg.isInGame()) { GameServer.listGroup.remove(lg); System.out.println("Group left"); } else if (lg.isInGame()) { c.getP(c.getSelection()).setDisconnected(true); } break; } } } } catch (IOException e2) { e2.printStackTrace(); } if (c != null) { GameServer.listClient.remove(this.c.getPseudo()); } break; } } } public Compte getC() { return c; } public void setC(Compte c) { this.c = c; } public Socket getSock() { return sock; } public synchronized void sendObject(Object o) { try { if (!sock.isClosed()) { oos.reset(); oos.writeObject(o); oos.flush(); } } catch (IOException e) { e.printStackTrace(); } } public synchronized void sendObject(Object o, Object o1) { try { if (!sock.isClosed()) { oos.reset(); oos.writeObject(o); oos.flush(); oos.reset(); oos.writeObject(o1); oos.flush(); } } catch (IOException e) { e.printStackTrace(); } } public synchronized void sendGroup() { boolean found = false; if (c != null && !sock.isClosed()) { for (Group lg : GameServer.listGroup) { if (lg.getC1().equals(c.getPseudo()) && GameServer.listClient.get(lg.getC1()) != null && GameServer.listClient.get(lg.getC2()) != null) { if (!lg.isInGame()) { lg.setP(0, c.getP(c.getSelection())); lg.setP(1, GameServer.listClient.get(lg.getC2()).getC() .getP(GameServer.listClient.get(lg.getC2()).getC().getSelection())); sendObject("GROUP", lg); GameServer.listClient.get(lg.getC2()).sendObject("GROUP", lg); } found = true; break; } else if (lg.getC2().equals(c.getPseudo()) && GameServer.listClient.get(lg.getC1()) != null && GameServer.listClient.get(lg.getC2()) != null) { if (!lg.isInGame()) { lg.setP(0, GameServer.listClient.get(lg.getC1()).getC() .getP(GameServer.listClient.get(lg.getC1()).getC().getSelection())); lg.setP(1, c.getP(c.getSelection())); sendObject("GROUP", lg); GameServer.listClient.get(lg.getC1()).sendObject("GROUP", lg); } found = true; break; } } } if (!found) { sendObject("GROUP", "NULL"); sendCompte(); } } public synchronized void sendCompte() { try { if (!sock.isClosed()) { oos.reset(); oos.writeObject("COMPTE"); oos.flush(); oos.reset(); oos.writeObject(c); oos.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
true
3569e1611a3a706b55598168720f64be45375c58
Java
Ghazibenslama/SMD-master
/src/org/processmining/plugins/epml/EpmlAttributeType.java
UTF-8
1,650
2.296875
2
[]
no_license
package org.processmining.plugins.epml; import org.xmlpull.v1.XmlPullParser; /** * @author hverbeek * * <xs:complexType name="typeAttrType"> <xs:complexContent> * <xs:extension base="epml:tExtensibleElements"> <xs:sequence> * <xs:element name="description" type="xs:string" minOccurs="0"/> * </xs:sequence> <xs:attribute name="typeId" type="xs:string"/> * </xs:extension> </xs:complexContent> </xs:complexType> */ public class EpmlAttributeType extends EpmlExtensibleElements { public final static String TAG = "attributeType"; /* * Attributes */ private String typeId; /* * Elements */ private EpmlDescription description; public EpmlAttributeType() { super(TAG); typeId = null; description = null; } protected void importAttributes(XmlPullParser xpp, Epml epml) { super.importAttributes(xpp, epml); String value = xpp.getAttributeValue(null, "typeId"); if (value != null) { typeId = value; } } protected String exportAttributes() { String s = super.exportAttributes(); if (typeId != null) { s += exportAttribute("typeId", typeId); } return s; } protected boolean importElements(XmlPullParser xpp, Epml epml) { if (super.importElements(xpp, epml)) { return true; } if (xpp.getName().equals(EpmlDescription.TAG)) { description = new EpmlDescription(); description.importElement(xpp, epml); return true; } /* * Unknown start tag. */ return false; } protected String exportElements() { String s = super.exportElements(); if (description != null) { s += description.exportElement(); } return s; } }
true
d7ffff4237c7a6e1def713f0c52e3f3e1c6e1aff
Java
songmatianqi/javaProject
/src/reverseString.java
UTF-8
354
3.203125
3
[]
no_license
public class reverseString { public static void main(String[] args) { // write your code here char[] s = new char[] {'a', 'b', 'c'}; for (int i = 0; i < s.length / 2; i++) { char t = s[i]; s[i] = s[s.length - i -1]; s[s.length - i - 1] = t; } System.out.println(s); } }
true
0a2d19e83700151527da92c0553513604a88251a
Java
mbaleczny/compass-app
/app/src/main/java/mariuszbaleczny/compass/location/CompassToLocationProvider.java
UTF-8
6,871
2.1875
2
[ "Apache-2.0" ]
permissive
package mariuszbaleczny.compass.location; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.GeomagneticField; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.util.Log; import mariuszbaleczny.compass.Constants; import mariuszbaleczny.compass.R; import mariuszbaleczny.compass.Utils; public class CompassToLocationProvider implements SensorEventListener, LocationListener { private final static String LOCATION_PROVIDER = "LocationProvider"; private final Context context; private final LocationManager locationManager; private final SensorManager sensorManager; private final Sensor sensor; private int northAngle = 0; private int targetLocationAngle = 0; private boolean providerStarted = false; private float[] rotationMatrix = new float[9]; private float[] orientationVector = new float[3]; private Location myLocation = new Location(LOCATION_PROVIDER); private Location targetLocation; private GeomagneticField geomagneticField; private CompassToLocationListener compassToLocationListener; public CompassToLocationProvider(final Context context) { this.context = context; this.sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); this.sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); } public void setCompassToLocationListener(final CompassToLocationListener compassToLocationListener) { this.compassToLocationListener = compassToLocationListener; } @Override public void onLocationChanged(Location location) { myLocation = location; Log.d(getClass().getName(), String.format("latitude: %f, longitude: %f", myLocation.getLatitude(), myLocation.getLongitude())); geomagneticField = new GeomagneticField( (float) myLocation.getLatitude(), (float) myLocation.getLongitude(), (float) myLocation.getAltitude(), myLocation.getTime()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { Log.d(getClass().getName(), provider + " : Location Services ON"); if (provider.contains(context.getString(R.string.gps_provider)) || provider.contains(context.getString(R.string.network_provider))) { compassToLocationListener.setLayoutElementsOnProvider(true); } } @Override public void onProviderDisabled(String provider) { Log.d(getClass().getName(), provider + " : Location Services OFF"); if (provider.contains(context.getString(R.string.gps_provider)) || provider.contains(context.getString(R.string.network_provider))) { compassToLocationListener.setLayoutElementsOnProvider(false); setTargetLocation(null); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void setTargetLocation(Location location) { targetLocation = location; } @Override public void onSensorChanged(SensorEvent event) { SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values.clone()); float azimuthInRadians = SensorManager.getOrientation(rotationMatrix, orientationVector)[Constants.Z_AXIS_ROTATION]; northAngle = Utils.convertRadiansToDegreesRounded(azimuthInRadians); updateAngle(); } private void updateAngle() { calculateTrueNorthAngleIfPossible(); calculateLocationAngleIfPossible(); compassToLocationListener.onCompassPointerRotate(northAngle, targetLocationAngle); } private void calculateTrueNorthAngleIfPossible() { if (geomagneticField != null) { northAngle += geomagneticField.getDeclination(); } } private void calculateLocationAngleIfPossible() { if (targetLocation != null && myLocation != null) { int bearing = (int) myLocation.bearingTo(targetLocation); targetLocationAngle = northAngle - bearing; } else { targetLocationAngle = 0; } } public void startIfNotStarted() { if (!providerStarted) { sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); for (final String provider : locationManager.getProviders(true)) { if (LocationManager.GPS_PROVIDER.equals(provider) || LocationManager.NETWORK_PROVIDER.equals(provider)) { if (myLocation == null) { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } myLocation = locationManager.getLastKnownLocation(provider); } locationManager.requestLocationUpdates(provider, Constants.MIN_UPDATE_INTERVAL_MS, Constants.MIN_DISTANCE_UPDATE_IN_METERS, this); } } providerStarted = true; } } public void stopIfStarted() { if (providerStarted) { sensorManager.unregisterListener(this, sensor); locationManager.removeUpdates(this); providerStarted = false; } } public interface CompassToLocationListener { void onCompassPointerRotate(int roseAngle, int needleAngle); void setLayoutElementsOnProvider(boolean enabled); } }
true
ffa026470b413feb10039d1af9a524cb2c9d2640
Java
Sandymonastirli/SeaFightNewEdition
/RandomStrategy.java
UTF-8
646
2.96875
3
[]
no_license
//Monastirli Chrysanthi import java.util.ArrayList; import java.util.Random; public class RandomStrategy { private static final int BOARD_DIM = 10; private ArrayList<Vector2> targets; public RandomStrategy() { initTargets(); } private void initTargets() { targets = new ArrayList<Vector2>(); for (int i=0;i<BOARD_DIM;i++) { for (int j=0;j<BOARD_DIM;j++) { targets.add(new Vector2(i,j)); } } } public Vector2 nextStrike() { Random rand = new Random(); int temp = rand.nextInt(targets.size()); return (targets.get(temp)); } public void update(Vector2 point) { targets.remove(point); } }
true
29f5a33291616cd2399c7484ed5e15435ad2f6d5
Java
hammer7903/api-book-challenger
/src/main/java/com/mx/api/book/challenge/app/exception/ExamenException.java
UTF-8
626
2.171875
2
[]
no_license
package com.mx.api.book.challenge.app.exception; import org.springframework.http.HttpStatus; import lombok.Getter; @Getter public class ExamenException extends Exception { /** * */ private static final long serialVersionUID = -1L; private HttpStatus status; private String message; public ExamenException(Throwable cause) { super(cause); } public ExamenException(String message) { super(message); } public ExamenException(String message, HttpStatus status) { super(message); this.message = message; this.status = status; } }
true
c5081a99c5d4e35703083e0640d7c26ce43999ac
Java
maardiansyah/java
/src/apps/kota.java
UTF-8
49,584
2.390625
2
[]
no_license
/* * 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 apps; import asset.koneksi; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Locale; import javax.swing.JOptionPane; import javax.swing.Timer; import javax.swing.table.DefaultTableModel; /** * * @author User */ public class kota extends javax.swing.JFrame { Connection connection; DefaultTableModel model; /** * Creates new form kota */ public kota() { initComponents(); Tampil_Jam(); Tampil_Tanggal(); connection=koneksi.connection(); tKota.requestFocus(); tableKota(); tableTerminal(); cmbBox(); } //isi data combo box public void cmbBox(){ try { String query = "SELECT * FROM kota"; Statement st = connection.createStatement(); ResultSet res = st.executeQuery(query); while (res.next()){ cbKota.addItem(res.getString("kota")); } res.last(); int jumKota = res.getRow(); res.first(); } catch (SQLException e){} } private void tableKota(){ model = (DefaultTableModel) tabKota.getModel(); try{ Statement stat = connection.createStatement(); String sql = "SELECT * FROM kota"; ResultSet res = stat.executeQuery(sql); while(res.next ()){ Object[ ] obj = new Object[2]; obj[0] = res.getString("id"); obj[1] = res.getString("kota"); model.addRow(obj); } }catch(SQLException err){ err.printStackTrace(); } } private void tableTerminal(){ model = (DefaultTableModel) tabTerminal.getModel(); try{ Statement stat = connection.createStatement(); String sql = "SELECT * FROM terminal"; ResultSet res = stat.executeQuery(sql); while(res.next ()){ Object[ ] obj = new Object[4]; obj[0] = res.getString("id"); obj[1] = res.getString("kota"); obj[2] = res.getString("terminal"); //obj[3] = res.getString("harga"); model.addRow(obj); } }catch(SQLException err){ err.printStackTrace(); } } private void tambahKota(){ PreparedStatement statement = null; String sql = "INSERT INTO kota (kota) VALUES (?);"; try{ statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, tKota.getText()); statement.executeUpdate(); } catch(SQLException ex){ ex.printStackTrace(); } finally{ try{ statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void tambahTerminal(){ PreparedStatement statement = null; String sql = "INSERT INTO terminal (kota,terminal) VALUES (?,?);"; try{ statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, cbKota.getSelectedItem().toString()); statement.setString(2, tTerminal.getText()); //statement.setString(3, tHarga.getText()); statement.executeUpdate(); } catch(SQLException ex){ ex.printStackTrace(); } finally{ try{ statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void deleteKota(){ PreparedStatement statement = null; String sql = "DELETE FROM kota WHERE id=?"; try{ statement = connection.prepareStatement(sql); statement.setString(1, tIdKota.getText()); statement.executeUpdate(); } catch (SQLException ex){ ex.printStackTrace(); } finally{ try { statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void deleteTerminal(){ PreparedStatement statement = null; String sql = "DELETE FROM terminal WHERE id=?"; try{ statement = connection.prepareStatement(sql); statement.setString(1, tIdTerminal.getText()); statement.executeUpdate(); } catch (SQLException ex){ ex.printStackTrace(); } finally{ try { statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void refreshKota(){ model = (DefaultTableModel) tabKota.getModel(); model.setRowCount(0); tableKota(); } private void refreshTerminal(){ model = (DefaultTableModel) tabTerminal.getModel(); model.setRowCount(0); tableTerminal(); tCariTerminal.setText(""); } private void resetKota(){ tIdKota.setText(""); tKota.setText(""); } private void resetTerminal(){ tIdTerminal.setText(""); tTerminal.setText(""); //tHarga.setText(""); cbKota.setSelectedItem("--- Pilih Kota ---"); } private void updateKota(){ PreparedStatement statement = null; String sql = "Update kota set kota=? Where id=? ;"; try{ statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, tKota.getText()); statement.setString(2, tIdKota.getText()); statement.executeUpdate(); } catch(SQLException ex){ ex.printStackTrace(); } finally{ try{ statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void updateTerminal(){ PreparedStatement statement = null; String sql = "Update terminal set terminal=?, kota=? Where id=? ;"; try{ statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, tTerminal.getText()); statement.setString(2, cbKota.getSelectedItem().toString()); //statement.setString(3, tHarga.getText()); statement.setString(3, tIdTerminal.getText()); statement.executeUpdate(); } catch(SQLException ex){ ex.printStackTrace(); } finally{ try{ statement.close(); }catch (SQLException ex){ ex.printStackTrace(); } } } private void searchKota(){ model = (DefaultTableModel) tabKota.getModel(); PreparedStatement statement = null; try{ String sql = "select*from kota where kota like ?"; statement = connection.prepareStatement(sql); statement.setString(1,"%"+ tCariKota.getText()+"%"); ResultSet res = statement.executeQuery(); while(res.next()){ Object[ ] obj = new Object[7]; obj[0] = res.getString("id"); obj[1] = res.getString("kota"); model.addRow(obj); } }catch(SQLException err){ err.printStackTrace(); } } private void searchTerminal(){ model = (DefaultTableModel) tabTerminal.getModel(); PreparedStatement statement = null; try{ String sql = "select*from terminal where terminal like ?"; //"SELECT * FROM user,pengguna WHERE " //+"mhs.idProdi=prodi.idProdi AND mhs.idKonsen=konsentrasi.idKonsen AND kota like ?"; statement = connection.prepareStatement(sql); statement.setString(1,"%"+ tCariTerminal.getText()+"%"); ResultSet res = statement.executeQuery(); while(res.next()){ Object[ ] obj = new Object[7]; obj[0] = res.getString("id"); obj[1] = res.getString("kota"); obj[2] = res.getString("terminal"); // obj[3] = res.getString("harga"); model.addRow(obj); } }catch(SQLException err){ err.printStackTrace(); } } public void Tampil_Jam(){ ActionListener taskPerformer = new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String nol_jam = "", nol_menit = "",nol_detik = ""; java.util.Date dateTime = new java.util.Date(); int nilai_jam = dateTime.getHours(); int nilai_menit = dateTime.getMinutes(); int nilai_detik = dateTime.getSeconds(); if(nilai_jam <= 9) nol_jam= "0"; if(nilai_menit <= 9) nol_menit= "0"; if(nilai_detik <= 9) nol_detik= "0"; String jam = nol_jam + Integer.toString(nilai_jam); String menit = nol_menit + Integer.toString(nilai_menit); String detik = nol_detik + Integer.toString(nilai_detik); textJam.setText(jam+":"+menit+":"+detik+""); } }; new Timer(1000, taskPerformer).start(); } public void Tampil_Tanggal() { java.util.Date tglsekarang = new java.util.Date(); SimpleDateFormat smpdtfmt = new SimpleDateFormat("dd MMMMMMMMM yyyy", Locale.getDefault()); String tanggal = smpdtfmt.format(tglsekarang); texTgl.setText(tanggal); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSeparator1 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tIdKota = new javax.swing.JTextField(); tKota = new javax.swing.JTextField(); bTambahKota = new javax.swing.JButton(); bUbahKota = new javax.swing.JButton(); bHapusKota = new javax.swing.JButton(); bResetKota = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); tCariKota = new javax.swing.JTextField(); bCariKota = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabKota = new javax.swing.JTable(); texTgl = new javax.swing.JLabel(); textJam = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); tTerminal = new javax.swing.JTextField(); cbKota = new javax.swing.JComboBox<>(); tIdTerminal = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); bTambahTerm = new javax.swing.JButton(); bResetTerm = new javax.swing.JButton(); bUbahTerm = new javax.swing.JButton(); bHapusTerm = new javax.swing.JButton(); bRefreshTerminal = new javax.swing.JButton(); bCariTerminal = new javax.swing.JButton(); tCariTerminal = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); tabTerminal = new javax.swing.JTable(); bRefreshKota = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); menu = new javax.swing.JMenu(); mBeranda = new javax.swing.JMenuItem(); mTransaksi = new javax.swing.JMenuItem(); mPengguna = new javax.swing.JMenuItem(); mKendaraan = new javax.swing.JMenuItem(); laporan = new javax.swing.JMenu(); mLaporan = new javax.swing.JMenuItem(); jMenu9 = new javax.swing.JMenu(); mLogout = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Data Daerah"); jLabel1.setFont(new java.awt.Font("Century", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(51, 153, 255)); jLabel1.setText("Data Daerah Tujuan"); jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel2.setText("FORM KOTA"); jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel4.setText("ID"); jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel5.setText("Kota"); tIdKota.setEditable(false); bTambahKota.setText("Tambah"); bTambahKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bTambahKotaActionPerformed(evt); } }); bUbahKota.setText("Update"); bUbahKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bUbahKotaActionPerformed(evt); } }); bHapusKota.setText("Hapus"); bHapusKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bHapusKotaActionPerformed(evt); } }); bResetKota.setText("Reset"); bResetKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bResetKotaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(42, 42, 42) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(bTambahKota) .addComponent(bHapusKota, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bUbahKota, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bResetKota, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tIdKota, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tKota, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(43, 43, 43)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tIdKota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tKota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bTambahKota) .addComponent(bResetKota)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bHapusKota) .addComponent(bUbahKota)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel3.setText("Pencarian"); bCariKota.setText("Cari"); bCariKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bCariKotaActionPerformed(evt); } }); tabKota.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Kota" } )); tabKota.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabKotaMouseClicked(evt); } }); jScrollPane1.setViewportView(tabKota); texTgl.setText("Tanggal"); textJam.setText("Jam"); jPanel2.setBackground(new java.awt.Color(0, 255, 255)); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel6.setText("FORM TERMINAL"); jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel7.setText("Kota"); jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel8.setText("Terminal"); cbKota.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--- Pilih Kota ---" })); tIdTerminal.setEditable(false); jLabel9.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N jLabel9.setText("ID"); bTambahTerm.setText("Tambah"); bTambahTerm.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bTambahTermActionPerformed(evt); } }); bResetTerm.setText("Reset"); bResetTerm.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bResetTermActionPerformed(evt); } }); bUbahTerm.setText("Update"); bUbahTerm.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bUbahTermActionPerformed(evt); } }); bHapusTerm.setText("Hapus"); bHapusTerm.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bHapusTermActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(jLabel6)) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jLabel9)) .addGap(23, 23, 23) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tIdTerminal) .addComponent(tTerminal) .addComponent(cbKota, 0, 137, Short.MAX_VALUE))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bHapusTerm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bTambahTerm)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bUbahTerm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bResetTerm, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addContainerGap(40, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(tIdTerminal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(cbKota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(tTerminal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(56, 56, 56) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bTambahTerm) .addComponent(bResetTerm)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bHapusTerm) .addComponent(bUbahTerm)) .addContainerGap(13, Short.MAX_VALUE)) ); bRefreshTerminal.setText("Refresh"); bRefreshTerminal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRefreshTerminalActionPerformed(evt); } }); bCariTerminal.setText("Cari"); bCariTerminal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bCariTerminalActionPerformed(evt); } }); jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jLabel11.setText("Pencarian"); tabTerminal.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Kota", "Terminal" } )); tabTerminal.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabTerminalMouseClicked(evt); } }); jScrollPane2.setViewportView(tabTerminal); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11) .addGap(26, 26, 26) .addComponent(tCariTerminal, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(bCariTerminal) .addGap(18, 18, 18) .addComponent(bRefreshTerminal) .addGap(0, 20, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane2) .addContainerGap()))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(tCariTerminal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bCariTerminal) .addComponent(bRefreshTerminal)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); bRefreshKota.setText("Refresh"); bRefreshKota.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRefreshKotaActionPerformed(evt); } }); menu.setText("Menu"); mBeranda.setText("Beranda"); mBeranda.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mBerandaActionPerformed(evt); } }); menu.add(mBeranda); mTransaksi.setText("Transaksi"); mTransaksi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mTransaksiActionPerformed(evt); } }); menu.add(mTransaksi); mPengguna.setText("Pengguna"); mPengguna.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mPenggunaActionPerformed(evt); } }); menu.add(mPengguna); mKendaraan.setText("Kendaraan"); mKendaraan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mKendaraanActionPerformed(evt); } }); menu.add(mKendaraan); jMenuBar1.add(menu); laporan.setText("Laporan"); mLaporan.setText("Laporan"); mLaporan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mLaporanActionPerformed(evt); } }); laporan.add(mLaporan); jMenuBar1.add(laporan); jMenu9.setText("User"); mLogout.setText("Exit"); mLogout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { mLogoutActionPerformed(evt); } }); jMenu9.add(mLogout); jMenuBar1.add(jMenu9); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(texTgl) .addGap(18, 18, 18) .addComponent(textJam) .addGap(34, 34, 34)) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(26, 26, 26) .addComponent(tCariKota, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(bCariKota) .addGap(18, 18, 18) .addComponent(bRefreshKota) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()))) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(textJam) .addComponent(texTgl)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(tCariKota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bCariKota) .addComponent(bRefreshKota)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void bCariKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCariKotaActionPerformed // TODO add your handling code here: if(!tCariKota.getText().trim().isEmpty()){ model=(DefaultTableModel) tabKota.getModel(); model.setRowCount(0); searchKota(); tCariKota.setText(""); }else { JOptionPane.showMessageDialog(this, "Masukan Kota yang ingin di cari!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bCariKotaActionPerformed private void bUbahKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bUbahKotaActionPerformed // TODO add your handling code here: if(!tIdKota.getText().trim().isEmpty()&&!tKota.getText().trim().isEmpty()){ updateKota(); JOptionPane.showMessageDialog(this,"Kota Sudah Diperbaharui", "Notifikasi", JOptionPane.INFORMATION_MESSAGE); resetKota(); refreshKota(); }else {JOptionPane.showMessageDialog(this,"Pembaharuan gagal. Harap Periksa Kembali kelengkapan Data!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bUbahKotaActionPerformed private void mTransaksiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mTransaksiActionPerformed // TODO add your handling code here: new transaksi().setVisible(true); this.dispose(); }//GEN-LAST:event_mTransaksiActionPerformed private void bUbahTermActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bUbahTermActionPerformed // TODO add your handling code here: if(!tIdTerminal.getText().trim().isEmpty()){ updateTerminal(); JOptionPane.showMessageDialog(this,"Data Terminal Sudah Diperbaharui", "Notifikasi", JOptionPane.INFORMATION_MESSAGE); resetTerminal(); refreshTerminal(); }else {JOptionPane.showMessageDialog(this,"Pembaharuan gagal. Harap Periksa Kembali kelengkapan Data!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bUbahTermActionPerformed private void bRefreshKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRefreshKotaActionPerformed // TODO add your handling code here: refreshKota(); tCariKota.setText(""); }//GEN-LAST:event_bRefreshKotaActionPerformed private void bRefreshTerminalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRefreshTerminalActionPerformed // TODO add your handling code here: refreshTerminal(); }//GEN-LAST:event_bRefreshTerminalActionPerformed private void bCariTerminalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCariTerminalActionPerformed // TODO add your handling code here: if(!tCariTerminal.getText().trim().isEmpty()){ model=(DefaultTableModel) tabTerminal.getModel(); model.setRowCount(0); searchTerminal(); tCariTerminal.setText(""); }else { JOptionPane.showMessageDialog(this, "Masukan Terminal yang ingin di cari!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bCariTerminalActionPerformed private void bTambahKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bTambahKotaActionPerformed // TODO add your handling code here: if(!tKota.getText().trim().isEmpty()){ tambahKota(); resetKota(); refreshKota(); JOptionPane.showMessageDialog(this,"Selamat Kota Berhasil Ditambahkan", "Notifikasi", JOptionPane.INFORMATION_MESSAGE); }else {JOptionPane.showMessageDialog(this,"Nama Kota Belum diisi!!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bTambahKotaActionPerformed private void bHapusKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bHapusKotaActionPerformed // TODO add your handling code here: if(!tIdKota.getText().trim().isEmpty()){ int alert = JOptionPane.showConfirmDialog(this,"Anda Yakin ingin menghapus Kota ini?", "Notifikasi", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (alert == JOptionPane.YES_OPTION){ deleteKota(); refreshKota(); resetKota(); JOptionPane.showMessageDialog(this, "Kota berhassil dihapus", "Notifikasi", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Pilih Kota terlebih dahulu!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bHapusKotaActionPerformed private void bHapusTermActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bHapusTermActionPerformed // TODO add your handling code here: if(!tIdTerminal.getText().trim().isEmpty()){ int alert = JOptionPane.showConfirmDialog(this,"Anda Yakin ingin menghapus Terminal ini?", "Notifikasi", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (alert == JOptionPane.YES_OPTION){ deleteTerminal(); refreshTerminal(); resetTerminal(); JOptionPane.showMessageDialog(this, "Terminal berhassil dihapus", "Notifikasi", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Pilih Terminal terlebih dahulu!", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bHapusTermActionPerformed private void bTambahTermActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bTambahTermActionPerformed // TODO add your handling code here: String cmb = "--- Pilih Kota ---"; if(cbKota.getSelectedItem()==cmb){ JOptionPane.showMessageDialog(this,"Pilih Kota Terlebih Dahulu","Notifikasi", JOptionPane.WARNING_MESSAGE); }else if(//!tIdTerminal.getText().trim().isEmpty() //&&!cbKota.getText().trim().isEmpty() !tTerminal.getText().trim().isEmpty()){ tambahTerminal(); resetTerminal(); refreshTerminal(); JOptionPane.showMessageDialog(this,"Selamat Terminal Tujuan Bertambah", "Notifikasi", JOptionPane.INFORMATION_MESSAGE); }else {JOptionPane.showMessageDialog(this,"GAGAL MENAMBAHKAN!! Harap lengkapi form", "Notifikasi", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_bTambahTermActionPerformed private void bResetKotaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bResetKotaActionPerformed // TODO add your handling code here: resetKota(); }//GEN-LAST:event_bResetKotaActionPerformed private void bResetTermActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bResetTermActionPerformed // TODO add your handling code here: resetTerminal(); }//GEN-LAST:event_bResetTermActionPerformed private void tabKotaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabKotaMouseClicked // TODO add your handling code here: int row=tabKota.getSelectedRow(); String uId=tabKota.getModel().getValueAt(row,0).toString(); String query = "SELECT * FROM kota WHERE id="+uId+""; tIdKota.setText(tabKota.getModel().getValueAt(tabKota.getSelectedRow(),0).toString()); tKota.setText(tabKota.getModel().getValueAt(tabKota.getSelectedRow(),1).toString()); }//GEN-LAST:event_tabKotaMouseClicked private void mBerandaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mBerandaActionPerformed // TODO add your handling code here: new dashboard().setVisible(true); this.dispose(); }//GEN-LAST:event_mBerandaActionPerformed private void mPenggunaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mPenggunaActionPerformed // TODO add your handling code here: new user().setVisible(true); this.dispose(); }//GEN-LAST:event_mPenggunaActionPerformed private void mKendaraanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mKendaraanActionPerformed // TODO add your handling code here: new kendaraan().setVisible(true); this.dispose(); }//GEN-LAST:event_mKendaraanActionPerformed private void tabTerminalMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabTerminalMouseClicked // TODO add your handling code here: int row=tabTerminal.getSelectedRow(); String uId=tabTerminal.getModel().getValueAt(row,0).toString(); String query = "SELECT * FROM terrminal WHERE id="+uId+""; String cbkt = "Select kota from terminal where id="+uId+""; tIdTerminal.setText(tabTerminal.getModel().getValueAt(tabTerminal.getSelectedRow(),0).toString()); tTerminal.setText(tabTerminal.getModel().getValueAt(tabTerminal.getSelectedRow(),2).toString()); //tHarga.setText(tabTerminal.getModel().getValueAt(tabTerminal.getSelectedRow(),3).toString()); cbKota.setSelectedItem(tabTerminal.getModel().getValueAt(tabTerminal.getSelectedRow(),1).toString()); // String cmbox = model.getValueAt(tabTerminal.getSelectedRow(),1).toString(); // switch(cmbox){ // case "+"cbkt"+"; // cbKota.setSelectedItem(cbkt); // break; // } }//GEN-LAST:event_tabTerminalMouseClicked private void mLaporanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mLaporanActionPerformed // TODO add your handling code here: new laporan().setVisible(true); this.dispose(); }//GEN-LAST:event_mLaporanActionPerformed private void mLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mLogoutActionPerformed // TODO add your handling code here: new login().setVisible(true); this.dispose(); }//GEN-LAST:event_mLogoutActionPerformed /** * @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(kota.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(kota.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(kota.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(kota.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 kota().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bCariKota; private javax.swing.JButton bCariTerminal; private javax.swing.JButton bHapusKota; private javax.swing.JButton bHapusTerm; private javax.swing.JButton bRefreshKota; private javax.swing.JButton bRefreshTerminal; private javax.swing.JButton bResetKota; private javax.swing.JButton bResetTerm; private javax.swing.JButton bTambahKota; private javax.swing.JButton bTambahTerm; private javax.swing.JButton bUbahKota; private javax.swing.JButton bUbahTerm; private javax.swing.JComboBox<String> cbKota; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; 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.JMenu jMenu9; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JMenu laporan; private javax.swing.JMenuItem mBeranda; private javax.swing.JMenuItem mKendaraan; private javax.swing.JMenuItem mLaporan; private javax.swing.JMenuItem mLogout; private javax.swing.JMenuItem mPengguna; private javax.swing.JMenuItem mTransaksi; private javax.swing.JMenu menu; private javax.swing.JTextField tCariKota; private javax.swing.JTextField tCariTerminal; private javax.swing.JTextField tIdKota; private javax.swing.JTextField tIdTerminal; private javax.swing.JTextField tKota; private javax.swing.JTextField tTerminal; private javax.swing.JTable tabKota; private javax.swing.JTable tabTerminal; private javax.swing.JLabel texTgl; private javax.swing.JLabel textJam; // End of variables declaration//GEN-END:variables }
true
1c070781374fce54f6c40882cf2853f592fdeb91
Java
ivoelz/SpringAssignment
/src/Classes/SaleConsoleOutput.java
UTF-8
770
2.46875
2
[]
no_license
package Classes; import Interface.SalesInput; import Interface.SalesOutput; //import Interface.SalesReport; import Interface.ShippingPolicy; import java.util.List; public class SaleConsoleOutput { private final SalesInput input; private final SalesOutput output; //private SalesReport salesReport; private final ShippingPolicy shippingPolicy; public SaleConsoleOutput(SalesInput input, SalesOutput output, ShippingPolicy shippingPolicy) { this.input = input; this.output = output; this.shippingPolicy = shippingPolicy; } public void getReport() { List<Sale> saleList = input.getSales(shippingPolicy); for (Sale sale : saleList) { this.output.output(sale.toString()); } } }
true
f0dfb35a15a2b73587f2193b1ccf95541edbbbdb
Java
atambe/assessment
/src/main/java/com/sapient/assessment/domain/BPITimeResponse.java
UTF-8
1,350
2.5
2
[]
no_license
package com.sapient.assessment.domain; public class BPITimeResponse { private String updated; private String updatedISO; public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getUpdatedISO() { return updatedISO; } public void setUpdatedISO(String updatedISO) { this.updatedISO = updatedISO; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((updated == null) ? 0 : updated.hashCode()); result = prime * result + ((updatedISO == null) ? 0 : updatedISO.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BPITimeResponse other = (BPITimeResponse) obj; if (updated == null) { if (other.updated != null) return false; } else if (!updated.equals(other.updated)) return false; if (updatedISO == null) { if (other.updatedISO != null) return false; } else if (!updatedISO.equals(other.updatedISO)) return false; return true; } @Override public String toString() { return "BPITimeResponse [updated=" + updated + ", updatedISO=" + updatedISO + "]"; } }
true
562b456e2251cf057ba6dd7b773169b22963fed0
Java
geogeorgiou/employee_app
/src/main/java/com/login/employee/service/LoginUserServiceImpl.java
UTF-8
1,788
2.40625
2
[ "MIT" ]
permissive
package com.login.employee.service; import com.login.employee.domain.LoginUser; import com.login.employee.enums.RoleType; import com.login.employee.exception.DuplicateEmailException; import com.login.employee.mapper.LoginUserToLoginUserModel; import com.login.employee.model.LoginUserModel; import com.login.employee.repository.LoginUserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class LoginUserServiceImpl implements LoginUserService { @Autowired private LoginUserRepository userRepo; @Autowired private LoginUserToLoginUserModel mapper; @Autowired private PasswordEncoder encoder; @Override public LoginUserModel findByEmail(String email){ //needs some exception handling here if exists etc Optional<LoginUser> user = userRepo.findByEmail(email); return mapper.toLoginUserModel(user.get()); } @Override public LoginUser createUser(LoginUserModel userModel) { LoginUser loginUser = new LoginUser(); String userEmail = userModel.getEmail(); Optional<LoginUser> duplicateUsr = userRepo.findByEmail(userEmail); //throw exception if email already exists! if(duplicateUsr.isPresent()) throw new DuplicateEmailException(userEmail); loginUser.setEmail(userModel.getEmail()); loginUser.setRole(userModel.getRole() != null ? userModel.getRole() : RoleType.USER); //encrypt password loginUser.setPassword(encoder.encode(userModel.getPassword())); loginUser.setLogname(userModel.getLogName()); return userRepo.save(loginUser); } }
true
f9a7beb9f4da3c6d539153a29e831cabd89afe7a
Java
agsneutron/IPA-2016
/programacionJava/src/Polimorfismo/PoliDos.java
UTF-8
389
2.9375
3
[ "MIT" ]
permissive
package Polimorfismo; /** * Created by dds on 15/11/2016. */ public class PoliDos { public void musica(String musicaMeGusta,String bandaMusicaMeGusta){ System.out.println("Polimorfimo DOS"); System.out.println("A mi me gusta el " + musicaMeGusta); System.out.println("y la banda de " + musicaMeGusta + " que mas me gusta es " + bandaMusicaMeGusta); } }
true
b81598c734b75494d9efc519b7ee4e9feddd0944
Java
noah-wisch/bibliocache
/src/main/java/com/theironyard/entities/Book.java
UTF-8
5,673
3.25
3
[]
no_license
package com.theironyard.entities; import com.google.api.services.books.model.Volume; import javax.persistence.*; import java.text.BreakIterator; import java.util.List; import java.util.Locale; /** * Created by kelseynewman on 2/7/17. */ @Entity @Table(name = "books") public class Book { @Id @GeneratedValue Integer id; @Column(nullable = false) String title; @Column String author; @Column(nullable = false) String category; @Column(nullable = false) Integer readingLevel; @Column(length = 1000)//needed to increase length attribute of so that JPA would accept longer String value //algorithm would not produce accurate results with the standard default length of 255 String bookExcerpt; @Column String infoLink; public Book() { } public Book(Volume volume, User user) { this.title = volume.getVolumeInfo().getTitle(); List<String> authors = volume.getVolumeInfo().getAuthors(); if (authors != null && authors.size() > 0) { this.author = authors.get(0); } else { this.author = "Unknown";//returns "Unknown" if no author is listed to prevent NullPointerException } this.category = user.getCategory(); this.readingLevel = 1;//hard coded for books that do not have an excerpt to be evaluated this.infoLink = volume.getVolumeInfo().getInfoLink(); } public Book(String title, String author, String category, Integer readingLevel) { this.title = title; this.author = author; this.category = category; this.readingLevel = readingLevel; } public Book(Integer id, String title, String author, String category, Integer readingLevel) { this.id = id; this.title = title; this.author = author; this.category = category; this.readingLevel = readingLevel; } public String getInfoLink() { return infoLink; } public void setInfoLink(String infoLink) { this.infoLink = infoLink; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Integer getReadingLevel() { return readingLevel; } public void setReadingLevel(Integer readingLevel) { this.readingLevel = readingLevel; } public String getBookExcerpt() { return bookExcerpt; } public void setBookExcerpt(String bookExcerpt) { this.bookExcerpt = bookExcerpt; } /* Formula - Automated Readability Index Reading Level = 4.71(characters/words) + 0.5 (words/sentences) - 21.43 Always round up (cast as an int and add 1). Extract a passage from the book and find the number of characters, words and sentences in it to determine that book's approximate reading level. */ public static Integer readingLevelOfBook (Book book) { String paragraph = book.getBookExcerpt(); // String paragraph = new String(); //book.setReadingLevel( return (int)Math.ceil((4.71 * (charactersPresent(paragraph)/(double)wordsPresent(paragraph))) + (0.5 * (wordsPresent(paragraph)/sentencesPresent(paragraph))) - 21.43); } public static int charactersPresent(String paragraph) { return paragraph .replaceAll("\\p{P}", "")//removes all punctuation .replaceAll("\\s", "")//removes all white space .toCharArray().length;//adds remaining characters to a char array and finds the length (i.e. number of characters) } public static int wordsPresent (String paragraph) { return paragraph.split(" ").length - 1;//turns paragraph into an array of strings split on whitespace. //returns the number of elements in the words array (i.e. number of words in the paragraph) //subtracts one b/c the formula calls for the amount of white space in a paragraph } public static int sentencesPresent(String paragraph) { int sentences = 0; BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US); //breaks a piece of text into sentences according to the conventions of the english language iterator.setText(paragraph);//sets the paragraph as the text to be examined int lastIndex = iterator.first();//sets the last index of a sentence to the first boundary while (lastIndex != BreakIterator.DONE) {//while that index is not the last boundary in the sentence, do this: int firstIndex = lastIndex;//set last index to the first index of the next sentence lastIndex = iterator.next();//last index is now set to the next boundary if (lastIndex != BreakIterator.DONE) {//if the last boundary has not been reached paragraph.substring(firstIndex, lastIndex);//create a substring from the first to the last index of the current sentence sentences++;//increase count of sentences by one } } return sentences;//returns total number of sentences } }
true
4db567016ffe72d70e6a2e591569504839f942b3
Java
binsvivi/SyberUnifyId
/app/src/main/java/com/star/demo/service/Config.java
UTF-8
4,622
1.789063
2
[]
no_license
/* * Copyright (C) 2016. Beijing Yuan Xin Technology Co.,Ltd. All rights reserved. * Authors: * Zhao Dongshuang <zhaodongshuang@syberos.com> * * This software, including documentation, is protected by copyright controlled * by Beijing Yuan Xin Technology Co.,Ltd. All rights are reserved. */ //package com.syberos.systemupdate; package com.star.demo.service; import android.content.Context; import android.content.SharedPreferences; /** * Created by zhaodongshuang on 17-3-1. */ class Config { private static final String PREFERENCES_NAME = "CONFIGURATION_UNIFYID"; private static SharedPreferences preferences = Storage.Context().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); private static final String KEY_CONFIG_UDID = "KEY_CONFIG_UDID_OTA"; private static final String KEY_CONFIG_VERSION = "KEY_CONFIG_VERSION_OTA"; private static final String KEY_CONFIG_UNIFYID_KEY = "KEY_CONFIG_UNIFYID_KEY"; private static final String KEY_CONFIG_PRODUCT = "KEY_CONFIG_PRODUCT_OTA"; private static final String KEY_CONFIG_CHECK_UPDATE_URL = "KEY_CONFIG_CHECK_UPDATE_URL_OTA"; private static final String KEY_CONFIG_UPDATE_PATH = "KEY_CONFIG_UPDATE_PATH_OTA"; private static final String KEY_CONFIG_UPDATE_FILE_NAME = "KEY_CONFIG_UPDATE_FILE_NAME_OTA"; private static final String KEY_CONFIG_TEST_BUTTON_VISIBLE = "KEY_CONFIG_TEST_BUTTON_VISIBLE_OTA"; private static final String KEY_CONFIG_VERSION_SUFFIX_VISIBLE = "KEY_CONFIG_VERSION_SUFFIX_VISIBLE_OTA"; private static final String KEY_CONFIG_DOWNLOAD_URL = "KEY_CONFIG_DOWNLOAD_URL_OTA"; private static final String KEY_CONFIG_BATTERY_STATUS = "KEY_CONFIG_BATTERY_STATUS_OTA"; static String Udid() { // if (Utils.isDebugType()) { // return preferences.getString(KEY_CONFIG_UDID, ""); // } return ""; } static String configVersion() { if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_VERSION, ""); } return ""; } static String unifyidKey() { // if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_UNIFYID_KEY, ""); // } // return ""; } static void putUnifyidKey(String key) { // if (Utils.isDebugType()) { preferences.edit().putString(KEY_CONFIG_UNIFYID_KEY, key); // } // return ""; } static String Product() { if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_PRODUCT, ""); } return ""; } static String CheckUpdateUrl() { if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_CHECK_UPDATE_URL, "https://www.zoomte.cn"); } return "https://www.zoomte.cn"; } static String UploadUrl() { //if (Utils.isDebugType()) { // return preferences.getString(KEY_CONFIG_CHECK_UPDATE_URL, "https://www.zoomte.cn"); //} return "124.192.38.8:6060/upfiles"; } final private static String MiddleBranchCode = "_MM"; final private static String MiddleBranchSavePath = "/ssota"; final private static String NormalBranchSavePath = "/data/upgrade"; // static String UpdatePath() { // if (Utils.isDebugType()) { // if (Utils.versionSuffix().contains(MiddleBranchCode)) { // return preferences.getString(KEY_CONFIG_UPDATE_PATH, MiddleBranchSavePath); // } // return preferences.getString(KEY_CONFIG_UPDATE_PATH, NormalBranchSavePath); // } // if (Utils.versionSuffix().contains(MiddleBranchCode)) { // return MiddleBranchSavePath; // } // return NormalBranchSavePath; // } static String UpdateFileName() { if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_UPDATE_FILE_NAME, "update.zip"); } return "update.zip"; } static boolean TestButtonVisible() { return Utils.isDebugType() && preferences.getBoolean(KEY_CONFIG_TEST_BUTTON_VISIBLE, false); } static boolean VersionSuffixVisible() { return Utils.isDebugType() && preferences.getBoolean(KEY_CONFIG_VERSION_SUFFIX_VISIBLE, true); } static String DownloadUrl() { if (Utils.isDebugType()) { return preferences.getString(KEY_CONFIG_DOWNLOAD_URL, ""); } return ""; } static int batteryStatus() { if (Utils.isDebugType()) { return preferences.getInt(KEY_CONFIG_BATTERY_STATUS, Utils.NORMAL); } return Utils.NORMAL; } }
true
fb924b7f2de0c5e157a8df63493571880b5b0ccc
Java
MorphiaOrg/morphia
/core/src/main/java/dev/morphia/aggregation/codecs/stages/FillCodec.java
UTF-8
2,340
2.1875
2
[ "Apache-2.0" ]
permissive
package dev.morphia.aggregation.codecs.stages; import java.util.List; import java.util.Locale; import dev.morphia.aggregation.expressions.impls.Expression; import dev.morphia.aggregation.stages.Fill; import dev.morphia.aggregation.stages.Fill.Method; import dev.morphia.query.Sort; import org.bson.BsonWriter; import org.bson.codecs.EncoderContext; import static dev.morphia.aggregation.codecs.ExpressionHelper.array; import static dev.morphia.aggregation.codecs.ExpressionHelper.document; import static dev.morphia.aggregation.codecs.ExpressionHelper.expression; import static dev.morphia.aggregation.codecs.ExpressionHelper.value; public class FillCodec extends StageCodec<Fill> { @Override public Class<Fill> getEncoderClass() { return Fill.class; } @Override protected void encodeStage(BsonWriter writer, Fill fill, EncoderContext encoderContext) { document(writer, () -> { if (fill.partitionBy() != null) { expression(getDatastore(), writer, "partitionBy", fill.partitionBy(), encoderContext); } List<String> partitionByFields = fill.partitionByFields(); if (partitionByFields != null) { array(writer, "partitionByFields", () -> { partitionByFields.forEach(writer::writeString); }); } Sort[] sorts = fill.sortBy(); if (sorts != null) { document(writer, "sortBy", () -> { for (Sort sort : sorts) { writer.writeInt64(sort.getField(), sort.getOrder()); } }); } document(writer, "output", () -> { fill.fields().forEach((key, value) -> { if (value instanceof Expression) { document(writer, key, () -> { expression(getDatastore(), writer, "value", (Expression) value, encoderContext); }); } else if (value instanceof Fill.Method) { document(writer, key, () -> { value(writer, "method", ((Method) value).name().toLowerCase(Locale.ROOT)); }); } }); }); }); } }
true
a9e68db33b16ac5b318f3a0ff51c574ab6ca8d65
Java
nikitakyrpenko/steunje
/src/main/com/negeso/framework/command/SimpleCommand.java
UTF-8
1,024
2.1875
2
[]
no_license
/* * @(#)SimpleCommand.java Created on 04.02.2004 * * Copyright (c) 2004 Negeso Ukraine * * This software is the confidential and proprietary information of Negeso * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with Negeso. */ package com.negeso.framework.command; import org.apache.log4j.Logger; import com.negeso.framework.controller.ResponseContext; /** * Always returns result AbstractCommand#RESULT_SUCCESS. * Can be used with a View which does the real job. * * @version $Revision: 6$ * @author Stanislav Demchenko */ public class SimpleCommand extends AbstractCommand { private static Logger logger = Logger.getLogger(SimpleCommand.class); public ResponseContext execute() { logger.debug("+ -"); ResponseContext response = new ResponseContext(); response.setResultName(RESULT_SUCCESS); return response; } }
true
9dfe6c645a4a7a5487bf6652ba6b2cbe5207c4f9
Java
speedhawk1/CollectionTest
/src/javaLanguageLearning/SetTest.java
UTF-8
585
3.125
3
[]
no_license
package javaLanguageLearning; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Created by Administrator on 2017/6/8. */ public class SetTest { static Set collectBySet(String strTest){ String[] strTestArray = strTest.split(" "); return new HashSet(Arrays.asList(strTestArray)); } public static void main(String[] args) { String strTest = "mine is blue and the blue is mine."; StdOut.print(collectBySet(strTest) + "and" +"\t"+ collectBySet(strTest).size()); } }
true
bf52867a20b9b67c40fedde0a45b2d6b17a1481c
Java
cash2one/91
/zz91/ast1949-persist/src/main/java/com/ast/ast1949/persist/bbs/BbsUserProfilerDao.java
UTF-8
1,473
1.96875
2
[]
no_license
/** * Copyright 2011 ASTO. * All right reserved. * Created on 2011-6-28 */ package com.ast.ast1949.persist.bbs; import java.util.List; import com.ast.ast1949.domain.bbs.BbsUserProfilerDO; import com.ast.ast1949.dto.PageDto; import com.ast.ast1949.dto.bbs.BbsUserProfilerDto; /** * @author mays (mays@zz91.com) * * created on 2011-6-28 */ public interface BbsUserProfilerDao { public Integer queryIntegralByAccount(String account); public Integer countProfilerByAccount(String account); public Integer insertProfiler(BbsUserProfilerDO profiler); public List<BbsUserProfilerDO> queryTopByPostNum(Integer size); public Integer updatePostNumber(String account,Integer postNumber); public BbsUserProfilerDO queryProfilerOfAccount(String account); public Integer updateReplyCount(Integer replyCount,String account); /** * 判断是否存在此用户 * */ public Integer countUserProfilerByAccount(String accountName); public BbsUserProfilerDO queryUserByAccount(String accountName); public BbsUserProfilerDO queryUserByCompanyId(Integer companyId); /** * 查询最新用户 * */ public List<BbsUserProfilerDO> queryNewUser(Integer size); public List<BbsUserProfilerDO> queryByAdmin(BbsUserProfilerDto searchDto,PageDto<BbsUserProfilerDto> page); public Integer queryCountByAdmin(BbsUserProfilerDto searchDto); /** * 计算该积分排名 * @param integral * @return */ public Integer queryRank(Integer integral); }
true
bc46012c3fbf24db7be8e243dc0cbedbca8218d2
Java
I027369/lemonademouth
/src/main/java/com/moonshot/restaurant/entity/Order.java
UTF-8
3,917
2.125
2
[]
no_license
package com.moonshot.restaurant.entity; import java.time.OffsetDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity(name = "RestaurantOrder") public class Order { @Id @GeneratedValue(strategy=GenerationType.AUTO, generator="order_seq_gen") @SequenceGenerator(name="order_seq_gen", sequenceName="ORDER_SEQ") private Long id; @ManyToOne(fetch = FetchType.LAZY) @NotNull private Restaurant restaurant; @OneToOne @NotNull private AppUser appUser; @OneToOne private RestaurantTable restaurantTable; private String orderType; //mobile/table @Column(precision=10, scale=2) private float totalAmount; @Column(precision=10, scale=2) private float tax; @Column(precision=10, scale=2) private float subTotal; private String currency; private String status; // In-process/paid private OffsetDateTime timestamp; private String message; //create the orderitem in the context of order i.e first create order and later add order items // don't create order and order items together //@OneToMany (cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="order") //private List<OrderItem> item = new ArrayList<>(); public Order() { super(); // TODO Auto-generated constructor stub } public Order(Long id, Restaurant restaurant, AppUser appUser, RestaurantTable restaurantTable, String orderType, float totalAmount, String currency, String status, OffsetDateTime timestamp) { super(); this.id = id; this.restaurant = restaurant; this.appUser = appUser; this.restaurantTable = restaurantTable; this.orderType = orderType; this.totalAmount = totalAmount; this.currency = currency; this.status = status; this.timestamp = timestamp; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Restaurant getRestaurant() { return restaurant; } public void setRestaurant(Restaurant restaurant) { this.restaurant = restaurant; } public AppUser getAppUser() { return appUser; } public void setAppUser(AppUser appUser) { this.appUser = appUser; } public RestaurantTable getRestaurantTable() { return restaurantTable; } public void setRestaurantTable(RestaurantTable restaurantTable) { this.restaurantTable = restaurantTable; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public float getTotalAmount() { return totalAmount; } public void setTotalAmount(float totalAmount) { this.totalAmount = totalAmount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } public float getTax() { return tax; } public void setTax(float tax) { this.tax = tax; } public float getSubTotal() { return subTotal; } public void setSubTotal(float subTotal) { this.subTotal = subTotal; if (this.restaurant != null && this.restaurant.getTaxPercentage() > 0) { this.tax = (this.subTotal * this.restaurant.getTaxPercentage())/100; } this.totalAmount = this.subTotal + this.tax; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
true
e217453266da0accb60857040548ef36968eb299
Java
Rea2/HT2
/src/test/pages/PO_ManageJenkins.java
UTF-8
1,349
2.40625
2
[]
no_license
package pages; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * Created by Raik Yauheni on 10.12.2018. */ public class PO_ManageJenkins extends PO { @FindBy(xpath = "//*/dt[text()= 'Manage Users']") private WebElement dt; @FindBy(xpath = "//*/dd[text()= 'Create/delete/modify users that can log in to this Jenkins']") private WebElement dd; @FindBy(xpath = "//a/following::dt[text() = 'Manage Users']/ancestor::a") private WebElement linkWithDt_ManageUsers; public PO_ManageJenkins(WebDriver driver) { super(driver); // Провекрка того факта, что мы на верной странице. if ((!driver.getTitle().equals("Manage Jenkins [Jenkins]")) ) { throw new IllegalStateException("Wrong site page!"); } } // Провекрка того факта, что мы на верной странице. public boolean isDtExist()throws NoSuchElementException { return (isWebElementExist(dt)); } public boolean isDdExist() throws NoSuchElementException { return (isWebElementExist(dd)); } public WebElement getLinkWithDt_ManageUsers() { return linkWithDt_ManageUsers; } }
true
c09a2cda81a35fba163cbfd571f291ce058c5fbd
Java
catataw/Core-1
/src/org/safs/staf/embedded/HandleInterface.java
UTF-8
774
2.078125
2
[]
no_license
package org.safs.staf.embedded; import com.ibm.staf.STAFException; import com.ibm.staf.STAFResult; public interface HandleInterface { public void setHandleId(String handleId); public void register() throws STAFException; public String submit(String where, String handler, String request) throws STAFException; public STAFResult submit2(String where, String handler, String request); /** * @param target -- destination handle name for the message. * @param message -- the message to send. */ public STAFResult sendQueueMessage(String target, String message) throws STAFException; public STAFResult acceptQueueMessage(String message); public STAFResult getQueueMessage(int timeout); public int getHandle(); public void unRegister()throws STAFException; }
true
50372edd0b19d2e761aa343d82b9e3a29406d6df
Java
ryojikaji/school
/JP/Szwarc/Lab_5_zadanie_1.java
UTF-8
731
3.4375
3
[]
no_license
/* Zainicjuj zmienną typu double wartością 9,997 i przypisz jej wartość do zmiennej typu int, dokonując rzutowania. Wypisz otrzymay wynik. Zmienną z zadania 1 wypisz na ekran, dokonując rzutowania na typ int w momencie przekazania wartości do metody println. Dokonaj rzutowania liczby 100 na typ char, przekazując wartość do metody println. */ package Szwarc; public class Lab_5_zadanie_1 { public static void main(String[] args) { double zmienna = 9.997; int zmienna1; zmienna1 = (int)zmienna; System.out.print(zmienna1+"\n"); System.out.print((int)zmienna+"\n"); System.out.print((char)100+"\n"); } }
true
0e0106138ec5867d71396e0b5764675ed976378d
Java
lRENyaaa/RealPlugin
/src/fr/crafter/tickleman/realplugin/RealItemType.java
UTF-8
12,352
2.5
2
[]
no_license
package fr.crafter.tickleman.realplugin; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; //#################################################################################### RealItemType public class RealItemType { /** * Minecraft type identifier of item */ private String typeId; /** * Variant code of item, for items than can have variants * Equals ItemStack.getDurability() for items that can be damaged * Is null for non-applicable items */ private short variant; //------------------------------------------------------------------------------------- ItemStack public RealItemType(ItemStack itemStack) { this(itemStack.getType().name(), itemStack.getDurability()); } //------------------------------------------------------------------------------------- ItemStack public RealItemType(RealItemStack itemStack) { this(itemStack.getTypeId(), itemStack.getDurability()); } //-------------------------------------------------------------------------------------- ItemType public RealItemType(Material material) { this(material.name(), (short)0); } //-------------------------------------------------------------------------------------- ItemType public RealItemType(Material material, short variant) { this(material.name(), variant); } //-------------------------------------------------------------------------------------- ItemType public RealItemType(String typeId) { this(typeId, (short)0); } //-------------------------------------------------------------------------------------- ItemType public RealItemType(String typeId, short variant) { setTypeIdVariant(typeId, variant); } //----------------------------------------------------------------------------------- getMaterial public Material getMaterial() { return Material.valueOf(this.typeId); } //------------------------------------------------------------------------------------- getNameOf private static String getNameOf(Object object) { String name = null; if (object != null) { for (Method method : object.getClass().getDeclaredMethods()) { if ((method.getParameterTypes().length == 0)) { if (method.getReturnType().getName().equals("java.lang.String")) { //noinspection CatchMayIgnoreException try { name = (String) method.invoke(object); break; } catch (Exception e) { } } else if ( method.getName().equals("getParent") && (method.getParameterTypes().length == 0) ) { //noinspection CatchMayIgnoreException try { Object object2 = method.invoke(object); name = getNameOf(object2); if (name.length() > 0) { break; } } catch (Exception e) { } } } } if ((name == null) || (name.length() == 0)) { name = object.getClass().getName(); } while (name.contains(".")) { name = name.substring(name.indexOf(".") + 1); } if (name.length() > 5) { if (name.substring(0, 5).equalsIgnoreCase("block")) { name = name.substring(5); } else if (name.substring(0, 4).equalsIgnoreCase("item")) { name = name.substring(4); } } } return (name == null) ? "" : name; } //--------------------------------------------------------------------------------------- getName public String getName() { return getName(typeId); } //--------------------------------------------------------------------------------------- getName public static String getName(String typeId) { System.out.print("i Change " + typeId); Object object = Material.valueOf(typeId).toString(); String name = getNameOf(object); for (int i = 0; i < name.length(); i ++) { if ((name.charAt(i) >= 'A') && (name.charAt(i) <= 'Z')) { if (i == 0) { name = (char)(name.charAt(i) - 'A' + 'a') + name.substring(i + 1); } else if (name.charAt(i - 1) == ' ') { name = name.substring(0, i) + (char)(name.charAt(i) - 'A' + 'a') + name.substring(i + 1); } else { name = name.substring(0, i) + " " + (char)(name.charAt(i) - 'A' + 'a') + name.substring(i + 1); } } } System.out.println(" into " + name); return name; } //------------------------------------------------------------------------------------- getTypeId public String getTypeId() { return typeId; } //------------------------------------------------------------------------------------ getVariant public short getVariant() { return variant; } //--------------------------------------------------------------------------------------- isBlock public static boolean isBlock(String typeId) { return Material.valueOf(typeId).isBlock(); } //--------------------------------------------------------------------------------- parseItemType public static RealItemType parseItemType(String typeIdVariant) { if (typeIdVariant.contains(":")) { String[] split = typeIdVariant.split(":"); return new RealItemType(split[0], Short.parseShort(split[1])); } else { return new RealItemType(typeIdVariant); } } //------------------------------------------------------------------------- parseItemTypeKeywords public static RealItemType parseItemTypeKeywords(String[] keyWords) { try { return RealItemType.parseItemType(keyWords[0]); } catch (Exception e) { return RealItemType.parseItemType("0"); } } //------------------------------------------------------------------------------------- setTypeId public void setTypeId(String typeId) { setTypeIdVariant(typeId, variant); } //------------------------------------------------------------------------------------ isSameItem public boolean isSameItem(RealItemType itemType) { return (itemType.getTypeId().equals(getTypeId())) && (itemType.getVariant() == getVariant()); } //------------------------------------------------------------------------------ setTypeIdVariant public void setTypeIdVariant(String typeId, short variant) { this.typeId = typeId; setVariant(variant); } //------------------------------------------------------------------------------------ setVariant public void setVariant(short variant) { if (typeIdHasVariant(typeId)) { this.variant = ((variant < 0) ? 0 : variant); } else { this.variant = 0; } } //--------------------------------------------------------------------------------- toNamedString public String toNamedString() { return getName() + ((getVariant() != 0) ? " : " + getVariant() : ""); } //-------------------------------------------------------------------------------------- toString @Override public String toString() { return getTypeId() + ((getVariant() != 0) ? ":" + getVariant() : ""); } //------------------------------------------------------------------------------- typeIdHasDamage public static Boolean typeIdHasDamage(String typeId) { return !typeIdHasVariant(typeId); } //------------------------------------------------------------------------------ typeIdHasVariant public static Boolean typeIdHasVariant(String typeId) { return // those codes have variant : durability is an item variant instead of damage // - blocks (typeId.equals(Material.LEGACY_WOOD.name())) // 5 || (typeId.equals(Material.LEGACY_SAPLING.name())) // 6 || (typeId.equals(Material.LEGACY_LOG.name())) // 17 || (typeId.equals(Material.LEGACY_LEAVES.name())) // 18 || (typeId.equals(Material.LEGACY_LONG_GRASS.name())) // 31 || (typeId.equals(Material.LEGACY_WOOL.name())) // 35 || (typeId.equals(Material.LEGACY_DOUBLE_STEP.name())) // 43 || (typeId.equals(Material.LEGACY_STEP.name())) // 44 || (typeId.equals(Material.JUKEBOX.name())) // 84 || (typeId.equals(Material.LEGACY_SMOOTH_BRICK.name())) // 98 || (typeId.equals(Material.LEGACY_HUGE_MUSHROOM_1.name())) // 99 || (typeId.equals(Material.LEGACY_HUGE_MUSHROOM_2.name())) // 100 || (typeId.equals(Material.LEGACY_WOOD_DOUBLE_STEP.name())) // 125 || (typeId.equals(Material.LEGACY_WOOD_STEP.name())) // 126 || (typeId.equals(Material.LEGACY_COBBLE_WALL.name())) // 139 || (typeId.equals(Material.LEGACY_SKULL.name())) // 144 || (typeId.equals(Material.QUARTZ_BLOCK.name())) // 155 || (typeId.equals(Material.LEGACY_HARD_CLAY.name())) // 159 || (typeId.equals(Material.LEGACY_LEAVES_2.name())) // 161 || (typeId.equals(Material.LEGACY_LOG_2.name())) // 162 || (typeId.equals(Material.LEGACY_CARPET.name())) // 171 // - items || (typeId.equals(Material.COAL.name())) // 263 || (typeId.equals(Material.GOLDEN_APPLE.name())) // 322 || (typeId.equals(Material.LEGACY_RAW_FISH.name())) // 349 || (typeId.equals(Material.LEGACY_COOKED_FISH.name())) // 350 || (typeId.equals(Material.LEGACY_INK_SACK.name())) // 351 || (typeId.equals(Material.MAP.name())) // 358 || (typeId.equals(Material.POTION.name())) // 373 || (typeId.equals(Material.LEGACY_MONSTER_EGG.name())) // 383 || (typeId.equals(Material.LEGACY_BOOK_AND_QUILL.name())) // 386 || (typeId.equals(Material.LEGACY_SKULL_ITEM.name())) // 397 ; } //------------------------------------------------------------------------------- typeIdMaxDamage public static short typeIdMaxDamage(String typeId) { if (typeIdHasVariant(typeId)) { return 0; } else if (isBlock(typeId)) { /* // this could be easily broken on bukkit next updates, // but I mean that blocks are never traded with a damage value, as they are // damaged only when you hit them, and are never damaged when in inventories //noinspection CatchMayIgnoreException,TryWithIdenticalCatches try { Field strength = Block.class.getField("durability"); if (!strength.isAccessible()) { strength.setAccessible(true); } // TODO Check if e() is the right replacement for getById[] return (short) Math.round(strength.getDouble(Block.b(typeId))); } catch (IllegalArgumentException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (NoSuchFieldException e) { } System.out.println("default damage 128 for item id " + typeId); */ return 128; } else { Material material = Material.getMaterial(typeId); return (material == null) ? 0 : material.getMaxDurability(); } } //-------------------------------------------------------------------------------- typeIdVariants public static short[] typeIdVariants(RealItemType parseItemType) { if ( parseItemType.typeId.equals(Material.LEGACY_LOG.name()) || parseItemType.typeId.equals(Material.LEGACY_LEAVES.name()) || parseItemType.typeId.equals(Material.LEGACY_SAPLING.name()) ) { return new short[]{0, 1, 2, 3, 4, 5, 6, 7}; } else if ( parseItemType.typeId.equals(Material.LEGACY_DOUBLE_STEP.name()) || parseItemType.typeId.equals(Material.LEGACY_STEP.name()) ) { return new short[]{0, 1, 2, 3, 4, 5, 6}; } else if ( parseItemType.typeId.equals(Material.LEGACY_WOOL.name()) || parseItemType.typeId.equals(Material.LEGACY_INK_SACK.name()) ) { return new short[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; } else if (parseItemType.typeId.equals(Material.COAL.name())) { return new short[]{0, 1}; } else if (parseItemType.typeId.equals(Material.POTION.name())) { return new short[]{ 0, 16, 32, 64, 8192, 8193, 8257, 8225, 8194, 8258, 8226, 8195, 8259, 8197, 8229, 8201, 8265, 8233, 8196, 8260, 8228, 8200, 8264, 8202, 8266, 8204, 8236, 16384, 16385, 16449, 16417, 16386, 16450, 16418, 16387, 16451, 16389, 16421, 16393, 16457, 16425, 16388, 16452, 16420, 16392, 16456, 16394, 16458, 16396, 16428 }; } else if (parseItemType.typeId.equals(Material.LEGACY_MONSTER_EGG.name())) { return new short[]{ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 94, 95, 96, 97, 98, 120 }; } else { return new short[]{}; } } }
true
7f09ffd69ab18d5e876e82c39128003437ee97ce
Java
qwerasdfzxcvtgbyh/jiaogui_datacollect
/service-core/src/main/java/com/qmtec/servicecore/dao/TbDBSMapper.java
UTF-8
3,925
1.890625
2
[]
no_license
package com.qmtec.servicecore.dao; import com.qmtec.servicecore.entity.TbDBS; import com.qmtec.servicecore.entity.example.TbDBSExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TbDBSMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ long countByExample(TbDBSExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int deleteByExample(TbDBSExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int deleteByPrimaryKey(Long dbId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int insert(TbDBS record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int insertSelective(@Param("record") TbDBS record, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ TbDBS selectOneByExample(TbDBSExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ TbDBS selectOneByExampleSelective(@Param("example") TbDBSExample example, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ List<TbDBS> selectByExampleSelective(@Param("example") TbDBSExample example, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ List<TbDBS> selectByExample(TbDBSExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ TbDBS selectByPrimaryKeySelective(@Param("dbId") Long dbId, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ TbDBS selectByPrimaryKey(Long dbId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int updateByExampleSelective(@Param("record") TbDBS record, @Param("example") TbDBSExample example, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int updateByExample(@Param("record") TbDBS record, @Param("example") TbDBSExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int updateByPrimaryKeySelective(@Param("record") TbDBS record, @Param("selective") TbDBS.Column ... selective); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table DBS * * @mbg.generated */ int updateByPrimaryKey(TbDBS record); }
true
8a2122149e30ef60bd5012c195467d277688a490
Java
Bungeefan/Minecraft-Plugins
/BungeeSystem/src/me/bungeefan/commands/PingCMD.java
WINDOWS-1250
1,215
2.625
3
[ "MIT" ]
permissive
package me.bungeefan.commands; import me.bungeefan.BungeeSystem; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; public class PingCMD extends Command { private BungeeSystem instance; public PingCMD(BungeeSystem instance, String name) { super(name); this.instance = instance; } public void execute(CommandSender cs, String[] args) { if (args.length == 0) { if (cs instanceof ProxiedPlayer) { ProxiedPlayer p = (ProxiedPlayer) cs; p.sendMessage(instance.prefix + "7Dein Ping8\u00BB e" + p.getPing() + "ms"); } else { cs.sendMessage(instance.sendausgabe("Allgemein.KeinSpieler")); } } else if (args.length == 1) { ProxiedPlayer player = ProxyServer.getInstance().getPlayer(args[0]); if (player != null) { cs.sendMessage(instance.prefix + player.getDisplayName() + "7's 7Ping 8\u00BB e" + player.getPing() + "ms"); } else { cs.sendMessage(instance.prefix + "cDer Spieler e" + args[0] + " cist nicht online."); } } else { cs.sendMessage(instance.prefix + "cDieser Befehl existiert nicht."); } } }
true
4e000257dee6d66ceb3a88244edf54484d84be7c
Java
jimmy-rojas/StudentGeolocation
/src/test/java/com/organization/student_geolocation/core/ClassroomUtilTest.java
UTF-8
2,773
2.59375
3
[]
no_license
package com.organization.student_geolocation.core; import com.organization.student_geolocation.core.model.Classroom; import com.organization.student_geolocation.core.model.Student; import java.util.ArrayList; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; public class ClassroomUtilTest { @Test public void scenario1() { List<Student> studentList = new ArrayList<Student>(){{ add(new Student("John Wilson", 34.069149, -118.442639)); add(new Student("Jane Graham", 34.069601, -118.441862)); add(new Student("Pam Bam", 34.071513, -118.441181)); }}; List<Classroom> classroomList = new ArrayList<Classroom>(){{ add(new Classroom("Principles of computational geo-location analysis", 34.069140, -118.442689)); add(new Classroom("Sedimentary Petrology", 34.069585, -118.441878)); add(new Classroom("Introductory Psychobiology", 34.069742, -118.441312)); add(new Classroom("Art of Listening", 34.070223, -118.440193)); add(new Classroom("Art History", 34.071528, -118.441211)); }}; List<Student> expectedStudentList = new ArrayList<Student>(){{ add(new Student("John Wilson", 34.069149, -118.442639)); add(new Student("Jane Graham", 34.069601, -118.441862)); add(new Student("Pam Bam", 34.071513, -118.441181)); }}; List<Student> result = ClassroomUtil.studentsInClasses(studentList, classroomList); assert(result.size() == expectedStudentList.size()); assertTrue(result.containsAll(expectedStudentList)); } @Test public void scenario2() { List<Student> studentList = new ArrayList<Student>(){{ add(new Student("John Wilson", 34.069849, -118.443539)); add(new Student("Jane Graham", 34.069901, -118.441562)); add(new Student("Pam Bam", 34.071523, -118.441171)); }}; List<Classroom> classroomList = new ArrayList<Classroom>(){{ add(new Classroom("Principles of computational geo-location analysis", 34.069140, -118.442689)); add(new Classroom("Sedimentary Petrology", 34.069585, -118.441878)); add(new Classroom("Introductory Psychobiology", 34.069742, -118.441312)); add(new Classroom("Art of Listening", 34.070223, -118.440193)); add(new Classroom("Art History", 34.071528, -118.441211)); }}; List<Student> expectedStudentList = new ArrayList<Student>(){{ add(new Student("Pam Bam", 34.071523, -118.441171)); }}; List<Student> result = ClassroomUtil.studentsInClasses(studentList, classroomList); assert(result.size() == expectedStudentList.size()); assertTrue(result.containsAll(expectedStudentList)); } @Test (expected = IllegalArgumentException.class) public void scenario3_secure_NPE() { ClassroomUtil.studentsInClasses(null, null); } }
true
377d7bf849f4dc63ad2ba360a26eaec4384cafa9
Java
6MrZou6/SSM
/Online_Pharmacy/src/main/java/com/it/zyx/service/OrdersService.java
UTF-8
509
1.960938
2
[]
no_license
package com.it.zyx.service; import com.it.zyx.entity.Medicine; import com.it.zyx.entity.Order; import com.it.zyx.entity.OrderDetail; import java.util.List; import java.util.Map; public interface OrdersService { /*Map<Integer,Integer> medicines_num是以medicine的id为key,数量为value的map*/ void addOrder(Order order, List<Integer> mids, Map<Integer,Integer> medicines_num); List<Order> findAll(); List<OrderDetail> findOrderDetailByOid(int oid); Order findOrderById(int id); }
true
b4404b27e8b1665e8bc251070d681c3122c837dc
Java
LuisEnri2000/lab6_LuisEnriquez
/src/adminSerie.java
UTF-8
3,022
2.953125
3
[ "MIT" ]
permissive
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; class adminSerie { ArrayList<Serie> listaSeries = new ArrayList(); File archivo = null; public adminSerie() { } public adminSerie(String ruta) { archivo = new File(ruta); } public ArrayList<Serie> getListaSeries() { return listaSeries; } public void setListaSeries(ArrayList<Serie> listaSeries) { this.listaSeries = listaSeries; } public File getArchivo() { return archivo; } public void setArchivo(File archivo) { this.archivo = archivo; } public void escribirArchivo() throws IOException { FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(archivo, false); bw = new BufferedWriter(fw); for (Serie t : listaSeries) { bw.write(t.getNombre() + ";"); bw.write(t.getDuracion() + ";"); bw.write(t.getCateg() + ";"); bw.write(t.getActores() + ";"); bw.write(t.getTemp() + ";"); bw.write(t.getProd() + ";"); bw.write(t.getIdioma() + ";"); bw.write(t.isDob() + ";"); bw.write(t.isSub() + ""); bw.newLine(); } bw.flush(); } catch (Exception e) { } bw.close(); fw.close(); } public void cargarArchivo() { File f = null; FileReader fr = null; BufferedReader br = null; listaSeries = new ArrayList(); if (archivo.exists()) { try { f = new File("./series.txt"); fr = new FileReader(f); br = new BufferedReader(fr); boolean log = false; String l; while ((l = br.readLine()) != null) { String[] al = l.split(";"); String nombre = al[0]; int duracion = Integer.parseInt( al[1]); String categ = al[2]; String actores = al[3]; int temp = Integer.parseInt(al[4]); String compa = al[5]; String idioma = al[6]; boolean dob = al[7].equals("true")? true:false; boolean sub = al[8].equals("true")? true:false; Serie s = new Serie(nombre,duracion,categ,actores,temp,compa,idioma,dob,sub); listaSeries.add(s); } br.close(); fr.close(); } catch (Exception e) { } } } }
true
32e54a4f8480fee279e10f137647ac3215710250
Java
Scofield-Zhang/recode
/app/src/main/java/com/example/myapplication/activity/MainActivity.java
UTF-8
39,934
1.75
2
[]
no_license
package com.example.myapplication.activity; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.opengl.GLES20; import android.opengl.Matrix; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Choreographer; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.myapplication.R; import com.example.myapplication.opengl.AspectFrameLayout; import com.example.myapplication.opengl.CameraUtils; import com.example.myapplication.opengl.CircularEncoder; import com.example.myapplication.opengl.Drawable2d; import com.example.myapplication.opengl.EglCore; import com.example.myapplication.opengl.GlUtil; import com.example.myapplication.opengl.ScaledDrawable2d; import com.example.myapplication.opengl.Sprite2d; import com.example.myapplication.opengl.Texture2dProgram; import com.example.myapplication.opengl.TextureMovieEncoder2; import com.example.myapplication.opengl.VideoEncoderCore; import com.example.myapplication.opengl.WindowSurface; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, SeekBar.OnSeekBarChangeListener, AdapterView.OnItemSelectedListener, View.OnClickListener, SurfaceTexture.OnFrameAvailableListener , Choreographer.FrameCallback{ public static final String TAG = "MainActivity"; private SurfaceView cameraOnTextureSurfaceView; private TextView tfcCameraParamsText; private TextView tfcRectSizeText; private TextView tfcZoomAreaText; private TextView tfcZoomLabelText; private SeekBar tfcZoomSeekbar; private TextView tfcSizeLabelText; private SeekBar tfcSizeSeekbar; private TextView tfcRotateLabelText; private SeekBar tfcRotateSeekbar; private SurfaceHolder holder; // holder 赋值 private SurfaceHolder sSurfaceHolder; private boolean mFileSaveInProgress; private int mCameraPreviewWidth, mCameraPreviewHeight; private float mCameraPreviewFps; private int mRectWidth, mRectHeight; private int mZoomWidth, mZoomHeight; private int mRotateDeg; private static final int DEFAULT_SIZE_PERCENT = 50;// private static final int DEFAULT_ZOOM_PERCENT = 0; private static final int DEFAULT_ROTATE_PERCENT = 0; private MainHandler mHandler; private RenderThread mRenderThread; private static final int REQ_CAMERA_WIDTH = 1280; private static final int REQ_DESIRED_FPS = 30; private static final int REQ_CAMERA_HEIGHT = 720; private Button toggleRecording; private Spinner spinner; private boolean mRecordingEnabled = false; // controls button state private Camera mCamera; private CameraHandler mCameraHandler; private float mSecondsOfVideo; private File mOutputFile; private CircularEncoder mCircEncoder; @Override //当进度发生改变的时候 public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mRenderThread == null) { return; } RenderHandler handler = mRenderThread.getHandler(); if (seekBar == tfcZoomSeekbar) { handler.sendZoomValue(progress); } else if (seekBar == tfcSizeSeekbar) { handler.sendSizeValue(progress); } else if (seekBar == tfcRotateSeekbar) { handler.sendRotateValue(progress); } else { throw new RuntimeException("unknown seek bar"); } handler.sendRedraw(); } @Override //开始跟踪拖到的时候 public void onStartTrackingTouch(SeekBar seekBar) { } @Override //当用户结束对滑块滑动时,调用该方法 public void onStopTrackingTouch(SeekBar seekBar) { } @Override // 解析手势触摸事件 public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_DOWN: if (mRenderThread != null) { RenderHandler handler = mRenderThread.getHandler(); handler.sendPosition((int) x, (int) y); } break; default: break; } return true; } private void releaseCamera() { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Spinner spinner = (Spinner) parent; // 获取选择的位置 final int selectedItemPosition = spinner.getSelectedItemPosition(); /*cameraOnTextureSurfaceView.queueEvent(new Runnable() { @Override public void run() { // notify the renderer that we want to change the encoder's state mRenderer.changeFilterMode(selectedItemPosition); } });*/ } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public void onClick(View v) { RenderHandler rh = mRenderThread.getHandler(); if (rh != null) { mRecordingEnabled = !mRecordingEnabled; updateControls(); rh.setRecordingEnabled(mRecordingEnabled); Toast.makeText(this,"mRecordingEnabled",Toast.LENGTH_LONG).show(); } } @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { //cameraOnTextureSurfaceView.requestRender(); } @Override public void doFrame(long frameTimeNanos) { } /** * 渲染线程助手 */ private class RenderHandler extends Handler { private static final int MSG_SURFACE_AVAILABLE = 0; private static final int MSG_SURFACE_CHANGED = 1; private static final int MSG_SURFACE_DESTROYED = 2; private static final int MSG_SHUTDOWN = 3; private static final int MSG_FRAME_AVAILABLE = 4; private static final int MSG_ZOOM_VALUE = 5; private static final int MSG_SIZE_VALUE = 6; private static final int MSG_ROTATE_VALUE = 7; private static final int MSG_POSITION = 8; private static final int MSG_REDRAW = 9; private static final int MSG_RECORDING_ENABLED = 10; private static final int MSG_RECORD_METHOD = 11; // 我们不需要一个软引用,在轮询器消失的时候 但是这个不影响 private WeakReference<RenderThread> renderThreadWeakReference; public RenderHandler(RenderThread rt) { renderThreadWeakReference = new WeakReference<>(rt); } /** * Sends the "surface available" message. If the surface was newly created (i.e. * this is called from surfaceCreated()), set newSurface to true. If this is * being called during Activity startup for a previously-existing surface, set * newSurface to false. * <p> * The flag tells the caller whether or not it can expect a surfaceChanged() to * arrive very soon. * <p> * Call from UI thread. * 如果是刚创建的就是1 如果是activity启动期间被调用的以前就存在的就是0 * * @param holder * @param newSurface */ public void sendSurfaceAvailable(SurfaceHolder holder, boolean newSurface) { sendMessage(obtainMessage(MSG_SURFACE_AVAILABLE, newSurface ? 1 : 0, 0, holder)); } /** * 发送surface发生变化的消息 * * @param format * @param width * @param height */ public void sendSurfaceChanged(@SuppressWarnings("unused") int format, int width, int height) { // 忽略format sendMessage(obtainMessage(MSG_SURFACE_CHANGED, width, height)); } /** * 发送surface销毁的消息 */ public void sendSurfaceDestroyed() { sendMessage(obtainMessage(MSG_SURFACE_DESTROYED)); } /** * 同上 */ public void sendShutdown() { sendMessage(obtainMessage(MSG_SHUTDOWN)); } /** * 发送surface available 的消息 */ public void sendFrameAvailable() { sendMessage(obtainMessage(MSG_FRAME_AVAILABLE)); } /** * 发送 焦距变化的消息 */ public void sendZoomValue(int progress) { sendMessage(obtainMessage(MSG_ZOOM_VALUE, progress, 0)); } /** * 发送尺寸发生变的消息 */ public void sendSizeValue(int progress) { sendMessage(obtainMessage(MSG_SIZE_VALUE, progress, 0)); } /** * @param progress */ public void sendRotateValue(int progress) { sendMessage(obtainMessage(MSG_ROTATE_VALUE, progress, 0)); } /** * 位置消息 * * @param x * @param y */ public void sendPosition(int x, int y) { sendMessage(obtainMessage(MSG_POSITION, x, y)); } public void sendRedraw() { sendMessage(obtainMessage(MSG_REDRAW)); } public void setRecordingEnabled(boolean enabled) { sendMessage(obtainMessage(MSG_RECORDING_ENABLED, enabled ? 1 : 0, 0)); } public void setRecordMethod(int recordMethod) { sendMessage(obtainMessage(MSG_RECORD_METHOD, recordMethod, 0)); } @Override public void handleMessage(Message msg) { int what = msg.what; RenderThread renderThread = renderThreadWeakReference.get(); if (renderThread == null) { return; } switch (what) { case MSG_SURFACE_AVAILABLE: renderThread.surfaceAvailable((SurfaceHolder) msg.obj, msg.arg1 != 0); break; case MSG_SURFACE_CHANGED: renderThread.surfaceChanged(msg.arg1, msg.arg2); break; case MSG_SURFACE_DESTROYED: renderThread.surfaceDestroy(); break; case MSG_SHUTDOWN: renderThread.shutDown(); break; case MSG_FRAME_AVAILABLE: renderThread.frameAvailable(); break; case MSG_ZOOM_VALUE: renderThread.setZoom(msg.arg1); break; case MSG_SIZE_VALUE: renderThread.setSize(msg.arg1); break; case MSG_ROTATE_VALUE: renderThread.setRotate(msg.arg1); break; case MSG_POSITION: renderThread.setPosition(msg.arg1, msg.arg2); break; case MSG_REDRAW: renderThread.draw(); break; case MSG_RECORDING_ENABLED: renderThread.setRecordingEnabled(msg.arg1 != 0); break; case MSG_RECORD_METHOD: renderThread.setRecordMethod(msg.arg1); break; default: throw new RuntimeException("unknown message"); } } } /** * 渲染线程 * 实现侦听器的接口 */ private class RenderThread extends Thread implements SurfaceTexture.OnFrameAvailableListener { private final Sprite2d[] mEdges; private final SurfaceHolder mSurfaceHolder; private int mCameraPreviewWidth, mCameraPreviewHeight; private MainHandler mMainHandler; private volatile RenderHandler mHandler; // 锁 private Object mStartLock = new Object(); //准备的状态 private boolean mReady = false; private EglCore mEglCore; private WindowSurface mWindowSurface; private Texture2dProgram mTexProgram; private final ScaledDrawable2d mRectDrawable = new ScaledDrawable2d(Drawable2d.Prefab.RECTANGLE); private final Sprite2d mRect; private int mWindowSurfaceWidth, mWindowSurfaceHeight; private float mPosY, mPosX; private float[] mDisplayProjectionMatrix; private float mSizePercent = DEFAULT_SIZE_PERCENT; private float mZoomPercent = DEFAULT_ZOOM_PERCENT; private float mRotePercent = DEFAULT_ROTATE_PERCENT; private SurfaceTexture mCameraTexture; private Rect mVideoRect; private WindowSurface mInputWindowSurface; private int mRecordMethod; private boolean mRecordingEnabled; private TextureMovieEncoder2 mVideoEncoder; // 通过构造方法将MainHandler 传过来 public RenderThread(SurfaceHolder holder, MainHandler mHandler, File outputFile) { mMainHandler = mHandler; mSurfaceHolder = holder; mOutputFile = outputFile; mVideoRect = new Rect(); mDisplayProjectionMatrix = new float[16]; Matrix.setIdentityM(mDisplayProjectionMatrix, 0); mRect = new Sprite2d(mRectDrawable); mEdges = new Sprite2d[4]; } @Override public void run() { super.run(); //子线程创建轮询器对消息队列进行轮询 Looper.prepare(); //创建一个线程助手在线程准备好之前 mHandler = new RenderHandler(this); synchronized (mStartLock) { mReady = true; mStartLock.notify();//如果当前的线程不是自己的 } // Prepare EGL and open the camera before we start handling messages. // 在处理消息之前 准备EGL 打开相机 // mEglCore = new EglCore(newSharedContext, EglCore.FLAG_RECORDABLE); mEglCore = new EglCore(null, EglCore.FLAG_RECORDABLE); openCamera(REQ_CAMERA_WIDTH, REQ_CAMERA_HEIGHT, REQ_DESIRED_FPS); //开始轮询 //Constructor flag: surface must be recordable. This discourages EGL from using a pixel //format that cannot be converted efficiently to something usable by the video encoder. Looper.loop(); // 释放相机 releaseCamera(); releaseGl(); mEglCore.release(); synchronized (mStartLock) { mReady = false; } } public void surfaceAvailable(SurfaceHolder holder, boolean newSurface) { Surface surface = holder.getSurface(); mWindowSurface = new WindowSurface(mEglCore, surface, false); mWindowSurface.makeCurrent(); mTexProgram = new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT); int textureId = mTexProgram.createTextureObject(); mCameraTexture = new SurfaceTexture(textureId); mRect.setTexture(textureId); if (!newSurface) { mWindowSurfaceWidth = mWindowSurface.getWidth(); mWindowSurfaceHeight = mWindowSurface.getHeight(); finishSurfaceSetup(); } mCameraTexture.setOnFrameAvailableListener(this); } private void setRecordMethod(int recordMethod) { Log.d(TAG, "RT: setRecordMethod " + recordMethod); mRecordMethod = recordMethod;} /** * 设置完成 */ private void finishSurfaceSetup() { int width = mWindowSurfaceWidth; int height = mWindowSurfaceHeight; // Use full window. GLES20.glViewport(0, 0, width, height); // Simple orthographic projection, with (0,0) in lower-left corner. Matrix.orthoM(mDisplayProjectionMatrix, 0, 0, width, 0, height, -1, 1); // Default position is center of screen. mPosX = width / 2.0f; mPosY = height / 2.0f; updateGeometry(); try { // 设置纹理 mCamera.setPreviewTexture(mCameraTexture); } catch (IOException e) { throw new RuntimeException(e); } //开始预览 mCamera.startPreview(); } /** * Updates the geometry of mRect, based on the size of the window and the current * values set by the UI. * 更新几何 */ private void updateGeometry() { int width = mWindowSurfaceWidth; int height = mWindowSurfaceHeight; int min = Math.min(width, height); float scaled = min * (mSizePercent / 100.0f) * 1.25f; // Size float cameraAspect = (float) mCameraPreviewWidth / mCameraPreviewHeight; int newWidth = Math.round(scaled * cameraAspect); int newHeight = Math.round(scaled); // 变焦 float zoomFactor = 1.0f - (mZoomPercent / 100f); // 设置默认旋转的角度 int rotateAngle = Math.round(360 * (mRotePercent / 100f)); // 设置初始角度 mRect.setPosition(mPosX, mPosY); // 设置旋转角 mRect.setRotation(rotateAngle); // 设置缩放大小 mRect.setScale(newWidth, newHeight); // 变焦 mRectDrawable.setScale(zoomFactor); //消息发送到主线程 mMainHandler.sendRectSize(newWidth, newHeight); mMainHandler.sendZoomArea(Math.round(mCameraPreviewWidth * zoomFactor), Math.round(mCameraPreviewHeight * zoomFactor)); mMainHandler.sendRotateAngle(rotateAngle); } private void releaseGl() { GlUtil.checkGlError("releaseGl start"); if (mWindowSurface != null) { mWindowSurface.release(); mWindowSurface = null; } if (mTexProgram != null) { mTexProgram.release(); mTexProgram = null; } GlUtil.checkGlError("release error"); mEglCore.makeNothingCurrent(); } private void openCamera(int desiredWidth, int desiredHeight, int desiredFps) { // 对相机进行非空判断 if (mCamera != null) { throw new RuntimeException("相机已经初始化完成"); } Camera.CameraInfo info = new Camera.CameraInfo(); //获取相机摄像头的数量 int numberOfCameras = Camera.getNumberOfCameras(); //是否是前置摄像头 如果是就打开 for (int i = 0; i < numberOfCameras; i++) { Camera.getCameraInfo(i, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { mCamera = Camera.open(i); break; } } // 如果相机为空就打开 if (mCamera == null) { Log.d("onFrameAvailable", "openCamera: " + numberOfCameras); mCamera = Camera.open(); } if (mCamera == null) { throw new RuntimeException("不能开启相机"); } Camera.Parameters parameters = mCamera.getParameters(); CameraUtils.choosePreviewSize(parameters, desiredWidth, desiredHeight); int thousandFps = CameraUtils.chooseFixedPreviewFps(parameters, desiredFps * 1000); //是否设置相机提示音 parameters.setRecordingHint(true); //设置相机的参数 mCamera.setParameters(parameters); // 设置帧数的范围 int[] fpsRange = new int[2]; // 获取预览的尺寸 Camera.Size previewSize = parameters.getPreviewSize(); // 获取帧率的范围 parameters.getPreviewFpsRange(fpsRange); String previewFacts = previewSize.width + "x" + previewSize.height; if (fpsRange[0] == fpsRange[1]) { previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps"; } else { previewFacts += " @[" + (fpsRange[0] / 1000.0) + "-" + (fpsRange[1] / 1000.0) + "]fps"; } mCameraPreviewWidth = previewSize.width; mCameraPreviewHeight = previewSize.height; // 讲相机的参数发送的主线程 mMainHandler.sendCameraParams(mCameraPreviewWidth, mCameraPreviewHeight, thousandFps / 1000.0f); } /** * 返回线程助手 * * @return */ public RenderHandler getHandler() { return mHandler; } /** * 处理surface变化信息 * * @param width * @param height */ public void surfaceChanged(int width, int height) { mWindowSurfaceWidth = width; mWindowSurfaceHeight = height; finishSurfaceSetup(); } /** * 线程等待知道UI线程的调用 */ public void waitUntilReady() { synchronized (mStartLock) { while (!mReady) { try { mStartLock.wait(); } catch (InterruptedException e) { //e.printStackTrace(); } } } } /** * 停止 */ public void shutDown() { Looper.myLooper().quit(); } /** * 处理销毁消息 */ public void surfaceDestroy() { releaseGl(); } /** * 处理从相机传来的帧数据 */ public void frameAvailable() { mCameraTexture.updateTexImage();//更新图像 draw(); } private void draw() { GlUtil.checkGlError("draw start"); GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); mRect.draw(mTexProgram, mDisplayProjectionMatrix); // Use this to "publish" the current frame. mWindowSurface.swapBuffers(); GlUtil.checkGlError("draw error"); } public void setZoom(int percent) { mZoomPercent = percent; updateGeometry(); } public void setRotate(int progress) { mRotePercent = progress; updateGeometry(); } public void setSize(int progress) { mSizePercent = progress; updateGeometry(); } public void setPosition(int x, int y) { mPosX = x; mPosY = mWindowSurfaceHeight - y; updateGeometry(); } @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { mHandler.sendFrameAvailable(); } public void setRecordingEnabled(boolean recordingEnabled) { if (recordingEnabled == mRecordingEnabled) { return; } if (recordingEnabled) { startEncoder(); } else { stopEncoder(); } mRecordingEnabled = recordingEnabled; } private void stopEncoder() { if (mVideoEncoder != null) { mVideoEncoder.stopRecording(); // TODO: wait (briefly) until it finishes shutting down so we know file is // complete, or have a callback that updates the UI mVideoEncoder = null; } if (mInputWindowSurface != null) { mInputWindowSurface.release(); mInputWindowSurface = null; } } private void startEncoder() { // Record at 1280x720, regardless of the window dimensions. The encoder may // explode if given "strange" dimensions, e.g. a width that is not a multiple // of 16. We can box it as needed to preserve dimensions. final int BIT_RATE = 4000000; // 4Mbps final int VIDEO_WIDTH = 1280; final int VIDEO_HEIGHT = 720; int windowWidth = mWindowSurface.getWidth(); int windowHeight = mWindowSurface.getHeight(); float windowAspect = (float) windowHeight / (float) windowWidth; int outWidth, outHeight; if (VIDEO_HEIGHT > VIDEO_WIDTH * windowAspect) { // limited by narrow width; reduce height outWidth = VIDEO_WIDTH; outHeight = (int) (VIDEO_WIDTH * windowAspect); } else { // limited by short height; restrict width outHeight = VIDEO_HEIGHT; outWidth = (int) (VIDEO_HEIGHT / windowAspect); } int offX = (VIDEO_WIDTH - outWidth) / 2; int offY = (VIDEO_HEIGHT - outHeight) / 2; mVideoRect.set(offX, offY, offX + outWidth, offY + outHeight); Log.d("Adjusting", "Adjusting window " + windowWidth + "x" + windowHeight + " to +" + offX + ",+" + offY + " " + mVideoRect.width() + "x" + mVideoRect.height()); VideoEncoderCore encoderCore; try { encoderCore = new VideoEncoderCore(VIDEO_WIDTH, VIDEO_HEIGHT, BIT_RATE, mOutputFile); } catch (IOException ioe) { throw new RuntimeException(ioe); } mInputWindowSurface = new WindowSurface(mEglCore, encoderCore.getInputSurface(), true); mVideoEncoder = new TextureMovieEncoder2(encoderCore); } } /** * 主线程助手 */ private class MainHandler extends Handler { private static final int MSG_SEND_CAMERA_PARAMS0 = 0; private static final int MSG_SEND_CAMERA_PARAMS1 = 1; private static final int MSG_SEND_RECT_SIZE = 2; private static final int MSG_SEND_ZOOM_AREA = 3; private static final int MSG_SEND_ROTATE_ANGLE = 4; private static final int MSG_FILE_SAVE_COMPLETE = 5; private static final int MSG_BUFFER_STATUS = 6; private WeakReference<MainActivity> mWeakActivity; /** * 将Activity通过构造函数传递进来 * * @param activity */ public MainHandler(MainActivity activity) { mWeakActivity = new WeakReference<MainActivity>(activity); } /** * <p> * 将相机参数信息发送的到主线程来回调渲染线程 * <p/> */ public void sendCameraParams(int width, int height, float fps) { // The right way to do this is to bundle them up into an object. The lazy // way is to send two messages. sendMessage(obtainMessage(MSG_SEND_CAMERA_PARAMS0, width, height)); sendMessage(obtainMessage(MSG_SEND_CAMERA_PARAMS1, (int) fps * 1000, 0)); } /** * Sends the updated rect size to the main thread. * <p> * Call from render thread. * 更新尺寸 */ public void sendRectSize(int width, int height) { sendMessage(obtainMessage(MSG_SEND_RECT_SIZE, width, height)); } /** * 更新焦距 * * @param width * @param height */ public void sendZoomArea(int width, int height) { sendMessage(obtainMessage(MSG_SEND_ZOOM_AREA, width, height)); } /** * 更新旋转角度 * * @param rotateAngle */ public void sendRotateAngle(int rotateAngle) { sendMessage(obtainMessage(MSG_SEND_ROTATE_ANGLE, rotateAngle, 0)); } @Override public void handleMessage(Message msg) { MainActivity mainActivity = mWeakActivity.get(); if (mainActivity == null) { return; } switch (msg.what) { case MSG_SEND_CAMERA_PARAMS0: mainActivity.mCameraPreviewWidth = msg.arg1; mainActivity.mCameraPreviewHeight = msg.arg2; break; case MSG_SEND_CAMERA_PARAMS1: mainActivity.mCameraPreviewFps = msg.arg1 / 1000.0f; mainActivity.updateControls(); break; case MSG_SEND_RECT_SIZE: mainActivity.mRectWidth = msg.arg1; mainActivity.mRectHeight = msg.arg2; //更新UI mainActivity.updateControls(); break; case MSG_SEND_ZOOM_AREA: mainActivity.mZoomWidth = msg.arg1; mainActivity.mZoomHeight = msg.arg2; //更新UI mainActivity.updateControls(); break; case MSG_SEND_ROTATE_ANGLE: mainActivity.mRotateDeg = msg.arg1; //更新UI mainActivity.updateControls(); break; case MSG_FILE_SAVE_COMPLETE: mainActivity.fileSaveComplete(msg.arg1); break; case MSG_BUFFER_STATUS: long duration = (((long) msg.arg1) << 32) | (((long) msg.arg2) & 0xffffffffL); mainActivity.updateBufferStatus(duration); break; default: throw new RuntimeException("unknown message" + msg.what); } } } private void fileSaveComplete(int status) { if (!mFileSaveInProgress) { throw new RuntimeException("WEIRD: got fileSaveCmplete when not in progress"); } mFileSaveInProgress = false; updateControls(); String str = getString(R.string.nowRecording); if (status == 0) { str = getString(R.string.recordingSucceeded); } else { str = getString(R.string.recordingFailed, status); } Toast toast = Toast.makeText(this, str + "<<<" + status, Toast.LENGTH_SHORT); toast.show(); } private void updateBufferStatus(long duration) { mSecondsOfVideo = duration / 1000000.0f; updateControls(); } private void updateControls() { String str = getString(R.string.tfcCameraParams, mCameraPreviewWidth, mCameraPreviewHeight, mCameraPreviewFps); TextView tv = (TextView) findViewById(R.id.tfcCameraParams_text); tv.setText(str); str = getString(R.string.tfcRectSize, mRectWidth, mRectHeight); tv = (TextView) findViewById(R.id.tfcRectSize_text); tv.setText(str); str = getString(R.string.tfcZoomArea, mZoomWidth, mZoomHeight); tv = (TextView) findViewById(R.id.tfcZoomArea_text); tv.setText(str); int id = mRecordingEnabled ? R.string.toggleRecordingOff : R.string.toggleRecordingOn; toggleRecording.setText(id); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mOutputFile = new File(getFilesDir(), "camera-haha.mp4"); mHandler = new MainHandler(this); mSecondsOfVideo = 0.0f; initView();//初始化View initListener();//初始化监听 initData(); updateControls();//更行界面文字 } private void initView() { cameraOnTextureSurfaceView = (SurfaceView) findViewById(R.id.cameraOnTexture_surfaceView); // 纹理布局添加Holder holder = cameraOnTextureSurfaceView.getHolder(); // 添加回调 holder.addCallback(this); tfcCameraParamsText = (TextView) findViewById(R.id.tfcCameraParams_text); tfcRectSizeText = (TextView) findViewById(R.id.tfcRectSize_text); tfcZoomAreaText = (TextView) findViewById(R.id.tfcZoomArea_text); tfcZoomLabelText = (TextView) findViewById(R.id.tfcZoomLabel_text); tfcZoomSeekbar = (SeekBar) findViewById(R.id.tfcZoom_seekbar); tfcSizeLabelText = (TextView) findViewById(R.id.tfcSizeLabel_text); tfcSizeSeekbar = (SeekBar) findViewById(R.id.tfcSize_seekbar); tfcRotateLabelText = (TextView) findViewById(R.id.tfcRotateLabel_text); tfcRotateSeekbar = (SeekBar) findViewById(R.id.tfcRotate_seekbar); toggleRecording = (Button) findViewById(R.id.toggleRecordingOn); spinner = (Spinner) findViewById(R.id.cameraFilter_spinner); mCameraHandler = new CameraHandler(this); //cameraOnTextureSurfaceView.setEGLContextClientVersion(2); // select GLES 2.0 // mRenderer = new CameraSurfaceRenderer(mCameraHandler, sVideoEncoder, outputFile); //cameraOnTextureSurfaceView.setRenderer(mRenderer); //cameraOnTextureSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } private void initListener() { //seekBar 初始值 tfcZoomSeekbar.setProgress(DEFAULT_ZOOM_PERCENT); tfcSizeSeekbar.setProgress(DEFAULT_SIZE_PERCENT); tfcRotateSeekbar.setProgress(DEFAULT_ROTATE_PERCENT); // seekBar 监听 tfcZoomSeekbar.setOnSeekBarChangeListener(this); tfcSizeSeekbar.setOnSeekBarChangeListener(this); tfcRotateSeekbar.setOnSeekBarChangeListener(this); spinner.setOnItemSelectedListener(this); toggleRecording.setOnClickListener(this); } private void initData() { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.cameraFilterNames, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); // 获取视频编码器的状态 } @Override // surfaceHolder.callback 当view创建的时候 public void surfaceCreated(SurfaceHolder holder) { if (sSurfaceHolder != null) { throw new RuntimeException("surfaceHolder 已经存在"); } //holder 赋值 sSurfaceHolder = holder; if (mRenderThread != null) { RenderHandler handler = mRenderThread.getHandler(); handler.sendSurfaceAvailable(holder, true); } else { Log.d(TAG, "render thread not running"); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (mRenderThread != null) { RenderHandler handler = mRenderThread.getHandler(); handler.sendSurfaceChanged(format, width, height); } else { Log.d(TAG, "surfaceChanged: "); return; } } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (mRenderThread != null) { RenderHandler handler = mRenderThread.getHandler(); handler.sendSurfaceDestroyed(); } sSurfaceHolder = null; } static class CameraHandler extends Handler { public static final int MSG_SET_SURFACE_TEXTURE = 0; // Weak reference to the Activity; only access this from the UI thread. private WeakReference<MainActivity> mWeakActivity; public CameraHandler(MainActivity activity) { mWeakActivity = new WeakReference<MainActivity>(activity); } /** * Drop the reference to the activity. Useful as a paranoid measure to ensure that * attempts to access a stale Activity through a handler are caught. */ public void invalidateHandler() { mWeakActivity.clear(); } @Override // runs on UI thread public void handleMessage(Message inputMessage) { int what = inputMessage.what; Log.d(TAG, "CameraHandler [" + this + "]: what=" + what); MainActivity activity = mWeakActivity.get(); if (activity == null) { Log.w(TAG, "CameraHandler.handleMessage: activity is null"); return; } switch (what) { case MSG_SET_SURFACE_TEXTURE: //activity.handleSetSurfaceTexture((SurfaceTexture) inputMessage.obj); break; default: throw new RuntimeException("unknown msg " + what); } } } @Override protected void onResume() { super.onResume(); updateControls(); mRenderThread = new RenderThread(holder, mHandler, mOutputFile); mRenderThread.setName("TexFromCam Render"); AspectFrameLayout layout = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl); layout.setAspectRatio((double) mCameraPreviewWidth / mCameraPreviewHeight); mRenderThread.start(); mRenderThread.waitUntilReady(); RenderHandler handler = mRenderThread.getHandler(); handler.sendZoomValue(tfcZoomSeekbar.getProgress()); handler.sendSizeValue(tfcSizeSeekbar.getProgress()); handler.sendRotateValue(tfcRotateSeekbar.getProgress()); handler.setRecordMethod(1); if (sSurfaceHolder != null) { handler.sendSurfaceAvailable(sSurfaceHolder, false); } else { Log.d(TAG, "没有……"); } } @Override protected void onPause() { super.onPause(); releaseCamera(); /* cameraOnTextureSurfaceView.queueEvent(new Runnable() { @Override public void run() { // Tell the renderer that it's about to be paused so it can clean up. mRenderer.notifyPausing(); } });*/ // cameraOnTextureSurfaceView.onPause(); RenderHandler handler = mRenderThread.getHandler(); handler.sendShutdown(); try { mRenderThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } mRenderThread = null; } @Override protected void onDestroy() { super.onDestroy(); } private void handleSetSurfaceTexture(SurfaceTexture st) { st.setOnFrameAvailableListener(this); try { mCamera.setPreviewTexture(st); } catch (IOException ioe) { throw new RuntimeException(ioe); } mCamera.startPreview(); } // Camera filters; must match up with cameraFilterNames in strings.xml static final int FILTER_NONE = 0; static final int FILTER_BLACK_WHITE = 1; static final int FILTER_BLUR = 2; static final int FILTER_SHARPEN = 3; static final int FILTER_EDGE_DETECT = 4; static final int FILTER_EMBOSS = 5; }
true
e73ff4d93127967e5e9a616204fe073b9462b2ac
Java
davidgomezrubio/sf-jwt-oauth2
/src/main/java/com/dgr/app/SpringSecurityConfig.java
UTF-8
1,841
2.046875
2
[]
no_license
package com.dgr.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.dgr.app.services.JpaUserDetailsService; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JpaUserDetailsService userDetailsService; @Autowired private BCryptPasswordEncoder passwordEncoder; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/", "/css/**", "/js/**", "/images/**", "/companies", "/api-rest-doc/**", "/landing/**").permitAll() .antMatchers("/companies/{id}").hasAnyRole("ADMIN_COMPANY") .antMatchers("/companies/form/**").hasAnyRole("ADMIN") .antMatchers("/companies/delete/**").hasAnyRole("ADMIN") .antMatchers("/api-rest/**").hasAnyRole("USER") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .passwordParameter("password") .usernameParameter("username") .and() .logout().permitAll() .and() .exceptionHandling().accessDeniedPage("/error_403"); } @Autowired public void configurerGlobal(AuthenticationManagerBuilder builder) throws Exception { try { builder.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Error en el builder.userDetailsService: " + e); } } }
true
3921e668b732619fdcb569cbe07fb32007255aba
Java
maheshwar8622/maheshrepo
/amazon/src/test/java/com/amazon/baseclass/TopMenu.java
UTF-8
252
1.710938
2
[]
no_license
package com.amazon.baseclass; import org.openqa.selenium.WebDriver; public class TopMenu { public WebDriver driver; public TopMenu (WebDriver driver){ this.driver = driver; } public void addCart(){ } public void Signout(){ } }
true
da3ff02ab85d4286c214cd0f0ace67b65cb8d500
Java
cliveyao/EKPV12
/ekp/src/com/landray/kmss/tib/sys/sap/connector/forms/TibSysSapRfcSearchInfoForm.java
UTF-8
2,614
1.976563
2
[]
no_license
package com.landray.kmss.tib.sys.sap.connector.forms; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import com.landray.kmss.common.convertor.FormConvertor_IDToModel; import com.landray.kmss.common.convertor.FormToModelPropertyMap; import com.landray.kmss.common.forms.ExtendForm; import com.landray.kmss.tib.sys.core.util.TibSysCoreUtil; import com.landray.kmss.tib.sys.sap.connector.model.TibSysSapRfcSearchInfo; import com.landray.kmss.tib.sys.sap.connector.model.TibSysSapRfcSetting; /** * rfc函数查询 Form * * @author zhangtian * @version 1.0 2011-12-20 */ public class TibSysSapRfcSearchInfoForm extends ExtendForm { /** * 标题 */ protected String docSubject = null; /** * @return 标题 */ public String getDocSubject() { return docSubject; } /** * @param docSubject 标题 */ public void setDocSubject(String docSubject) { this.docSubject = docSubject; } /** * xml数据 */ protected String fdData = null; // 用于将一些特殊字符转化后在前端展示 public String getFdDataView() { return TibSysCoreUtil.filter(fdData); } /** * @return xml数据 */ public String getFdData() { return fdData; } /** * @param fdData xml数据 */ public void setFdData(String fdData) { this.fdData = fdData; } /** * rfc函数_id的ID */ protected String fdRfcId = null; /** * @return rfc函数_id的ID */ public String getFdRfcId() { return fdRfcId; } /** * @param fdRfcId rfc函数_id的ID */ public void setFdRfcId(String fdRfcId) { this.fdRfcId = fdRfcId; } /** * rfc函数_id的名称 */ protected String fdRfcName = null; /** * @return rfc函数_id的名称 */ public String getFdRfcName() { return fdRfcName; } /** * @param fdRfcName rfc函数_id的名称 */ public void setFdRfcName(String fdRfcName) { this.fdRfcName = fdRfcName; } public void reset(ActionMapping mapping, HttpServletRequest request) { docSubject = null; fdData = null; fdRfcId = null; fdRfcName = null; super.reset(mapping, request); } public Class getModelClass() { return TibSysSapRfcSearchInfo.class; } private static FormToModelPropertyMap toModelPropertyMap; public FormToModelPropertyMap getToModelPropertyMap() { if (toModelPropertyMap == null) { toModelPropertyMap = new FormToModelPropertyMap(); toModelPropertyMap.putAll(super.getToModelPropertyMap()); toModelPropertyMap.put("fdRfcId", new FormConvertor_IDToModel("fdRfc", TibSysSapRfcSetting.class)); } return toModelPropertyMap; } }
true
8e676da91ebc7192620b2af5c0365c3fab9e3adb
Java
emcry666/project-scape
/rs3 files/876 Deob/source/com/jagex/QuickChatStringType.java
UTF-8
3,621
1.59375
2
[ "Apache-2.0" ]
permissive
/* Class636 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; public class QuickChatStringType { public static QuickChatStringType QC_SLAYER_TASK; public static QuickChatStringType QC_ITEM; static QuickChatStringType QC_RANK; static QuickChatStringType QC_SKILL; static QuickChatStringType aClass636_8286; public static QuickChatStringType aClass636_8287; static QuickChatStringType QC_FRIEND_CHAT; static QuickChatStringType QC_MINIGAME_POINTS; public static QuickChatStringType QC_ITEM_TRADE; public static QuickChatStringType QC_EXPERIENCE; public int serverToClientBytes; public static QuickChatStringType QC_GENERAL = new QuickChatStringType(0, 2, 2, 1); static QuickChatStringType QC_SOULWARS; static QuickChatStringType QC_COMBAT_LEVEL; public int id; public int clientToServerBytes; static QuickChatStringType QC_COMBAT_LEVEL_AVERAGE; public int dataCount; public static Class149 aClass149_8300; static { QC_ITEM = new QuickChatStringType(1, 2, 2, 0); aClass636_8286 = new QuickChatStringType(2, 4, 4, 0); QC_SKILL = new QuickChatStringType(4, 1, 1, 1); QC_SLAYER_TASK = new QuickChatStringType(6, 0, 4, 2); aClass636_8287 = new QuickChatStringType(7, 0, 1, 1); QC_RANK = new QuickChatStringType(8, 0, 4, 1); QC_MINIGAME_POINTS = new QuickChatStringType(9, 0, 4, 1); QC_ITEM_TRADE = new QuickChatStringType(10, 2, 2, 0); QC_EXPERIENCE = new QuickChatStringType(11, 0, 1, 2); QC_FRIEND_CHAT = new QuickChatStringType(12, 0, 1, 0); QC_COMBAT_LEVEL_AVERAGE = new QuickChatStringType(13, 0, 1, 0); QC_SOULWARS = new QuickChatStringType(14, 0, 4, 1); QC_COMBAT_LEVEL = new QuickChatStringType(15, 0, 1, 0); } QuickChatStringType(int id, int clientToServerBytes, int serverToClientBytes, int dataCount) { this.id = id * -908979839; this.clientToServerBytes = clientToServerBytes * 60716293; this.serverToClientBytes = 1740949473 * serverToClientBytes; this.dataCount = dataCount * 173275855; } static final void method10445(InterfaceComponentDefinitions class250, Class242 class242, Class669 class669, byte i) { class250.anInt2707 = (class669.anIntArray8557[(class669.anInt8558 -= 2138772399) * 1357652815]) * -697127929; Login.method15991(class250, (byte) -126); } static final void method10446(Class669 class669, int i) { class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = Class61.method1418((byte) 106); } static final void method10447(Class669 class669, byte i) { class669.anInt8558 -= -17422498; int i_5_ = class669.anIntArray8557[1357652815 * class669.anInt8558]; int i_6_ = class669.anIntArray8557[1 + class669.anInt8558 * 1357652815]; Class553.method9164(7, i_5_, i_6_, "", 221978259); } public static void method10448(byte i) { for (Class523_Sub27_Sub8 class523_sub27_sub8 = ((Class523_Sub27_Sub8) Class36.aClass697_339.first(-1426448868)); null != class523_sub27_sub8; class523_sub27_sub8 = ((Class523_Sub27_Sub8) Class36.aClass697_339.next(768418218))) { if (1060081949 * class523_sub27_sub8.anInt11719 > 1) { class523_sub27_sub8.anInt11719 = 0; Class36.aClass209_335.method3770(class523_sub27_sub8, (5220346430341563535L * (((Class523_Sub27_Sub6) (class523_sub27_sub8.aClass697_11718.aClass523_Sub27_8763.aClass523_Sub27_10551)).aLong11628))); class523_sub27_sub8.aClass697_11718.removeFromQueue(1739026943); } } Class36.anInt336 = 0; Class36.anInt330 = 0; Class36.aClass708_342.method14235((byte) -96); Class36.aClass14_338.method733(1750455891); Class36.aClass697_339.removeFromQueue(57845863); Class36.aBool326 = false; } }
true
cdd5a0836687a1332150118ceb03f13dc589e3a9
Java
Okami-Kato/jwd-critics
/src/main/java/com/epam/jwd_critics/controller/command/impl/guest/OpenSignInPageCommand.java
UTF-8
906
2.109375
2
[]
no_license
package com.epam.jwd_critics.controller.command.impl.guest; import com.epam.jwd_critics.controller.command.Attribute; import com.epam.jwd_critics.controller.command.Command; import com.epam.jwd_critics.controller.command.CommandRequest; import com.epam.jwd_critics.controller.command.CommandResponse; import com.epam.jwd_critics.controller.command.Parameter; import com.epam.jwd_critics.controller.command.ServletDestination; import com.epam.jwd_critics.controller.command.TransferType; public class OpenSignInPageCommand implements Command { @Override public CommandResponse execute(CommandRequest req) { String previousPage = req.getParameter(Parameter.PREVIOUS_PAGE); if (previousPage != null) { req.setSessionAttribute(Attribute.PREVIOUS_PAGE, previousPage); } return new CommandResponse(ServletDestination.SIGN_IN, TransferType.REDIRECT); } }
true
0c528dae0ef702a0f8b73f91e6e74878ea2211b7
Java
GabLast/CRUDSimpleSpringBoot
/src/main/java/edu/pucmm/eict/crudspringboot/Models/Estudiante.java
UTF-8
1,057
2.4375
2
[]
no_license
package edu.pucmm.eict.crudspringboot.Models; import edu.pucmm.eict.crudspringboot.Database.Fake; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Getter @Setter public class Estudiante { private int matricula; private String nombre; private String apellido; private String telefono; public Estudiante() { } public Estudiante(String nombre, String apellido, String telefono) { this.matricula = generateID(); this.nombre = nombre; this.apellido = apellido; this.telefono = telefono; } public static int generateID() { if(Fake.getInstancia().getEstudiantes().size() > 0) { return 10000000 + (Fake.getInstancia().getEstudiantes().get(Fake.getInstancia().getEstudiantes().size() - 1).getMatricula() - 10000000) + 1; }else { return 10000000; } } }
true
d706b657e8976ffdbbb39f74111cbff39409b700
Java
byambaa005/waa-meditation-attendance-system
/backend/src/main/java/edu/mum/waa/backend/meditation/ws/entity/User.java
UTF-8
1,248
2.15625
2
[ "MIT" ]
permissive
package edu.mum.waa.backend.meditation.ws.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.time.Instant; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = {"username"}) }) @Data @NoArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Basic @Size(max = 15) private String username; @NotBlank @Size(max = 100) @JsonIgnore private String password; @CreatedDate private Instant createdAt; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<>(); public User(@Size(max = 15) String username, @NotBlank @Size(max = 100) String password) { this.username = username; this.password = password; } }
true
2e695e7bd55d09800ac3fa69cba6f9295dad73f3
Java
jaekeun0422/Java
/java/SortObject.java
UTF-8
702
4.0625
4
[]
no_license
//(19-2) object형 정렬 import java.util.Arrays; class Person1 implements Comparable { private int age; public Person1(int age) { this.age = age; } @Override public int compareTo(Object ar) { Person1 p = (Person1)ar; return this.age - p.age; } @Override public String toString() { return "나이: " + age; } } class SortObject { public static void main(String[] args) { Person1[] arr = new Person1[3]; arr[0] = new Person1(20); arr[1] = new Person1(30); arr[2] = new Person1(10); Arrays.sort(arr); for(Person1 p : arr) System.out.println(p); } }
true
2cd7167906816cf5f06d7e403e50763ecdcf7802
Java
star12138/dbLog
/src/main/java/com/xfn/dbLog/exception/VcException.java
UTF-8
328
2.03125
2
[]
no_license
package com.xfn.dbLog.exception; /** * Created by xfn-ac on 16/6/20. */ public class VcException extends XFNException { public VcException(String msg){ super(msg); } public VcException(int code){ super(code); } public VcException(int code,String msg){ super(code,msg); } }
true
bfc9c2106fd65ed5951df2e3641ed24d33194398
Java
shanirub/vorbereitung-cs2013
/src/Launcher.java
UTF-8
303
2.1875
2
[]
no_license
public class Launcher { public static void main(String args[]) { Model model = new Model(); model.initialise(); MainFrame mainFrame = new MainFrame(); Controller controller = new Controller(mainFrame, model); mainFrame.initialise(model, controller); } }
true
5f63d02281bfb6c30d84b0adb90eef4546c5ceed
Java
thetlwinoo/epm-web
/src/main/java/com/epmweb/server/web/rest/StripeClientResource.java
UTF-8
1,542
2.109375
2
[]
no_license
package com.epmweb.server.web.rest; import com.epmweb.server.service.StripeClientService; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Map; /** * StripeClientResource controller */ @RestController @RequestMapping("/api") public class StripeClientResource { private final Logger log = LoggerFactory.getLogger(StripeClientResource.class); private final StripeClientService stripeClientService; public StripeClientResource(StripeClientService stripeClientService) { this.stripeClientService = stripeClientService; } @CrossOrigin(origins = "http://localhost:4200") @PostMapping(value = "/stripe-client/charge", produces = MediaType.APPLICATION_JSON_VALUE) public Map<String, Object> chargeCard(@Valid @RequestBody String payload) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree(payload); JsonNode jsonNode1 = actualObj.get("token"); JsonNode jsonNode2 = actualObj.get("amount"); JsonNode jsonNode3 = actualObj.get("orderId"); String token = jsonNode1.textValue(); Double amount = jsonNode2.doubleValue(); Number orderId = jsonNode3.numberValue(); return this.stripeClientService.chargeNewCard(token, amount, orderId); } }
true
75e762ec4856d83093526ba2d0694256e3a203ff
Java
tvd12/calabash
/calabash-persist/src/main/java/com/tvd12/calabash/persist/action/PersistActionQueueManager.java
UTF-8
2,508
2.75
3
[ "Apache-2.0" ]
permissive
package com.tvd12.calabash.persist.action; import java.util.HashMap; import java.util.Map; public class PersistActionQueueManager { protected final PersistActionQueueFactory queueFactory; protected final Map<String, PersistActionQueue> delayedQueues; protected final Map<String, PersistActionQueue> immediateQueues; public PersistActionQueueManager(PersistActionQueueFactory queueFactory) { this.queueFactory = queueFactory; this.delayedQueues = new HashMap<>(); this.immediateQueues = new HashMap<>(); } public PersistActionQueue getDelayedQueue(String mapName) { PersistActionQueue queue = delayedQueues.get(mapName); if (queue == null) { queue = newQueue(mapName, delayedQueues); } return queue; } public PersistActionQueue getImmediateQueue(String mapName) { PersistActionQueue queue = immediateQueues.get(mapName); if (queue == null) { queue = newQueue(mapName, immediateQueues); } return queue; } protected PersistActionQueue newQueue( String mapName, Map<String, PersistActionQueue> queues ) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queues) { PersistActionQueue queue = queues.get(mapName); if (queue == null) { queue = queueFactory.newActionQueue(mapName); queues.put(mapName, queue); } return queue; } } public Map<String, PersistActionQueue> getReadyDelayedQueues() { Map<String, PersistActionQueue> readyQueues = new HashMap<>(); synchronized (delayedQueues) { for (String mapName : delayedQueues.keySet()) { PersistActionQueue queue = delayedQueues.get(mapName); if (queue.isReady()) { readyQueues.put(mapName, queue); } } } return readyQueues; } public Map<String, PersistActionQueue> getReadyImmediateQueues() { Map<String, PersistActionQueue> readyQueues = new HashMap<>(); synchronized (immediateQueues) { for (String mapName : immediateQueues.keySet()) { PersistActionQueue queue = immediateQueues.get(mapName); if (queue.size() > 0) { readyQueues.put(mapName, queue); } } } return readyQueues; } }
true
5fe475d794b6ba4ca0f8d977df37666c3c601777
Java
jjmnbv/km_dev
/kmzyc-promotion/kmzyc-promotion-api/src/main/java/com/kmzyc/promotion/remote/service/BaseProductRemoteService.java
UTF-8
2,566
1.875
2
[]
no_license
package com.kmzyc.promotion.remote.service; import java.util.List; import com.alibaba.fastjson.JSONObject; import com.km.framework.page.Pagination; import com.kmzyc.promotion.app.vobject.BaseProduct; import com.kmzyc.promotion.app.vobject.PriceInfo; import com.kmzyc.promotion.app.vobject.PromotionInfo; import com.kmzyc.promotion.app.vobject.PromotionProduct; public interface BaseProductRemoteService { /** * 获取加价购商品价格 * * @param promotionId活动ID * @return * @throws Exception */ public List<BaseProduct> getAddPriceCarProductInfoList(Long promotionId) throws Exception; /** * 获取赠品 * * @param promotionId活动ID * @return * @throws Exception */ public List<BaseProduct> getGiftProduct(Long promotionId) throws Exception; /** * 参加某活动的商品 * * @param page * @param promotion * @return * @throws Exception */ public Pagination getAppActivityProductList(Pagination page, PromotionInfo promotion) throws Exception; /** * 获取特价产品价格和限购信息 * * @param skuId产品skuId * @param promotionId活动ID * @return * @throws Exception */ public PromotionProduct getPromotionProductPrice(Long skuId, Long promotionId) throws Exception; /** * 获取活动产品列表 * * @param page * @param promotion * @return * @throws Exception */ public Pagination getAppPromotionProductList(Pagination page, PromotionInfo promotion) throws Exception; /** * 计算价格 * * @param uid 用户ID * @param jo 产品集合包括:cpArray普通产品集合,格式:'cpArray':[{'skuId':****,'amount':*},{' s k u I d ' : * ****,'amount':*}] comArray套餐集合,格式:'comArray':[{'comId':****,'amount': * *},{'comId':****,'amount':*}] pmArray活动产品集合,格式:'pmArray':[{'pid', * ***,'rid':***,'skuId':***},{'pid',***,'rid':***,'skuId':***}] * @throws Exception */ public JSONObject getcalcPrice(Long uid, JSONObject jo) throws Exception; /** * 根据SKUID获取缓存价格 * * @param skuId * @return * @throws Exception */ public PriceInfo getCachePriceBySkuId(Long skuId) throws Exception; /** * 根据 渠道号SKUID获取缓存价格(搜索调用) * * @param skuId * @return * @throws Exception */ public PriceInfo getCachePriceBySkuId_New(Long skuId) throws Exception; }
true
5d9c9313f1dc748b1936ae50bd63aca5a767c425
Java
t-okeya/reddog_sample
/src/main/java/reddog_sample/action/user/IndexAction.java
UTF-8
1,590
2.03125
2
[ "Apache-2.0" ]
permissive
package reddog_sample.action.user; import java.util.Map; import java.util.TreeMap; import javax.annotation.Resource; import org.seasar.struts.annotation.ActionForm; import org.seasar.struts.annotation.Execute; import reddog_sample.action.AbstractBaseAction; import reddog_sample.form.user.IndexForm; import reddog_sample.ignore.dto.RdUserDto; import reddog_sample.service.RdUserService; import reddog_sample.service.SF; // ユーザ > ユーザ検索 public class IndexAction extends AbstractBaseAction { @Resource @ActionForm protected IndexForm indexForm; @Resource protected RdUserDto rdUserDto; // -------------------------------------------------------- @Execute(validator = false) public String index() throws Exception { // --------------------------------------------------------------- // 条件セット // --------------------------------------------------------------- Map<String, String> conditions = new TreeMap<String, String>(); conditions.put(RdUserService.CK_LOGINID, indexForm.cndLoginId); conditions.put(RdUserService.CK_USERNAME, indexForm.cndUserName); // ログイン者本人は除く conditions.put(RdUserService.CK_NOT_ID, String.valueOf(rdUserDto.userId)); // --------------------------------------------------------------- // データを取得してFormへセット // --------------------------------------------------------------- indexForm.rdUsers = SF.rdUser.search(conditions); return "index.jsp"; } }
true
321bb14fd8de49f2c3be5c8ff8679ab3c9ff9595
Java
Lipek71/covid19
/src/main/java/covid19/Vaccinations.java
UTF-8
1,915
2.734375
3
[]
no_license
package covid19; import java.time.LocalDateTime; public class Vaccinations { private int vaccinationId; private int citizenId; private LocalDateTime vaccinationDate; private String status; private String note; private String vaccinationType; public Vaccinations(int citizenId, LocalDateTime vaccinationDate, String status, String note, String vaccinationType) { this.citizenId = citizenId; this.vaccinationDate = vaccinationDate; this.status = status; this.note = note; this.vaccinationType = vaccinationType; } public Vaccinations(int vaccinationId, int citizenId, LocalDateTime vaccinationDate, String status, String note, String vaccinationType) { this.vaccinationId = vaccinationId; this.citizenId = citizenId; this.vaccinationDate = vaccinationDate; this.status = status; this.note = note; this.vaccinationType = vaccinationType; } public int getVaccinationId() { return vaccinationId; } public int getCitizenId() { return citizenId; } public LocalDateTime getVaccinationDate() { return vaccinationDate; } public String getStatus() { return status; } public String getNote() { return note; } public String getVaccinationType() { return vaccinationType; } public void setVaccinationId(int vaccinationId) { this.vaccinationId = vaccinationId; } @Override public String toString() { return "Vaccinations{" + "vaccinationId=" + vaccinationId + ", citizenId=" + citizenId + ", vaccinationDate=" + vaccinationDate + ", status='" + status + '\'' + ", note='" + note + '\'' + ", vaccinationType='" + vaccinationType + '\'' + '}'; } }
true
ce61f822082cb79e70e72369507156885b41ce26
Java
patrickfav/indoor-positioning
/src/main/java/at/ac/tuwien/inso/indoor/sensorserver/services/requests/OUILookupRequest.java
UTF-8
1,734
2.4375
2
[]
no_license
package at.ac.tuwien.inso.indoor.sensorserver.services.requests; import at.ac.tuwien.inso.indoor.sensorserver.persistence.ObjectMapperManager; import at.ac.tuwien.inso.indoor.sensorserver.persistence.model.network.OUIMacInfo; import at.ac.tuwien.inso.indoor.sensorserver.services.exceptions.SensorRequestException; import com.fasterxml.jackson.databind.ObjectMapper; import javax.ws.rs.core.Response; import java.io.IOException; /** * Created by PatrickF on 06.10.2014. */ public class OUILookupRequest extends ARequest<OUIMacInfo> { private static final String OUI_URL = "http://www.macvendorlookup.com/api/v2/"; private String macAddress; private ObjectMapper objectMapper; public OUILookupRequest(String macAddress) { this.macAddress = macAddress; this.objectMapper = ObjectMapperManager.createMapperForAPI(); } @Override public OUIMacInfo startRequest() throws SensorRequestException { try { ResponseWrapper responseWrapper = runRequest("GET", OUI_URL + convertMacToSearchableString(macAddress), "", true); if (responseWrapper.getResponse().getStatus() == Response.Status.OK.getStatusCode()) { try { return objectMapper.readValue(responseWrapper.getBody(), OUIMacInfo.class); } catch (IOException e) { log.error("Could not parse oui lookup result", e); } } return null; } catch (Exception e) { log.error("error while OUI lookup", e); return null; } } private String convertMacToSearchableString(String macAddress) { return macAddress.replace(":", "-").substring(0, 8); } }
true
ca63068e5ac3f014e8ebe083fde1f80739740c11
Java
hidday/DirectFarming
/app/src/main/java/com/example/hidday/directfarming/AppActivities/LoginActivity.java
UTF-8
8,349
2.453125
2
[]
no_license
package com.example.hidday.directfarming.AppActivities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.hidday.directfarming.DBfunctions.DBHandler; import com.example.hidday.directfarming.DBfunctions.UserFunctions; import com.example.hidday.directfarming.R; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.widget.TextView; public class LoginActivity extends Activity { Button btnLogin; Button btnLinkToRegister; EditText inputEmail; EditText inputPassword; TextView loginErrorMsg; // JSON Response node names private static String KEY_SUCCESS = "success"; private static String KEY_ERROR = "error"; private static String KEY_ERROR_MSG = "error_msg"; private static String KEY_UID = "uid"; private static String KEY_NAME = "name"; private static String KEY_EMAIL = "email"; private static String KEY_CREATED_AT = "created_at"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Importing all assets like buttons, text fields inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); btnLogin = (Button) findViewById(R.id.email_sign_in_button); btnLinkToRegister = (Button) findViewById(R.id.register); loginErrorMsg = (TextView) findViewById(R.id.login_error); // Login button Click Event btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); UserFunctions userFunction = new UserFunctions(); Log.d("Button", "Login"); JSONObject json = userFunction.loginUser(email, password); // check for login response try { if (json.getString(KEY_SUCCESS) != null) { loginErrorMsg.setText(""); String res = json.getString(KEY_SUCCESS); if(Integer.parseInt(res) == 1){ // user successfully logged in // Store user details in SQLite Database DBHandler db = new DBHandler(getApplicationContext()); JSONObject json_user = json.getJSONObject("user"); // Clear all previous data in database userFunction.logoutUser(getApplicationContext()); db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); // Launch Dashboard Screen Intent dashboard = new Intent(getApplicationContext(), ActiveEvents.class); // Close all views before launching Dashboard dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(dashboard); // Close Login Screen finish(); }else{ // Error in login loginErrorMsg.setText("Incorrect username/password"); } } } catch (JSONException e) { e.printStackTrace(); } } }); // Link to Register Screen btnLinkToRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i; i = new Intent(LoginActivity.this,RegisterActivity.class); startActivity(i); finish(); } }); } } /* public class LoginActivity extends Activity { // Declare Variables Button loginbutton; Button register; String usernametxt; String passwordtxt; EditText password; EditText username; /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the view from main.xml setContentView(R.layout.activity_login); // Locate EditTexts in main.xml username = (EditText) findViewById(R.id.email); password = (EditText) findViewById(R.id.password); // Locate Buttons in main.xml loginbutton = (Button) findViewById(R.id.email_sign_in_button); register = (Button) findViewById(R.id.register); // Login Button Click Listener loginbutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // Retrieve the text entered from the EditText usernametxt = username.getText().toString(); passwordtxt = password.getText().toString(); // Send data to Parse.com for verification ParseUser.logInInBackground(usernametxt, passwordtxt, new LogInCallback() { public void done(ParseUser user, ParseException e) { if (user != null) { // If user exist and authenticated, send user to WelcomeActivity.class MainActivity.myName=usernametxt; Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Successfully Logged in", Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText( getApplicationContext(), "No such user exist, please register", Toast.LENGTH_LONG).show(); } } }); } }); // Sign up Button Click Listener register.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // Retrieve the text entered from the EditText usernametxt = username.getText().toString(); passwordtxt = password.getText().toString(); // Force user to fill up the form if (usernametxt.equals("") && passwordtxt.equals("")) { Toast.makeText(getApplicationContext(), "Please complete the sign up form", Toast.LENGTH_LONG).show(); } else { // Save new user data into Parse.com Data Storage ParseUser user = new ParseUser(); user.setUsername(usernametxt); user.setPassword(passwordtxt); user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { // Show a simple Toast message upon successful registration Toast.makeText(getApplicationContext(), "Successfully Signed up, please log in.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Sign up Error", Toast.LENGTH_LONG) .show(); } } }); } } }); } */
true
1f0e259592713304a7e442bc0fee8b6615d82524
Java
yanmarques/project-thursday
/src/br/common/validation/textValues/DatePickerValue.java
UTF-8
484
2.6875
3
[ "MIT" ]
permissive
package br.common.validation.textValues; import br.common.validation.InputTextValue; import javafx.scene.control.DatePicker; import java.time.LocalDate; public class DatePickerValue implements InputTextValue { private DatePicker datePicker; public DatePickerValue(DatePicker datePicker) { this.datePicker = datePicker; } @Override public String getText() { LocalDate date = datePicker.getValue(); if (date == null) { return ""; } return date.toString(); } }
true
230bb97720c4e057329433bab0f1773e84726c71
Java
sharmasha2nk/spring
/SpringAppContext/src/main/java/com/sunnyj/spring/SampleService.java
UTF-8
88
1.617188
2
[]
no_license
package com.sunnyj.spring; public interface SampleService { String getMessage(); }
true
f7579e74bd3983fa40c651d718d8c808f42ff3fd
Java
fauzan2720/WSIBD-Aplikasi-Laundry-Berbasis-Desktop
/RumahLaundry/src/halm_transaksi.java
UTF-8
67,168
1.921875
2
[]
no_license
import java.awt.HeadlessException; import koneksi.koneksi; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.view.JasperViewer; /* * 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. */ /** * * @author Ilham Nugraha */ public class halm_transaksi extends javax.swing.JFrame { private Connection conn; private Statement st; private ResultSet rs; public halm_transaksi() { initComponents(); setTitle("Halaman Transaksi"); conn = koneksi.getConnection(); id_pelanggan(); input_otomatis(); jns_laundry(); tampil_tanggal_sekarang(); hidden(); } public void hidden() { ket_plain.setVisible(false); total_plain.setVisible(false); total.setVisible(false); banyak_jaket.setVisible(false); xjaket.setVisible(false); cbjaket.setVisible(false); rp_jaket.setVisible(false); harga_jaket.setVisible(false); banyak_selimut.setVisible(false); xselimut.setVisible(false); cbselimut.setVisible(false); rp_selimut.setVisible(false); harga_selimut.setVisible(false); banyak_handuk.setVisible(false); xhanduk.setVisible(false); cbhanduk.setVisible(false); rp_handuk.setVisible(false); harga_handuk.setVisible(false); banyak_boneka.setVisible(false); xboneka.setVisible(false); cbboneka.setVisible(false); rp_boneka.setVisible(false); harga_boneka.setVisible(false); Harga1.setText("0"); txt_jml_kg.setText("0"); harga_jaket.setText("0"); harga_selimut.setText("0"); harga_handuk.setText("0"); harga_boneka.setText("0"); } public void id_pelanggan() { try { String sql = "SELECT * FROM tb_member"; st = conn.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { String jns = rs.getString("id_member"); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "GAGAL MENAMPILKAN DATA"); } } public void total_plain() { try { int jaket, selimut, handuk, boneka; // int jaket = 0, selimut = 0, handuk = 0, boneka = 0; jaket = Integer.parseInt(harga_boneka.getText()); selimut = Integer.parseInt(harga_selimut.getText()); handuk = Integer.parseInt(harga_handuk.getText()); boneka = Integer.parseInt(harga_boneka.getText()); int total = jaket + selimut + handuk + boneka; total_plain.setText(Integer.toString(total)); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } public void tampil() { try { Statement stt = conn.createStatement(); String sql = "SELECT nama, alamat from tb_member where id_member='" +txt_id_pelanggan.getText()+"'"; ResultSet res = stt.executeQuery(sql); while(res.next()){ Object[] ob = new Object[2]; ob[0]= res.getString(1); ob[1]= res.getString(2); txt_nama.setText((String) ob[0]); txt_alamat.setText((String) ob[1]); } res.close(); stt.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } public void jns_laundry() { try { String sql = "SELECT * FROM tb_jns_laundry"; st = conn.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { String jns = rs.getString("nama_jns_laundry"); jns_laundry.addItem(jns); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "GAGAL MENAMPILKAN DATA"); } } public void tampil_tanggal_sekarang() { Date ys = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); tgl_diterima.setText(sdf.format(ys)); } public void input_otomatis() { try { st = conn.createStatement(); rs = st.executeQuery("SELECT * FROM tb_laundry order by id_laundry desc"); if (rs.next()) { String kode = rs.getString("id_laundry").substring(5); String auto_number = "" + (Integer.parseInt(kode) + 1); String Nol = ""; if(auto_number.length()==1) { Nol = "000"; } else if (auto_number.length() == 2) { Nol = "00"; } else if(auto_number.length() == 3) { Nol = "0"; } else if(auto_number.length() == 4) { Nol = ""; } no_invoice.setText("TRAN-" + Nol + auto_number); } else { no_invoice.setText("TRAN-0001"); } } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Hitung = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); no_invoice = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); dashboard = new javax.swing.JButton(); pelanggan_baru = new javax.swing.JButton(); transaksi = new javax.swing.JButton(); data_pelanggan = new javax.swing.JButton(); laporan_pendapatan = new javax.swing.JButton(); Hitung1 = new javax.swing.JPanel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); banyak_jaket = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel30 = new javax.swing.JLabel(); no_invoice1 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jLabel36 = new javax.swing.JLabel(); dashboard1 = new javax.swing.JButton(); pelanggan_baru1 = new javax.swing.JButton(); transaksi1 = new javax.swing.JButton(); data_pelanggan1 = new javax.swing.JButton(); laporan_pendapatan1 = new javax.swing.JButton(); jaket = new javax.swing.JCheckBox(); boneka = new javax.swing.JCheckBox(); total = new javax.swing.JLabel(); ket_plain = new javax.swing.JLabel(); total_plain = new javax.swing.JLabel(); selimut = new javax.swing.JCheckBox(); handuk = new javax.swing.JCheckBox(); cbselimut = new javax.swing.JComboBox<>(); cbjaket = new javax.swing.JComboBox<>(); cbboneka = new javax.swing.JComboBox<>(); cbhanduk = new javax.swing.JComboBox<>(); xboneka = new javax.swing.JLabel(); rp_selimut = new javax.swing.JLabel(); txt_jml_kg = new javax.swing.JTextField(); xjaket = new javax.swing.JLabel(); xselimut = new javax.swing.JLabel(); xhanduk = new javax.swing.JLabel(); banyak_boneka = new javax.swing.JTextField(); banyak_selimut = new javax.swing.JTextField(); banyak_handuk = new javax.swing.JTextField(); rp_jaket = new javax.swing.JLabel(); rp_handuk = new javax.swing.JLabel(); rp_boneka = new javax.swing.JLabel(); txt_total_harga = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); txt_jml_potong1 = new javax.swing.JTextField(); jns_laundry = new javax.swing.JComboBox<>(); txt_alamat = new javax.swing.JTextField(); txt_nama = new javax.swing.JTextField(); txt_id_pelanggan = new javax.swing.JTextField(); tgl_diterima = new javax.swing.JTextField(); txt_tgl_selesai = new com.toedter.calendar.JDateChooser(); btnCetakInvoice = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); harga_jaket = new javax.swing.JTextField(); harga_boneka = new javax.swing.JTextField(); harga_selimut = new javax.swing.JTextField(); harga_handuk = new javax.swing.JTextField(); Harga1 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); Hitung.setBackground(new java.awt.Color(180, 199, 231)); Hitung.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 102, 255), null)); Hitung.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 51, 153)); jLabel1.setText("ID PELANGGAN"); Hitung.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 60, 143, 30)); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 51, 153)); jLabel6.setText("NAMA"); Hitung.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 130, -1, -1)); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(0, 51, 153)); jLabel7.setText("ALAMAT"); Hitung.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 190, -1, -1)); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(0, 51, 153)); jLabel10.setText("JUMLAH KG"); Hitung.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 420, -1, -1)); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(0, 51, 153)); jLabel11.setText("JENIS PAKAIAN LAIN"); Hitung.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 490, -1, -1)); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(0, 51, 153)); jLabel5.setText("DITERIMA"); Hitung.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 380, -1, -1)); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(0, 51, 153)); jLabel15.setText("SELESAI TANGGAL:"); Hitung.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 450, -1, -1)); jPanel4.setBackground(new java.awt.Color(218, 227, 243)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel14.setBackground(new java.awt.Color(45, 85, 151)); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N jLabel14.setForeground(new java.awt.Color(45, 85, 151)); jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rumahlaundry/transaksi.png"))); // NOI18N jLabel14.setText("TRANSAKSI"); jPanel4.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 342, -1)); Hitung.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 0, 1160, 60)); no_invoice.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N no_invoice.setForeground(new java.awt.Color(45, 85, 151)); no_invoice.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); Hitung.add(no_invoice, new org.netbeans.lib.awtextra.AbsoluteConstraints(1080, 340, 140, 30)); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel13.setForeground(new java.awt.Color(45, 85, 151)); jLabel13.setText("No. Invoice: "); Hitung.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 340, 120, 30)); jPanel3.setBackground(new java.awt.Color(156, 194, 230)); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setBackground(new java.awt.Color(51, 102, 255)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rumahlaundry/logorl.png"))); // NOI18N jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(23, 6, -1, -1)); jLabel3.setBackground(new java.awt.Color(45, 85, 151)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N jLabel3.setForeground(new java.awt.Color(45, 85, 151)); jLabel3.setText("RUMAH"); jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 19, -1, -1)); jLabel4.setBackground(new java.awt.Color(45, 85, 151)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N jLabel4.setForeground(new java.awt.Color(45, 85, 151)); jLabel4.setText("LAUNDRY"); jPanel3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 62, -1, -1)); dashboard.setBackground(new java.awt.Color(230, 244, 241)); dashboard.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N dashboard.setForeground(new java.awt.Color(45, 85, 151)); dashboard.setText("DASHBOARD"); dashboard.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dashboardActionPerformed(evt); } }); jPanel3.add(dashboard, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 124, 276, 47)); pelanggan_baru.setBackground(new java.awt.Color(230, 244, 241)); pelanggan_baru.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N pelanggan_baru.setForeground(new java.awt.Color(45, 85, 151)); pelanggan_baru.setText("PELANGGAN BARU"); pelanggan_baru.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pelanggan_baruActionPerformed(evt); } }); jPanel3.add(pelanggan_baru, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 177, 276, 47)); transaksi.setBackground(new java.awt.Color(230, 244, 241)); transaksi.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N transaksi.setForeground(new java.awt.Color(45, 85, 151)); transaksi.setText("TRANSAKSI"); transaksi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { transaksiActionPerformed(evt); } }); jPanel3.add(transaksi, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 230, 276, 47)); data_pelanggan.setBackground(new java.awt.Color(230, 244, 241)); data_pelanggan.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N data_pelanggan.setForeground(new java.awt.Color(45, 85, 151)); data_pelanggan.setText("DATA PELANGGAN"); data_pelanggan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { data_pelangganActionPerformed(evt); } }); jPanel3.add(data_pelanggan, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 283, 276, 47)); laporan_pendapatan.setBackground(new java.awt.Color(230, 244, 241)); laporan_pendapatan.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N laporan_pendapatan.setForeground(new java.awt.Color(45, 85, 151)); laporan_pendapatan.setText("LAPORAN PENDAPATAN"); laporan_pendapatan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { laporan_pendapatanActionPerformed(evt); } }); jPanel3.add(laporan_pendapatan, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 336, 276, 47)); Hitung.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 920)); Hitung1.setBackground(new java.awt.Color(180, 199, 231)); Hitung1.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 102, 255), null)); Hitung1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel19.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel19.setForeground(new java.awt.Color(0, 51, 153)); jLabel19.setText("ID PELANGGAN"); Hitung1.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 60, 143, 30)); jLabel20.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel20.setForeground(new java.awt.Color(0, 51, 153)); jLabel20.setText("NAMA"); Hitung1.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 130, -1, -1)); jLabel21.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel21.setForeground(new java.awt.Color(0, 51, 153)); jLabel21.setText("ALAMAT"); Hitung1.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 190, -1, -1)); jLabel24.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel24.setForeground(new java.awt.Color(0, 51, 153)); jLabel24.setText("JUMLAH KG"); Hitung1.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 420, -1, -1)); banyak_jaket.setAutoscrolls(false); banyak_jaket.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { banyak_jaketActionPerformed(evt); } }); banyak_jaket.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { banyak_jaketKeyReleased(evt); } }); Hitung1.add(banyak_jaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 520, 30, 20)); jLabel25.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel25.setForeground(new java.awt.Color(0, 51, 153)); jLabel25.setText("JENIS PAKAIAN LAIN"); Hitung1.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 490, -1, -1)); jLabel27.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel27.setForeground(new java.awt.Color(0, 51, 153)); jLabel27.setText("DITERIMA"); Hitung1.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 380, -1, -1)); jLabel28.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel28.setForeground(new java.awt.Color(0, 51, 153)); jLabel28.setText("SELESAI TANGGAL:"); Hitung1.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 450, -1, -1)); jLabel29.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rumahlaundry/logo besar.png"))); // NOI18N Hitung1.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 80, 280, 250)); jPanel5.setBackground(new java.awt.Color(218, 227, 243)); jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel30.setBackground(new java.awt.Color(45, 85, 151)); jLabel30.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N jLabel30.setForeground(new java.awt.Color(45, 85, 151)); jLabel30.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rumahlaundry/transaksi.png"))); // NOI18N jLabel30.setText("TRANSAKSI"); jPanel5.add(jLabel30, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 342, -1)); Hitung1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 0, 1160, 60)); no_invoice1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N no_invoice1.setForeground(new java.awt.Color(45, 85, 151)); no_invoice1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); Hitung1.add(no_invoice1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1080, 340, 140, 30)); jLabel31.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel31.setForeground(new java.awt.Color(45, 85, 151)); jLabel31.setText("No. Invoice: "); Hitung1.add(jLabel31, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 340, 120, 30)); jLabel32.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel32.setForeground(new java.awt.Color(0, 51, 153)); jLabel32.setText("JUMLAH POTONG"); Hitung1.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 250, -1, -1)); jLabel33.setText("Rp."); Hitung1.add(jLabel33, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 390, -1, -1)); jPanel6.setBackground(new java.awt.Color(156, 194, 230)); jPanel6.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel34.setBackground(new java.awt.Color(51, 102, 255)); jLabel34.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rumahlaundry/logorl.png"))); // NOI18N jPanel6.add(jLabel34, new org.netbeans.lib.awtextra.AbsoluteConstraints(23, 6, -1, -1)); jLabel35.setBackground(new java.awt.Color(45, 85, 151)); jLabel35.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N jLabel35.setForeground(new java.awt.Color(45, 85, 151)); jLabel35.setText("RUMAH"); jPanel6.add(jLabel35, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 19, -1, -1)); jLabel36.setBackground(new java.awt.Color(45, 85, 151)); jLabel36.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N jLabel36.setForeground(new java.awt.Color(45, 85, 151)); jLabel36.setText("LAUNDRY"); jPanel6.add(jLabel36, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 62, -1, -1)); dashboard1.setBackground(new java.awt.Color(230, 244, 241)); dashboard1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N dashboard1.setForeground(new java.awt.Color(45, 85, 151)); dashboard1.setText("DASHBOARD"); dashboard1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dashboard1ActionPerformed(evt); } }); jPanel6.add(dashboard1, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 124, 276, 47)); pelanggan_baru1.setBackground(new java.awt.Color(230, 244, 241)); pelanggan_baru1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N pelanggan_baru1.setForeground(new java.awt.Color(45, 85, 151)); pelanggan_baru1.setText("PELANGGAN BARU"); pelanggan_baru1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pelanggan_baru1ActionPerformed(evt); } }); jPanel6.add(pelanggan_baru1, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 177, 276, 47)); transaksi1.setBackground(new java.awt.Color(230, 244, 241)); transaksi1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N transaksi1.setForeground(new java.awt.Color(45, 85, 151)); transaksi1.setText("TRANSAKSI"); transaksi1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { transaksi1ActionPerformed(evt); } }); jPanel6.add(transaksi1, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 230, 276, 47)); data_pelanggan1.setBackground(new java.awt.Color(230, 244, 241)); data_pelanggan1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N data_pelanggan1.setForeground(new java.awt.Color(45, 85, 151)); data_pelanggan1.setText("DATA PELANGGAN"); data_pelanggan1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { data_pelanggan1ActionPerformed(evt); } }); jPanel6.add(data_pelanggan1, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 283, 276, 47)); laporan_pendapatan1.setBackground(new java.awt.Color(230, 244, 241)); laporan_pendapatan1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N laporan_pendapatan1.setForeground(new java.awt.Color(45, 85, 151)); laporan_pendapatan1.setText("LAPORAN PENDAPATAN"); laporan_pendapatan1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { laporan_pendapatan1ActionPerformed(evt); } }); jPanel6.add(laporan_pendapatan1, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 336, 276, 47)); Hitung1.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 920)); jaket.setBackground(new java.awt.Color(180, 199, 231)); jaket.setText("JAKET"); jaket.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jaketActionPerformed(evt); } }); Hitung1.add(jaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 520, 90, -1)); boneka.setBackground(new java.awt.Color(180, 199, 231)); boneka.setText("BONEKA"); boneka.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bonekaActionPerformed(evt); } }); Hitung1.add(boneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 560, 90, -1)); total.setText("Total ="); Hitung1.add(total, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 600, -1, -1)); ket_plain.setVerticalAlignment(javax.swing.SwingConstants.TOP); Hitung1.add(ket_plain, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 600, 330, 20)); total_plain.setVerticalAlignment(javax.swing.SwingConstants.TOP); total_plain.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { total_plainMouseClicked(evt); } }); Hitung1.add(total_plain, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 600, 130, 20)); selimut.setBackground(new java.awt.Color(180, 199, 231)); selimut.setText("SELIMUT"); selimut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selimutActionPerformed(evt); } }); Hitung1.add(selimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 560, 90, -1)); handuk.setBackground(new java.awt.Color(180, 199, 231)); handuk.setText("HANDUK"); handuk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { handukActionPerformed(evt); } }); Hitung1.add(handuk, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 520, 90, -1)); cbselimut.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "-", "M", "L", "XL" })); cbselimut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbselimutActionPerformed(evt); } }); Hitung1.add(cbselimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 560, 60, -1)); cbjaket.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "-", "M", "L", "XL" })); cbjaket.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbjaketActionPerformed(evt); } }); Hitung1.add(cbjaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 520, 60, -1)); cbboneka.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "-", "M", "L", "XL" })); cbboneka.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbbonekaActionPerformed(evt); } }); Hitung1.add(cbboneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 560, 60, -1)); cbhanduk.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "-", "M", "L", "XL" })); cbhanduk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbhandukActionPerformed(evt); } }); Hitung1.add(cbhanduk, new org.netbeans.lib.awtextra.AbsoluteConstraints(720, 520, 60, -1)); xboneka.setFont(new java.awt.Font("Open Sans", 0, 14)); // NOI18N xboneka.setText("x"); Hitung1.add(xboneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 560, 20, -1)); rp_selimut.setText("Rp."); Hitung1.add(rp_selimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 580, -1, -1)); txt_jml_kg.setAutoscrolls(false); txt_jml_kg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_jml_kgActionPerformed(evt); } }); txt_jml_kg.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txt_jml_kgKeyReleased(evt); } }); Hitung1.add(txt_jml_kg, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 440, 500, 30)); xjaket.setFont(new java.awt.Font("Open Sans", 0, 14)); // NOI18N xjaket.setText("x"); Hitung1.add(xjaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 520, 20, -1)); xselimut.setFont(new java.awt.Font("Open Sans", 0, 14)); // NOI18N xselimut.setText("x"); Hitung1.add(xselimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 560, 20, -1)); xhanduk.setFont(new java.awt.Font("Open Sans", 0, 14)); // NOI18N xhanduk.setText("x"); Hitung1.add(xhanduk, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 520, 20, -1)); banyak_boneka.setAutoscrolls(false); banyak_boneka.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { banyak_bonekaActionPerformed(evt); } }); banyak_boneka.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { banyak_bonekaKeyReleased(evt); } }); Hitung1.add(banyak_boneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 560, 30, 20)); banyak_selimut.setAutoscrolls(false); banyak_selimut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { banyak_selimutActionPerformed(evt); } }); banyak_selimut.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { banyak_selimutKeyReleased(evt); } }); Hitung1.add(banyak_selimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 560, 30, 20)); banyak_handuk.setAutoscrolls(false); banyak_handuk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { banyak_handukActionPerformed(evt); } }); banyak_handuk.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { banyak_handukKeyReleased(evt); } }); Hitung1.add(banyak_handuk, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 520, 30, 20)); rp_jaket.setText("Rp."); Hitung1.add(rp_jaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 540, -1, -1)); rp_handuk.setText("Rp."); Hitung1.add(rp_handuk, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 540, -1, -1)); rp_boneka.setText("Rp."); Hitung1.add(rp_boneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 580, -1, -1)); txt_total_harga.setAutoscrolls(false); txt_total_harga.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_total_hargaActionPerformed(evt); } }); Hitung1.add(txt_total_harga, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 650, 500, 30)); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel12.setForeground(new java.awt.Color(0, 51, 153)); jLabel12.setText("TOTAL HARGA"); Hitung1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 630, -1, -1)); txt_jml_potong1.setAutoscrolls(false); Hitung1.add(txt_jml_potong1, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 280, 500, 30)); jns_laundry.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "--Pilih--" })); jns_laundry.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jns_laundryActionPerformed(evt); } }); jns_laundry.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jns_laundryKeyReleased(evt); } }); Hitung1.add(jns_laundry, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 350, 500, 30)); txt_alamat.setEditable(false); txt_alamat.setAutoscrolls(false); Hitung1.add(txt_alamat, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 210, 500, 30)); txt_nama.setEditable(false); txt_nama.setAutoscrolls(false); Hitung1.add(txt_nama, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 150, 500, 30)); txt_id_pelanggan.setAutoscrolls(false); txt_id_pelanggan.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txt_id_pelangganKeyReleased(evt); } }); Hitung1.add(txt_id_pelanggan, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 90, 500, 30)); tgl_diterima.setEditable(false); tgl_diterima.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tgl_diterimaActionPerformed(evt); } }); Hitung1.add(tgl_diterima, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 410, 290, 30)); txt_tgl_selesai.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { txt_tgl_selesaiPropertyChange(evt); } }); Hitung1.add(txt_tgl_selesai, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 470, 290, 30)); btnCetakInvoice.setBackground(new java.awt.Color(230, 244, 241)); btnCetakInvoice.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N btnCetakInvoice.setForeground(new java.awt.Color(45, 85, 151)); btnCetakInvoice.setText("CETAK INVOICE"); btnCetakInvoice.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); btnCetakInvoice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCetakInvoiceActionPerformed(evt); } }); Hitung1.add(btnCetakInvoice, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 520, 290, 40)); jButton1.setText("Cek Total"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); Hitung1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 620, 100, -1)); harga_jaket.setEditable(false); harga_jaket.setBackground(new java.awt.Color(180, 199, 231)); harga_jaket.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { harga_jaketActionPerformed(evt); } }); Hitung1.add(harga_jaket, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 540, 80, 20)); harga_boneka.setEditable(false); harga_boneka.setBackground(new java.awt.Color(180, 199, 231)); Hitung1.add(harga_boneka, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 580, 80, 20)); harga_selimut.setEditable(false); harga_selimut.setBackground(new java.awt.Color(180, 199, 231)); Hitung1.add(harga_selimut, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 580, 80, 20)); harga_handuk.setEditable(false); harga_handuk.setBackground(new java.awt.Color(180, 199, 231)); Hitung1.add(harga_handuk, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 540, 80, 20)); Harga1.setText("0"); Harga1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Harga1KeyReleased(evt); } }); Hitung1.add(Harga1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 390, 90, -1)); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(0, 51, 153)); jLabel8.setText("JENIS LAUNDRY"); Hitung1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 330, -1, -1)); Hitung.add(Hitung1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jLabel37.setText("Rp."); Hitung.add(jLabel37, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 310, -1, -1)); 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() .addComponent(Hitung, javax.swing.GroupLayout.PREFERRED_SIZE, 1437, Short.MAX_VALUE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Hitung, javax.swing.GroupLayout.PREFERRED_SIZE, 919, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jns_laundryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jns_laundryActionPerformed // TODO add your handling code here: try { Statement stt = conn.createStatement(); String sql = "SELECT harga FROM tb_jns_laundry WHERE nama_jns_laundry='" +jns_laundry.getSelectedItem()+"'"; ResultSet res = stt.executeQuery(sql); while(res.next()){ Object[] ob = new Object[1]; ob[0] = res.getString(1); Harga1.setText((String) ob[0]); } res.close(); stt.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }//GEN-LAST:event_jns_laundryActionPerformed private void btnCetakInvoiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCetakInvoiceActionPerformed // TODO add your handling code here: // masuk ke tb_laundry String id_laundry = no_invoice.getText(); String jenis_laundry = jns_laundry.getSelectedItem().toString(); String jumlah_potong = txt_jml_potong1.getText(); String jumlahKG = txt_jml_kg.getText(); String jenis_pakaian_lain = ket_plain.getText(); String total_harga = txt_total_harga.getText(); try { String sql = "INSERT INTO tb_laundry (id_laundry, nama_jns_laundry, jml_potong, jml_kg," + " nama_jns_plain, total_harga) VALUES (?,?,?,?,?,?)"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, id_laundry); pst.setString(2, jenis_laundry); pst.setString(3, jumlah_potong); pst.setString(4, jumlahKG); pst.setString(5, jenis_pakaian_lain); pst.setString(6, total_harga); pst.execute(); } catch (HeadlessException | SQLException e) { JOptionPane.showMessageDialog(null, e); } // masuk ke tb_transaksi String id_member = txt_id_pelanggan.getText().toString(); String diterima = tgl_diterima.getText(); SimpleDateFormat ubahFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = String.valueOf(ubahFormat.format(txt_tgl_selesai.getDate())); try { String sql = "INSERT INTO tb_transaksi (id_member, tgl_terima, tgl_selesai, id_laundry) VALUES (?,?,?,?)"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, id_member); pst.setString(2, diterima); pst.setString(3, date); pst.setString(4, id_laundry); pst.execute(); JOptionPane.showMessageDialog(this, "Transaksi berhasil ditambahkan"); } catch (HeadlessException | SQLException e) { JOptionPane.showMessageDialog(null, e); } // cetak invoice Connection koneksi = null; try { Class.forName("com.mysql.jdbc.Driver"); koneksi = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/db_laundry", "root", ""); } catch (ClassNotFoundException ex) { Logger.getLogger(halm_transaksi.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(halm_transaksi.class.getName()).log(Level.SEVERE, null, ex); } String file = ("src/Report/nota_laundry.jrxml"); HashMap hash = new HashMap(); hash.put("id", no_invoice.getText()); JasperReport jr; try { jr = JasperCompileManager.compileReport(file); JasperPrint jp = JasperFillManager.fillReport(jr, hash, koneksi); JasperViewer.viewReport(jp); } catch (JRException ex) { System.out.println(ex); } }//GEN-LAST:event_btnCetakInvoiceActionPerformed private void tgl_diterimaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tgl_diterimaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tgl_diterimaActionPerformed private void txt_jml_kgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_jml_kgActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_jml_kgActionPerformed private void txt_total_hargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_total_hargaActionPerformed // TODO add your handling code here }//GEN-LAST:event_txt_total_hargaActionPerformed private void txt_id_pelangganKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_id_pelangganKeyReleased // TODO add your handling code here: tampil(); }//GEN-LAST:event_txt_id_pelangganKeyReleased private void jns_laundryKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jns_laundryKeyReleased // TODO add your handling code here: }//GEN-LAST:event_jns_laundryKeyReleased private void Harga1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Harga1KeyReleased // TODO add your handling code here: }//GEN-LAST:event_Harga1KeyReleased private void txt_jml_kgKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_jml_kgKeyReleased // TODO add your handling code here: int JumlahBarang1, HargaBarang1; JumlahBarang1 = Integer.parseInt(txt_jml_kg.getText()); HargaBarang1 = Integer.parseInt(Harga1.getText()); int jns_pakaian = HargaBarang1 * JumlahBarang1; txt_total_harga.setText(Integer.toString(jns_pakaian)); }//GEN-LAST:event_txt_jml_kgKeyReleased private void dashboardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dashboardActionPerformed // TODO add your handling code here: new halm_dashboard().setVisible(true); dispose(); }//GEN-LAST:event_dashboardActionPerformed private void pelanggan_baruActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pelanggan_baruActionPerformed // TODO add your handling code here: new halm_pelanggan_baru().setVisible(true); dispose(); }//GEN-LAST:event_pelanggan_baruActionPerformed private void transaksiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transaksiActionPerformed // TODO add your handling code here: }//GEN-LAST:event_transaksiActionPerformed private void data_pelangganActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_data_pelangganActionPerformed // TODO add your handling code here: new halm_data_pelanggan().setVisible(true); dispose(); }//GEN-LAST:event_data_pelangganActionPerformed private void laporan_pendapatanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_laporan_pendapatanActionPerformed // TODO add your handling code here: new halm_pendapatan().setVisible(true); dispose(); }//GEN-LAST:event_laporan_pendapatanActionPerformed private void txt_tgl_selesaiPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txt_tgl_selesaiPropertyChange // TODO add your handling code here: if (txt_tgl_selesai.getDate() != null) { SimpleDateFormat ubahFormat = new SimpleDateFormat("yyyy-MM-dd"); String date = String.valueOf(ubahFormat.format(txt_tgl_selesai.getDate())); } }//GEN-LAST:event_txt_tgl_selesaiPropertyChange private void banyak_jaketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_banyak_jaketActionPerformed // TODO add your handling code here: }//GEN-LAST:event_banyak_jaketActionPerformed private void banyak_jaketKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_banyak_jaketKeyReleased // TODO add your handling code here: try { int harga, banyak; harga = Integer.parseInt(harga_jaket.getText()); banyak = Integer.parseInt(banyak_jaket.getText()); int total = harga * banyak; harga_jaket.setText(Integer.toString(total)); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_banyak_jaketKeyReleased private void dashboard1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dashboard1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_dashboard1ActionPerformed private void pelanggan_baru1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pelanggan_baru1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pelanggan_baru1ActionPerformed private void transaksi1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transaksi1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_transaksi1ActionPerformed private void data_pelanggan1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_data_pelanggan1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_data_pelanggan1ActionPerformed private void laporan_pendapatan1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_laporan_pendapatan1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_laporan_pendapatan1ActionPerformed private void jaketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jaketActionPerformed // TODO add your handling code here: if(jaket.isSelected()) { ket_plain.setText(ket_plain.getText() +"\n JAKET"); ket_plain.setVisible(true); total.setVisible(true); total_plain.setVisible(true); jaket.setVisible(true); banyak_jaket.setVisible(true); xjaket.setVisible(true); cbjaket.setVisible(true); rp_jaket.setVisible(true); harga_jaket.setVisible(true); } else { ket_plain.setText(""); harga_jaket.setText("0"); banyak_jaket.setVisible(false); xjaket.setVisible(false); cbjaket.setVisible(false); rp_jaket.setVisible(false); harga_jaket.setVisible(false); } }//GEN-LAST:event_jaketActionPerformed private void cbjaketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbjaketActionPerformed // TODO add your handling code here: String ukuran = (String)cbjaket.getSelectedItem(); switch (ukuran){ case "M": harga_jaket.setText("1000"); break; case "L": harga_jaket.setText("2000"); break; case "XL": harga_jaket.setText("3000"); break; default: JOptionPane.showMessageDialog(this, "Silahkan pilih untuk melanjutkan!"); } }//GEN-LAST:event_cbjaketActionPerformed private void cbselimutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbselimutActionPerformed // TODO add your handling code here: String ukuran = (String)cbselimut.getSelectedItem(); switch (ukuran){ case "M": harga_selimut.setText("3000"); break; case "L": harga_selimut.setText("5000"); break; case "XL": harga_selimut.setText("7000"); break; } }//GEN-LAST:event_cbselimutActionPerformed private void cbhandukActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbhandukActionPerformed // TODO add your handling code here: String ukuran = (String)cbhanduk.getSelectedItem(); switch (ukuran){ case "M": harga_handuk.setText("1000"); break; case "L": harga_handuk.setText("1500"); break; case "XL": harga_handuk.setText("2000"); break; } }//GEN-LAST:event_cbhandukActionPerformed private void cbbonekaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbbonekaActionPerformed // TODO add your handling code here: String ukuran = (String)cbboneka.getSelectedItem(); switch (ukuran){ case "M": harga_boneka.setText("4000"); break; case "L": harga_boneka.setText("7000"); break; case "XL": harga_boneka.setText("10000"); break; } }//GEN-LAST:event_cbbonekaActionPerformed private void banyak_bonekaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_banyak_bonekaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_banyak_bonekaActionPerformed private void banyak_bonekaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_banyak_bonekaKeyReleased // TODO add your handling code here: try { int harga, banyak; harga = Integer.parseInt(harga_boneka.getText()); banyak = Integer.parseInt(banyak_boneka.getText()); int total = harga * banyak; harga_boneka.setText(Integer.toString(total)); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_banyak_bonekaKeyReleased private void banyak_selimutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_banyak_selimutActionPerformed // TODO add your handling code here: }//GEN-LAST:event_banyak_selimutActionPerformed private void banyak_selimutKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_banyak_selimutKeyReleased // TODO add your handling code here: try { int harga, banyak; harga = Integer.parseInt(harga_selimut.getText()); banyak = Integer.parseInt(banyak_selimut.getText()); int total = harga * banyak; harga_selimut.setText(Integer.toString(total)); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_banyak_selimutKeyReleased private void banyak_handukActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_banyak_handukActionPerformed // TODO add your handling code here: }//GEN-LAST:event_banyak_handukActionPerformed private void banyak_handukKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_banyak_handukKeyReleased // TODO add your handling code here:: try { int harga, banyak; harga = Integer.parseInt(harga_handuk.getText()); banyak = Integer.parseInt(banyak_handuk.getText()); int total = harga * banyak; harga_handuk.setText(Integer.toString(total)); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_banyak_handukKeyReleased private void selimutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selimutActionPerformed // TODO add your handling code here: if(selimut.isSelected()) { ket_plain.setText(ket_plain.getText() +"\n SELIMUT"); ket_plain.setVisible(true); total.setVisible(true); total_plain.setVisible(true); selimut.setVisible(true); banyak_selimut.setVisible(true); xselimut.setVisible(true); cbselimut.setVisible(true); rp_selimut.setVisible(true); harga_selimut.setVisible(true); } else { ket_plain.setText(""); harga_selimut.setText("0"); banyak_selimut.setVisible(false); xselimut.setVisible(false); cbselimut.setVisible(false); rp_selimut.setVisible(false); harga_selimut.setVisible(false); } }//GEN-LAST:event_selimutActionPerformed private void handukActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_handukActionPerformed // TODO add your handling code here: if(handuk.isSelected()) { ket_plain.setText(ket_plain.getText() +"\n HANDUK"); ket_plain.setVisible(true); total.setVisible(true); total_plain.setVisible(true); handuk.setVisible(true); banyak_handuk.setVisible(true); xhanduk.setVisible(true); cbhanduk.setVisible(true); rp_handuk.setVisible(true); harga_handuk.setVisible(true); } else { ket_plain.setText(""); harga_handuk.setText("0"); banyak_handuk.setVisible(false); xhanduk.setVisible(false); cbhanduk.setVisible(false); rp_handuk.setVisible(false); harga_handuk.setVisible(false); } }//GEN-LAST:event_handukActionPerformed private void bonekaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bonekaActionPerformed // TODO add your handling code here: if(boneka.isSelected()) { ket_plain.setText(ket_plain.getText() +"\n BONEKA"); ket_plain.setVisible(true); total.setVisible(true); total_plain.setVisible(true); boneka.setVisible(true); banyak_boneka.setVisible(true); xboneka.setVisible(true); cbboneka.setVisible(true); rp_boneka.setVisible(true); harga_boneka.setVisible(true); } else { ket_plain.setText(""); harga_boneka.setText("0"); banyak_boneka.setVisible(false); xboneka.setVisible(false); cbboneka.setVisible(false); rp_boneka.setVisible(false); harga_boneka.setVisible(false); } }//GEN-LAST:event_bonekaActionPerformed private void total_plainMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_total_plainMouseClicked // TODO add your handling code here: }//GEN-LAST:event_total_plainMouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: int jaket, selimut, handuk, boneka; jaket = Integer.parseInt(harga_jaket.getText()); selimut = Integer.parseInt(harga_selimut.getText()); handuk = Integer.parseInt(harga_handuk.getText()); boneka = Integer.parseInt(harga_boneka.getText()); int total = jaket + selimut + handuk + boneka; total_plain.setText(Integer.toString(total)); // untuk jenis laundry + jenis pakaian lain int JumlahBarang1, HargaBarang1; JumlahBarang1 = Integer.parseInt(txt_jml_kg.getText()); HargaBarang1 = Integer.parseInt(Harga1.getText()); int jns_pakaian = HargaBarang1 * JumlahBarang1; int total_bayar = total + jns_pakaian; txt_total_harga.setText(Integer.toString(total_bayar)); }//GEN-LAST:event_jButton1ActionPerformed private void harga_jaketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_harga_jaketActionPerformed // TODO add your handling code here: }//GEN-LAST:event_harga_jaketActionPerformed /** * @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(halm_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(halm_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(halm_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(halm_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new halm_transaksi().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Harga1; private javax.swing.JPanel Hitung; private javax.swing.JPanel Hitung1; private javax.swing.JTextField banyak_boneka; private javax.swing.JTextField banyak_handuk; private javax.swing.JTextField banyak_jaket; private javax.swing.JTextField banyak_selimut; private javax.swing.JCheckBox boneka; private javax.swing.JButton btnCetakInvoice; private javax.swing.JComboBox<String> cbboneka; private javax.swing.JComboBox<String> cbhanduk; private javax.swing.JComboBox<String> cbjaket; private javax.swing.JComboBox<String> cbselimut; private javax.swing.JButton dashboard; private javax.swing.JButton dashboard1; private javax.swing.JButton data_pelanggan; private javax.swing.JButton data_pelanggan1; private javax.swing.JCheckBox handuk; private javax.swing.JTextField harga_boneka; private javax.swing.JTextField harga_handuk; private javax.swing.JTextField harga_jaket; private javax.swing.JTextField harga_selimut; private javax.swing.JButton jButton1; 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 jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; 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.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JCheckBox jaket; private javax.swing.JComboBox<String> jns_laundry; private javax.swing.JLabel ket_plain; private javax.swing.JButton laporan_pendapatan; private javax.swing.JButton laporan_pendapatan1; private javax.swing.JLabel no_invoice; private javax.swing.JLabel no_invoice1; private javax.swing.JButton pelanggan_baru; private javax.swing.JButton pelanggan_baru1; private javax.swing.JLabel rp_boneka; private javax.swing.JLabel rp_handuk; private javax.swing.JLabel rp_jaket; private javax.swing.JLabel rp_selimut; private javax.swing.JCheckBox selimut; private javax.swing.JTextField tgl_diterima; private javax.swing.JLabel total; private javax.swing.JLabel total_plain; private javax.swing.JButton transaksi; private javax.swing.JButton transaksi1; private javax.swing.JTextField txt_alamat; private javax.swing.JTextField txt_id_pelanggan; private javax.swing.JTextField txt_jml_kg; private javax.swing.JTextField txt_jml_potong1; private javax.swing.JTextField txt_nama; private com.toedter.calendar.JDateChooser txt_tgl_selesai; private javax.swing.JTextField txt_total_harga; private javax.swing.JLabel xboneka; private javax.swing.JLabel xhanduk; private javax.swing.JLabel xjaket; private javax.swing.JLabel xselimut; // End of variables declaration//GEN-END:variables }
true
494c399ceabd4b86424c45ba79d5dc7bf7027fa7
Java
allenallen/core_spring_training
/jpa-hibernate/jpa-mapping/src/main/java/mapping/hibernate/usertype/demo/package-info.java
UTF-8
849
2.15625
2
[]
no_license
/** * This is for the instructor to use as a demo, and not for * participants/students. */ @TypeDefs({ @TypeDef(typeClass = PersistentMonthAsInteger.class, defaultForType = Month.class), @TypeDef(typeClass = PersistentYearAsInteger.class, defaultForType = Year.class), @TypeDef(typeClass = PersistentMonetaryAmountAsAmountAndCurrency.class, defaultForType = MonetaryAmount.class), }) package mapping.hibernate.usertype.demo; import java.time.Month; import java.time.Year; import javax.money.MonetaryAmount; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import mapping.hibernate.usertype.demo.PersistentMonthAsInteger; import mapping.hibernate.usertype.demo.PersistentYearAsInteger; import mapping.hibernate.usertype.demo.PersistentMonetaryAmountAsAmountAndCurrency;
true
db277b3ca1b4c281719cd441ef52e0be3b493b85
Java
leoschet/cloudstorage
/src/restservices/cloudstorage/BucketManager.java
UTF-8
6,174
2.515625
3
[ "MIT" ]
permissive
package restservices.cloudstorage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import restservices.exception.ElementAlreadyExistsException; import restservices.exception.ElementNotFoundException; import restservices.exception.InvalidInputException; import restservices.exception.OverWriteException; public class BucketManager extends Thread{ private Bucket bucket; private String fileName; private BlockingQueue<Message> requestQueue; public BucketManager(int id) { this.fileName = "Bucket_" + id + ".xml"; } public void run(){ requestQueue = new LinkedBlockingQueue<Message>(); this.bucket = readFile(); while(true){ Message request; Message response; request = getRequest(); switch ((ERequestMessageType) request.type) { case ADD: response = add(request); break; case OVERWRITE: response = overwrite(request); break; case REMOVE: response = remove(request); break; case SEARCH: response = search(request); break; case SEARCH_INTERVAL: response = searchInterval(request); break; case GET_ALL: response = getAll(); break; case CLEAN: response = clean(); break; default: response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); break; } sendResponse(request,response); if(request.type == ERequestMessageType.ADD || request.type == ERequestMessageType.OVERWRITE || request.type == ERequestMessageType.REMOVE|| request.type == ERequestMessageType.CLEAN){ writeFile(); } } } private void sendResponse(Message request, Message response) { try { request.getCaller().getQueue().put(response); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Message add(Message request){ Message response; if(request.getElement() != null){ try { this.bucket.add(request.getElement()); //writeFile(); response = new Message(EResponseMessageType.OK); }catch (ElementAlreadyExistsException e1) { response = new Message(EResponseMessageType.ERR); response.setException(e1); } } else{ response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); } return response; } private Message search(Message request){ Message response; if(request.getKey() != null){ try { response = new Message(EResponseMessageType.OK); response.setElement(this.bucket.search(request.getKey())); } catch (ElementNotFoundException e1) { response = new Message(EResponseMessageType.ERR); response.setException(e1); } } else{ response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); } return response; } private Message overwrite(Message request){ Message response; if(request.getElement() != null){ try { this.bucket.remove(request.getElement().getKey()); } catch (ElementNotFoundException elementNotFoundException) {} try { this.bucket.add(request.getElement()); response = new Message(EResponseMessageType.OK); } catch (ElementAlreadyExistsException elementAlreadyExistsException) { response = new Message(EResponseMessageType.ERR); response.setException(new OverWriteException()); } } else{ response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); } return response; } private Message remove(Message request){ Message response; if(request.getKey() != null){ try { this.bucket.remove(request.getKey()); //writeFile(); response = new Message(EResponseMessageType.OK); } catch (ElementNotFoundException elementNotFoundException) { response = new Message(EResponseMessageType.ERR); response.setException(elementNotFoundException); } } else{ response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); } return response; } private Message searchInterval(Message request){ Message response; if (request.getFirstKey() != null && request.getLastKey() != null) { Bucket bucket = new Bucket(this.bucket.searchInterval(request.getFirstKey(),request.getLastKey())); response = new Message(EResponseMessageType.OK); response.setBucket(bucket); } else{ response = new Message(EResponseMessageType.ERR); response.setException(new InvalidInputException()); } return response; } private Message getAll(){ Message response; response = new Message(EResponseMessageType.OK); response.setBucket(this.bucket); return response; } private Message clean(){ this.bucket = new Bucket(); //writeFile(); return new Message(EResponseMessageType.OK); } public String getFileName() { return fileName; } private void writeFile(){ try { JAXBContext contextObj = JAXBContext.newInstance(Bucket.class); Marshaller marshallerObj = contextObj.createMarshaller(); marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshallerObj.marshal(bucket, new FileOutputStream(fileName)); } catch (FileNotFoundException | JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Bucket readFile(){ Bucket bucket = null; try { File file = new File(fileName); JAXBContext jaxbContext = JAXBContext.newInstance(Bucket.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); bucket = (Bucket) jaxbUnmarshaller.unmarshal(file); } catch (JAXBException e) { bucket = new Bucket(); } return bucket; } public void queueMessage(Message msg) throws InterruptedException { requestQueue.put(msg); } private Message getRequest() { Message msg = null; while (msg == null) { msg = requestQueue.poll(); } return msg; } }
true
fa9b2e1d8bcdef2aeaa83621c0f55957be04049d
Java
igor-baiborodine/campsite-booking
/src/test/java/com/kiroule/campsite/booking/api/service/BookingServiceImplConcurrentTestIT.java
UTF-8
7,802
2.078125
2
[]
no_license
package com.kiroule.campsite.booking.api.service; import static com.kiroule.campsite.booking.api.TestHelper.CAMPSITE_ID; import static com.kiroule.campsite.booking.api.TestHelper.buildBooking; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.api.Fail.fail; import static org.assertj.core.util.Lists.newArrayList; import static org.junit.jupiter.api.Assertions.assertTrue; import com.kiroule.campsite.booking.api.BaseTestIT; import com.kiroule.campsite.booking.api.model.Booking; import com.kiroule.campsite.booking.api.model.Campsite; import com.kiroule.campsite.booking.api.repository.BookingRepository; import com.kiroule.campsite.booking.api.repository.CampsiteRepository; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.SneakyThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Concurrent integration tests for {@link BookingServiceImpl}. * * @author Igor Baiborodine */ class BookingServiceImplConcurrentTestIT extends BaseTestIT { @Autowired BookingRepository bookingRepository; @Autowired BookingService bookingService; @Autowired CampsiteRepository campsiteRepository; ExecutorService executor; LocalDate now; @BeforeEach void tearDown() { bookingRepository.deleteAll(); now = LocalDate.now(); } @Nested class CreateBooking { List<Booking> newBookings; @BeforeEach void beforeEach() { newBookings = null; } @Test void given_3_new_bookings_with_same_booking_dates__then_only_1_created() { given_threeBookingsWithSameBookingDates(1, 2); when_createBookingsConcurrently(); then_assertExecutorTerminated(); then_assertCreatedBooking(); } private void given_threeBookingsWithSameBookingDates(int startPlusDays, int endPlusDays) { Campsite campsite = campsiteRepository.findById(CAMPSITE_ID).get(); newBookings = asList( buildBooking(now.plusDays(startPlusDays), now.plusDays(endPlusDays), UUID.randomUUID(), campsite), buildBooking(now.plusDays(startPlusDays), now.plusDays(endPlusDays), UUID.randomUUID(), campsite), buildBooking(now.plusDays(startPlusDays), now.plusDays(endPlusDays), UUID.randomUUID(), campsite)); } private void when_createBookingsConcurrently() { executor = Executors.newFixedThreadPool(newBookings.size()); newBookings.forEach(b -> executor.execute(() -> bookingService.createBooking(b))); executor.shutdown(); } private void then_assertCreatedBooking() { Iterable<Booking> bookings = bookingRepository.findAll(); assertThat(bookings).hasSize(1); UUID uuid = bookings.iterator().next().getUuid(); // To avoid org.hibernate.LazyInitializationException for campsite field, // use BookingService to fetch booking in question Booking createdBooking = bookingService.findByUuid(uuid); Booking newBooking = newBookings.stream().filter(b -> b.getUuid().equals(uuid)).findFirst().get(); assertThat(createdBooking).usingRecursiveComparison() .ignoringFields("id", "version", "createdAt", "updatedAt", "campsite").isEqualTo(newBooking); assertThat(createdBooking.getCampsite()).usingRecursiveComparison() .ignoringFields("$$_hibernate_interceptor").isEqualTo(newBooking.getCampsite()); } } @Nested class UpdateBooking { List<Booking> existingBookings; List<Booking> existingBookingUpdates; @BeforeEach void beforeEach() { existingBookings = new ArrayList<>(); existingBookingUpdates = new ArrayList<>(); } @Test void given_2_updates_for_same_existing_booking__then_only_1_update_executed() { given_existingBooking(1, 2, UUID.randomUUID()); given_twoUpdatesForExistingBooking(); when_updateBookingConcurrently(); then_assertExecutorTerminated(); then_assertOptimisticLockingBookingUpdate(); } @Test void given_3_updated_bookings_with_same_booking_dates__then_only_1_updated() { given_existingBooking(1, 2, UUID.randomUUID()); given_existingBooking(3, 4, UUID.randomUUID()); given_existingBooking(5, 6, UUID.randomUUID()); given_sameBookingDatesUpdateForExistingBookings(7, 8); when_updateBookingConcurrently(); then_assertExecutorTerminated(); then_assertPessimisticLockingBookingUpdate(7, 8); } private void given_existingBooking(int startPlusDays, int endPlusDays, UUID uuid) { Booking booking = buildBooking(now.plusDays(startPlusDays), now.plusDays(endPlusDays), uuid); Booking savedBooking = bookingRepository.save(booking); existingBookings.add(savedBooking); assumeThat(savedBooking.isNew()).isFalse(); assumeThat(savedBooking.isActive()).isTrue(); assumeThat(savedBooking.getVersion()).isEqualTo(0L); } private void given_twoUpdatesForExistingBooking() { existingBookingUpdates = asList( updateBooking(0, 3, 5), updateBooking(0, 13, 15)); } private void given_sameBookingDatesUpdateForExistingBookings(int startPlusDays, int endPlusDays) { existingBookingUpdates = asList( updateBooking(0, startPlusDays, endPlusDays), updateBooking(1, startPlusDays, endPlusDays), updateBooking(2, startPlusDays, endPlusDays)); } private Booking updateBooking(int index, int startPlusDays, int endPlusDays) { Booking booking = existingBookings.get(index); Booking updatedBooking = booking.toBuilder().startDate(now.plusDays(startPlusDays)) .endDate(now.plusDays(endPlusDays)).build(); updatedBooking.setCreatedAt(booking.getCreatedAt()); updatedBooking.setUpdatedAt(booking.getUpdatedAt()); return updatedBooking; } private void when_updateBookingConcurrently() { executor = Executors.newFixedThreadPool(existingBookingUpdates.size()); existingBookingUpdates.forEach(b -> executor.execute(() -> bookingService.updateBooking(b))); executor.shutdown(); } private void then_assertOptimisticLockingBookingUpdate() { List<Booking> bookings = newArrayList(bookingRepository.findAll()); assertThat(bookings).hasSize(1); Booking updatedBooking = bookings.get(0); assertThat(updatedBooking.getVersion()).isEqualTo(1L); assertThat(updatedBooking.getStartDate()).isNotEqualTo(existingBookings.get(0).getStartDate()); assertThat(updatedBooking.getEndDate()).isNotEqualTo(existingBookings.get(0).getEndDate()); } private void then_assertPessimisticLockingBookingUpdate(int startPlusDays, int endPlusDays) { List<Booking> bookings = newArrayList(bookingRepository.findAll()); assertThat(bookings).hasSize(3); bookings.forEach(b -> { if (b.getVersion() == 0L) { assertThat(b.getStartDate()).isNotEqualTo(now.plusDays(startPlusDays)); assertThat(b.getEndDate()).isNotEqualTo(now.plusDays(endPlusDays)); } else if (b.getVersion() == 1L) { assertThat(b.getStartDate()).isEqualTo(now.plusDays(startPlusDays)); assertThat(b.getEndDate()).isEqualTo(now.plusDays(endPlusDays)); } else { fail("Illegal version value for %s", b); } }); } } @SneakyThrows private void then_assertExecutorTerminated() { assertTrue(executor.awaitTermination(1, TimeUnit.MINUTES)); } }
true
8cf5b70d467fa81b8b40ae803fcbcbd36ac4ee14
Java
arielalvesdutra/hcrpr-backend
/src/test/java/dev/arielalvesdutra/hcrpr/builders/dto/builders/CreateTechniqueDTOBuilder.java
UTF-8
565
2.4375
2
[]
no_license
package dev.arielalvesdutra.hcrpr.builders.dto.builders; import dev.arielalvesdutra.hcrpr.controllers.dto.CreateTechniqueDTO; public class CreateTechniqueDTOBuilder { private CreateTechniqueDTO techniqueDto = new CreateTechniqueDTO(); public CreateTechniqueDTOBuilder withName(String name) { this.techniqueDto.setName(name); return this; } public CreateTechniqueDTOBuilder withDescription(String description) { this.techniqueDto.setDescription(description); return this; } public CreateTechniqueDTO build() { return this.techniqueDto; } }
true
683cfb199380261eac098d1ba4e6499411b22546
Java
akki27/QrCodeScanner
/app/src/main/java/com/akki/qrcodescanner/network/DataApis.java
UTF-8
1,093
2.328125
2
[]
no_license
package com.akki.qrcodescanner.network; import android.content.Context; import android.util.Log; import com.akki.qrcodescanner.model.GenericResponse; import com.akki.qrcodescanner.util.CommonUtils; import static android.content.ContentValues.TAG; /** * Created by E01106 on 11/10/2017. */ public class DataApis { private Context mContext; String networkError = "Network not found!"; /** * Constructor of DataApis * @param context The context of the class which instantiate it */ public DataApis(Context context){ this.mContext = context; } public void loginWithServer(final String monumentName, final String userName, final String password, final ApiCallback<GenericResponse> callback){ Log.d(TAG,"loginWithServer()"); if (CommonUtils.hasInternetConnection(mContext)) { if (monumentName != null && userName != null && password != null) { //Execute Api here and send the callbacks to the caller } } else { callback.onError(networkError); } } }
true
ed448abdc3d9ec23bb12a3fcf45b02febd6b7aea
Java
zbw910611/java-basic
/src/main/java/com/zbw/basic/JavaBasic.java
UTF-8
3,413
2.96875
3
[]
no_license
package com.zbw.basic; import com.alibaba.fastjson.JSON; import com.zbw.basic.excel.export.entity.Student; import java.util.ArrayList; import java.util.List; public class JavaBasic { public static void main(String[] args){ // System.out.println("JavaBasic"); // List<String> stringList = new ArrayList<>(); // stringList.add("1"); // stringList.add("2"); // stringList.add("3"); // System.out.println(stringList); // //使用二维数组生成排班模型 // int[][] arr = new int[4][31]; // int data; //数值 // //循环赋值,获取排班模板 // for(int row = 0;row < arr.length;row++){ // for(int col = 0;col <arr[row].length;col++){ // data = row + col + 1; // arr[row][col] = data %3+1; // } // } //// System.out.println(JSON.toJSONString(data)); // System.out.println(JSON.toJSONString(arr)); // // for(int row = 0;row < arr.length;row++){ // for(int col = 0;col <arr[row].length;col++){ // System.out.print(arr[row][col]); // } // System.out.println(); // } // Long i = Long.parseLong("1000"); // Long j = Long.parseLong("1000"); // System.out.print(i.equals(j)); // List<Student> studentList1 = new ArrayList<>(); // List<Student> studentList2 = new ArrayList<>(); // Student student = new Student(); // student.setId("11"); // studentList1.add(student); // student = new Student(); // student.setId("12"); // studentList1.add(student); // student = new Student(); // student.setId("13"); // studentList1.add(student); // // student = new Student(); // student.setId("11"); // studentList2.add(student); // student = new Student(); // student.setId("12"); // studentList2.add(student); // student = new Student(); // student.setId("13"); // studentList2.add(student); // student = new Student(); // student.setId("14"); // studentList2.add(student); // student = new Student(); // student.setId("15"); // studentList2.add(student); // student = new Student(); // student.setId("16"); // studentList2.add(student); // System.out.println(JSON.toJSONString(studentList1)); // System.out.println(JSON.toJSONString(studentList2)); // // for (int i = 0;i <= studentList2.size() - 1;i++){ // if (studentList1.size() -1 >= i){ // System.out.println(i); // } else { // System.out.println("a" + i); // } // } String string = "develop##wl0001"; // System.out.println(string.indexOf("#")); // System.out.println(string.substring(0,string.indexOf("#"))); // System.out.println(string.substring(string.indexOf("#") + 1,string.length())); // String string1 = "develop#wl0001"; // System.out.println(string1.lastIndexOf("#")); // System.out.println(string.substring(0,string.lastIndexOf("#"))); // System.out.println(string1.substring(string1.lastIndexOf("#") + 1,string1.length())); System.out.println(string.length()); System.out.println(string.substring(0,15)); System.out.println(); } }
true
394b973aaa90227620c3cf7b79246167a7ad969e
Java
unclebae/boot-file-upload
/src/main/java/com/example/boot/fileupload/demofileuploadboot/FormDataWithFile.java
UTF-8
233
1.507813
2
[]
no_license
package com.example.boot.fileupload.demofileuploadboot; import org.springframework.web.multipart.MultipartFile; public class FormDataWithFile { private String name; private String email; private MultipartFile file; }
true
73fa94d29f2ad5a03998c9a44558791405bb1d9d
Java
KKAKDI/FRESEARCH
/2. 개발/FreSearch/src/main/java/org/fs/mapper/StatsMapper.java
UTF-8
1,170
1.554688
2
[]
no_license
package org.fs.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.fs.domain.Criteria; import org.fs.domain.StatsVO; public interface StatsMapper { public List<StatsVO> getList(); public List<StatsVO> getMemberList(); public List<StatsVO> getAttCategory(); public List<StatsVO> getAge(); public int getAddr(String addr); public List<StatsVO> getCategory(String area); public List<StatsVO> getCategoryAge(@Param("startAge")int startAge,@Param("endAge") int endAge); public List<StatsVO> getCategorySex(String sex); public List<StatsVO> getCategoryMarriage(String marriage); public List<StatsVO> getTable(StatsVO vo); public List<StatsVO> getTableTest(@Param("vo")StatsVO vo, @Param("cri")Criteria cri); public int getTableCount(StatsVO vo); public List<StatsVO> getTableSearch(@Param("vo")StatsVO vo, @Param("cri")Criteria cri); public List<StatsVO> getStatsContent(String subj_code); public List<StatsVO> getStatsContentShortAnswer(String subj_code); public int contentCount(String subj_code); public List<StatsVO> header(String mb_email); public int headerUpdate(String subj_code); }
true
fb0e03342f126943bb722a9f506613ab9250bfbd
Java
459190939/springmvc-wang
/project-wang/wang-notify/src/main/java/com/wang/rocketmq/spring/SendMessByRq.java
UTF-8
1,869
2.203125
2
[ "MIT" ]
permissive
package com.wang.rocketmq.spring; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.alibaba.rocketmq.client.producer.SendResult; import com.alibaba.rocketmq.client.producer.SendStatus; import com.alibaba.rocketmq.common.message.Message; @Service(value = "sendMessByRq") public class SendMessByRq { private org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(this.getClass()); @Resource private Producer rocketMqProducer; public boolean send(String topic, String tags, String keys, String body) { boolean flag=false; try { Message msg = new Message(topic, tags, keys, body.getBytes("UTF8")); logger.info("************************准备发送信息************************"); SendResult result = rocketMqProducer.send(msg); // 当消息发送失败时如何处理 if (result == null || result.getSendStatus() != SendStatus.SEND_OK) { // TODO logger.info("************************发送失败,发送状态:" + result.getSendStatus() + "************************"); } else { logger.info("************************id:" + result.getMsgId() +" result:" + result.getSendStatus()+"************************"); flag=true; } } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } }finally{ } return flag; } public static void main(String[] args) { new SendMessByRq().send("HomeActionTopic", "sms", "1", "test"); } }
true
c7a35d83f11d949baed11001c41a78cdfc6d45b9
Java
SunseekerUser/strategy-app
/src/utilities/KmlParser.java
UTF-8
2,388
2.3125
2
[]
no_license
package utilities; import de.micromata.opengis.kml.v_2_2_0.*; import javafx.application.Platform; import javafx.scene.control.Alert; import java.io.File; import java.util.List; /** * Created by broderick on 09/04/17. */ public class KmlParser { public static void main(String[] args) { checkLegs(); // getLegs("./kml/ASC 2016.kml"); } public static void checkLegs() { File folder = new File("kml"); if (!folder.exists()) { folder.mkdir(); kmlError(); } File[] files = folder.listFiles(); if (files.length < 1) { kmlError(); } for (File file : files) { String[] nameTokens = file.getName().split("\\.(?=[^\\.]+$)"); File testFolder = new File("legs/" + nameTokens[0]); // System.out.println(testFolder.getName()); // if(!testFolder.exists()){ getLegs("./kml/" + file.getName()); // } } } private static void getLegs(String filepath) { final Kml kml = Kml.unmarshal(new File(filepath)); final Document document = (Document) kml.getFeature(); String eventName = document.getName(); // System.out.println(eventName); List<Feature> features = document.getFeature(); for (Object object : features) { Folder folder = (Folder) object; String legName = folder.getName(); legName = legName.replace(":", ""); List<Feature> folderFeatures = folder.getFeature(); for (Object folderFeature : folderFeatures) { Placemark placemark = (Placemark) folderFeature; Geometry geometry = placemark.getGeometry(); if (geometry instanceof LineString) { // System.out.println(legName); LineString lineString = (LineString) geometry; List<Coordinate> coordinates = lineString.getCoordinates(); String newFolderName = String.format("legs/%s", eventName); File directory = new File(newFolderName); // System.out.println(newFolderName); // if (!directory.exists()) { directory.mkdir(); // } String newFileName = String.format("legs/%s/%s", eventName, legName); File file = new File(newFileName); Position.convertCoordinatesToPosition(coordinates, newFileName); } } } } private static void kmlError() { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("KML Error"); alert.setHeaderText("KML Error"); alert.setContentText(".kml file must be placed inside kml folder"); alert.showAndWait(); Platform.exit(); System.exit(1); } }
true
292fad93fa776a33a16e8e4b66b7dfb25608703c
Java
jsinglet/VerilyIdeaPlugin
/src/verily/facet/VerilyFrameworkSupportProvider.java
UTF-8
2,254
1.804688
2
[]
no_license
package verily.facet; import com.intellij.facet.ui.FacetBasedFrameworkSupportProvider; import com.intellij.framework.library.DownloadableLibraryService; import com.intellij.framework.library.FrameworkSupportWithLibrary; import com.intellij.ide.util.frameworkSupport.FrameworkSupportConfigurableBase; import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel; import com.intellij.ide.util.frameworkSupport.FrameworkSupportProviderBase; import com.intellij.ide.util.frameworkSupport.FrameworkVersion; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ui.configuration.libraries.CustomLibraryDescription; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import verily.library.VerilyLibraryType; import java.util.List; public class VerilyFrameworkSupportProvider extends FacetBasedFrameworkSupportProvider<VerilyFacet> { public VerilyFrameworkSupportProvider() { super(VerilyFacetType.INSTANCE); } @Override protected void setupConfiguration(VerilyFacet facet, ModifiableRootModel rootModel, FrameworkVersion version) { // } @Override public String getTitle() { return "Verily Framework"; } @NotNull @Override public FrameworkSupportConfigurableBase createConfigurable(@NotNull FrameworkSupportModel model) { return new VerilyFrameworkSupportConfigurable(this, model, getVersions(), getVersionLabelText()); } private static class VerilyFrameworkSupportConfigurable extends FrameworkSupportConfigurableBase implements FrameworkSupportWithLibrary { private VerilyFrameworkSupportConfigurable(FrameworkSupportProviderBase frameworkSupportProvider, FrameworkSupportModel model, @NotNull List<FrameworkVersion> versions, @Nullable String versionLabelText) { super(frameworkSupportProvider, model, versions, versionLabelText); } @Override @NotNull public CustomLibraryDescription createLibraryDescription() { return DownloadableLibraryService.getInstance().createDescriptionForType(VerilyLibraryType.class); } @Override public boolean isLibraryOnly() { return false; } } }
true
7278a8649dcde0ad9104a6324cd3a95053361e73
Java
Demokrator/BlueJ
/HINDERNISSE.java
UTF-8
1,272
2.671875
3
[]
no_license
import ea.*; import java.util.*; public class HINDERNISSE { protected Figur hinderniss; //private Rechteck hinderniss; // nur temporär protected int ID = 1; private int x; private int y; private int breite; private int laenge; private Random zufall; private String[] pfade = {"files/visual/figuren/Mauer.eaf", "files/visual/figuren/Kugel.eaf"}; public HINDERNISSE(int Nx,int Ny,int Nb, int Nl) { x=Nx; y=Ny; breite=Nb; laenge=Nl; zufall = new Random(); int tmpSprite = zufall.nextInt(pfade.length); hinderniss = new Figur(Nx, Ny, pfade[tmpSprite]); //hinderniss=new Rechteck(Nx,Ny,Nb,Nl); } public void bewegen(int x, int y) { hinderniss.bewegen(x, y); } public HINDERNISSE getThis() { return this; } public int getX() { return (int)hinderniss.getX(); } public int getY() { return (int)hinderniss.getY(); } public int getBreite() { return (int)hinderniss.getBreite(); } public int getHoehe() { return (int)hinderniss.getHoehe(); } public Figur getRechteck() { return hinderniss; } }
true
3e6a2ce0bffa8336677c393cebbb30174fbd5dde
Java
18218368055/july
/src/july/july-utils/src/main/java/com/qylyx/july/utils/check/ValidateUtils.java
UTF-8
4,557
3.046875
3
[]
no_license
package com.qylyx.july.utils.check; import java.util.Collection; import org.apache.commons.lang3.StringUtils; /** * 验证工具类 * @author Qiaoxin.Hong * */ public class ValidateUtils { /** * 是否为空 * <pre> * null => true * coll.size() == 0 => true * </pre> * @param coll 集合 * @return true:为空 false:不为空 */ public static boolean isEmpty(Collection<?> coll) { return coll == null || coll.size() == 0; } /** * 是否不为空 * <pre> * null => false * coll.size() == 0 => false * </pre> * @param coll 集合 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(Collection<?> coll) { return !isEmpty(coll); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param coll 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(Object[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param coll 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(Object[] arr) { return isEmpty(arr); } /** * 是否为空,只要有一元素为空 * <pre> * null => true * "" => true * </pre> * @param arr * @return */ public static boolean isEmpty(String...arr) { for (String str : arr) { if (StringUtils.isEmpty(str)) return true; } return false; } /** * 是否不为空,只要有一元素为空 * <pre> * null => false * "" => false * </pre> * @param arr * @return */ public static boolean isNotEmpty(String...arr) { return isEmpty(arr); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param arr 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(char[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param arr 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(char[] arr) { return !isEmpty(arr); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param arr 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(int[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param arr 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(int[] arr) { return !isEmpty(arr); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param arr 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(long[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param arr 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(long[] arr) { return !isEmpty(arr); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param arr 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(double[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param arr 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(double[] arr) { return !isEmpty(arr); } /** * 是否为空 * <pre> * null => true * arr.length == 0 => true * </pre> * @param arr 数组 * @return true:为空 false:不为空 */ public static boolean isEmpty(float[] arr) { return arr == null || arr.length ==0; } /** * 是否不为空 * <pre> * null => false * arr.length == 0 => false * </pre> * @param arr 数组 * @return true:不为空 false:为空 */ public static boolean isNotEmpty(float[] arr) { return !isEmpty(arr); } }
true
d19efa85debfbd5cd0c8fa5f15f71f68e9b8deff
Java
jh950925/green
/Study/src/Day027/Ex001.java
UTF-8
1,715
3.890625
4
[]
no_license
package Day027; class CA{ private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } public CA() { super(); System.out.println("[CA() 1. CA안의 a 변수 : 인스턴스변수 a 를 사용할 수 있게 생성자가 초기화"); System.out.println("\t"+this.toString()); } public CA(int a) { super(); this.a = a; } @Override public String toString() { return "CA [a=" + a + "]"; } } class CB extends CA{ private int b; public CB() { super(); System.out.println("[CB() 1. CB안의 b 변수 : 인스턴스변수 b 를 사용할 수 있게 생성자가 초기화"); System.out.println("\t"+this.toString()); // CB [b=0] } public CB(int b) { super(); this.b = b; } @Override public String toString() { return "CB [b=" + b + "]"; } } public class Ex001 { public static void main(String[] args) { System.out.println("1-1. 상속이란 객체를 재활용하는것이 목적임."); System.out.println("1-2. 상속을 하려면 기존의 어떤 클래스가 먼저 생성되어야 함."); System.out.println("1-3. 클래스 생성순서 Object => CA => CB"); CB fishbread = new CB(); System.out.println(fishbread); //생성되는 순서 : Object => CA => CB //호출되는 순서 : CB => CA => Object ////////////////////////////////// //객체 => 클래스 : 어떤 사물을 나타낼대는 상태와 행위로 구분하여 표시하는 것이 가능하다. //Object [멤버변수 : / 멤버함수 : ] //CA [멤버변수 : a=0 / 멤버함수 : ----------, getA, setA ] //CA [멤버변수 : b=0 / 멤버함수 : @Override toString(), getB, setB ] } }
true
a2df3fa82849a37cffb27a060b637fc24294fe96
Java
simraan09/java-tutorial
/UserInput.java
UTF-8
260
3.125
3
[]
no_license
import java.util.Scanner; public class UserInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int age = scanner.nextInt(); System.out.println("Age: " + age); scanner.close(); } }
true
dd04ae0093a851b14ae58142ff71623476120e76
Java
triniwiz/android-runtime
/test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/StreamWriter.java
UTF-8
307
2.046875
2
[ "Apache-2.0" ]
permissive
package com.telerik.metadata; import java.io.IOException; public interface StreamWriter { int getPosition() throws IOException; void write(byte b) throws IOException; void write(byte[] buffer) throws IOException; void flush() throws IOException; void close() throws IOException; }
true
8b2dad1dbdd468c3ee5f3bdf71dcecd608fcbd3c
Java
wuyizhong/SpringFramework.wangmeng.definition
/benefits/benefits-moudle/benefits-bean/src/main/java/com/lx/benefits/bean/vo/entercreditinfo/CreditRefundRecorderExcelModel.java
UTF-8
2,466
2.078125
2
[]
no_license
package com.lx.benefits.bean.vo.entercreditinfo; import java.math.BigDecimal; import java.util.Date; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.metadata.BaseRowModel; import com.lx.benefits.bean.enums.CreditType; /** * 退款记录表格 * * @author qixian * */ public class CreditRefundRecorderExcelModel extends BaseRowModel { @ExcelProperty(index = 1, value = "退款编号") private String cashNumber; @ExcelProperty(index = 1, value = "企业名称") private String enterprName; private Integer creditType; @ExcelProperty(index = 1, value = "退款类型") private String creditTypeName; @ExcelProperty(index = 1, value = "退款金额") private BigDecimal cashAmount; @ExcelProperty(index = 1, value = "审批人") private String checkUser; @ExcelProperty(index = 1, value = "退款时间") private Date checkTime; @ExcelProperty(index = 1, value = "打款凭证") private String payVoucher; public String getCashNumber() { return cashNumber; } public void setCashNumber(String cashNumber) { this.cashNumber = cashNumber; } public String getEnterprName() { return enterprName; } public void setEnterprName(String enterprName) { this.enterprName = enterprName; } public Integer getCreditType() { return creditType; } public void setCreditType(Integer creditType) { this.creditType = creditType; if (creditType != null) { if (CreditType.encourage.getCode() == creditType) { this.setCreditTypeName("认可激励积分"); } else if (CreditType.normal.getCode() == creditType) { this.setCreditTypeName("普通积分"); } else if (CreditType.festive.getCode() == creditType) { this.setCreditTypeName("节日积分"); } } } public String getCreditTypeName() { return creditTypeName; } public void setCreditTypeName(String creditTypeName) { this.creditTypeName = creditTypeName; } public BigDecimal getCashAmount() { return cashAmount; } public void setCashAmount(BigDecimal cashAmount) { this.cashAmount = cashAmount; } public String getCheckUser() { return checkUser; } public void setCheckUser(String checkUser) { this.checkUser = checkUser; } public Date getCheckTime() { return checkTime; } public void setCheckTime(Date checkTime) { this.checkTime = checkTime; } public String getPayVoucher() { return payVoucher; } public void setPayVoucher(String payVoucher) { this.payVoucher = payVoucher; } }
true
e1f41e92ad074579f3ea2a090888a8f0d9acb1a5
Java
arya6198/netflix-pseudonymizer
/scoreboard/src/main/java/es/jmgoncalv/pseudo/scoreboard/ScoreboardMain.java
UTF-8
2,804
2.375
2
[]
no_license
package es.jmgoncalv.pseudo.scoreboard; import java.io.File; import java.io.IOException; import java.util.NoSuchElementException; import java.util.Scanner; import es.jmgoncalv.pseudo.netflix.Dataset; import es.jmgoncalv.pseudo.netflix.UserIdMap; public class ScoreboardMain { public static final String USERS_INDEX_FILE = "users.index.txt"; public static final String DATASET_DIR = "training_set"; public static final String MAPPING_FILE = "pseudo-mapping.txt"; // public static final String ORIGINAL_DIR = "pseudo"; // public static final String PSEUDO_DIR = "verify"; // public static final String OUTPUT_ORIGINAL = "scoreboard-output-original.txt"; // public static final String OUTPUT_PSEUDO = "scoreboard-output-pseudo.txt"; public static void main(String[] args) throws IOException, InterruptedException { // default args String tDir = "."; String aDir = "~"+File.separator+"pseudo"; String out = "scoreboard-output.txt"; double errorMargin = 0.02; // get args if (args.length>0) { tDir = args[0]; if (args.length>1) { aDir = args[1]; if (args.length>2) { try { errorMargin = Double.parseDouble(args[2]); } catch (NumberFormatException e) { System.out.println("Error: Could not parse error margin '"+args[2]+"'!"); } if (args.length>3) out = args[3]; } } } // initialize target dataset File[] tFileList = new File(tDir+File.separator+DATASET_DIR).listFiles(); File tUserIndexFile = new File(tDir+File.separator+USERS_INDEX_FILE); if (tFileList==null) System.out.println("Directory "+(new File(tDir+File.separator+DATASET_DIR)).getAbsolutePath()+" does not exist!"); if (!tUserIndexFile.exists()) System.out.println("File "+tUserIndexFile.getAbsolutePath()+" does not exist!"); Dataset tds = new Dataset(tFileList, tUserIndexFile); Thread.sleep(2000); // initialize aux source dataset File[] aFileList = new File(aDir+File.separator+DATASET_DIR).listFiles(); File aUserIndexFile = new File(aDir+File.separator+USERS_INDEX_FILE); if (aFileList==null) System.out.println("Directory "+(new File(aDir+File.separator+DATASET_DIR)).getAbsolutePath()+" does not exist!"); if (!aUserIndexFile.exists()) System.out.println("File "+aUserIndexFile.getAbsolutePath()+" does not exist!"); Dataset ads = new Dataset(aFileList, aUserIndexFile); // load mapping between target and source ids File mappingFile = new File(tDir+File.separator+MAPPING_FILE); UserIdMap uim = new UserIdMap(mappingFile, ads); // assumes aux source is the original // calculation ScoreboardSampling smc = new ScoreboardSampling(ads, tds, uim, errorMargin, tDir+File.separator+out); //smc.outputResults(tDir+File.separator+out); } }
true
ded606c2e9d0a9ba22d592bb552ac2fc63101388
Java
wangbaisme/waveSideView
/src/main/java/com/gdszzy/test03/wavesidebar/ui/ContactGroupsAdapter.java
UTF-8
3,123
2.1875
2
[]
no_license
package com.gdszzy.test03.wavesidebar.ui; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.gdszzy.test03.R; import java.util.List; /** * Contact联系人适配器 */ public class ContactGroupsAdapter extends RecyclerView.Adapter<ContactGroupsAdapter.ContactsViewHolder> { private Context context; private List<ContactModel.ContactGroup> contactGroups; private static final String TAG = "ContactGroupsAdapter"; private int lastItem = -1; private int currentItem = -1; private int currentChildItem = -1; public ContactGroupsAdapter(List<ContactModel.ContactGroup> contactGroups) { this.contactGroups = contactGroups; } @Override public ContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { this.context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.layaout_item_contacts, null); return new ContactsViewHolder(view); } @Override public void onBindViewHolder(ContactsViewHolder holder, int position) { ContactModel.ContactGroup contactGroup = contactGroups.get(position); holder.tvIndex.setVisibility(View.VISIBLE); holder.tvIndex.setText(contactGroup.getIndex()); ContactsAdapter mAdapter = new ContactsAdapter(contactGroup.getList()) { @Override void onSelect(ContactModel contact, int childPosition) { if (currentItem != position) { lastItem = currentItem; currentItem = position; currentChildItem = childPosition; setSelectItem(); } else { if (currentChildItem != childPosition) { setSelect(currentChildItem, childPosition); currentChildItem = childPosition; } } } }; if (currentItem == position) { mAdapter.setSelect(currentChildItem); } holder.itemRecyclerView.setItemAnimator(null); holder.itemRecyclerView.setLayoutManager(new GridLayoutManager(context, 5)); holder.itemRecyclerView.setAdapter(mAdapter); } private void setSelectItem() { if (lastItem != -1) notifyItemChanged(lastItem); notifyItemChanged(currentItem); } @Override public int getItemCount() { return contactGroups.size(); } class ContactsViewHolder extends RecyclerView.ViewHolder { TextView tvIndex; RecyclerView itemRecyclerView; ContactsViewHolder(View itemView) { super(itemView); tvIndex = (TextView) itemView.findViewById(R.id.tv_index); itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler); } } }
true
88948bbb9b8a779ba408c4ac9d3ea7307da3d265
Java
mustafaduyarer/Assignment-6-Nested-For-Loop-Level-EXTRA-SPICY-
/Question_6.java
UTF-8
285
3.0625
3
[]
no_license
package Assignment6_NestedForLoop; public class Question_6 { public static void main(String[] args) { for(int x=1;x<=5;x++) { int a=0,b=4; for(int y=1;y<=x; y++){ int s=x+a; System .out.print (s+"" + ""); a=a+b; b--; } System .out .println (); } } }
true
28840dc75d45e32e34a7b470feb9418115f21f66
Java
gaoxiaofei90/hospital-parent
/hospital-service/src/main/java/com/llw/hospital/dto/SysDemoDto.java
UTF-8
1,623
1.804688
2
[]
no_license
package com.llw.hospital.dto; import com.jcl.dto.BaseDto; import java.util.Date; public class SysDemoDto extends BaseDto { private Long demoId; private String name; private Integer sex; private Long orgId; private Date ctime; private String aaa027; private Integer sysCode; private String busiType; private String zoneCode; public String getBusiType() { return busiType; } public void setBusiType(String busiType) { this.busiType = busiType; } public String getZoneCode() { return zoneCode; } public void setZoneCode(String zoneCode) { this.zoneCode = zoneCode; } public Integer getSysCode() { return sysCode; } public void setSysCode(Integer sysCode) { this.sysCode = sysCode; } public String getAaa027() { return aaa027; } public void setAaa027(String aaa027) { this.aaa027 = aaa027; } public Long getDemoId() { return demoId; } public void setDemoId(Long demoId) { this.demoId = demoId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Long getOrgId() { return orgId; } public void setOrgId(Long orgId) { this.orgId = orgId; } public Date getCtime() { return ctime; } public void setCtime(Date ctime) { this.ctime = ctime; } }
true
17b40448e6dcbe4dcb47dbe8ca4be117b0e78a1f
Java
phamtruong0216/laptoppnt
/src/main/java/com/phamngoctruong/laptoppnt/model/Order.java
UTF-8
2,730
2.015625
2
[]
no_license
package com.phamngoctruong.laptoppnt.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Entity @Table(name = "orders") @JsonIgnoreType public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonProperty("transaction") @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "transaction_id") private Transaction transaction; @Column(name = "sku_order") private String sku_order; @Column(name = "price") private double price; @JsonProperty("user") @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}) @JoinColumn(name = "user_id") private User user; @Column(name = "quantity") private int quantity; @Column(name = "total") private double total; @JsonProperty("address") @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "address_id") private AddressOrder address; @JsonFormat(pattern="dd/MM/yyyy") @Column(name = "created_date") @DateTimeFormat(pattern = "yyyy-MM-dd") @Temporal(TemporalType.DATE) private Date createdDate; @Column(name = "processs") private boolean processs; @JsonProperty("payment") @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "pay_id") private Payment payment; @JsonProperty("product") @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinTable(name = "orders_products", joinColumns = { @JoinColumn(name = "orders_id") }, inverseJoinColumns = { @JoinColumn(name = "products_id") }) private List<Product> product = new ArrayList<Product>(); @Column(name = "note") private String note; }
true
679599fb2c6060947aa4d6753210a1cc253346f2
Java
threimer/goobi
/Goobi/src/de/sub/goobi/export/download/ExportPdf.java
UTF-8
11,237
1.585938
2
[]
no_license
package de.sub.goobi.export.download; /** * This file is part of the Goobi Application - a Workflow tool for the support of mass digitization. * * Visit the websites for more information. * - https://goobi.io * - https://www.intranda.com * - https://github.com/intranda/goobi * * 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 2 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, write to the Free Software Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions * of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to * link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this * library, you may extend this exception to your version of the library, but you are not obliged to do so. If you do not wish to do so, delete this * exception statement from your version. */ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.faces.context.FacesContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.goobi.beans.Process; import de.sub.goobi.config.ConfigurationHelper; import de.sub.goobi.helper.FacesContextHelper; import de.sub.goobi.helper.Helper; import de.sub.goobi.helper.NIOFileUtils; import de.sub.goobi.helper.StorageProvider; import de.sub.goobi.helper.exceptions.DAOException; import de.sub.goobi.helper.exceptions.ExportFileException; import de.sub.goobi.helper.exceptions.SwapException; import de.sub.goobi.helper.exceptions.UghHelperException; import de.sub.goobi.helper.tasks.CreatePdfFromServletThread; import de.sub.goobi.metadaten.MetadatenHelper; import ugh.dl.Fileformat; import ugh.exceptions.DocStructHasNoTypeException; import ugh.exceptions.MetadataTypeNotAllowedException; import ugh.exceptions.PreferencesException; import ugh.exceptions.ReadException; import ugh.exceptions.TypeNotAllowedForParentException; import ugh.exceptions.WriteException; public class ExportPdf extends ExportMets { @Override public boolean startExport(Process myProzess, String inZielVerzeichnis) throws IOException, InterruptedException, PreferencesException, WriteException, DocStructHasNoTypeException, MetadataTypeNotAllowedException, ExportFileException, UghHelperException, ReadException, SwapException, DAOException, TypeNotAllowedForParentException { /* * -------------------------------- Read Document -------------------------------- */ Fileformat gdzfile = myProzess.readMetadataFile(); String zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis); this.myPrefs = myProzess.getRegelsatz().getPreferences(); /* * -------------------------------- first of all write mets-file in images-Folder of process -------------------------------- */ Path metsTempFile = StorageProvider.getInstance().createTemporaryFile(myProzess.getTitel(), ".xml"); writeMetsFile(myProzess, metsTempFile.toString(), gdzfile, true); Helper.setMeldung(null, myProzess.getTitel() + ": ", "mets file created"); Helper.setMeldung(null, myProzess.getTitel() + ": ", "start pdf generation now"); if (logger.isDebugEnabled()) { logger.debug("METS file created: " + metsTempFile); } FacesContext context = FacesContextHelper.getCurrentFacesContext(); HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest(); String fullpath = req.getRequestURL().toString(); String servletpath = context.getExternalContext().getRequestServletPath(); String myBasisUrl = fullpath.substring(0, fullpath.indexOf(servletpath)); Path imagesPath = Paths.get(myProzess.getImagesTifDirectory(true)); if (!StorageProvider.getInstance().isFileExists(imagesPath) || StorageProvider.getInstance().list(imagesPath.toString(), NIOFileUtils.imageNameFilter).isEmpty()) { imagesPath = Paths.get(myProzess.getImagesOrigDirectory(true)); } Path pdfPath = Paths.get(myProzess.getOcrPdfDirectory()); Path altoPath = Paths.get(myProzess.getOcrAltoDirectory()); if (!ConfigurationHelper.getInstance().isPdfAsDownload()) { /* * -------------------------------- use contentserver api for creation of pdf-file -------------------------------- */ CreatePdfFromServletThread pdf = new CreatePdfFromServletThread(); pdf.setMetsURL(metsTempFile.toUri().toURL()); pdf.setTargetFolder(Paths.get(zielVerzeichnis)); pdf.setInternalServletPath(myBasisUrl); pdf.setImagePath(imagesPath); pdf.setPdfPath(pdfPath); pdf.setAltoPath(altoPath); if (logger.isDebugEnabled()) { logger.debug("Taget directory: " + zielVerzeichnis); logger.debug("Using ContentServer2 base URL: " + myBasisUrl); } pdf.initialize(myProzess); pdf.start(); } else { try { /* * -------------------------------- define path for mets and pdfs -------------------------------- */ URL goobiContentServerUrl = null; String contentServerUrl = ConfigurationHelper.getInstance().getGoobiContentServerUrl(); String imageSource = "&imageSource=" + imagesPath.toUri(); String pdfSource = "&pdfSource=" + pdfPath.toUri(); String altoSource = "&altoSource=" + altoPath.toUri(); /* * -------------------------------- using mets file -------------------------------- */ if (StorageProvider.getInstance().isFileExists(metsTempFile)) { /* if no contentserverurl defined use internal goobiContentServerServlet */ if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/gcs/gcs?action=pdf&metsFile="; } goobiContentServerUrl = new URL(contentServerUrl + metsTempFile.toUri().toURL() + imageSource + pdfSource + altoSource + "&targetFileName=" + myProzess.getTitel() + ".pdf"); /* * -------------------------------- mets data does not exist or is invalid -------------------------------- */ } else { if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/cs/cs?action=pdf&images="; } String url = ""; List<Path> meta = StorageProvider.getInstance().listFiles(myProzess.getImagesTifDirectory(true), NIOFileUtils.imageNameFilter); ArrayList<String> filenames = new ArrayList<String>(); for (Path data : meta) { String file = ""; file += data.toUri().toURL(); filenames.add(file); } Collections.sort(filenames, new MetadatenHelper(null, null)); for (String f : filenames) { url = url + f + "$"; } String imageString = url.substring(0, url.length() - 1); String targetFileName = "&targetFileName=" + myProzess.getTitel() + ".pdf"; goobiContentServerUrl = new URL(contentServerUrl + imageString + imageSource + pdfSource + altoSource + targetFileName); } /* * -------------------------------- get pdf from servlet and forward response to file -------------------------------- */ if (!context.getResponseComplete()) { if (logger.isDebugEnabled()) { logger.debug("Redirecting pdf request to " + goobiContentServerUrl.toString()); } HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); String fileName = myProzess.getTitel() + ".pdf"; ServletContext servletContext = (ServletContext) context.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); response.sendRedirect(goobiContentServerUrl.toString()); context.responseComplete(); } // if (Files.exists(metsTempFile)) { // Path tempMets = Paths.get(metsTempFile.toUri().toURL().toString()); // Files.delete(metsTempFile); // } } catch (Exception e) { /* * -------------------------------- report Error to User as Error-Log -------------------------------- */ Writer output = null; String text = "error while pdf creation: " + e.getMessage(); Path file = Paths.get(zielVerzeichnis, myProzess.getTitel() + ".PDF-ERROR.log"); try { logger.error(e); output = new BufferedWriter(new FileWriter(file.toFile())); output.write(text); output.close(); } catch (IOException e1) { } return false; } } return true; } }
true
14c1b40f849f1fde10abe13aac120dd56ef4c067
Java
mmonroe4058/Lab4.1
/Lab 4.1/src/Deck.java
UTF-8
1,292
3.484375
3
[]
no_license
import java.util.ArrayList; public class Deck { private ArrayList<Card> unDealt = new ArrayList<Card>(); private ArrayList<Card> Dealt = new ArrayList<Card>(); public Deck(String[] ranks, String[] suits, int[] values) { for(int x = 0; x < ranks.length; x++) { for(int y = 0; y < suits.length; y++) { for(int z = 0; z < values.length; z++) { Card card1 = new Card(ranks[x],suits[y],values[z]); unDealt.add(card1); } } } } public boolean isEmpty() { if(unDealt.size() == 0) { return true; } return false; } public int size() { return unDealt.size(); } public ArrayList<Card> getUndealt() { return unDealt; } public Card deal() { if(!isEmpty()) { Card x = unDealt.get((int) Math.random() * unDealt.size()); Dealt.add(x); unDealt.remove(x); return x; } return null; } public void shuffle() { int k = 0; int r = 0; for(int i = 0; i < Dealt.size(); i++) { unDealt.add(i, Dealt.get(i)); Dealt.remove(i); } while(k > 1) { r = ((int)Math.random()*51); Card temp1 = Dealt.get(k); Card temp2 = Dealt.get(r); Dealt.set(k, temp2); Dealt.set(r, temp1); k--; } } }
true
13440015418d14f3e764c50ba6e7ed6b2177078e
Java
Titanssword/icbc
/icbc-core/src/main/java/tiger/core/domain/device/EquipmentInfoDomain.java
UTF-8
11,897
2.140625
2
[]
no_license
package tiger.core.domain.device; import tiger.core.domain.BaseDomain; import java.util.Date; /** * Created by archer on 2017/1/9. */ public class EquipmentInfoDomain {//extends BaseDomain{ /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.id * * @mbggenerated */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Equ_Serial_Num * * @mbggenerated */ private String equSerialNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.CPU_Num * * @mbggenerated */ private String cpuNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Memory_Size * * @mbggenerated */ private String memorySize; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.OS_Versions * * @mbggenerated */ private String osVersions; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Browser_Versions * * @mbggenerated */ private String browserVersions; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Browser_Language * * @mbggenerated */ private String browserLanguage; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Screen_Resolution * * @mbggenerated */ private String screenResolution; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.APP_Versions * * @mbggenerated */ private String appVersions; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Factory_Info * * @mbggenerated */ private String factoryInfo; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Party_Id * * @mbggenerated */ private String partyId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Jnl_Dt * * @mbggenerated */ private Date jnlDt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column equipmentinfo.Jnl_Tm * * @mbggenerated */ private String jnlTm; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.id * * @return the value of equipmentinfo.id * * @mbggenerated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.id * * @param id the value for equipmentinfo.id * * @mbggenerated */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Equ_Serial_Num * * @return the value of equipmentinfo.Equ_Serial_Num * * @mbggenerated */ public String getEquSerialNum() { return equSerialNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Equ_Serial_Num * * @param equSerialNum the value for equipmentinfo.Equ_Serial_Num * * @mbggenerated */ public void setEquSerialNum(String equSerialNum) { this.equSerialNum = equSerialNum == null ? null : equSerialNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.CPU_Num * * @return the value of equipmentinfo.CPU_Num * * @mbggenerated */ public String getCpuNum() { return cpuNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.CPU_Num * * @param cpuNum the value for equipmentinfo.CPU_Num * * @mbggenerated */ public void setCpuNum(String cpuNum) { this.cpuNum = cpuNum == null ? null : cpuNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Memory_Size * * @return the value of equipmentinfo.Memory_Size * * @mbggenerated */ public String getMemorySize() { return memorySize; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Memory_Size * * @param memorySize the value for equipmentinfo.Memory_Size * * @mbggenerated */ public void setMemorySize(String memorySize) { this.memorySize = memorySize == null ? null : memorySize.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.OS_Versions * * @return the value of equipmentinfo.OS_Versions * * @mbggenerated */ public String getOsVersions() { return osVersions; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.OS_Versions * * @param osVersions the value for equipmentinfo.OS_Versions * * @mbggenerated */ public void setOsVersions(String osVersions) { this.osVersions = osVersions == null ? null : osVersions.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Browser_Versions * * @return the value of equipmentinfo.Browser_Versions * * @mbggenerated */ public String getBrowserVersions() { return browserVersions; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Browser_Versions * * @param browserVersions the value for equipmentinfo.Browser_Versions * * @mbggenerated */ public void setBrowserVersions(String browserVersions) { this.browserVersions = browserVersions == null ? null : browserVersions.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Browser_Language * * @return the value of equipmentinfo.Browser_Language * * @mbggenerated */ public String getBrowserLanguage() { return browserLanguage; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Browser_Language * * @param browserLanguage the value for equipmentinfo.Browser_Language * * @mbggenerated */ public void setBrowserLanguage(String browserLanguage) { this.browserLanguage = browserLanguage == null ? null : browserLanguage.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Screen_Resolution * * @return the value of equipmentinfo.Screen_Resolution * * @mbggenerated */ public String getScreenResolution() { return screenResolution; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Screen_Resolution * * @param screenResolution the value for equipmentinfo.Screen_Resolution * * @mbggenerated */ public void setScreenResolution(String screenResolution) { this.screenResolution = screenResolution == null ? null : screenResolution.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.APP_Versions * * @return the value of equipmentinfo.APP_Versions * * @mbggenerated */ public String getAppVersions() { return appVersions; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.APP_Versions * * @param appVersions the value for equipmentinfo.APP_Versions * * @mbggenerated */ public void setAppVersions(String appVersions) { this.appVersions = appVersions == null ? null : appVersions.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Factory_Info * * @return the value of equipmentinfo.Factory_Info * * @mbggenerated */ public String getFactoryInfo() { return factoryInfo; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Factory_Info * * @param factoryInfo the value for equipmentinfo.Factory_Info * * @mbggenerated */ public void setFactoryInfo(String factoryInfo) { this.factoryInfo = factoryInfo == null ? null : factoryInfo.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Party_Id * * @return the value of equipmentinfo.Party_Id * * @mbggenerated */ public String getPartyId() { return partyId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Party_Id * * @param partyId the value for equipmentinfo.Party_Id * * @mbggenerated */ public void setPartyId(String partyId) { this.partyId = partyId == null ? null : partyId.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Jnl_Dt * * @return the value of equipmentinfo.Jnl_Dt * * @mbggenerated */ public Date getJnlDt() { return jnlDt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Jnl_Dt * * @param jnlDt the value for equipmentinfo.Jnl_Dt * * @mbggenerated */ public void setJnlDt(Date jnlDt) { this.jnlDt = jnlDt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column equipmentinfo.Jnl_Tm * * @return the value of equipmentinfo.Jnl_Tm * * @mbggenerated */ public String getJnlTm() { return jnlTm; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column equipmentinfo.Jnl_Tm * * @param jnlTm the value for equipmentinfo.Jnl_Tm * * @mbggenerated */ public void setJnlTm(String jnlTm) { this.jnlTm = jnlTm == null ? null : jnlTm.trim(); } }
true
39559ffc92e53630f7a658d99997dbd5dbe4bf5f
Java
wyxy2005/FlymeTools
/src/com/zhixin/flymeTools/hook/ActionMenuViewHook.java
UTF-8
1,578
2.0625
2
[]
no_license
package com.zhixin.flymeTools.hook; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.widget.ImageView; import com.zhixin.flymeTools.Util.ReflectionUtil; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; /** * Created by ZXW on 2014/12/23. */ public class ActionMenuViewHook extends ActivityMethodHook.WindowFocusMethod { public ActionMenuViewHook(final Resources mResources) { super(mResources); } protected void beforeHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable { } @Override protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable { Object presenter = param.thisObject; Object mOverflowButton = ReflectionUtil.getObjectField(presenter, "mOverflowButton"); if (mOverflowButton instanceof ImageView) { Context context = (Context) XposedHelpers.getObjectField(presenter, "mContext"); if (context instanceof Activity) { Activity activity = (Activity) context; ActivityMethodHook.doMethodHookCallBack(activity, mResources, param, this, mOverflowButton); } } } @Override public void doMethodHook(MethodHookParam param, Activity thisObject, ActivityColorHook activityColorHook, Object args) { if (args != null) { if (args instanceof ImageView) { activityColorHook.updateOverflowButton((ImageView) args); } } } }
true
bf2af055cd9c9ad5635b38f3c1cd8d9c463160b4
Java
bitsanity/keymaster
/app/src/main/java/a/keymaster/cryptils/BIP38.java
UTF-8
4,181
2.53125
3
[ "MIT" ]
permissive
package a.keymaster.cryptils; import com.lambdaworks.crypto.SCrypt; import java.util.Arrays; // warning: performance of SCrypt is very poor - multiple separate // implementations have same problem. // // Ref: // https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki public class BIP38 { public static String encrypt( byte[] pvkey, String pphrase ) throws Exception { String addr = new BitcoinAddress( pvkey ).toString(); byte[] addresshash = Arrays.copyOfRange( SHA256.doubleHash(addr.getBytes("ASCII")), 0, 4 ); byte[] derKey = SCrypt.scrypt(pphrase.getBytes("UTF-8"), addresshash, SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_LEN); byte[] derivedHalf1 = Arrays.copyOfRange( derKey, 0, 32 ); byte[] derivedHalf2 = Arrays.copyOfRange( derKey, 32, 64 ); byte[] block1 = new byte[16]; byte[] block2 = new byte[16]; for ( int ii = 0; ii < 16; ii++ ) { block1[ii] = (byte)( pvkey[ii] ^ derivedHalf1[ii] ); block2[ii] = (byte)( pvkey[ii+16] ^ derivedHalf1[ii+16] ); } AES256 aes = new AES256( derivedHalf2 ); byte[] encryptedHalf1 = aes.encrypt( block1 ); byte[] encryptedHalf2 = aes.encrypt( block2 ); byte[] header = { (byte)0x01, (byte)0x42, FLAGBYTE }; byte[] epk = ByteOps.concat( header, addresshash ); epk = ByteOps.concat( epk, encryptedHalf1 ); epk = ByteOps.concat( epk, encryptedHalf2 ); String result = Base58Check.encode( epk ); return result; } public static byte[] decrypt( String enckey, String pphrase ) throws Exception { byte[] rawkey = Base58Check.decode( enckey ); if (null == rawkey) throw new Exception( "null enckey" ); if (39 != rawkey.length) throw new Exception( "length must be 39" ); if ( (byte)0x01 != rawkey[0] ) throw new Exception( "BIP38.decrypt: first byte myst be 0x01" ); if ( (byte)0x42 != rawkey[1] ) throw new Exception( "BIP38.decrypt: second byte myst be 0x42" ); byte[] addresshash = Arrays.copyOfRange( rawkey, 3, 7 ); byte[] derKey = SCrypt.scrypt( pphrase.getBytes("UTF-8"), addresshash, SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_LEN ); byte[] derHalf1 = Arrays.copyOfRange( derKey, 0, 32 ); byte[] derHalf2 = Arrays.copyOfRange( derKey, 32, 64 ); byte[] pvkeyenc = Arrays.copyOfRange(rawkey, 7, 39); byte[] pvkeyxored = new AES256( derHalf2 ).decrypt( pvkeyenc ); return ByteOps.xor( pvkeyxored, derHalf1 ); } public static void main( String[] args ) throws Exception { String[] pphrases = new String[] { "TestingOneTwoThree", "Satoshi" }; // test vectors from ref in header byte[] red0 = HexString.decode( "0xCBF4B9F70470856BB4F40F80B87EDB90865997FFEE6DF315AB166D713AF433A5" ); String black = encrypt( red0, pphrases[0] ); assert( black.equals( "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg") ); byte[] decrypted = decrypt( black, pphrases[0] ); assert( Arrays.equals(red0, decrypted) ); byte[] red1 = HexString.decode( "0x09C2686880095B1A4C249EE3AC4EEA8A014F11E6F986D0B5025AC1F39AFBD9AE" ); black = encrypt( red1, pphrases[1] ); assert( black.equals( "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq") ); decrypted = decrypt( black, pphrases[1] ); assert( Arrays.equals(red1, decrypted) ); System.out.println( "BIP38: PASS" ); } // FLAGBYTE bitmap: // 1100 0000 (0xC0) - set for non-EC-multiplied keys // 0010 0000 (0x20) - set if convert with compressed pub key fmt // 0001 0000 (0x10) - reserved for future spec, must be zero // 0000 1000 (0x08) - reserved for future spec, must be zero // 0000 0100 (0x04) - must be 0 for non-EC-multiplied keys private static final byte FLAGBYTE = (byte)0b1100_0000; private static final int SCRYPT_N = 16384; private static final int SCRYPT_R = 8; private static final int SCRYPT_P = 8; private static final int SCRYPT_LEN = 64; }
true
fcf3360a50aac87621f6ef0c58691fa76ccb8035
Java
vgoh/de.htwg.se.texasholdem
/de.htwg.se.texasholdem/test/de/htwg/se/texasholdem/controller/imp/ModelManagerImpTest.java
UTF-8
3,031
2.828125
3
[]
no_license
package de.htwg.se.texasholdem.controller.imp; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import de.htwg.se.texasholdem.controller.ModelManager; import de.htwg.se.texasholdem.model.Player; import de.htwg.se.texasholdem.model.imp.CardImp; import de.htwg.se.texasholdem.model.imp.PlayerImp; public class ModelManagerImpTest { ModelManager modelManager; Player p1, p2, p3; @Before public void _setup() { modelManager = new ModelManagerImp(); modelManager.resetGame(); p1 = new PlayerImp("Spieler 1"); p2 = new PlayerImp("Spieler 2"); p3 = new PlayerImp("Spieler 3"); modelManager.addPlayer(p1); modelManager.addPlayer(p2); modelManager.addPlayer(p3); modelManager.setHoleCards(p1); for (int i = 0; i < 3; i++) { modelManager.addCommunityCard(); } } @Test public void getBigBlind_inputSmallBlindThreeThousand_returnsBigBlindSixThousand() { modelManager.setSmallBlind(3000); Assert.assertEquals(6000, modelManager.getBigBlind()); } @Test public void getCards_inputTwoCardsForPlayer_returnsTwoCards() { Assert.assertEquals(CardImp.class, modelManager.getHoleCards(p1).get(0).getClass()); Assert.assertEquals(CardImp.class, modelManager.getHoleCards(p1).get(1).getClass()); Assert.assertEquals(2, modelManager.getHoleCards(p1).size()); } @Test public void getCommunityCards_inputThreeCommunityCards_returnsListWithThreeCommunityCards() { Assert.assertEquals(3, modelManager.getCommunityCards().size()); } @Test public void getPlayerList_addTwoPlayers_returnsListWithTwoPlayers() { Assert.assertEquals(3, modelManager.getPlayerList().size()); } @Test public void getSmallBlind_inputSmallBlindTwoThousand_returnSmallBlindTwoThousand() { modelManager.setSmallBlind(2000); Assert.assertEquals(2000, modelManager.getSmallBlind()); } @Test public void hasMoney_inputPlayerWithMoney_returnsTrue() { modelManager.addPlayer(p1); modelManager.setPlayerMoney(p1, 3000); Assert.assertTrue(modelManager.hasMoney(p1)); } @Test public void hasMoney_inputPlayerWithoutMoney_returnsFalse() { modelManager.addPlayer(p1); modelManager.setPlayerMoney(p1, 0); Assert.assertFalse(modelManager.hasMoney(p1)); } @Test public void resetGame_inputPotAndHoleCardsAndShuffledDeckAndCommunityCards_clearsAllListsAndPot() { modelManager.setPot(3000); Assert.assertFalse(modelManager.getPot() == 0); Assert.assertFalse(modelManager.getHoleCards(p1).isEmpty()); Assert.assertFalse(modelManager.getDeck().getCards().size() == 52); Assert.assertFalse(modelManager.getCommunityCards().isEmpty()); modelManager.resetGame(); Assert.assertTrue(modelManager.getPot() == 0); Assert.assertTrue(modelManager.getHoleCards(p1).isEmpty()); Assert.assertTrue(modelManager.getDeck().getCards().size() == 52); Assert.assertTrue(modelManager.getCommunityCards().isEmpty()); } @Test public void getDealer_setDealer_returnsDealerPlayer() { modelManager.setDealer(p1); Assert.assertEquals(p1, modelManager.getDealer()); } }
true
06040b216277149f6ed4e9eca989beb87729a910
Java
MaZiTeng/TeamProject
/src/BugAssassins/AIStrategy.java
UTF-8
120
1.5
2
[]
no_license
package BugAssassins; public class AIStrategy { // 不知道有啥,但是我想写一个你们都打不败的AI }
true
bfb31da75c524e7ed0fe5ec9ca882615378e704d
Java
lyokofirelyte/Ataxia
/ataxia/com/github/lyokofirelyte/Ataxia/message/Channel.java
UTF-8
383
1.851563
2
[]
no_license
package com.github.lyokofirelyte.Ataxia.message; public enum Channel { ANY("0"), FAQ("199663127363715074"), TIKI_LOUNGE("199737300471513088"), MINECRAFT("202230311273103362"), //SERVER("199755588421419009"), MUSIC("202184926085251072"), MOVIES("199666762105618433"); Channel(String id){ this.id = id; } private String id; public String getId(){ return id; } }
true
9c23d57e7292b2ed9f584ff7a139228b05da42b4
Java
karunmatharu/Android-4.4-Pay-by-Data
/sdk/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormatter.java
UTF-8
3,651
1.84375
2
[ "BSD-3-Clause", "EPL-1.0", "MIT" ]
permissive
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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.android.ide.eclipse.adt.internal.editors.formatting; import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.formatter.FormattingContext; import org.eclipse.jface.text.formatter.FormattingContextProperties; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IContentFormatterExtension; import org.eclipse.jface.text.formatter.IFormattingContext; import org.eclipse.jface.text.formatter.IFormattingStrategy; import org.eclipse.wst.xml.core.text.IXMLPartitions; /** * Formatter which replaces the Eclipse formatter for the Android XML editors, and * delegates to it if the user has chosen to use the Eclipse formatter instead by turning * off {@link AdtPrefs#getUseCustomXmlFormatter()} */ public class AndroidXmlFormatter implements IContentFormatter, IContentFormatterExtension { @Override public final void format(IDocument document, IRegion region) { /** * This method is probably not going to be called. It is part of the * {@link IContentFormatter} but since we also implement * {@link IContentFormatterExtension} Eclipse should /* be calling * {@link #format(IDocument,IFormattingContext)} instead. However, for * completeness (and because other implementations of {@link IContentFormatter} * also do this we might as well make the method behave correctly */ FormattingContext context = new FormattingContext(); context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE); context.setProperty(FormattingContextProperties.CONTEXT_REGION, region); format(document, context); } @Override public IFormattingStrategy getFormattingStrategy(String contentType) { return new AndroidXmlFormattingStrategy(); } @Override public void format(IDocument document, IFormattingContext context) { context.setProperty(FormattingContextProperties.CONTEXT_MEDIUM, document); formatMaster(context, document, 0, document.getLength()); } protected void formatMaster(IFormattingContext context, IDocument document, int offset, int length) { try { final int delta= offset - document.getLineInformationOfOffset(offset).getOffset(); offset -= delta; length += delta; } catch (BadLocationException exception) { // Do nothing } AndroidXmlFormattingStrategy strategy = new AndroidXmlFormattingStrategy(); context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, new TypedPosition(offset, length, IXMLPartitions.XML_DEFAULT)); strategy.formatterStarts(context); strategy.format(); strategy.formatterStops(); } }
true
e50c9db44c2921c66c99934170051f05d55e2ba1
Java
Meshine001/LetsStudy
/app/src/main/java/com/meshine/letsstudyclient/tools/EventUtil.java
UTF-8
1,854
2.390625
2
[]
no_license
package com.meshine.letsstudyclient.tools; import android.util.Log; import com.meshine.letsstudyclient.bean.Event; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Meshine on 16/5/23. */ public class EventUtil { private static final String TAG = EventUtil.class.getName(); public static List<Event> parseEventsData(String data) { try { List<Event> events = new ArrayList<>(); JSONObject jo = new JSONObject(data); JSONArray ja = JSONUtil.getJSONArray(jo, "data"); for (int i = 0; i < ja.length(); i++) { JSONObject eventJo = ja.getJSONObject(i); Event event = new Event( eventJo.getLong("id"), eventJo.getInt("eventType"), eventJo.getString("title"), eventJo.getInt("count"), eventJo.getInt("limit"), eventJo.getLong("dateTime"), eventJo.getLong("endTime"), eventJo.getString("place"), eventJo.getString("details"), eventJo.getLong("createTime"), eventJo.getString("userName"), eventJo.getString("pic1"), eventJo.getString("pic2"), eventJo.getString("pic3"), eventJo.getString("pic4") ); events.add(event); } for (Event e:events){ Log.i(TAG,e.toString()); } return events; } catch (JSONException e) { e.printStackTrace(); return null; } } }
true
55f0a67b1de28f55ebbcd7a5058cf0a8fdb65ee6
Java
AdmiralSbs/Product
/src/JListKitchen.java
UTF-8
690
2.734375
3
[]
no_license
import javax.swing.*; import java.util.ArrayList; class JListKitchen extends JList<ObjectKitchen> { //Largely structured off JAutoComboBox //Utilizes the model directly due to no need to check its contents private final DefaultListModel<ObjectKitchen> defaultListModel = new DefaultListModel<>(); JListKitchen() { super(); setCellRenderer(new JListCellRenderer()); setModel(defaultListModel); setList(new ArrayList<>()); } void setList(ArrayList<ObjectKitchen> l) { defaultListModel.removeAllElements(); for (ObjectKitchen ok : l) defaultListModel.addElement(ok); setSelectedIndex(-1); } }
true
56e3ef9faae47b99a5c9736ae45347edd05812e0
Java
632215/HouseKeeper
/app/src/main/java/com/jinke/housekeeper/bean/AppHandleInfo.java
UTF-8
574
1.84375
2
[]
no_license
package com.jinke.housekeeper.bean; /** * Created by root on 1/9/17. */ public class AppHandleInfo { /** * taskId : 232510 * processId : 1483944169562 */ private String taskId; private String processId; public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessId() { return processId; } public void setProcessId(String processId) { this.processId = processId; } }
true
e83fc18da9c53a3c9bdfce82009091816d187a40
Java
zulus23/JavaExportData
/src/ru/zhukov/domain/AccountRecord.java
UTF-8
3,265
2.46875
2
[]
no_license
package ru.zhukov.domain; /** * Created by Gukov on 28.03.2016. * Проводка в АиТ */ public class AccountRecord { private int id; private String department; private String employee; private String debit; private String credit; private Double summa; private String costItem; private String objectId; private String taxArticle; private String cfo; private String code; //Код начисления private int year; private int month; private String description; public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getEmployee() { return employee; } public void setEmployee(String employee) { this.employee = employee; } public String getDebit() { return debit; } public void setDebit(String debit) { this.debit = debit; } public String getCredit() { return credit; } public void setCredit(String credit) { this.credit = credit; } public Double getSumma() { return summa; } public void setSumma(Double summa) { this.summa = summa; } public String getCostItem() { return costItem; } public void setCostItem(String costItem) { this.costItem = costItem; } public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public String getTaxArticle() { return taxArticle; } public void setTaxArticle(String taxArticle) { this.taxArticle = taxArticle; } public String getCfo() { return cfo; } public void setCfo(String cfo) { this.cfo = cfo; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "AccountRecord{" + "employee='" + employee + '\'' + ", debit='" + debit + '\'' + ", credit='" + credit + '\'' + ", summa=" + summa + ", year=" + year + ", month=" + month + ", description='" + description + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AccountRecord)) return false; AccountRecord that = (AccountRecord) o; return getId() == that.getId(); } @Override public int hashCode() { return getId(); } }
true
e8019e8622efad0a28d397cda0e8156f9b91e5f7
Java
moutainhigh/source-data-router
/flink-job-scheduler/src/main/java/com/globalegrow/fixed/scheduler/BuryLogDataFlinkJob.java
UTF-8
3,765
2.21875
2
[]
no_license
package com.globalegrow.fixed.scheduler; import com.globalegrow.fixed.queen.FlinkBashJob; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Map; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicInteger; @Component @Data @Slf4j @Deprecated public class BuryLogDataFlinkJob { @Autowired private LinkedBlockingDeque<FlinkBashJob> flinkBashJobs; @Autowired BuryLogDataSyncByDay buryLogDataSyncByDay; @Autowired Map<String, FlinkBashJob> currentBuryLogJobs; private AtomicInteger atomicInteger = new AtomicInteger(0); //@Scheduled(fixedDelay = 10000) public void runFlinkJobFixed() throws InterruptedException { if (this.flinkBashJobs.size() > 0 && StringUtils.isEmpty(buryLogDataSyncByDay.getCurrentJobId()) && this.atomicInteger.get() == 0) { this.atomicInteger.set(1); log.info("当前任务 id 为空,提交新任务"); FlinkBashJob job = this.flinkBashJobs.take(); log.info("任务信息:{}", job); Process process = null; //List<String> processList = new ArrayList<String>(); try { process = Runtime.getRuntime().exec(job.getFlinkCommandLine()); //process.waitFor(); try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line = ""; while ((line = input.readLine()) != null) { //processList.add(line); log.info("任务信息:{}", line); //log.info("任务提交状态: {}", line.indexOf("Job has been submitted with JobID")); if (line.indexOf("Job has been submitted with JobID") >= 0) { String[] lines = line.substring(line.indexOf("Job has been submitted with JobID")).split(" "); String jobId = lines[lines.length - 1]; log.info("{} 任务 id {}", job.getJobName(), jobId); this.currentBuryLogJobs.put(jobId, job); this.buryLogDataSyncByDay.setCurrentJobId(jobId); Thread.sleep(1000); this.atomicInteger.set(0); } } } try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { String line = ""; while ((line = input.readLine()) != null) { //processList.add(line); log.info("任务错误信息: {}", line); /* if (line.indexOf("Job has been submitted with JobID") > 0) { String[] lines = line.substring(line.indexOf("Job has been submitted with JobID")).split(" "); String jobId = lines[lines.length - 1]; log.info("{} 任务 id {}", job.getJobName(), jobId); this.buryLogDataSyncByDay.setCurrentJobId(jobId); Thread.sleep(1000); this.atomicInteger.set(0); }*/ } } } catch (Exception e) { log.error("flink 任务出错", e); } } } }
true
cc8c6320f561ead2b7674cc04a66672480d49c21
Java
genNAowl/Arc
/arc-core/src/arc/Net.java
UTF-8
9,163
3.140625
3
[ "MIT" ]
permissive
package arc; import arc.struct.*; import arc.func.Cons; import arc.util.*; import java.io.InputStream; /** * Provides methods to perform networking operations, such as simple HTTP get and post requests, and TCP server/client socket * communication.</p> * <p> * To perform an HTTP request create a {@link HttpRequest} with the HTTP method (see {@link HttpMethod} for common methods) and * invoke {@link #httpPost(String, String, Cons, Cons)} with it and a listener. After the HTTP * request was processed, the listener is called with a {@link HttpResponse} with the HTTP response values and * an status code to determine if the request was successful or not.</p> * <p> * @author mzechner * @author noblemaster * @author arielsan */ public class Net{ private NetJavaImpl impl = new NetJavaImpl(); /** Whether to block on HTTP requests. Default is false. */ public void setBlock(boolean block){ impl.setBlock(block); } /** * Process the specified {@link HttpRequest} and reports the {@link HttpResponse} to the specified listener. * . * @param httpRequest The {@link HttpRequest} to be performed. * @param success The listener to call once the HTTP response is ready to be processed. * @param failure The listener to call if the request fails. */ public void http(HttpRequest httpRequest, Cons<HttpResponse> success, Cons<Throwable> failure){ impl.http(httpRequest, success, failure); } /** Sends a basic HTTP GET request.*/ public void httpGet(String url, Cons<HttpResponse> success, Cons<Throwable> failure){ http(new HttpRequest().method(HttpMethod.GET).url(url), success, failure); } /** Sends a basic HTTP POST request.*/ public void httpPost(String url, String content, Cons<HttpResponse> success, Cons<Throwable> failure){ http(new HttpRequest().method(HttpMethod.POST).content(content).url(url), success, failure); } /** HTTP response interface with methods to get the response data as a byte[], a {@link String} or an {@link InputStream}. */ public interface HttpResponse{ /** * Returns the data of the HTTP response as a byte[]. * <p> * <b>Note</b>: This method may only be called once per response. * </p> * @return the result as a byte[] or null in case of a timeout or if the operation was canceled/terminated abnormally. The * timeout is specified when creating the HTTP request, with {@link HttpRequest#timeout(int)} */ byte[] getResult(); /** * Returns the data of the HTTP response as a {@link String}. * <p> * <b>Note</b>: This method may only be called once per response. * </p> * @return the result as a string or null in case of a timeout or if the operation was canceled/terminated abnormally. The * timeout is specified when creating the HTTP request, with {@link HttpRequest#timeout(int)} */ String getResultAsString(); /** * Returns the data of the HTTP response as an {@link InputStream}. <b><br> * Warning:</b> Do not store a reference to this InputStream. The underlying HTTP connection will be closed after that * callback finishes executing. Reading from the InputStream after it's connection has been closed will lead to exception. * @return An {@link InputStream} with the {@link HttpResponse} data. */ InputStream getResultAsStream(); /** Returns the {@link HttpStatus} containing the statusCode of the HTTP response. */ HttpStatus getStatus(); /** * Returns the value of the header with the given name as a {@link String}, or null if the header is not set. */ String getHeader(String name); /** * Returns a Map of the headers. The keys are Strings that represent the header name. Each values is a List of Strings that * represent the corresponding header values. */ ObjectMap<String, Seq<String>> getHeaders(); } /** Provides all HTTP methods to use when creating a {@link HttpRequest}.*/ public enum HttpMethod{ GET, POST, PUT, DELETE, HEAD, CONNECT, OPTIONS, TRACE } public static class HttpRequest{ /** The HTTP method. */ public HttpMethod method; /** The URL to send this request to.*/ public String url; public ObjectMap<String, String> headers = new ObjectMap<>(); /**The time to wait for the HTTP request to be processed, use 0 to block until it is done. The timeout is used for both * the timeout when establishing TCP connection, and the timeout until the first byte of data is received.*/ public int timeout = 2000; /**The content to be used in the HTTP request: A string encoded in the corresponding Content-Encoding set in the headers, with the data to send with the * HTTP request. For example, in case of HTTP GET, the content is used as the query string of the GET while on a * HTTP POST it is used to send the POST data.*/ public String content; /**The content as a stream to be used for a POST for example, to transmit custom data.*/ public InputStream contentStream; /**Length of the content stream.*/ public long contentLength; /**Sets whether 301 and 302 redirects are followed. By default true. Can't be changed in the web backend because this uses * XmlHttpRequests which always redirect.*/ public boolean followRedirects = true; /** Whether a cross-origin request will include credentials. By default false. */ public boolean includeCredentials = false; public HttpRequest(){ } public HttpRequest(HttpMethod method){ this.method = method; } public HttpRequest method(HttpMethod method){ this.method = method; return this; } public HttpRequest url(String url){ this.url = url; return this; } public HttpRequest timeout(int timeout){ this.timeout = timeout; return this; } public HttpRequest redirects(boolean followRedirects){ this.followRedirects = followRedirects; return this; } public HttpRequest credentials(boolean includeCredentials){ this.includeCredentials = includeCredentials; return this; } public HttpRequest header(String name, String value){ headers.put(name, value); return this; } public HttpRequest content(String content){ this.content = content; return this; } public HttpRequest content(InputStream contentStream, long contentLength){ this.contentStream = contentStream; this.contentLength = contentLength; return this; } } /** Defines the status of an HTTP request.*/ public enum HttpStatus{ UNKNOWN_STATUS(-1), CONTINUE(100), SWITCHING_PROTOCOLS(101), PROCESSING(102), OK(200), CREATED(201), ACCEPTED(202), NON_AUTHORITATIVE_INFORMATION(203), NO_CONTENT(204), RESET_CONTENT(205), PARTIAL_CONTENT(206), MULTI_STATUS(207), MULTIPLE_CHOICES(300), MOVED_PERMANENTLY(301), MOVED_TEMPORARILY(302), SEE_OTHER(303), NOT_MODIFIED(304), USE_PROXY(305), TEMPORARY_REDIRECT(307), BAD_REQUEST(400), UNAUTHORIZED(401), PAYMENT_REQUIRED(402), FORBIDDEN(403), NOT_FOUND(404), METHOD_NOT_ALLOWED(405), NOT_ACCEPTABLE(406), PROXY_AUTHENTICATION_REQUIRED(407), REQUEST_TIMEOUT(408), CONFLICT(409), GONE(410), LENGTH_REQUIRED(411), PRECONDITION_FAILED(412), REQUEST_TOO_LONG(413), REQUEST_URI_TOO_LONG(414), UNSUPPORTED_MEDIA_TYPE(415), REQUESTED_RANGE_NOT_SATISFIABLE(416), EXPECTATION_FAILED(417), INSUFFICIENT_SPACE_ON_RESOURCE(419), METHOD_FAILURE(420), UNPROCESSABLE_ENTITY(422), LOCKED(423), FAILED_DEPENDENCY(424), INTERNAL_SERVER_ERROR(500), NOT_IMPLEMENTED(501), BAD_GATEWAY(502), SERVICE_UNAVAILABLE(503), GATEWAY_TIMEOUT(504), HTTP_VERSION_NOT_SUPPORTED(505), INSUFFICIENT_STORAGE(507); private static IntMap<HttpStatus> byCode; public final int code; HttpStatus(int code){ this.code = code; } /** Find an HTTP status enum by code.*/ public static HttpStatus byCode(int code){ if(byCode == null){ byCode = new IntMap<>(); for(HttpStatus status : HttpStatus.values()){ byCode.put(status.code, status); } } return byCode.get(code, UNKNOWN_STATUS); } } }
true
bc7aa262f2384b32859941f74c3c12e71edced74
Java
JetBrains/intellij-community
/java/java-tests/testData/inspection/dataFlow/fixture/DereferenceInThrowMessage.java
UTF-8
236
2.234375
2
[ "Apache-2.0" ]
permissive
import org.jetbrains.annotations.*; public class DereferenceInThrowMessage { void test(@Nullable Object obj) { if (obj != null && obj.hashCode() == 0) { throw new RuntimeException("Hashcode: " + obj.hashCode()); } } }
true
aa9b38aada96840badf6eab829f967e0ba7eb010
Java
aparneshgaurav/raniCodeRepoBuildLeverage
/workspace/StreamIntegerTerminalOperationReduceMax.java
UTF-8
873
3.453125
3
[]
no_license
package com.poc.rcm.java.eight; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Consumer; public class StreamIntegerTerminalOperationReduceMax { public static void main(String[] args) { String alphabet = "a"; // TODO Auto-generated method stub List<Integer> listHere = new LinkedList<Integer>(); listHere.add(10); listHere.add(70); listHere.add(30); /** * doing reduce terminal operation and printing if reduce has some data with it */ listHere.stream().map(record -> { record = 100 * record; return record; } ).reduce( (record1,record2) -> { if(record1 > record2){ return record1; } else{ return record2; } } ).ifPresent(record -> { System.out.println(record); } ); } }
true