blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
c60c175f453b913e6315c4fb0715947be17a5902
4b9326a0ff859993b0daf6a0f5e405f7c718e18e
/src/main/java/io/github/yangziwen/webmonitor/metrics/bean/Metrics.java
d46ea2da12a972f617d0032dc45fa722f4096fa3
[]
no_license
3zamn/web-monitor
36bfab32e0044429f037dd92b13252e47292f910
d4f21e5ada968919c55e5453a4e4044832dae10b
refs/heads/master
2021-05-01T03:17:22.205561
2018-01-01T09:10:52
2018-01-01T09:10:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,821
java
package io.github.yangziwen.webmonitor.metrics.bean; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import com.alibaba.fastjson.annotation.JSONField; import javafx.util.Pair; public class Metrics { protected AtomicLong cnt = new AtomicLong(0); protected AtomicInteger min = new AtomicInteger(0); protected AtomicInteger max = new AtomicInteger(0); protected AtomicLong sum = new AtomicLong(0L); @JSONField(serialize = false) protected Distribution distribution = new Distribution(); public long getCnt() { return cnt.get(); } public int getMin() { return min.get(); } public int getMax() { return max.get(); } public long getSum() { return sum.get(); } public int getAvg() { if (cnt.get() == 0) { return 0; } return new Long(sum.get() / cnt.get()).intValue(); } @SuppressWarnings("restriction") public List<Pair<String, Integer>> getDistributionList() { Map<String, Integer> map = this.distribution.toMap(); return map.entrySet().stream() .map(entry -> new Pair<>(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); } public Distribution getDistribution() { return distribution; } public void setDistribution(Distribution distribution) { this.distribution = distribution; } public void doStats(int value) { if (value <= 0) { return; } cnt.incrementAndGet(); sum.addAndGet(value); int maxValue; while (value > (maxValue = max.get())) { if (max.compareAndSet(maxValue, value)) { break; } } int minValue; while (value < (minValue = min.get()) || minValue <= 0) { if (min.compareAndSet(minValue, value)) { break; } } distribution.doStats(value); } public Metrics merge(Metrics other) { if (other == null) { return this; } cnt.addAndGet(other.getCnt()); sum.addAndGet(other.getSum()); int thisMax, otherMax; while ((otherMax = other.getMax()) > (thisMax = this.getMax())) { if (max.compareAndSet(thisMax, otherMax)) { break; } } int thisMin, otherMin; while ((otherMin = other.getMin()) < (thisMin = this.getMin()) || thisMin <= 0) { if (min.compareAndSet(thisMin, otherMin)) { break; } } this.distribution.merge(other.distribution); return this; } }
9364846e01382f08e7250ec5e66eb909a26b4962
16b9703c2f2ce7120bd7b571d267cbba22a62f59
/spring-framework-master/spring-context/src/main/java/org/springframework/remoting/rmi/RmiProxyFactoryBean.java
270ded45b22e4e93a4efb84a0670b9eb33aa385b
[ "Apache-2.0" ]
permissive
Kloppe/Spring
5017e770b106092345d0b3c42ca44984db32aa0c
863f75a6874225698c6532de9dc1cedf471855ca
refs/heads/master
2023-03-17T18:50:26.827722
2019-06-25T12:25:46
2019-06-25T12:25:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,724
java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.remoting.rmi; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.FactoryBean; import org.springframework.util.Assert; /** * {@link FactoryBean} for RMI proxies, supporting both conventional RMI services * and RMI invokers. Exposes the proxied service for use as a bean reference, * using the specified service interface. Proxies will throw Spring's unchecked * RemoteAccessException on remote invocation failure instead of RMI's RemoteException. * * <p>The service URL must be a valid RMI URL like "rmi://localhost:1099/myservice". * RMI invokers work at the RmiInvocationHandler level, using the same invoker stub * for any service. Service interfaces do not have to extend {@code java.rmi.Remote} * or throw {@code java.rmi.RemoteException}. Of course, in and out parameters * have to be serializable. * * <p>With conventional RMI services, this proxy factory is typically used with the * RMI service interface. Alternatively, this factory can also proxy a remote RMI * service with a matching non-RMI business interface, i.e. an interface that mirrors * the RMI service methods but does not declare RemoteExceptions. In the latter case, * RemoteExceptions thrown by the RMI stub will automatically get converted to * Spring's unchecked RemoteAccessException. * * <p>The major advantage of RMI, compared to Hessian, is serialization. * Effectively, any serializable Java object can be transported without hassle. * Hessian has its own (de-)serialization mechanisms, but is HTTP-based and thus * much easier to setup than RMI. Alternatively, consider Spring's HTTP invoker * to combine Java serialization with HTTP-based transport. * * @author Juergen Hoeller * @since 13.05.2003 * @see #setServiceInterface * @see #setServiceUrl * @see RmiClientInterceptor * @see RmiServiceExporter * @see java.rmi.Remote * @see java.rmi.RemoteException * @see org.springframework.remoting.RemoteAccessException * @see org.springframework.remoting.caucho.HessianProxyFactoryBean * @see org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean * * * * 客户端的实现 * * 根据客户端配置文件,锁定入口类为RMIProxyFactoryBean,同样根据类的层次结构查找人口函数,如图 12-2 所示 * * 根据层次关系以及之前的分析,我们提出该类实现比较重要的接口,InitializingBean,BeanClassLoaderAware以及MethodInterceptor * * 其中实现了InitializingBean,则Spring会确保此初始化bean时调用afterPropertiesSet进行逻辑的初始化 * * 同时,RMI proxyFactoryBean实现了FactoryBean接口,那么当获取Bean时并不是直接获取bean,而是获取该bean的getObject方法 * * public Object getObject(){ * return this.serviceProxy; * } * 这样,我们似乎已经形成了一个大致的轮廓,当获取该bean时,首先通过afterPropertiesSet创建代理类,并使用当前类作为增强方法,而在调用该 * bean时其实返回的是代理类,既然调用的地代理类,那么又会使用当前bean作为增强器进行增强,也就是说会调用RMIProxyFactoryBean的父类 * RMIClientInterceptor的invoke方法 * * * */ public class RmiProxyFactoryBean extends RmiClientInterceptor implements FactoryBean<Object>, BeanClassLoaderAware { private Object serviceProxy; @Override public void afterPropertiesSet() { super.afterPropertiesSet(); Class<?> ifc = getServiceInterface(); Assert.notNull(ifc, "Property 'serviceInterface' is required"); // 同时RMIProxyFactoryBean又实现了Bean接口,那么当获取Bean时并不是直接获取bean,而是获取该bean的getObject方法 this.serviceProxy = new ProxyFactory(ifc, this).getProxy(getBeanClassLoader()); } @Override public Object getObject() { return this.serviceProxy; } @Override public Class<?> getObjectType() { return getServiceInterface(); } @Override public boolean isSingleton() { return true; } }
57f2df574f80b99826e15cb5ad39b3b422f02435
10560e08bda730b73dabe15854a9abead1a4a870
/MARLINE/DuEvaluateModel.java
d33f9670abf131c40c76a2dc566dc4f38d6e51f6
[]
no_license
minkull/MARLINE
c86a5cc419f057edab06ac5b3420c9924daff530
b243a44065023b54f74ee82b3b81276d42257464
refs/heads/master
2022-12-18T09:55:57.909618
2020-09-21T11:32:48
2020-09-21T11:32:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,627
java
package Others; /** * */ import java.util.ArrayList; import java.util.List; import com.yahoo.labs.samoa.instances.Instance; import moa.core.DoubleVector; import java.io.Serializable; /** * @author hd168 * */ public class DuEvaluateModel implements Serializable{ protected int instanceSize; protected int conceptPosition; protected boolean slideWindow; protected int slideWindowSize; protected int count; protected int correctTimes; protected int numOfExamplesReceived; protected List<Double> evaAccuracy; protected List<Double> evaSlideAccuracy; protected List<Boolean> results; protected double tp = 0.0; protected double fn = 0.0; protected double fp = 0.0; protected double tn = 0.0; protected double g_mean = 0.0; public DuEvaluateModel() { } public void evaluateInitialize(int conceptPosition, boolean slideWindow, int slideWindowSize) { //this.instanceSize = instanceSize; this.conceptPosition = conceptPosition; this.slideWindow = slideWindow; this.slideWindowSize = slideWindowSize; this.count = 0; this.correctTimes = 0; this.numOfExamplesReceived = 0; this.evaAccuracy = new ArrayList<Double>(); this.evaSlideAccuracy = new ArrayList<Double>(); this.results = new ArrayList<Boolean>(); } public void evaluation(Instance inst, DoubleVector prediction) { this.numOfExamplesReceived++; //Calculate G-Mean //this.evaluationWithGMean(inst, prediction); //++++++++= if(this.slideWindow) this.evaluationWithSlideWindow(inst, prediction); else this.evaluationWithAccuracy(inst, prediction); } protected void evaluationWithGMean(Instance inst, DoubleVector prediction) { if(inst.classValue() == 0.0) { if(prediction.maxIndex() == (int)inst.classValue()) this.tp++; else this.fn++; }else { if(prediction.maxIndex() == (int)inst.classValue()) this.tn++; else this.fp++; } this.g_mean = Math.sqrt((tp/(tp+fn))*(tn/(tn+fp))); } protected void evaluationWithAccuracy(Instance inst, DoubleVector prediction) { this.count++; //if(this.count == this.conceptPosition) { if(this.numOfExamplesReceived % this.conceptPosition == 0) { this.correctTimes = 0; this.count = 1; } if(prediction.maxIndex() == (int)inst.classValue()) { this.correctTimes++; } this.evaAccuracy.add((double)this.correctTimes/(double)this.count); //System.out.println("c: " + correctTimes); //System.out.println((double)this.correctTimes/(double)this.count); } protected void evaluationWithSlideWindow(Instance inst, DoubleVector prediction) { if(prediction.maxIndex() == (int)inst.classValue()) this.results.add(true); else this.results.add(false); int cTimes = 0; if(this.results.size() < this.slideWindowSize) { for(boolean p: this.results) { if(p) cTimes++; } this.evaSlideAccuracy.add((double)cTimes/(double)this.results.size()); }else { List<Boolean> tempResults = this.results.subList(this.results.size() - this.slideWindowSize + 1, this.results.size() - 1); for(boolean p: tempResults) { if(p) cTimes++; } this.evaSlideAccuracy.add((double)cTimes/(double)this.slideWindowSize); } //System.out.println(this.evaSlideAccuracy.get(this.evaSlideAccuracy.size() - 1)); } public List<Double> getResults(){ if(this.slideWindow) return this.getEvaSlideAccuracy(); else return this.getEvaAccuracy(); } public double getGMean() { return this.g_mean; } public List<Double> getEvaAccuracy(){ return this.evaAccuracy; } public List<Double> getEvaSlideAccuracy(){ return this.evaSlideAccuracy; } public int getNumOfExamplesReceived() { return this.numOfExamplesReceived; } public void addNumOfExamplesReceived() { this.numOfExamplesReceived++; } public double[] getMeasurement() { double[] results = new double[2]; results[0] = 0; results[1] = 0; List<Double> accuracy = this.getResults(); for(double r: accuracy) { results[0] += r; } results[0] = results[0]/(accuracy.size() - 1); //System.out.println(results[0]); for(double r: accuracy) { results[1] += Math.pow(r - results[0], 2); } results[1] = Math.sqrt(results[1]/(accuracy.size() - 1)); //System.out.println(results[1]); return results; } }
3f7ddbb6d36eb22b1573001639a45ed2045d87aa
064a8c7e7114cc0163fe820f6e99ca74b244b4d7
/Ghp5_pt1.java
c335ac2a6f69b9f08b4a5187fc2d650b0c189e8e
[]
no_license
Seth0110/CS249
3c4d232cc0e4a36e0d5ebe32148ceca32c3fd62b
77ee7a9f9dff17aa37af0a1e860eaa6a29dc9866
refs/heads/master
2020-03-09T20:59:04.582655
2018-04-10T21:40:36
2018-04-10T21:40:36
128,997,953
0
0
null
null
null
null
UTF-8
Java
false
false
3,610
java
/* Seth Sevier CS 249 V4_Problem_8_page_472 Define Pet as a superclass of Dog and Cat classes. Define acepromazine() and carprofen() in Pet to return 0. Overwrite both in methods to calculate the correct dosage. Takes no inputs, displays four dosages. */ import java.text.DecimalFormat; class Pet { /* Variables */ private String name; private int age; private double weight; /* Constructors */ public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println("Error: Negative age or weight"); System.exit(0); } else { age = initialAge; weight = initialWeight; } } public Pet(String initialName) { name = initialName; age = 0; weight = 0; } public Pet(int initialAge) { name = "No name yet."; weight = 0; if (initialAge < 0) { System.out.println("Error: Negative Age."); System.exit(0); } else age = initialAge; } public Pet(double initialWeight) { name = "No name yet"; age = 0; if (initialWeight == 0) { System.out.println("Error: Negative Weight."); System.exit(0); } else weight = initialWeight; } public Pet() { name = "No name yet."; age = 0; weight = 0; } /* Getters and Setters */ public int getAge() { return age; } public String getName() { return name; } public double getWeight() { return weight; } public void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge < 0) || (newWeight < 0)) { System.out.println("Error: Negative age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } } public void setName(String newName) { name = newName; } public void setWeight(double newWeight) { if (newWeight < 0) { System.out.println("Error: Negative weight"); System.exit(0); } else weight = newWeight; } /* Functions */ public String toString() { return ("Name: " + name + " Age: " + age + " years" + "\nWeight: " + weight + " pounds"); } public double acepromazine() { return 0; } public double carprofen() { return 0; } } class Cat extends Pet { public Cat(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public double acepromazine() { return ((this.getWeight() / 2.2) * (10 / .002)); } public double carprofen() { return ((this.getWeight() / 2.2) * (12 / .25)); } } class Dog extends Pet { public Dog(String initialName, int initialAge, double initialWeight) { super(initialName, initialAge, initialWeight); } public double acepromazine() { return ((this.getWeight() / 2.2) * (10 / .03)); } public double carprofen() { return ((this.getWeight() / 2.2) * (12 / .5)); } } public class Ghp5_pt1 { public static void main(String[] args) { DecimalFormat f = new DecimalFormat("###.#"); Cat catbert = new Cat("Catbert",3,7.0); Dog dogbert = new Dog("Dogbert",6,25.0); System.out.println(catbert.getName() + "'s Acepromazine dose: " + f.format(catbert.acepromazine())); System.out.println(catbert.getName() + "'s Carprofen dose: " + f.format(catbert.carprofen())); System.out.println(dogbert.getName() + "'s Acepromazine dose: " + f.format(dogbert.acepromazine())); System.out.println(dogbert.getName() + "'s Carprofen dose: " + f.format(dogbert.carprofen())); } }
ad5381a77a012aaaeb3bc6075d0bb5e227c97169
83b6a9a3d2be905c940b9166f7056c89c720eaf1
/compling.core/source/compling/context/Yylex.java
9bc935f4a30259c44240a148d6de6535475311c2
[]
no_license
icsi-berkeley/ecg_compling
75a07f301a9598661fa71ba5d764094b06b953b3
89c810d49119ba7cb76a7323ebbf051a9cfb9b9c
refs/heads/master
2021-09-15T01:57:44.493832
2015-12-14T18:42:08
2015-12-14T18:42:08
26,875,943
1
0
null
null
null
null
UTF-8
Java
false
true
28,226
java
/* The following code was generated by JFlex 1.4.3 on 5/15/12 4:22 PM */ package compling.context; import java_cup.runtime.Symbol; import compling.grammar.ecg.ecgreader.Location; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.3 * on 5/15/12 4:22 PM from the specification file * <tt>MiniOntology.lex</tt> */ public class Yylex implements java_cup.runtime.Scanner { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int commentstyle2 = 4; public static final int YYINITIAL = 0; public static final int commentstyle1 = 2; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1, 2, 2 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\10\0\1\1\1\43\1\5\1\0\1\42\1\4\22\0\1\43\1\0"+ "\1\3\5\0\1\12\1\13\1\7\2\0\1\11\1\0\1\6\12\11"+ "\1\32\6\0\1\26\1\16\1\21\1\30\1\17\1\31\1\41\1\10"+ "\1\24\1\10\1\40\1\27\1\35\1\23\1\37\1\34\1\36\1\22"+ "\1\14\1\20\1\15\1\25\2\10\1\33\1\10\1\0\1\2\2\0"+ "\1\10\1\0\1\26\1\16\1\21\1\30\1\17\1\31\1\41\1\10"+ "\1\24\1\10\1\40\1\27\1\35\1\23\1\37\1\34\1\36\1\22"+ "\1\14\1\20\1\15\1\25\2\10\1\33\1\10\57\0\1\10\12\0"+ "\1\10\4\0\1\10\5\0\27\10\1\0\37\10\1\0\u01ca\10\4\0"+ "\14\10\16\0\5\10\7\0\1\10\1\0\1\10\201\0\5\10\1\0"+ "\2\10\2\0\4\10\10\0\1\10\1\0\3\10\1\0\1\10\1\0"+ "\24\10\1\0\123\10\1\0\213\10\10\0\236\10\11\0\46\10\2\0"+ "\1\10\7\0\47\10\110\0\33\10\5\0\3\10\55\0\53\10\25\0"+ "\12\11\4\0\2\10\1\0\143\10\1\0\1\10\17\0\2\10\7\0"+ "\2\10\12\11\3\10\2\0\1\10\20\0\1\10\1\0\36\10\35\0"+ "\131\10\13\0\1\10\16\0\12\11\41\10\11\0\2\10\4\0\1\10"+ "\5\0\26\10\4\0\1\10\11\0\1\10\3\0\1\10\27\0\31\10"+ "\253\0\66\10\3\0\1\10\22\0\1\10\7\0\12\10\4\0\12\11"+ "\1\0\7\10\1\0\7\10\5\0\10\10\2\0\2\10\2\0\26\10"+ "\1\0\7\10\1\0\1\10\3\0\4\10\3\0\1\10\20\0\1\10"+ "\15\0\2\10\1\0\3\10\4\0\12\11\2\10\23\0\6\10\4\0"+ "\2\10\2\0\26\10\1\0\7\10\1\0\2\10\1\0\2\10\1\0"+ "\2\10\37\0\4\10\1\0\1\10\7\0\12\11\2\0\3\10\20\0"+ "\11\10\1\0\3\10\1\0\26\10\1\0\7\10\1\0\2\10\1\0"+ "\5\10\3\0\1\10\22\0\1\10\17\0\2\10\4\0\12\11\25\0"+ "\10\10\2\0\2\10\2\0\26\10\1\0\7\10\1\0\2\10\1\0"+ "\5\10\3\0\1\10\36\0\2\10\1\0\3\10\4\0\12\11\1\0"+ "\1\10\21\0\1\10\1\0\6\10\3\0\3\10\1\0\4\10\3\0"+ "\2\10\1\0\1\10\1\0\2\10\3\0\2\10\3\0\3\10\3\0"+ "\14\10\26\0\1\10\25\0\12\11\25\0\10\10\1\0\3\10\1\0"+ "\27\10\1\0\12\10\1\0\5\10\3\0\1\10\32\0\2\10\6\0"+ "\2\10\4\0\12\11\25\0\10\10\1\0\3\10\1\0\27\10\1\0"+ "\12\10\1\0\5\10\3\0\1\10\40\0\1\10\1\0\2\10\4\0"+ "\12\11\1\0\2\10\22\0\10\10\1\0\3\10\1\0\51\10\2\0"+ "\1\10\20\0\1\10\21\0\2\10\4\0\12\11\12\0\6\10\5\0"+ "\22\10\3\0\30\10\1\0\11\10\1\0\1\10\2\0\7\10\72\0"+ "\60\10\1\0\2\10\14\0\7\10\11\0\12\11\47\0\2\10\1\0"+ "\1\10\2\0\2\10\1\0\1\10\2\0\1\10\6\0\4\10\1\0"+ "\7\10\1\0\3\10\1\0\1\10\1\0\1\10\2\0\2\10\1\0"+ "\4\10\1\0\2\10\11\0\1\10\2\0\5\10\1\0\1\10\11\0"+ "\12\11\2\0\2\10\42\0\1\10\37\0\12\11\26\0\10\10\1\0"+ "\44\10\33\0\5\10\163\0\53\10\24\0\1\10\12\11\6\0\6\10"+ "\4\0\4\10\3\0\1\10\3\0\2\10\7\0\3\10\4\0\15\10"+ "\14\0\1\10\1\0\12\11\6\0\46\10\12\0\53\10\1\0\1\10"+ "\3\0\u0149\10\1\0\4\10\2\0\7\10\1\0\1\10\1\0\4\10"+ "\2\0\51\10\1\0\4\10\2\0\41\10\1\0\4\10\2\0\7\10"+ "\1\0\1\10\1\0\4\10\2\0\17\10\1\0\71\10\1\0\4\10"+ "\2\0\103\10\45\0\20\10\20\0\125\10\14\0\u026c\10\2\0\21\10"+ "\1\0\32\10\5\0\113\10\25\0\15\10\1\0\4\10\16\0\22\10"+ "\16\0\22\10\16\0\15\10\1\0\3\10\17\0\64\10\43\0\1\10"+ "\4\0\1\10\3\0\12\11\46\0\12\11\6\0\130\10\10\0\51\10"+ "\1\0\1\10\5\0\106\10\12\0\35\10\51\0\12\11\36\10\2\0"+ "\5\10\13\0\54\10\25\0\7\10\10\0\12\11\46\0\27\10\11\0"+ "\65\10\53\0\12\11\6\0\12\11\15\0\1\10\135\0\57\10\21\0"+ "\7\10\4\0\12\11\51\0\36\10\15\0\2\10\12\11\6\0\46\10"+ "\32\0\44\10\34\0\12\11\3\0\3\10\12\11\44\10\153\0\4\10"+ "\1\0\4\10\16\0\300\10\100\0\u0116\10\2\0\6\10\2\0\46\10"+ "\2\0\6\10\2\0\10\10\1\0\1\10\1\0\1\10\1\0\1\10"+ "\1\0\37\10\2\0\65\10\1\0\7\10\1\0\1\10\3\0\3\10"+ "\1\0\7\10\3\0\4\10\2\0\6\10\4\0\15\10\5\0\3\10"+ "\1\0\7\10\164\0\1\10\15\0\1\10\20\0\15\10\145\0\1\10"+ "\4\0\1\10\2\0\12\10\1\0\1\10\3\0\5\10\6\0\1\10"+ "\1\0\1\10\1\0\1\10\1\0\4\10\1\0\13\10\2\0\4\10"+ "\5\0\5\10\4\0\1\10\64\0\2\10\u0a7b\0\57\10\1\0\57\10"+ "\1\0\205\10\6\0\4\10\21\0\46\10\12\0\66\10\11\0\1\10"+ "\20\0\27\10\11\0\7\10\1\0\7\10\1\0\7\10\1\0\7\10"+ "\1\0\7\10\1\0\7\10\1\0\7\10\1\0\7\10\120\0\1\10"+ "\u01d5\0\2\10\52\0\5\10\5\0\2\10\4\0\126\10\6\0\3\10"+ "\1\0\132\10\1\0\4\10\5\0\51\10\3\0\136\10\21\0\33\10"+ "\65\0\20\10\u0200\0\u19b6\10\112\0\u51cc\10\64\0\u048d\10\103\0\56\10"+ "\2\0\u010d\10\3\0\20\10\12\11\2\10\24\0\57\10\20\0\31\10"+ "\10\0\106\10\61\0\11\10\2\0\147\10\2\0\4\10\1\0\2\10"+ "\16\0\12\10\120\0\10\10\1\0\3\10\1\0\4\10\1\0\27\10"+ "\35\0\64\10\16\0\62\10\34\0\12\11\30\0\6\10\3\0\1\10"+ "\4\0\12\11\34\10\12\0\27\10\31\0\35\10\7\0\57\10\34\0"+ "\1\10\12\11\46\0\51\10\27\0\3\10\1\0\10\10\4\0\12\11"+ "\6\0\27\10\3\0\1\10\5\0\60\10\1\0\1\10\3\0\2\10"+ "\2\0\5\10\2\0\1\10\1\0\1\10\30\0\3\10\43\0\6\10"+ "\2\0\6\10\2\0\6\10\11\0\7\10\1\0\7\10\221\0\43\10"+ "\15\0\12\11\6\0\u2ba4\10\14\0\27\10\4\0\61\10\u2104\0\u012e\10"+ "\2\0\76\10\2\0\152\10\46\0\7\10\14\0\5\10\5\0\1\10"+ "\1\0\12\10\1\0\15\10\1\0\5\10\1\0\1\10\1\0\2\10"+ "\1\0\2\10\1\0\154\10\41\0\u016b\10\22\0\100\10\2\0\66\10"+ "\50\0\14\10\164\0\5\10\1\0\207\10\23\0\12\11\7\0\32\10"+ "\6\0\32\10\13\0\131\10\3\0\6\10\2\0\6\10\2\0\6\10"+ "\2\0\3\10\43\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\1\1\2\2\2\3\1\2\1\4\1\5\1\6"+ "\11\4\1\1\1\7\2\10\1\1\2\11\2\0\1\12"+ "\1\13\1\14\2\4\1\15\10\4\2\0\1\1\1\16"+ "\1\1\1\0\1\12\1\0\1\17\2\4\1\20\1\21"+ "\2\4\1\22\1\4\1\23\1\24\2\4\1\25\1\4"+ "\1\26\5\4\1\27\3\4\1\30\14\4\1\31\1\4"+ "\1\32\6\4\1\33"; private static int [] zzUnpackAction() { int [] result = new int[99]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\44\0\110\0\154\0\220\0\264\0\154\0\330"+ "\0\374\0\154\0\154\0\u0120\0\u0144\0\u0168\0\u018c\0\u01b0"+ "\0\u01d4\0\u01f8\0\u021c\0\u0240\0\154\0\154\0\u0264\0\154"+ "\0\u0288\0\u02ac\0\u02d0\0\220\0\u02f4\0\154\0\154\0\154"+ "\0\u0318\0\u033c\0\374\0\u0360\0\u0384\0\u03a8\0\u03cc\0\u03f0"+ "\0\u0414\0\u0438\0\u045c\0\u02ac\0\u0480\0\u04a4\0\154\0\u04c8"+ "\0\u04ec\0\220\0\u0510\0\374\0\u0534\0\u0558\0\374\0\374"+ "\0\u057c\0\u05a0\0\374\0\u05c4\0\374\0\374\0\u05e8\0\u060c"+ "\0\374\0\u0630\0\u0654\0\u0678\0\u069c\0\u06c0\0\u06e4\0\u0708"+ "\0\154\0\u072c\0\u0750\0\u0774\0\154\0\u0798\0\u07bc\0\u07e0"+ "\0\u0804\0\u0828\0\u084c\0\u0870\0\u0894\0\u08b8\0\u08dc\0\u0900"+ "\0\u0924\0\374\0\u0948\0\374\0\u096c\0\u0990\0\u09b4\0\u09d8"+ "\0\u09fc\0\u0a20\0\374"; private static int [] zzUnpackRowMap() { int [] result = new int[99]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\3\4\1\5\1\6\1\7\1\10\1\4\1\11\1\4"+ "\1\12\1\13\1\14\2\11\1\15\1\16\1\11\1\17"+ "\1\20\1\21\3\11\1\22\1\23\1\4\1\11\1\24"+ "\5\11\2\25\4\26\1\27\1\30\36\26\4\31\1\6"+ "\1\7\1\32\1\33\34\31\44\0\2\34\1\35\1\36"+ "\2\0\36\34\5\0\1\7\44\0\1\37\1\40\44\0"+ "\2\11\2\0\16\11\1\0\7\11\12\0\2\11\2\0"+ "\1\11\1\41\1\11\1\42\12\11\1\0\7\11\12\0"+ "\2\11\2\0\16\11\1\0\3\11\1\43\3\11\12\0"+ "\2\11\2\0\16\11\1\0\1\44\6\11\12\0\2\11"+ "\2\0\3\11\1\45\12\11\1\0\7\11\12\0\2\11"+ "\2\0\16\11\1\0\4\11\1\46\2\11\12\0\2\11"+ "\2\0\7\11\1\47\6\11\1\0\7\11\12\0\2\11"+ "\2\0\3\11\1\50\12\11\1\0\7\11\12\0\2\11"+ "\2\0\1\11\1\51\6\11\1\52\5\11\1\0\7\11"+ "\12\0\2\11\2\0\3\11\1\53\12\11\1\0\7\11"+ "\7\0\1\30\36\0\4\31\2\0\1\54\1\55\40\31"+ "\2\0\1\56\1\0\40\31\2\0\1\57\1\60\34\31"+ "\1\34\1\61\1\35\1\62\1\0\1\63\35\34\1\61"+ "\10\0\2\11\2\0\2\11\1\64\13\11\1\0\7\11"+ "\12\0\2\11\2\0\4\11\1\65\11\11\1\0\7\11"+ "\12\0\2\11\2\0\16\11\1\0\1\11\1\66\5\11"+ "\12\0\2\11\2\0\13\11\1\67\2\11\1\0\2\11"+ "\1\70\4\11\12\0\2\11\2\0\7\11\1\71\6\11"+ "\1\0\7\11\12\0\2\11\2\0\1\72\13\11\1\73"+ "\1\11\1\0\7\11\12\0\2\11\2\0\15\11\1\74"+ "\1\0\7\11\12\0\2\11\2\0\7\11\1\75\6\11"+ "\1\0\7\11\12\0\2\11\2\0\13\11\1\76\2\11"+ "\1\0\7\11\12\0\2\11\2\0\6\11\1\77\7\11"+ "\1\0\7\11\2\0\4\31\3\0\1\60\40\31\2\0"+ "\1\56\1\55\40\31\2\0\1\54\1\60\34\31\1\34"+ "\1\61\1\35\1\36\1\0\1\63\35\34\1\61\1\0"+ "\1\63\1\34\2\0\1\63\35\0\1\63\10\0\2\11"+ "\2\0\5\11\1\100\10\11\1\0\7\11\12\0\2\11"+ "\2\0\3\11\1\101\12\11\1\0\7\11\12\0\2\11"+ "\2\0\2\11\1\102\13\11\1\0\7\11\12\0\2\11"+ "\2\0\4\11\1\103\11\11\1\0\7\11\12\0\2\11"+ "\2\0\1\104\15\11\1\0\7\11\12\0\2\11\2\0"+ "\1\105\15\11\1\0\7\11\12\0\2\11\2\0\1\11"+ "\1\106\14\11\1\0\7\11\12\0\2\11\2\0\13\11"+ "\1\107\2\11\1\0\7\11\12\0\2\11\2\0\1\110"+ "\15\11\1\0\7\11\12\0\2\11\2\0\16\11\1\111"+ "\7\11\12\0\2\11\2\0\10\11\1\112\5\11\1\0"+ "\7\11\12\0\2\11\2\0\6\11\1\113\7\11\1\0"+ "\7\11\12\0\2\11\2\0\16\11\1\0\4\11\1\114"+ "\2\11\12\0\2\11\2\0\16\11\1\115\7\11\12\0"+ "\2\11\2\0\1\116\15\11\1\0\7\11\12\0\2\11"+ "\2\0\6\11\1\117\7\11\1\0\7\11\12\0\2\11"+ "\2\0\5\11\1\120\10\11\1\0\7\11\12\0\2\11"+ "\2\0\4\11\1\121\11\11\1\0\7\11\12\0\2\11"+ "\2\0\3\11\1\122\12\11\1\0\7\11\12\0\2\11"+ "\2\0\16\11\1\0\5\11\1\123\1\11\12\0\2\11"+ "\2\0\3\11\1\124\12\11\1\0\7\11\12\0\2\11"+ "\2\0\7\11\1\125\6\11\1\0\7\11\12\0\2\11"+ "\2\0\10\11\1\126\5\11\1\0\7\11\12\0\2\11"+ "\2\0\7\11\1\127\6\11\1\0\7\11\12\0\2\11"+ "\2\0\4\11\1\130\11\11\1\0\7\11\12\0\2\11"+ "\2\0\7\11\1\131\6\11\1\0\7\11\12\0\2\11"+ "\2\0\4\11\1\132\11\11\1\0\7\11\12\0\2\11"+ "\2\0\10\11\1\133\5\11\1\0\7\11\12\0\2\11"+ "\2\0\16\11\1\0\6\11\1\134\12\0\2\11\2\0"+ "\7\11\1\135\6\11\1\0\7\11\12\0\2\11\2\0"+ "\4\11\1\136\11\11\1\0\7\11\12\0\2\11\2\0"+ "\3\11\1\137\12\11\1\0\7\11\12\0\2\11\2\0"+ "\6\11\1\140\7\11\1\0\7\11\12\0\2\11\2\0"+ "\11\11\1\141\4\11\1\0\7\11\12\0\2\11\2\0"+ "\12\11\1\142\3\11\1\0\7\11\12\0\2\11\2\0"+ "\13\11\1\143\2\11\1\0\7\11\2\0"; private static int [] zzUnpackTrans() { int [] result = new int[2628]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\0\1\1\1\11\2\1\1\11\2\1\2\11\11\1"+ "\2\11\1\1\1\11\3\1\2\0\3\11\13\1\2\0"+ "\1\1\1\11\1\1\1\0\1\1\1\0\25\1\1\11"+ "\3\1\1\11\26\1"; private static int [] zzUnpackAttribute() { int [] result = new int[99]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /* user code: */ protected int lineNum; public int getLineNumber() { return 1 + lineNum; /* zero-based */ } public Location getLocation() { return new Location(yytext(), file, getLineNumber(), yychar); } public String getMatchedText() { return yytext(); } public String file = "unknown file"; /** * Creates a new scanner * There is also a java.io.InputStream version of this constructor. * * @param in the java.io.Reader to read input from. */ public Yylex(java.io.Reader in) { this.zzReader = in; } /** * Creates a new scanner. * There is also java.io.Reader version of this constructor. * * @param in the java.io.Inputstream to read input from. */ public Yylex(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 1706) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>ZZ_INITIAL</tt>. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; yyline = yychar = yycolumn = 0; zzLexicalState = YYINITIAL; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached */ private void zzDoEOF() throws java.io.IOException { if (!zzEOFDone) { zzEOFDone = true; yyclose(); } } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public java_cup.runtime.Symbol next_token() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; yychar+= zzMarkedPosL-zzStartRead; boolean zzR = false; for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; zzCurrentPosL++) { switch (zzBufferL[zzCurrentPosL]) { case '\u000B': case '\u000C': case '\u0085': case '\u2028': case '\u2029': yyline++; zzR = false; break; case '\r': yyline++; zzR = true; break; case '\n': if (zzR) zzR = false; else { yyline++; } break; default: zzR = false; } } if (zzR) { // peek one character ahead if it is \n (if we have counted one line too much) boolean zzPeek; if (zzMarkedPosL < zzEndReadL) zzPeek = zzBufferL[zzMarkedPosL] == '\n'; else if (zzAtEOF) zzPeek = false; else { boolean eof = zzRefill(); zzEndReadL = zzEndRead; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; if (eof) zzPeek = false; else zzPeek = zzBufferL[zzMarkedPosL] == '\n'; } if (zzPeek) yyline--; } zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 4: { return new Symbol(sym.IDENTIFIER, 1 + lineNum, yychar, yytext()); } case 28: break; case 2: { System.err.printf("ERROR in file %s: unknown character '%s' at line %d\n", file, yytext(), lineNum + 1); Thread.dumpStack(); } case 29: break; case 16: { return new Symbol(sym.REL); } case 30: break; case 8: { ++lineNum; yybegin(YYINITIAL); } case 31: break; case 19: { return new Symbol(sym.FUN); } case 32: break; case 12: { yybegin(commentstyle2); } case 33: break; case 14: { yybegin(YYINITIAL); } case 34: break; case 27: { return new Symbol(sym.CURRENTINTERVAL); } case 35: break; case 20: { return new Symbol(sym.FIL); } case 36: break; case 9: { System.out.println("ERROR In file " + file + ": Unclosed comment"); } case 37: break; case 25: { return new Symbol(sym.PERSISTENT); } case 38: break; case 3: { ++lineNum; } case 39: break; case 21: { return new Symbol(sym.TYPE); } case 40: break; case 18: { return new Symbol(sym.IND); } case 41: break; case 22: { return new Symbol(sym.INST); } case 42: break; case 15: { return new Symbol(sym.SUB); } case 43: break; case 5: { return new Symbol(sym.OPENPAREN); } case 44: break; case 26: { return new Symbol(sym.NONBLOCKING); } case 45: break; case 17: { return new Symbol(sym.REM); } case 46: break; case 11: { yybegin(commentstyle1); } case 47: break; case 13: { return new Symbol(sym.EQ); } case 48: break; case 7: { /* nothing */ } case 49: break; case 24: { return new Symbol(sym.INSTS); } case 50: break; case 23: { return new Symbol(sym.DEFS); } case 51: break; case 10: { return new Symbol(sym.STR, new String(yytext())); } case 52: break; case 6: { return new Symbol(sym.CLOSEPAREN); } case 53: break; case 1: { } case 54: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; zzDoEOF(); { return new java_cup.runtime.Symbol(sym.EOF); } } else { zzScanError(ZZ_NO_MATCH); } } } } }
c34c355cc6b4a2679a550fe39ba229b022ad1148
52b0106e78cede2b898cee16370a415b3f77abbd
/wildfly-swarm-getting-started/src/main/java/app/HelloServiceImpl.java
587c7961db3a0f2ea157f25a170c409bc65a51cc
[ "MIT" ]
permissive
giruzou/sandbox
9d74746b40e8da7ab81fdd460815e54dc54db6d8
a5bcbcd1e505812e6917a78dda8163fbb50b4eba
refs/heads/master
2021-04-27T01:27:35.872424
2018-02-23T13:09:17
2018-02-23T13:09:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package app; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return String.format("Hello, %s!", name); } }
a58eb2651ba9f01a10024f8cc39fc116d2d16467
c14960d2173dd775e24c1d85a1234b4f41806e4a
/Oving2_Handleliste/src/modell/Cart.java
78f467879ca1d92b8473df09c607ff85de9457d0
[]
no_license
ahaggi/DAT104
92ea7027bb858e634a2af9d03aa17c59152a05bc
ca977f7fe5c168f906105f393da4161cf3f35637
refs/heads/master
2020-05-21T16:41:35.124550
2018-11-13T17:08:42
2018-11-13T17:08:42
63,260,158
0
0
null
null
null
null
UTF-8
Java
false
false
685
java
package modell; import java.util.ArrayList; import java.util.List; public class Cart { private List<Item> items = new ArrayList<>(); public void leggTilItem(Item item) { items.add(item); } public void slettItem(Item item) { items.remove(item); } public void slettItem_navn(String item_navn) { boolean funnet = false; for (int i = 0; i < items.size() && !funnet; i++) { if (items.get(i).getItem_navn().equals(item_navn)) { items.remove(items.get(i)); funnet=true; } } } public List<Item> getItems() { return items; } }
[ "abdallah@VAIO" ]
abdallah@VAIO
7d0d90a5a1c8ad45b26ca12ea1ce9c1018de586a
f1cb419f28fe43a697e759a1804b75cd9403ba99
/src/main/java/de/bguenthe/restapicdcswagger/OttoMarketStock.java
656f7e7ab78d61c60f9a302841438ec6d2b81cc3
[]
no_license
bguenthe/restapicdcswagger
de3165a0e9a329d04c6a88b79f893714d4e91b6b
070127b1329c9bab0d3cf8dee94ec7f06ea7162b
refs/heads/master
2020-03-26T03:40:12.561339
2018-08-12T12:40:27
2018-08-12T12:40:27
144,465,542
0
0
null
null
null
null
UTF-8
Java
false
false
4,596
java
package de.bguenthe.restapicdcswagger; public class OttoMarketStock { private String partnernummer; private String stylenummer; private String partnerArtikelnummer; private String konzernArtikelnummer; private String herstellerMarke; private String groesse; private String ean; private long verkaufspreis; private Long partnerbestand; private String letzeAenderungPartnerbestand; private long verfuegbaerOttoLagerbestand; private long nichtVerfuegbaerOttoLagerbestand; private long ottoGesamtbestand; private long freierGesamtbestand; public OttoMarketStock(String partnernummer, String stylenummer, String partner_Artikelnummer, String konzern_Artikelnummer, String hersteller_Marke, String groesse, String ean, long verkaufspreis, Long partnerbestand, String letze_Aenderung_Partnerbestand, long verfuegbaer_OTTO_Lagerbestand, long nicht_Verfuegbaer_OTTO_Lagerbestand, long OTTO_Gesamtbestand, long freier_Gesamtbestand) { this.partnernummer = partnernummer; this.stylenummer = stylenummer; partnerArtikelnummer = partner_Artikelnummer; konzernArtikelnummer = konzern_Artikelnummer; herstellerMarke = hersteller_Marke; this.groesse = groesse; this.ean = ean; this.verkaufspreis = verkaufspreis; this.partnerbestand = partnerbestand; letzeAenderungPartnerbestand = letze_Aenderung_Partnerbestand; verfuegbaerOttoLagerbestand = verfuegbaer_OTTO_Lagerbestand; nichtVerfuegbaerOttoLagerbestand = nicht_Verfuegbaer_OTTO_Lagerbestand; this.ottoGesamtbestand = OTTO_Gesamtbestand; freierGesamtbestand = freier_Gesamtbestand; } public String getPartnernummer() { return partnernummer; } public void setPartnernummer(String partnernummer) { this.partnernummer = partnernummer; } public String getStylenummer() { return stylenummer; } public void setStylenummer(String stylenummer) { this.stylenummer = stylenummer; } public String getPartnerArtikelnummer() { return partnerArtikelnummer; } public void setPartnerArtikelnummer(String partnerArtikelnummer) { this.partnerArtikelnummer = partnerArtikelnummer; } public String getKonzernArtikelnummer() { return konzernArtikelnummer; } public void setKonzernArtikelnummer(String konzernArtikelnummer) { this.konzernArtikelnummer = konzernArtikelnummer; } public String getHerstellerMarke() { return herstellerMarke; } public void setHerstellerMarke(String herstellerMarke) { this.herstellerMarke = herstellerMarke; } public String getGroesse() { return groesse; } public void setGroesse(String groesse) { this.groesse = groesse; } public String getEan() { return ean; } public void setEan(String ean) { this.ean = ean; } public long getVerkaufspreis() { return verkaufspreis; } public void setVerkaufspreis(long verkaufspreis) { this.verkaufspreis = verkaufspreis; } public Long getPartnerbestand() { return partnerbestand; } public void setPartnerbestand(Long partnerbestand) { this.partnerbestand = partnerbestand; } public String getLetzeAenderungPartnerbestand() { return letzeAenderungPartnerbestand; } public void setLetzeAenderungPartnerbestand(String letzeAenderungPartnerbestand) { this.letzeAenderungPartnerbestand = letzeAenderungPartnerbestand; } public long getVerfuegbaerOttoLagerbestand() { return verfuegbaerOttoLagerbestand; } public void setVerfuegbaerOttoLagerbestand(long verfuegbaerOttoLagerbestand) { this.verfuegbaerOttoLagerbestand = verfuegbaerOttoLagerbestand; } public long getNichtVerfuegbaerOttoLagerbestand() { return nichtVerfuegbaerOttoLagerbestand; } public void setNichtVerfuegbaerOttoLagerbestand(long nichtVerfuegbaerOttoLagerbestand) { this.nichtVerfuegbaerOttoLagerbestand = nichtVerfuegbaerOttoLagerbestand; } public long getOttoGesamtbestand() { return ottoGesamtbestand; } public void setOttoGesamtbestand(long ottoGesamtbestand) { this.ottoGesamtbestand = ottoGesamtbestand; } public long getFreierGesamtbestand() { return freierGesamtbestand; } public void setFreierGesamtbestand(long freierGesamtbestand) { this.freierGesamtbestand = freierGesamtbestand; } }
2b8a6ee1fdbf3d3bf522513676596bef677f8a3d
42b380c356ca8bcd17394d406e17ac0afb6654fb
/vertx-pin/zero-jet/src/main/java/cn/vertxup/jet/domain/tables/IApi.java
d275f2df6206affcb2113b17155feb4aad6eccec
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
netg5/vertx-zero
2a6ab0eaa9cab3359d7da334cd0fb8127e97039d
e94dd8a1ced717bcf8fe309e0798e87350307eaf
refs/heads/master
2020-08-11T01:30:27.626863
2019-10-11T14:46:51
2019-10-11T14:46:51
null
0
0
null
null
null
null
UTF-8
Java
false
true
12,395
java
/* * This file is generated by jOOQ. */ package cn.vertxup.jet.domain.tables; import cn.vertxup.jet.domain.Db; import cn.vertxup.jet.domain.Indexes; import cn.vertxup.jet.domain.Keys; import cn.vertxup.jet.domain.tables.records.IApiRecord; import org.jooq.*; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; import javax.annotation.Generated; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.10.8" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({"all", "unchecked", "rawtypes"}) public class IApi extends TableImpl<IApiRecord> { /** * The reference instance of <code>DB_ETERNAL.I_API</code> */ public static final IApi I_API = new IApi(); private static final long serialVersionUID = -1649445559; /** * The column <code>DB_ETERNAL.I_API.KEY</code>. 「key」- 接口ID */ public final TableField<IApiRecord, String> KEY = createField("KEY", org.jooq.impl.SQLDataType.VARCHAR(36).nullable(false), this, "「key」- 接口ID"); /** * The column <code>DB_ETERNAL.I_API.NAME</code>. 「name」- 接口名称 */ public final TableField<IApiRecord, String> NAME = createField("NAME", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「name」- 接口名称"); /** * The column <code>DB_ETERNAL.I_API.URI</code>. 「uri」- 接口路径,安全路径位于 /api 之下 */ public final TableField<IApiRecord, String> URI = createField("URI", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「uri」- 接口路径,安全路径位于 /api 之下"); /** * The column <code>DB_ETERNAL.I_API.METHOD</code>. 「method」- 接口对应的HTTP方法 */ public final TableField<IApiRecord, String> METHOD = createField("METHOD", org.jooq.impl.SQLDataType.VARCHAR(20), this, "「method」- 接口对应的HTTP方法"); /** * The column <code>DB_ETERNAL.I_API.CONSUMES</code>. 「consumes」- 当前接口使用的客户端 MIME */ public final TableField<IApiRecord, String> CONSUMES = createField("CONSUMES", org.jooq.impl.SQLDataType.CLOB, this, "「consumes」- 当前接口使用的客户端 MIME"); /** * The column <code>DB_ETERNAL.I_API.PRODUCES</code>. 「produces」- 当前接口使用的服务端 MIME */ public final TableField<IApiRecord, String> PRODUCES = createField("PRODUCES", org.jooq.impl.SQLDataType.CLOB, this, "「produces」- 当前接口使用的服务端 MIME"); /** * The column <code>DB_ETERNAL.I_API.SECURE</code>. 「secure」- 是否走安全通道,默认为TRUE */ public final TableField<IApiRecord, Boolean> SECURE = createField("SECURE", org.jooq.impl.SQLDataType.BIT, this, "「secure」- 是否走安全通道,默认为TRUE"); /** * The column <code>DB_ETERNAL.I_API.COMMENT</code>. 「comment」- 备注信息 */ public final TableField<IApiRecord, String> COMMENT = createField("COMMENT", org.jooq.impl.SQLDataType.CLOB, this, "「comment」- 备注信息"); /** * The column <code>DB_ETERNAL.I_API.TYPE</code>. 「type」- 通信类型,ONE-WAY / REQUEST-RESPONSE / PUBLISH-SUBSCRIBE */ public final TableField<IApiRecord, String> TYPE = createField("TYPE", org.jooq.impl.SQLDataType.VARCHAR(64), this, "「type」- 通信类型,ONE-WAY / REQUEST-RESPONSE / PUBLISH-SUBSCRIBE"); /** * The column <code>DB_ETERNAL.I_API.PARAM_MODE</code>. 「paramMode」- 参数来源,QUERY / BODY / DEFINE / PATH */ public final TableField<IApiRecord, String> PARAM_MODE = createField("PARAM_MODE", org.jooq.impl.SQLDataType.VARCHAR(20), this, "「paramMode」- 参数来源,QUERY / BODY / DEFINE / PATH"); /** * The column <code>DB_ETERNAL.I_API.PARAM_REQUIRED</code>. 「paramRequired」- 必须参数表,一个JsonArray用于返回 400基本验证(验证Query和Path) */ public final TableField<IApiRecord, String> PARAM_REQUIRED = createField("PARAM_REQUIRED", org.jooq.impl.SQLDataType.CLOB, this, "「paramRequired」- 必须参数表,一个JsonArray用于返回 400基本验证(验证Query和Path)"); /** * The column <code>DB_ETERNAL.I_API.PARAM_CONTAINED</code>. 「paramContained」- 必须参数表,一个JsonArray用于返回 400基本验证(验证Body) */ public final TableField<IApiRecord, String> PARAM_CONTAINED = createField("PARAM_CONTAINED", org.jooq.impl.SQLDataType.CLOB, this, "「paramContained」- 必须参数表,一个JsonArray用于返回 400基本验证(验证Body)"); /** * The column <code>DB_ETERNAL.I_API.IN_RULE</code>. 「inRule」- 参数验证、转换基本规则 */ public final TableField<IApiRecord, String> IN_RULE = createField("IN_RULE", org.jooq.impl.SQLDataType.CLOB, this, "「inRule」- 参数验证、转换基本规则"); /** * The column <code>DB_ETERNAL.I_API.IN_MAPPING</code>. 「inMapping」- 参数映射规则 */ public final TableField<IApiRecord, String> IN_MAPPING = createField("IN_MAPPING", org.jooq.impl.SQLDataType.CLOB, this, "「inMapping」- 参数映射规则"); /** * The column <code>DB_ETERNAL.I_API.IN_PLUG</code>. 「inPlug」- 参数请求流程中的插件 */ public final TableField<IApiRecord, String> IN_PLUG = createField("IN_PLUG", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「inPlug」- 参数请求流程中的插件"); /** * The column <code>DB_ETERNAL.I_API.IN_SCRIPT</code>. 「inScript」- 【保留】参数请求流程中的脚本控制 */ public final TableField<IApiRecord, String> IN_SCRIPT = createField("IN_SCRIPT", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「inScript」- 【保留】参数请求流程中的脚本控制"); /** * The column <code>DB_ETERNAL.I_API.WORKER_TYPE</code>. 「workerType」- Worker类型:JS / PLUG / STD */ public final TableField<IApiRecord, String> WORKER_TYPE = createField("WORKER_TYPE", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「workerType」- Worker类型:JS / PLUG / STD"); /** * The column <code>DB_ETERNAL.I_API.WORKER_ADDRESS</code>. 「workerAddress」- 请求发送地址 */ public final TableField<IApiRecord, String> WORKER_ADDRESS = createField("WORKER_ADDRESS", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「workerAddress」- 请求发送地址"); /** * The column <code>DB_ETERNAL.I_API.WORKER_CONSUMER</code>. 「workerConsumer」- 请求地址消费专用组件 */ public final TableField<IApiRecord, String> WORKER_CONSUMER = createField("WORKER_CONSUMER", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「workerConsumer」- 请求地址消费专用组件"); /** * The column <code>DB_ETERNAL.I_API.WORKER_CLASS</code>. 「workerClass」- OX | PLUG专用,请求执行器对应的JavaClass名称 */ public final TableField<IApiRecord, String> WORKER_CLASS = createField("WORKER_CLASS", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「workerClass」- OX | PLUG专用,请求执行器对应的JavaClass名称"); /** * The column <code>DB_ETERNAL.I_API.WORKER_JS</code>. 「workerJs」- JS 专用,JavaScript路径:runtime/workers/&lt;app&gt;/下的执行器 */ public final TableField<IApiRecord, String> WORKER_JS = createField("WORKER_JS", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「workerJs」- JS 专用,JavaScript路径:runtime/workers/<app>/下的执行器"); /** * The column <code>DB_ETERNAL.I_API.OUT_WRITER</code>. 「outWriter」- 响应格式处理器 */ public final TableField<IApiRecord, String> OUT_WRITER = createField("OUT_WRITER", org.jooq.impl.SQLDataType.VARCHAR(255), this, "「outWriter」- 响应格式处理器"); /** * The column <code>DB_ETERNAL.I_API.SERVICE_ID</code>. 「serviceId」- 关联的服务ID */ public final TableField<IApiRecord, String> SERVICE_ID = createField("SERVICE_ID", org.jooq.impl.SQLDataType.VARCHAR(36), this, "「serviceId」- 关联的服务ID"); /** * The column <code>DB_ETERNAL.I_API.SIGMA</code>. 「sigma」- 统一标识 */ public final TableField<IApiRecord, String> SIGMA = createField("SIGMA", org.jooq.impl.SQLDataType.VARCHAR(32), this, "「sigma」- 统一标识"); /** * The column <code>DB_ETERNAL.I_API.LANGUAGE</code>. 「language」- 使用的语言 */ public final TableField<IApiRecord, String> LANGUAGE = createField("LANGUAGE", org.jooq.impl.SQLDataType.VARCHAR(10), this, "「language」- 使用的语言"); /** * The column <code>DB_ETERNAL.I_API.ACTIVE</code>. 「active」- 是否启用 */ public final TableField<IApiRecord, Boolean> ACTIVE = createField("ACTIVE", org.jooq.impl.SQLDataType.BIT, this, "「active」- 是否启用"); /** * The column <code>DB_ETERNAL.I_API.METADATA</code>. 「metadata」- 附加配置数据 */ public final TableField<IApiRecord, String> METADATA = createField("METADATA", org.jooq.impl.SQLDataType.CLOB, this, "「metadata」- 附加配置数据"); /** * The column <code>DB_ETERNAL.I_API.CREATED_AT</code>. 「createdAt」- 创建时间 */ public final TableField<IApiRecord, LocalDateTime> CREATED_AT = createField("CREATED_AT", org.jooq.impl.SQLDataType.LOCALDATETIME, this, "「createdAt」- 创建时间"); /** * The column <code>DB_ETERNAL.I_API.CREATED_BY</code>. 「createdBy」- 创建人 */ public final TableField<IApiRecord, String> CREATED_BY = createField("CREATED_BY", org.jooq.impl.SQLDataType.VARCHAR(36), this, "「createdBy」- 创建人"); /** * The column <code>DB_ETERNAL.I_API.UPDATED_AT</code>. 「updatedAt」- 更新时间 */ public final TableField<IApiRecord, LocalDateTime> UPDATED_AT = createField("UPDATED_AT", org.jooq.impl.SQLDataType.LOCALDATETIME, this, "「updatedAt」- 更新时间"); /** * The column <code>DB_ETERNAL.I_API.UPDATED_BY</code>. 「updatedBy」- 更新人 */ public final TableField<IApiRecord, String> UPDATED_BY = createField("UPDATED_BY", org.jooq.impl.SQLDataType.VARCHAR(36), this, "「updatedBy」- 更新人"); /** * Create a <code>DB_ETERNAL.I_API</code> table reference */ public IApi() { this(DSL.name("I_API"), null); } /** * Create an aliased <code>DB_ETERNAL.I_API</code> table reference */ public IApi(String alias) { this(DSL.name(alias), I_API); } /** * Create an aliased <code>DB_ETERNAL.I_API</code> table reference */ public IApi(Name alias) { this(alias, I_API); } private IApi(Name alias, Table<IApiRecord> aliased) { this(alias, aliased, null); } private IApi(Name alias, Table<IApiRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * The class holding records for this type */ @Override public Class<IApiRecord> getRecordType() { return IApiRecord.class; } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Db.DB_ETERNAL; } /** * {@inheritDoc} */ @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.I_API_PRIMARY, Indexes.I_API_URI); } /** * {@inheritDoc} */ @Override public UniqueKey<IApiRecord> getPrimaryKey() { return Keys.KEY_I_API_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<IApiRecord>> getKeys() { return Arrays.<UniqueKey<IApiRecord>>asList(Keys.KEY_I_API_PRIMARY, Keys.KEY_I_API_URI); } /** * {@inheritDoc} */ @Override public IApi as(String alias) { return new IApi(DSL.name(alias), this); } /** * {@inheritDoc} */ @Override public IApi as(Name alias) { return new IApi(alias, this); } /** * Rename this table */ @Override public IApi rename(String name) { return new IApi(DSL.name(name), null); } /** * Rename this table */ @Override public IApi rename(Name name) { return new IApi(name, null); } }
22f2de18f09e2471162f0a64d49a9c5dba41894d
b56eb2e8faed0ded4c190f8669dc83cb45b8225d
/src/test/java/com/app/raghu/SpringBootWebApplicationTests.java
98c1b432b97e962c7e1e7531f89db63bae3115fd
[]
no_license
eshrsut/SpringBootWeb
c3677b9612c2dec136912fd47c57cec335bc6217
ae870dfe4f2bd1761d54a4831c6f7f719f824127
refs/heads/master
2021-10-22T06:15:07.584870
2019-03-08T18:18:09
2019-03-08T18:18:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
337
java
package com.app.raghu; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootWebApplicationTests { @Test public void contextLoads() { } }
dbc51925db8efbe97b4175bd445d63f6a8ee04d0
281d7509a7aeb4d34e97fe11be8294932e4e1c03
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/SkyStone/VuMarkIdentificationWebcam.java
0701ad9c4dcd2b21d2980b77dbb0e54ccd3bd55d
[ "BSD-3-Clause" ]
permissive
ftcgearedup/SkyStoneFTC
3c94121c1fa064ae48350efd0ebe65082b5749b7
aa287af60e31ec2628e95fa68ec7453e83d1d601
refs/heads/master
2020-09-04T00:24:20.568278
2020-03-11T23:48:55
2020-03-11T23:48:55
219,616,423
0
0
null
null
null
null
UTF-8
Java
false
false
10,016
java
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode.SkyStone; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.robotcontroller.external.samples.ConceptVuforiaNavigationWebcam; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix; import org.firstinspires.ftc.robotcore.external.matrices.VectorF; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark; import org.firstinspires.ftc.robotcore.external.navigation.VuMarkInstanceId; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables; /** * This OpMode illustrates the basics of using the Vuforia engine to determine * the identity of Vuforia VuMarks encountered on the field. The code is structured as * a LinearOpMode. It shares much structure with {@link ConceptVuforiaNavigationWebcam}; we do not here * duplicate the core Vuforia documentation found there, but rather instead focus on the * differences between the use of Vuforia for navigation vs VuMark identification. * * @see ConceptVuforiaNavigationWebcam * @see VuforiaLocalizer * @see VuforiaTrackableDefaultListener * see ftc_app/doc/tutorial/FTC_FieldCoordinateSystemDefinition.pdf * * Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list. * * IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as * is explained in {@link ConceptVuforiaNavigationWebcam}. */ @TeleOp(name="Concept: VuMark Id Webcam", group ="Concept") @Disabled public class VuMarkIdentificationWebcam extends LinearOpMode { public static final String TAG = "Vuforia VuMark Sample"; OpenGLMatrix lastLocation = null; /** * {@link #vuforia} is the variable we will use to store our instance of the Vuforia * localization engine. */ VuforiaLocalizer vuforia; /** * This is the webcam we are to use. As with other hardware devices such as motors and * servos, this device is identified using the robot configuration tool in the FTC application. */ WebcamName webcamName; @Override public void runOpMode() { /* * Retrieve the camera we are to use. */ webcamName = hardwareMap.get(WebcamName.class, "Webcam 1"); /* * To start up Vuforia, tell it the view that we wish to use for camera monitor (on the RC phone); * If no camera monitor is desired, use the parameterless constructor instead (commented out below). */ int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId); // OR... Do Not Activate the Camera Monitor View, to save power // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); /* * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function. * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer * web site at https://developer.vuforia.com/license-manager. * * Vuforia license keys are always 380 characters long, and look as if they contain mostly * random data. As an example, here is a example of a fragment of a valid key: * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ... * Once you've obtained a license key, copy the string from the Vuforia web site * and paste it in to your code on the next line, between the double quotes. */ parameters.vuforiaLicenseKey = " -- YOUR NEW VUFORIA KEY GOES HERE --- "; /** * We also indicate which camera on the RC we wish to use. For pedagogical purposes, * we use the same logic as in {@link ConceptVuforiaNavigationWebcam}. */ parameters.cameraName = webcamName; this.vuforia = ClassFactory.getInstance().createVuforia(parameters); /** * Load the data set containing the VuMarks for Relic Recovery. There's only one trackable * in this data set: all three of the VuMarks in the game were created from this one template, * but differ in their instance id information. * @see VuMarkInstanceId */ VuforiaTrackables relicTrackables = this.vuforia.loadTrackablesFromAsset("RelicVuMark"); VuforiaTrackable relicTemplate = relicTrackables.get(0); relicTemplate.setName("relicVuMarkTemplate"); // can help in debugging; otherwise not necessary telemetry.addData(">", "Press Play to start"); telemetry.update(); waitForStart(); relicTrackables.activate(); while (opModeIsActive()) { /** * See if any of the instances of {@link relicTemplate} are currently visible. * {@link RelicRecoveryVuMark} is an enum which can have the following values: * UNKNOWN, LEFT, CENTER, and RIGHT. When a VuMark is visible, something other than * UNKNOWN will be returned by {@link RelicRecoveryVuMark#from(VuforiaTrackable)}. */ RelicRecoveryVuMark vuMark = RelicRecoveryVuMark.from(relicTemplate); if (vuMark != RelicRecoveryVuMark.UNKNOWN) { /* Found an instance of the template. In the actual game, you will probably * loop until this condition occurs, then move on to act accordingly depending * on which VuMark was visible. */ telemetry.addData("VuMark", "%s visible", vuMark); /* For fun, we also exhibit the navigational pose. In the Relic Recovery game, * it is perhaps unlikely that you will actually need to act on this pose information, but * we illustrate it nevertheless, for completeness. */ OpenGLMatrix pose = ((VuforiaTrackableDefaultListener)relicTemplate.getListener()).getFtcCameraFromTarget(); telemetry.addData("Pose", format(pose)); /* We further illustrate how to decompose the pose into useful rotational and * translational components */ if (pose != null) { VectorF trans = pose.getTranslation(); Orientation rot = Orientation.getOrientation(pose, AxesReference.EXTRINSIC, AxesOrder.XYZ, AngleUnit.DEGREES); // Extract the X, Y, and Z components of the offset of the target relative to the robot double tX = trans.get(0); double tY = trans.get(1); double tZ = trans.get(2); // Extract the rotational components of the target relative to the robot double rX = rot.firstAngle; double rY = rot.secondAngle; double rZ = rot.thirdAngle; } } else { telemetry.addData("VuMark", "not visible"); } telemetry.update(); } } String format(OpenGLMatrix transformationMatrix) { return (transformationMatrix != null) ? transformationMatrix.formatAsTransform() : "null"; } }
68c15feab21c46a9decd75af94c01628166df55f
c11c3acb4300aecce3a613fb71e21ad56218d84e
/src/main/java/net/slipp/MyWebInitializer.java
3ebd1b3539bac5fd9ccdd38aa6f987a315527928
[]
no_license
dsptek/git_test
07d22a1da83703d788014c1732a5d24daae8ed3d
52b83d13e5b768b94e4e2e04f5a83ce09f22b2d7
refs/heads/master
2021-01-19T18:14:27.049287
2017-09-28T06:19:55
2017-09-28T06:19:55
101,118,145
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package net.slipp; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; public class MyWebInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MySlippApplication.class); } }
30928b3edbe605f6aeed62ee4cea00a9d0cf9fef
fb6ed48ecc6eab4496dacf32e8dd37e49908935a
/StringUnique.java
c9d738cd253ecf834ae5da4e603ee0294d891061
[]
no_license
shaktdi/Training
7f10b13e4338048fa418974d9d802e93b81d21a6
4f1418d3967e45cb72607f0d5ecc0c252da3786b
refs/heads/master
2020-04-22T00:07:00.967344
2019-02-11T06:14:33
2019-02-11T06:14:33
169,968,261
0
0
null
null
null
null
UTF-8
Java
false
false
794
java
package week5.day9and10; import java.util.Scanner; public class StringUnique { public static void main(String[] args) { String txt; int txtsize; Scanner sc = new Scanner (System.in); System.out.println("Enter the Input String"); txt = sc.nextLine(); sc.close(); txt = txt.toLowerCase().replaceAll("\\s", ""); txtsize = txt.length(); char[] txtchar = new char [txtsize]; txtchar = txt.toCharArray(); String output =""; for (int i =0 ; i<txtsize ; i++) { if (output.indexOf(txtchar[i]) == -1) { output = output + txtchar[i]; } } System.out.println(output); } }
d50d2194421f03d31d6d6903f99f974725755c2f
ba31608ec3915ddd13cca302f360004dac1543da
/Miwok/app/src/main/java/com/example/miwok/miwok/CharactersActivity.java
52c18455d506380aadbbcea4ec859ce695bec41e
[]
no_license
DerrickDK/AndroidProjects
5db1601a7c1694556fc3c25c15ac5ff80956c801
e15f271a3ddcf7559b2a583f37a9163df11ca3cc
refs/heads/master
2020-03-19T10:58:13.859488
2018-06-07T03:46:43
2018-06-07T03:46:43
136,417,675
0
0
null
null
null
null
UTF-8
Java
false
false
1,121
java
package com.example.miwok.miwok; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; public class CharactersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_characters); createList(); } public void createList(){ ArrayList<String> myNumbers = new ArrayList<>(); myNumbers.add("One"); myNumbers.add("Two"); LinearLayout myRootLayout = (LinearLayout) findViewById(R.id.rootView); TextView myText = new TextView(this); //this refers to the class and all of it's components //Read "TextView for this class called CharactersActivity which is connected to activity_characters") myText.setText(myNumbers.get(0)); myRootLayout.addView(myText); TextView myText2 = new TextView(this); myText2.setText(myNumbers.get(1)); myRootLayout.addView(myText2); } }
dd2a06e081ecf74992cf287f80d645b1d709e428
94e56686d04add92c164d94790b92e0e3e7e3c29
/photoworld/src/com/xiao/pojo/UserReply.java
2bc441bc4c2592b615de383d24740129915159f5
[]
no_license
xjf98/Photoworld
c444d0d851b7a1572b48516b6034ca45b86e7700
970057382c70c6774d5b9976604a0e20dcea9e5f
refs/heads/master
2021-06-26T07:37:43.418387
2021-01-22T02:01:49
2021-01-22T02:01:49
201,209,036
2
0
null
null
null
null
UTF-8
Java
false
false
971
java
package com.xiao.pojo; public class UserReply { private String rid; private String uid; private String username; private String r_content; private String userphoto; private String r_time; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getR_time() { return r_time; } public void setR_time(String r_time) { this.r_time = r_time; } public String getUserphoto() { return userphoto; } public void setUserphoto(String userphoto) { this.userphoto = userphoto; } public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getR_content() { return r_content; } public void setR_content(String r_content) { this.r_content = r_content; } }
64212da90a5ea851eeb16c5c3e1927fa22515c06
074a5c63c854abef5828ffcef383c74edc39e01a
/leapyearindicator/AverageScoreCalculator.java
2f89b94f8bbec0b7c17d6bab9d284b1de8bc857a
[]
no_license
imro1/leapYearIndicator
4bb2ef34b124262237d1fcdf6d0b9cbcaa33c2e3
5fa166124bdd61e461fd567de81ac6f24d9aeadd
refs/heads/main
2023-09-06T00:37:43.428643
2021-11-20T04:32:57
2021-11-20T04:32:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
926
java
/* * 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 birthyearcalculator; import java.util.Random; import java.util.Scanner; /** * * @author imran */ public class AverageScoreCalculator { public static void main(String[]args){ Scanner console = new Scanner(System.in); //input System.out.printf("Please enter the amount of random scores: "); int num = console.nextInt(); //output } public void calcAverageScore(int num){ Random rand = new Random(); int totalNums; double total = 0; for (totalNums=1; totalNums<=num; totalNums++){ int random = rand.nextInt(101); total += random; } double average = total/num; } }
dd48285190409b28063a38b9b45d08f08cbe6efd
6b59d73858048da73cdb544d8d0875fbcf11ca6d
/dts-common/src/main/java/com/le/dts/common/exception/RemotingTooMuchRequestException.java
a0d1ff71460e0f5a44acd11a3c9beca3f2a30e52
[]
no_license
suzuizui/dts-all
e63c2a901ca8c473faa9c490fe014089fb39d018
605b51b6ad53bc05871ee4755af4f19052eadea1
refs/heads/master
2021-01-01T19:50:20.484429
2017-07-29T03:20:59
2017-07-29T03:21:01
98,704,868
2
1
null
null
null
null
UTF-8
Java
false
false
1,085
java
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.le.dts.common.exception; /** * 异步调用或者Oneway调用,堆积的请求超过信号量最大值 * * @author shijia.wxr<[email protected]> * @since 2013-7-13 */ public class RemotingTooMuchRequestException extends RemotingException { private static final long serialVersionUID = 4326919581254519654L; public RemotingTooMuchRequestException(String message) { super(message); } }
8ae52609e883c9320143fea77753a9454b4f847e
307e5fc8dfbe96da14618117fae8a45d787c69e1
/app/src/main/java/com/stateunion/eatshop/util/CreateEiWeiMaImage.java
42fa04fc82c70974ee4de2b723b913a04f821595
[]
no_license
ligangqianggit/eatshop2
fea15cb2dbe2a873119013f88a503ee8726feab3
42fab1c1b988b7222034ac242c69ed1d745e657c
refs/heads/master
2022-03-05T15:34:44.732648
2019-12-02T07:19:29
2019-12-02T07:19:29
114,602,555
0
0
null
null
null
null
UTF-8
Java
false
false
2,217
java
package com.stateunion.eatshop.util; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.util.Hashtable; /** * Created by 青春 on 2017/12/13. */ public class CreateEiWeiMaImage { /** * @param order * @param width * @param height * @return 生成二维码 * <p> * 调用 Bitmap CreateQRImage = createZXing(apkDownLoadUrl, 700, 700);// 生成的二维码 * <p> * imageview.setImageBitmap */ public static Bitmap createZXing(String order, final int width, final int height) { try { // 判断URL合法性 if (order == null || "".equals(order) || order.length() < 1) { return null; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(order, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; // 下面这里按照二维码的算法,逐个生成二维码的图片, // 两个for循环是图片横列扫描的结果 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * width + x] = 0xffffffff; } } } // 生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; } }
b0336747dade22674bd9106324428e6a5dbef3d1
fbaa1fedf1196bcc45ba54a9dce2aab6fe0e1df6
/src/main/java/com/chinaunicom/integration/sync/dao/HbaseDao.java
e1089821f0d1678fc6d215480125a7f7c6707d64
[]
no_license
ycd2003/sync-elasticsearch
009c4dfc4aed13b0f2903eebf786c5d7c12da2e1
3e46763732e1354de17d90daea852746251aa11d
refs/heads/master
2020-12-15T08:21:00.618002
2019-12-03T06:07:03
2019-12-03T06:07:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
790
java
package com.chinaunicom.integration.sync.dao; public class HbaseDao { private final String tableName; private final String rowkey; private final String cf; private final String column; private final String value; public HbaseDao(String tableName, String rowkey, String cf, String column, String value) { this.tableName = tableName; this.rowkey = rowkey; this.cf = cf; this.column = column; this.value = value; } public String getTableName() { return tableName; } public String getRowkey() { return rowkey; } public String getCf() { return cf; } public String getColumn() { return column; } public String getValue() { return value; } }
8185939d9851a28007499710d84b5cd931c328a4
f30e678cd4ff9d342d98d3dcbf98b3c56e418ee4
/ChemMaster2/app/src/main/java/com/gary/chemmaster/util/CYLUrlFactory.java
f6f273fbf3e0d04dd53ca04f8bea456d1aceecfa
[]
no_license
long0133/ChemMaster_For_Android
dfde02df958bb9f08308a9f6d41b1f041c63b251
169833b895867564d6c8b67bed4cd3ee3de7839f
refs/heads/master
2020-07-24T04:42:58.903587
2016-12-14T02:23:25
2016-12-14T02:23:25
73,795,174
0
0
null
null
null
null
UTF-8
Java
false
false
1,306
java
package com.gary.chemmaster.util; import android.util.Log; import com.gary.chemmaster.entity.CYLEditor_Doi_Pub; import java.util.ArrayList; import java.util.List; /** * Created by gary on 2016/11/10. */ public class CYLUrlFactory { public static String getUrlOfAllEditorChoise() { return "http://pubs.acs.org/editorschoice/manuscripts.json?format=lite"; } public static String getUrlOfRencetEditorChoice(List<CYLEditor_Doi_Pub> pubs, int nums) { StringBuilder builder = new StringBuilder("http://pubs.acs.org/editorschoice/manuscripts.json?find=ByDoiEquals&"); for (int i = 0; i < nums; i ++) { CYLEditor_Doi_Pub pub = pubs.get(i); builder.append("doi%5B%5D="+pub.getDoi().replace("/","%2F")+"&"); } String s = builder.toString(); s = s.substring(0,s.length()-1); return s; } public static String getUrlOfAllNameReactionList() { return "http://www.organic-chemistry.org/namedreactions/"; } public static String getUrlOfAllTotalSynthesisList() { return "http://www.organic-chemistry.org/totalsynthesis/"; } public static String getUrlOfHighLightYearList() { return "http://www.organic-chemistry.org/Highlights/"; } }
9dccd2edf56a66c5dea7090d7dd085744e12f405
836b3a56285e69481ad7b8ee11542e023791d3b8
/src/JavaPrograms/13-3-15/Prop2.java
bc5aa8c43b470b520108bb4d5e3a253a3192e9d1
[]
no_license
dalalsunil1986/J2SE
ce3cfd7edea16f4d4e4ff40c2937930eb1482ed0
a6d57a36cfd64a9fdf54b2c0bf8794dd0bd5c4c2
refs/heads/master
2020-04-23T08:02:06.785299
2017-11-29T15:55:47
2017-11-29T15:55:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
//Prop2.java import java.util.*; class Prop2 { public static void main(String[] args) { Properties p=System.getProperties(); Enumeration en=p.keys(); while(en.hasMoreElements()) { //Object en=en.nextElement(); //Object en=p.get(en); System.out.println(en+">"+en); } } }
444642b5d482197e82e605a9fe717bbc26fcdcda
bead5c9388e0d70156a08dfe86d48f52cb245502
/Learning_Thingkin_in_Java/chapter_16/c_16_2/ArrayOptions.java
2f6553399f480e59bf6519b9bc5e82110abfe55f
[]
no_license
LinZiYU1996/Learning-Java
bd96e2af798c09bc52a56bf21e13f5763bb7a63d
a0d9f538c9d373c3a93ccd890006ce0e5e1f2d5d
refs/heads/master
2020-11-28T22:22:56.135760
2020-05-03T01:24:57
2020-05-03T01:24:57
229,930,586
0
0
null
null
null
null
UTF-8
Java
false
false
2,022
java
package chapter_16.c_16_2; import chapter_16.c_16_1.BerylliumSphere; import java.util.Arrays; import static chapter_6.c_6_1.c_6_1_3.Print.print; /** * @Author: Mr.Lin * @Description: * @Date: Create in 17:02 2020/1/6 */ public class ArrayOptions { public static void main(String[] args) { // Arrays of objects: BerylliumSphere[] a; // Local uninitialized variable BerylliumSphere[] b = new BerylliumSphere[5]; // The references inside the array are // automatically initialized to null: print("b: " + Arrays.toString(b)); BerylliumSphere[] c = new BerylliumSphere[4]; for(int i = 0; i < c.length; i++) if(c[i] == null) // Can test for null reference c[i] = new BerylliumSphere(); // Aggregate initialization: BerylliumSphere[] d = { new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere() }; // Dynamic aggregate initialization: a = new BerylliumSphere[]{ new BerylliumSphere(), new BerylliumSphere(), }; // (Trailing comma is optional in both cases) print("a.length = " + a.length); print("b.length = " + b.length); print("c.length = " + c.length); print("d.length = " + d.length); a = d; print("a.length = " + a.length); // Arrays of primitives: int[] e; // Null reference int[] f = new int[5]; // The primitives inside the array are // automatically initialized to zero: print("f: " + Arrays.toString(f)); int[] g = new int[4]; for(int i = 0; i < g.length; i++) g[i] = i*i; int[] h = { 11, 47, 93 }; // Compile error: variable e not initialized: //!print("e.length = " + e.length); print("f.length = " + f.length); print("g.length = " + g.length); print("h.length = " + h.length); e = h; print("e.length = " + e.length); e = new int[]{ 1, 2 }; print("e.length = " + e.length); } }
9e594ede82980862779442c8c68ec8d17b9d0eb3
b39d82fcb6094532c21847090afb00c10c3f5baf
/src/main/java/org/meowy/cqp/jcq/annotation/CQEventMapping.java
fc51de1e1c2c96a3e37601270038d8604a59eae1
[]
no_license
joslin1215/JCQ-CoolQ
f55297079aa624152e4645e63838c17bb6c6fe31
a4b1aed4767ba42d3e18ae456a73f49aa1a3bec8
refs/heads/master
2020-06-02T19:29:27.602099
2019-06-10T13:41:28
2019-06-10T13:41:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,764
java
package org.meowy.cqp.jcq.annotation; import java.lang.annotation.*; /** * Created by Sobte on 2018/6/14.<br> * Time: 2018/6/14 18:00<br> * Email: [email protected]<br> * 绑定符合条件 * * @author Sobte */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface CQEventMapping { /** * 事件类型,详见 {@link EventType 事件类型} , 默认 {@link EventType#GroupMsg 群消息事件} * * @return 事件类型 * @see EventType */ EventType[] type() default {}; /** * 匹配子类型,多个满足一个即可,多个匹配需同时满足 * * @return 子类型 */ int[] subType() default {}; /** * 匹配符合的群号,多个满足一个即可,多个匹配需同时满足 * * @return 群号 */ long[] fromGroup() default {}; /** * 匹配符合的QQ号,多个满足一个即可,多个匹配需同时满足 * * @return QQ号 */ long[] fromQQ() default {}; /** * 匹配符合的被操作QQ号,多个满足一个即可,多个匹配需同时满足 * * @return 被操作QQ号 */ long[] beingOperateQQ() default {}; /** * 匹配符合指定消息类型,多个满足一个即可,多个匹配需同时满足 * * @return 消息类型 * @see MsgType */ MsgType[] msgType() default {}; /** * 匹配消息前缀,多个满足一个即可,多个匹配需同时满足(完整匹配除外)<br> * 匹配指定功能的CQ码,键值为空即可,例:[CQ:at]<br> * 匹配指定功能的CQ码,指定的键值,例:[CQ:at,qq=123456] * * @return 消息前缀 */ String[] prefix() default {}; /** * 匹配消息包含内容,多个满足一个即可,多个匹配需同时满足(完整匹配除外)<br> * 匹配指定功能的CQ码,键值为空即可,例:[CQ:at]<br> * 匹配指定功能的CQ码,指定的键值,例:[CQ:at,qq=123456] * * @return 包含内容 */ String[] contains() default {}; /** * 完整匹配消息内容,多个满足一个即可,当满足此匹配,其他将忽略<br> * 匹配指定功能的CQ码,键值为空即可,例:[CQ:at]<br> * 匹配指定功能的CQ码,指定的键值,例:[CQ:at,qq=123456] * * @return 完整内容 */ String[] value() default {}; /** * 匹配消息后缀,多个满足一个即可,多个匹配需同时满足(完整匹配除外)<br> * 匹配指定功能的CQ码,键值为空即可,例:[CQ:at]<br> * 匹配指定功能的CQ码,指定的键值,例:[CQ:at,qq=123456] * * @return 消息后缀 */ String[] suffix() default {}; }
9f0604b709dca49bb2543870d36edfad4b9b4d3e
8adcadc0923b98233d523e11219887d8692351bc
/Backgroundable.java
0293f1980febf77b89bc01d231e7bc60b5ba430c
[]
no_license
EoinM95/CommandLine
aec390edc5ff2b5b3e021178a557d79ef687e2a4
aa9ee115240a448f26963ea70955be1976755660
refs/heads/master
2021-01-10T17:15:50.593293
2015-12-29T16:22:48
2015-12-29T16:22:48
47,703,165
0
1
null
2015-12-29T15:05:23
2015-12-09T16:18:05
Java
UTF-8
Java
false
false
129
java
public interface Backgroundable { public abstract void kill(); public abstract void setBackground(boolean background); }
d8edbec326506500bbbc111521eac02391228099
493a8065cf8ec4a4ccdf136170d505248ac03399
/net.sf.ictalive.dashboard/src/net/sf/ictalive/dashboard/PluginDashboardAction.java
541fee798cc2440aeb0bc7dae48ba2cbc4106db5
[]
no_license
ignasi-gomez/aliveclipse
593611b2d471ee313650faeefbed591c17beaa50
9dd2353c886f60012b4ee4fe8b678d56972dff97
refs/heads/master
2021-01-14T09:08:24.839952
2014-10-09T14:21:01
2014-10-09T14:21:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,165
java
package net.sf.ictalive.dashboard; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.PlatformUI; // This is the superclass of the abstract classes PluggedInDashboardAction and PluggedInWizardDashboardAction, which are // extended to provide the actual plugins for the dashboard. public class PluginDashboardAction<S> extends InternalDashboardAction<S> { private PluggedInDashboardAction<S> pluggedInAction; private String actionId; private boolean promptToSaveResources; // denotes whether the action should prompt to save any modified resources before running. // todo: it would be better to add an abstract boolean shouldPromptToSaveResources() in PluggedInDashboardAction // this way, each plugin needs to specify whether or not it should prompt to save the resources. // However, this means that all dashboard plugins will need to be updated. public PluginDashboardAction( String actionId, boolean promptToSaveResources ) { this.actionId = actionId; this.promptToSaveResources = promptToSaveResources; } public void init(DashboardFacade<S> context) { super.init(context); pluggedInAction = this.context.getPluggedInDashboardActions().get(actionId); if (pluggedInAction == null) System.err.println("No plugin for dashboard action: "+actionId); } public String getProblems() { if (pluggedInAction == null) return "No plugin has been registered for dashboard action:\n\n"+actionId; else if (context.getProject() == null) return "No project has been selected."; else { boolean isAliveProject = false; try { if (context.getProject().getNature("net.sf.ictalive.aliveclipse.projectNature") != null) isAliveProject = true; } catch (CoreException e) { } if (!isAliveProject) return "The selected project \""+context.getProject().getName()+"\" is not an ALIVE project."; else return pluggedInAction.getProblems(context.getState()); } } public void unguardedRun() { if (!promptToSaveResources || PlatformUI.getWorkbench().saveAllEditors(true)) { pluggedInAction.run(context.getState()); context.updateStatus(); } } }
faaafcb45f0a427055bbbad11170082f1aabbf93
bff07407ff3fd9cb397f313b72f6f4935e955311
/Problem_027.java
d15061ccc5afbfdaa098c17326d0b1f8d3eef756
[]
no_license
jwyce/Project-Euler-Problems
e1a08174eff0facfd89828bdfae3607924846efd
9725b3b5e6e29e7fa7bc6ec007586b3c59d167d4
refs/heads/master
2021-09-14T21:07:04.368995
2018-05-19T19:23:46
2018-05-19T19:23:46
96,117,379
1
1
null
null
null
null
UTF-8
Java
false
false
1,025
java
package euler; public class Problem_027 { static int quadraticPrimeProduct() { int product = 0; int mostConsecutivePrimes = 0; for(int a = -999; a < 1000; a++) { for(int b = -1000; b < 1001; b++) { int consecPrimes = consecutivePrimes(a, b); if(mostConsecutivePrimes < consecPrimes) { mostConsecutivePrimes = consecPrimes; product = a * b; // System.out.println(mostConsecutivePrimes + " : " + a + " * " + b + " = " + product); } } } return product; } private static int consecutivePrimes(int a, int b) { int primes = 0, n = 0; boolean isConsecutive = true; while(isConsecutive) { isConsecutive = isPrime((n*n) + (a*n) + b); n++; primes++; } return primes - 1; } private static boolean isPrime(long num) { if (num < 2) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (long i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } }
2ef1aa613dc1bf224574d19a9d2d1a70f3c977ca
6f05f7d5a67b6bb87956a22b988067ec772ba966
/data/train/java/1339ab74260fbde0e692174b48e5c8d7d05f8e67ItemHandler.java
1339ab74260fbde0e692174b48e5c8d7d05f8e67
[ "MIT" ]
permissive
harshp8l/deep-learning-lang-detection
93b6d24a38081597c610ecf9b1f3b92c7d669be5
2a54293181c1c2b1a2b840ddee4d4d80177efb33
refs/heads/master
2020-04-07T18:07:00.697994
2018-11-29T23:21:23
2018-11-29T23:21:23
158,597,498
0
0
MIT
2018-11-21T19:36:42
2018-11-21T19:36:41
null
UTF-8
Java
false
false
4,719
java
package dwo.gameserver.handler; import dwo.gameserver.handler.items.BeastSoulShot; import dwo.gameserver.handler.items.BeastSpice; import dwo.gameserver.handler.items.BeastSpiritShot; import dwo.gameserver.handler.items.BlessedSpiritShot; import dwo.gameserver.handler.items.Book; import dwo.gameserver.handler.items.Calculator; import dwo.gameserver.handler.items.ChangeAttribute; import dwo.gameserver.handler.items.ChristmasTree; import dwo.gameserver.handler.items.CustomItems; import dwo.gameserver.handler.items.Elixir; import dwo.gameserver.handler.items.EnchantAttribute; import dwo.gameserver.handler.items.EnchantScrolls; import dwo.gameserver.handler.items.EnergyStarStone; import dwo.gameserver.handler.items.EventItem; import dwo.gameserver.handler.items.ExtractableItems; import dwo.gameserver.handler.items.FishShots; import dwo.gameserver.handler.items.Harvester; import dwo.gameserver.handler.items.ItemSkills; import dwo.gameserver.handler.items.ItemSkillsTemplate; import dwo.gameserver.handler.items.ManaPotion; import dwo.gameserver.handler.items.Maps; import dwo.gameserver.handler.items.MercTicket; import dwo.gameserver.handler.items.NicknameColor; import dwo.gameserver.handler.items.OrbisBox; import dwo.gameserver.handler.items.PaganKeys; import dwo.gameserver.handler.items.PetFood; import dwo.gameserver.handler.items.QuestStart; import dwo.gameserver.handler.items.Recipes; import dwo.gameserver.handler.items.RollingDice; import dwo.gameserver.handler.items.ScrollOfResurrection; import dwo.gameserver.handler.items.Seed; import dwo.gameserver.handler.items.ShapeShifting; import dwo.gameserver.handler.items.ShowHtml; import dwo.gameserver.handler.items.SoulShots; import dwo.gameserver.handler.items.SpecialXMas; import dwo.gameserver.handler.items.SpiritShot; import dwo.gameserver.handler.items.SummonItems; import dwo.gameserver.handler.items.TeleportBookmark; import dwo.gameserver.model.items.base.L2EtcItem; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; public class ItemHandler implements IHandler<IItemHandler, L2EtcItem> { protected static Logger _log = LogManager.getLogger(ItemHandler.class); private final Map<String, IItemHandler> _handlers; private ItemHandler() { _handlers = new HashMap<>(); registerHandler(new BeastSoulShot()); registerHandler(new BeastSpice()); registerHandler(new BeastSpiritShot()); registerHandler(new BlessedSpiritShot()); registerHandler(new Book()); registerHandler(new Calculator()); registerHandler(new ChristmasTree()); registerHandler(new CustomItems()); registerHandler(new Elixir()); registerHandler(new EnchantAttribute()); registerHandler(new EnchantScrolls()); registerHandler(new EnergyStarStone()); registerHandler(new EventItem()); registerHandler(new ExtractableItems()); registerHandler(new OrbisBox()); registerHandler(new FishShots()); registerHandler(new Harvester()); registerHandler(new ItemSkills()); registerHandler(new ItemSkillsTemplate()); registerHandler(new ManaPotion()); registerHandler(new Maps()); registerHandler(new MercTicket()); registerHandler(new NicknameColor()); registerHandler(new PaganKeys()); registerHandler(new PetFood()); registerHandler(new QuestStart()); registerHandler(new Recipes()); registerHandler(new RollingDice()); registerHandler(new ScrollOfResurrection()); registerHandler(new ShowHtml()); registerHandler(new Seed()); registerHandler(new SoulShots()); registerHandler(new SpecialXMas()); registerHandler(new SpiritShot()); registerHandler(new SummonItems()); registerHandler(new TeleportBookmark()); registerHandler(new ChangeAttribute()); registerHandler(new ShapeShifting()); _log.log(Level.INFO, "Loaded " + size() + " Item Handlers"); } public static ItemHandler getInstance() { return SingletonHolder._instance; } @Override public void registerHandler(IItemHandler handler) { _handlers.put(handler.getClass().getSimpleName(), handler); } @Override public void removeHandler(IItemHandler handler) { synchronized(this) { _handlers.remove(handler.getClass().getSimpleName()); } } /** * Returns the handler of the item * * @param item designating the L2EtcItem * @return IItemHandler */ @Override public IItemHandler getHandler(L2EtcItem item) { if(item == null || item.getHandlerName() == null) { return null; } return _handlers.get(item.getHandlerName()); } @Override public int size() { return _handlers.size(); } private static class SingletonHolder { protected static final ItemHandler _instance = new ItemHandler(); } }
f9f2a7295e175ae6c32ea4453585ca29e6486b84
fff5f70bb00b6fd760b1ea648709abbafdaadcb8
/au.com.redbackconsulting.skillsurvey.api/src/main/java/au/com/redbackconsulting/skillsurvey/api/bean/DapsscoBean.java
771eb6d841add4db65b0561fee964b5e7f062751
[]
no_license
bhardwajsanjay/skillsurvey
f280cec69e7029541232d868e623403c81af67c4
903389805ab3c7e8ae2a07723ff54aa601e5e917
refs/heads/master
2021-01-01T17:47:31.351428
2014-12-27T12:40:23
2014-12-27T12:40:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,382
java
package au.com.redbackconsulting.skillsurvey.api.bean; import java.io.Serializable; import au.com.redbackconsulting.skillsurvey.persistence.model.Dapssco; import com.google.gson.annotations.Expose; public class DapsscoBean implements Serializable { @Expose private Long id; @Expose private Long occupatioId; @Expose private Long levelId; @Expose private String levelName; @Expose private String OccupationName; public String getLevelName() { return levelName; } public void setLevelName(String levelName) { this.levelName = levelName; } public String getOccupationName() { return OccupationName; } public void setOccupationName(String occupationName) { OccupationName = occupationName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getOccupatioId() { return occupatioId; } public void setOccupatioId(Long occupatioId) { this.occupatioId = occupatioId; } public Long getLevelId() { return levelId; } public void setLevelId(Long levelId) { this.levelId = levelId; } public static DapsscoBean get(Dapssco entity) { DapsscoBean bean = new DapsscoBean(); bean.setId(Long.valueOf(entity.getIddepssco())); // bean.setLevelId((entity.g.getLevelId())); return bean; } }
9c3dd561e05aaf5f59a440656ee7ff7791a0ed03
1e1622be9213041b2ac31475f977d37e2ae12bd5
/app/src/main/java/com/example/apnisavari/Model/DataMessage.java
a9fa36ba54ca80c139f96a5405709e58532e982c
[]
no_license
akshayagrg147/User-side-app-Apni-savari-
d48a1b4701ae8a0ea397cb41afd83f22855f03c9
82fabe435df1e35a9167c724f8c706ce8c60436d
refs/heads/master
2023-03-06T23:21:10.955277
2021-02-10T09:33:07
2021-02-10T09:33:07
337,676,143
0
0
null
null
null
null
UTF-8
Java
false
false
579
java
package com.example.apnisavari.Model; import java.util.Map; public class DataMessage { public String to; public Map<String,String> data; public DataMessage() { } public DataMessage(String to, Map<String, String> data) { this.to = to; this.data = data; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
85ab9d6bd2dd4a2eeded788f16345c9da90127f1
b24b8eb02c55d8eba3492218581b0e6a1a00b2ce
/src/test/java/wait/WaitTests.java
04d345965faa366c1bb634ea12b98ce766074e6c
[]
no_license
GiorgosVal/SeleniumWebDriver
bd046359bbf523f0ee7b2a0c872083385be0d9ef
48df11d3b77a895393af8b7a4f816bd647a422c4
refs/heads/master
2023-05-10T12:54:09.550784
2021-08-23T08:47:34
2021-08-23T08:47:34
240,948,655
0
0
null
2023-05-09T18:20:00
2020-02-16T19:05:38
Java
UTF-8
Java
false
false
893
java
package wait; import base.BaseTests; import org.testng.annotations.Test; import pages.DynamicLoadingExample1Page; import pages.DynamicLoadingExample2Page; import static org.testng.Assert.assertEquals; public class WaitTests extends BaseTests { @Test public void testWaitUntilHidden() { DynamicLoadingExample1Page dynamicLoadingExample1Page = homePage.clickDynamicLoad().clickExample1(); dynamicLoadingExample1Page.clickStart(); assertEquals(dynamicLoadingExample1Page.getLoadedText(), "Hello World!", "Loaded text incorrect"); } @Test public void testWaitUntilVisible() { DynamicLoadingExample2Page dynamicLoadingExample2Page = homePage.clickDynamicLoad().clickExample2(); dynamicLoadingExample2Page.clickStart(); assertEquals(dynamicLoadingExample2Page.getLoadedText(),"Hello World!", "Loaded text incorrect"); } }
9ce57d38c8342e4a043328db4e96996ef61260f1
2b4da40435a84e59edbc95529263c8696eac50f4
/HibernateMappingOneToOne/src/main/java/com/mapping/dao/StudentDao.java
59925a1324e760649018fbfc301400f4e62a88a8
[]
no_license
VikasGaikwad/Programs
df5af950eef3a616960317afb02f32ac91c061a6
52f514736dea1f2fee1b63f2b969e9e2733cd83e
refs/heads/master
2021-01-24T12:31:27.999614
2018-03-17T13:31:20
2018-03-17T13:31:20
117,962,490
0
0
null
null
null
null
UTF-8
Java
false
false
481
java
package com.mapping.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.mapping.configure.Confugure; import com.mapping.dto.Student; public class StudentDao { public static void saveStudent(Student stud) { SessionFactory sf=null; sf=Confugure.buildSessionFactory(); Session session=sf.openSession(); Transaction tx=session.beginTransaction(); session.save(stud); tx.commit(); session.close(); } }
45f3762fee6c9b36229508672bb9f2e94131278e
99380e534cf51b9635fafeec91a740e8521e3ed8
/javacenter/src/cn/jcenterhome/web/action/admin/AppAction.java
11d8197bff05cce211411ef2db65659be7a9f829
[]
no_license
khodabakhsh/cxldemo
d483c634e41bb2b6d70d32aff087da6fd6985d3f
9534183fb6837bfa11d5cad98489fdae0db526f1
refs/heads/master
2021-01-22T16:53:27.794334
2013-04-20T01:44:18
2013-04-20T01:44:18
38,994,185
1
0
null
null
null
null
UTF-8
Java
false
false
559
java
package cn.jcenterhome.web.action.admin; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import cn.jcenterhome.web.action.BaseAction; public class AppAction extends BaseAction { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ return mapping.findForward("app"); } }
dfaf055ae5303b0f143a2527864a608cf33667ad
a9b35390a7e677521c03746426b7a49fa139a0a0
/src/com/freedom/test/testlettcode/TestLettCode2.java
b1269be7e14aec6d4b8e7b21ec2a2ae1ed42e94d
[]
no_license
1787098791/testcsv
fed887f5b8518d65d6a8963d404c2152316bacff
bf421372b11a65375633056f6921be76108dadec
refs/heads/master
2021-03-04T02:16:50.129387
2020-03-09T10:13:21
2020-03-09T10:13:21
246,003,672
0
0
null
null
null
null
UTF-8
Java
false
false
3,270
java
package com.freedom.test.testlettcode; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author :wujie * @date :Created in 2019/11/2 14:44 * @description:测试2 * @version: 1.0.0 */ public class TestLettCode2 { //集合[1,2,3]+[2,3,4]输出3,5,7 因为321+432=753 public static void main(String[] args) { /*List<Integer> list1 = Stream.of(1,2,3).collect(Collectors.toList()); List<Integer> list2 = Stream.of(2,3,4).collect(Collectors.toList());*/ //创建链表 ListNode listNode1 = new ListNode(1); ListNode listNode12 = new ListNode(2); ListNode listNode13 = new ListNode(3); listNode1.setNext(listNode12); listNode12.setNext(listNode13); ListNode listNode2 = new ListNode(2); ListNode listNode22 = new ListNode(3); ListNode listNode23 = new ListNode(4); listNode2.setNext(listNode22); listNode22.setNext(listNode23); long s = System.currentTimeMillis(); ListNode test = testListNode(listNode1, listNode2); long e = System.currentTimeMillis(); ListNode myListNode; while(true){ if ((myListNode=test.getNext())!=null){ System.out.println(test.getBody()); test=myListNode; }else { System.out.println(test.getBody()); break; } } } //集合 public static List test(List<Integer> list1,List<Integer> list2){ Integer sum=0; Integer sum2=0; for (int i=list1.size()-1;i>=0;i--){ double pow = Math.pow(10, i); sum+=new Double(list1.get(i)* pow).intValue(); } for (int i=list2.size()-1;i>=0;i--){ double pow = Math.pow(10, i); sum2+=new Double(list2.get(i)* pow).intValue(); } Integer total=sum+sum2; String s = Integer.toString(total); String[] strs = s.split(""); ArrayList<Object> list = new ArrayList<>(); for (int i=strs.length-1;i>=0;i--){ list.add(Integer.parseInt(strs[i])); } return list; } //链表 public static ListNode testListNode(ListNode listNode1,ListNode listNode2){ Integer total=sum(listNode1,0)+ sum(listNode2,0); String[] strs = Integer.toString(total).split(""); ListNode listNodeTag=null; ListNode result=null; for (int i=0;i<strs.length;i++){ ListNode listNode = new ListNode(); listNode.setBody(Integer.parseInt(strs[i])); listNode.setNext(listNodeTag); listNodeTag=listNode; result=listNode; } return result; } //求和->递归 private static Integer sum(ListNode listNode,Integer tag){ if (listNode.getNext()==null){ return new Double(Math.pow(10,tag)).intValue()*listNode.getBody(); } Integer body = listNode.getBody(); ListNode next = listNode.getNext(); int sum = new Double(Math.pow(10, tag)).intValue()*body; tag++; return sum+sum(next,tag); } }
13edf83540a89ed1e4fad829e18611697427c6ea
c76a441a288fb505fc38d7420c9d653bdc48d6c6
/src/com/jswitch/asegurados/controlador/TitularGridController.java
4b0d1065ac165807735032914345c4734e2fc939
[]
no_license
ladriangb/jFASTSJ-base
01e7aa413629a0e9e0ef41432d0c2db150bfe097
7c4efd08d89ad242b16465321a839e833214acbf
refs/heads/master
2020-12-29T01:42:18.028860
2012-01-18T19:44:02
2012-01-18T19:44:02
2,182,134
0
0
null
null
null
null
UTF-8
Java
false
false
5,378
java
package com.jswitch.asegurados.controlador; import com.jswitch.asegurados.vista.TitularDetailFrame; import com.jswitch.base.controlador.General; import com.jswitch.base.controlador.util.DefaultColumnsFilter; import com.jswitch.base.controlador.util.DefaultGridFrameController; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Map; import com.jswitch.base.controlador.logger.LoggerUtil; import com.jswitch.base.controlador.util.DefaultDetailFrameController; import com.jswitch.base.modelo.HibernateUtil; import com.jswitch.base.modelo.util.bean.BeanVO; import com.jswitch.certificados.vista.CertificadoDetailFrame; import com.jswitch.persona.modelo.maestra.Persona; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.hibernate.type.Type; import org.openswing.swing.message.receive.java.ErrorResponse; import org.openswing.swing.message.receive.java.Response; import org.openswing.swing.message.receive.java.ValueObject; import org.openswing.swing.util.server.HibernateUtils; /** * * @author Orlando Becerra */ public class TitularGridController extends DefaultGridFrameController implements ActionListener { private String sql1; private Map filteredColumns; public TitularGridController(String gridFramePath, String detailFramePath, String claseModeloFullPath, String titulo) { super(gridFramePath, detailFramePath, claseModeloFullPath, titulo); DefaultColumnsFilter filter = new DefaultColumnsFilter(Persona.class.getName()); gridFrame.getGridControl().addListFilter("nombreLargo", filter); gridFrame.getGridControl().addListFilter("rif.cedulaCompleta", filter); gridFrame.getGridControl().addListFilter("ranking", filter); } @Override public Response loadData(int action, int startIndex, Map filteredColumns, ArrayList currentSortedColumns, ArrayList currentSortedVersusColumns, Class valueObjectType, Map otherGridParams) { System.out.println(); Session s = null; try { String sql = "SELECT DISTINCT C FROM " + claseModeloFullPath + " C "; // List<TipoPersona> tiposPersonasFiltradas = ((Personas2GridFrame) gridFrame).getTiposPersonaFiltro(); // if (tiposPersonasFiltradas != null && tiposPersonasFiltradas.size() != 0) { // sql += "WHERE T.id IN ( "; // sql += tiposPersonasFiltradas.get(0).getId(); // for (int i = 1; i < tiposPersonasFiltradas.size(); i++) { // TipoPersona tipo = tiposPersonasFiltradas.get(i); // sql += ", " + tipo.getId(); // } // sql += " )"; // } this.sql1 = sql; this.filteredColumns = filteredColumns; SessionFactory sf = HibernateUtil.getSessionFactory(); s = sf.openSession(); Response res = HibernateUtils.getBlockFromQuery( action, startIndex, General.licencia.getBlockSize(), filteredColumns, currentSortedColumns, currentSortedVersusColumns, valueObjectType, sql, new Object[0], new Type[0], "C", sf, s); // Response res = HibernateUtils.getAllFromQuery( // filteredColumns, // currentSortedColumns, // currentSortedVersusColumns, // valueObjectType, // sql, // new Object[0], // new Type[0], // "C", // sf, // s); return res; // SessionFactory sf = HibernateUtil.getSessionFactory(); // Session s = sf.openSession(); // Criteria c = s.createCriteria(Persona.class); // Criteria artistCriteria = c.createCriteria("tiposPersona"); // artistCriteria.add(Restrictions.like("idPropio", "%CON%")); // Response res = HibernateUtils.getAllFromCriteria(filteredColumns, currentSortedColumns, currentSortedVersusColumns, c, s); // s.close(); // return res; // SessionFactory sf = HibernateUtil.getSessionFactory(); // Session s = sf.openSession(); // Criteria c = s.createCriteria(Persona.class); // Criteria artistCriteria = c.createCriteria("tiposPersona"); // artistCriteria.add(Expression.like("idPropio", "%CON%")); // List l = c.list(); // s.close(); // return new VOListResponse(l, false, l.size()); } catch (Exception ex) { LoggerUtil.error(this.getClass(), "loadData", ex); return new ErrorResponse(ex.getMessage()); } finally { s.close(); } } @Override public void doubleClick(int rowNumber, ValueObject persistentObject) { //new PersonasDetailController(null, (BeanVO) persistentObject, null); new TitularDetailFrameController(TitularDetailFrame.class.getName(), null, (BeanVO) persistentObject, false); } @Override public void actionPerformed(ActionEvent e) { } }
a7728b003ad73da6ba3fc337b21e76850c115b09
55fbedbc06c813a717c09c4416dfb0f7f9909955
/Chapt2/src/pack/P117_2_10_13.java
8559a181be4768645f92d27b918ced83207bc4d5
[]
no_license
tklg/CompSci
d8002c94f9abcbbe7d0166f3dca1ed81737bd193
7848d2e43499eb8f6369119a4fb6a5fc18824817
refs/heads/master
2022-10-04T21:23:14.785642
2015-03-06T18:45:51
2015-03-06T18:45:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,105
java
package pack; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Scanner; import java.util.Random; import villa7.Print; public class P117_2_10_13 { private static Scanner sc; public static void main(String args[]) { sc = new Scanner(System.in); Print p = new Print(); DecimalFormat df3 = new DecimalFormat("#.###"); //DecimalFormat df2 = new DecimalFormat("#.##"); NumberFormat df2 = NumberFormat.getCurrencyInstance(); boolean canRun = true; while(canRun) { p.l("\nEnter question number (1 - 4): "); //2.10 - 2.13 (1 - 4) int qNum = sc.nextInt(); p.nl(""); switch(qNum) { case 1: //2.10 p.l("Enter lengths of 3 sides of triangle ABC, separated by spaces: "); double a = Math.abs(sc.nextDouble()), b = Math.abs(sc.nextDouble()), c = Math.abs(sc.nextDouble()); double perim = (a + b + c) / 2; double areaTri = Math.sqrt(perim * (perim - a) * (perim - b) * (perim - c)); p.nl("Area of triangle: " + df3.format(areaTri)); break; case 2: //2.11 p.l("Enter the odometer readings from the beginning of the trip:"); double odoA = sc.nextDouble(); p.l("Enter the odometer reading from the end of the trip: "); double odoB = sc.nextDouble(), totalMiles = odoB - odoA; if (totalMiles < 0) { p.nl("Are you really sure you went negative distance?"); } p.l("Enter the gallons of gas used: "); double gasUsed = sc.nextDouble(); double mpg = gasUsed / totalMiles; p.nl("Miles per gallon: " + mpg); break; case 3: //2.12 double valQ = 0.25, valD = 0.10, valN = 0.05, valP = 0.01; p.l("Enter number of quarters: "); int numQ = sc.nextInt(); p.l("Dimes? "); int numD = sc.nextInt(); p.l("Nickels? "); int numN = sc.nextInt(); p.l("Pennies? "); int numP = sc.nextInt(); double totalVal = ((valQ * numQ) + (valD * numD) + (valN * numN) + (valP * numP)); p.nl("The total value is " + df2.format(totalVal)); break; case 4: //2.13 p.nl("Generating phone number: "); Random rand = new Random(); int firstNum_1 = (int)Math.round(rand.nextDouble() * 6 + 1), secondNum_1 = (int)Math.round(rand.nextDouble() * 7), thirdNum_1 = (int)Math.round(rand.nextDouble() * 7); int fstNum_2 = (int)Math.round(rand.nextDouble() * 742); int fstNum_3 = (int)Math.round(rand.nextDouble() * 9999); if (fstNum_2 < 100) { fstNum_2 += 100; } if (fstNum_3 < 100) { fstNum_3 += 100; } p.nl("(" + firstNum_1 + secondNum_1 + thirdNum_1 + ")-" + fstNum_2 + "-"+ fstNum_3); break; case 0: //End program p.l("Terminating..."); canRun = false; break; default: //user entered a number >4 or <0 p.l("Invalid problem number, please enter a value from 1 - 4.\nEnter 0 to exit.\n"); break; } } } }
25e61129a78f81cd07c770a724d88617f84b80f9
a35e85d57deb194bc59d987182d8eadf6b529e2d
/chap06Lab/src/sec12/exam03_import/mycompany/Car.java
5fc682c852e7465a37d4c20a1c43a12de94397a1
[]
no_license
CaptLWM/javaLab
cac0c5c4178c8d2c2f76dadac28ef5cf4522cc5f
25c28159c43d7151fcf6743ded31cd83de931c3f
refs/heads/master
2023-09-04T10:16:54.905772
2021-09-16T08:13:43
2021-09-16T08:13:43
403,528,609
0
0
null
null
null
null
UTF-8
Java
false
false
555
java
package sec12.exam03_import.mycompany; import sec12.exam03_import.hankook.SnowTire; import sec12.exam03_import.hyundai.Engine;//모든 클래스 가지고 오려면 * 사용 import sec12.exam03_import.kumho.BigWidthTire; //ctrl+shift+o => 한번에 import public class Car { // 필드 //sec12.exam03_import.hyundai.Engine engine = new sec12.exam03_import.hyundai.Engine(); //import 안시켰으면 풀네임 다 적으면 됨 Engine engine = new Engine(); SnowTire tire1 = new SnowTire(); BigWidthTire tire2 = new BigWidthTire(); }
2b000cca4d833588ed0b44f0bf9f214c9faa0ddb
6cb6d33d73464e5b4421a9a07dac48663fab7e5a
/src/main/java/be/devriendt/advent/s2015/Day9TSP.java
3cc7061cd08a1533cf8885c88622421206128d94
[]
no_license
ddevrien/adventcode
3f905490a66ad692661e1cc25eb5ae0b74a62731
08734e9fad5b04139001731fee9025c2ff369770
refs/heads/master
2022-12-23T00:03:45.473137
2022-12-20T17:18:24
2022-12-20T17:18:24
47,456,385
0
0
null
null
null
null
UTF-8
Java
false
false
3,826
java
package be.devriendt.advent.s2015; import java.util.*; /** * Created by Dennis on 24/01/2016. * * 2022: we revisit! */ public class Day9TSP { public static int findShortestRoute(List<String> input) { HashMap<String, Node> nodes = createNodes(input); return nodes.values().stream() .mapToInt(node -> node.findShortestRoute(nodes.size())) .min() .orElseThrow(NoSuchElementException::new); } public static int findLongestRoute(List<String> input) { HashMap<String, Node> nodes = createNodes(input); return nodes.values().stream() .mapToInt(node -> node.findLongestRoute(nodes.size())) .max() .orElseThrow(NoSuchElementException::new); } private static HashMap<String, Node> createNodes(List<String> input) { HashMap<String, Node> nodes = new HashMap<>(); for(String line: input) { String[] parts = line.split(" "); Node from = nodes.computeIfAbsent(parts[0], name -> new Node(name)); Node to = nodes.computeIfAbsent(parts[2], name -> new Node(name)); int distance = Integer.parseInt(parts[4]); from.addRoute(new Route(from, to, distance)); to.addRoute(new Route(to, from, distance)); } return nodes; } private static class Node { String name; List<Route> routes; public Node(String name) { this.name = name; this.routes = new ArrayList<>(); } public void addRoute(Route route) { routes.add(route); } public int findShortestRoute(int nodesToVisit) { return routes.stream() .mapToInt(r -> r.to.findShortestRoute(r.distance, new ArrayList<>(List.of(r.from)), nodesToVisit)) .min() .orElseThrow(NoSuchElementException::new); } private int findShortestRoute(int curWeight, List<Node> visited, int nodesToVisit) { if (visited.size() == nodesToVisit - 1) { return curWeight; } int min = Integer.MAX_VALUE; for(Route r: routes) { if (!visited.contains(r.to)) { visited.add(r.from); min = Math.min(min, r.to.findShortestRoute(curWeight + r.distance, visited, nodesToVisit)); visited.remove(r.from); } } return min; } public int findLongestRoute(int nodesToVisit) { return routes.stream() .mapToInt(r -> r.to.findLongestRoute(r.distance, new ArrayList<>(List.of(r.from)), nodesToVisit)) .max() .orElseThrow(NoSuchElementException::new); } private int findLongestRoute(int curWeight, List<Node> visited, int nodesToVisit) { if (visited.size() == nodesToVisit - 1) { return curWeight; } int max = 0; for(Route r: routes) { if (!visited.contains(r.to)) { visited.add(r.from); max = Math.max(max, r.to.findLongestRoute(curWeight + r.distance, visited, nodesToVisit)); visited.remove(r.from); } } return max; } } private static class Route { Node from; Node to; int distance; public Route(Node from, Node to, int distance) { this.from = from; this.to = to; this.distance = distance; } @Override public String toString() { return from.name + " -> " + to.name + ": " + distance; } } }
685405e8a44aab24ed3f1f496ca942fe77b661ad
054137c25b625896cc2adba4ae724a4096f95223
/src/main/java/com/gsy/controller/rest/IndexController.java
94ecb06721122e30cf1596a1d39ac3977fbef058
[]
no_license
gongshiyun/eshop
c33309e91691f7e5acfa524026821080f5e96733
0da44372b150fdfc71b80b2e3a007f4cc6350474
refs/heads/master
2021-01-15T10:58:03.706557
2017-08-07T18:17:29
2017-08-07T18:17:29
99,605,211
0
0
null
null
null
null
UTF-8
Java
false
false
351
java
package com.gsy.controller.rest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class IndexController { @RequestMapping(value = "/login") public String index() { return "login"; } }
5cb5c94539e06ff01c1331eafd6bcd635a029b05
6f371db12cac3bc7e6e23e8dee182c32ce8de0cb
/Fruit.java
e875b12f7acbd0d4e8afdc86505a7dcc6193a9b7
[]
no_license
GaikarChaitali/new_one
ed563230c68486135b63f80ff5f05c7d3b1ec16b
6d4ed19c74b256c9e13b23ba9d82c94fcc9cbe24
refs/heads/master
2020-04-04T13:38:40.755656
2019-02-12T12:30:09
2019-02-12T12:30:09
155,969,572
0
0
null
null
null
null
UTF-8
Java
false
false
915
java
package StreamAssignment; public class Fruit { public String name,color; public int calories,price; public Fruit(String name,int calories,int price,String color) { this.calories=calories; this.color=color; this.name=name; this.price=price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getCalories() { return calories; } public void setCalories(int calories) { this.calories = calories; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Fruit [name=" + name + ", color=" + color + ", calories=" + calories + ", price=" + price + "]"; } }
ec92e9ff2dcf52d235957fa2a723aea33fafdb53
86e1a91914303dcd495fe4b0c387c7fa774463cd
/app/src/main/java/com/example/nvvuong/service/StartService.java
af42ae107caf9b408e52e4755adf1a9c142c679a
[]
no_license
vanvuong14117/ServiceAndroid
793c4be30dc848af4eb6306f2a290d53446cae3d
4b6213ed36da9220da51324420ba05f316d218d5
refs/heads/master
2020-03-19T07:42:33.404164
2018-06-05T08:04:21
2018-06-05T08:04:21
136,141,978
0
0
null
null
null
null
UTF-8
Java
false
false
1,293
java
package com.example.nvvuong.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.widget.Toast; public class StartService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } //khoi tao 1 lan , chay lai thi ko dung ham nay nua chay tiep ham command duoi @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { //Toast.makeText(this, "onStartCommand", Toast.LENGTH_LONG).show(); //return super.onStartCommand( intent, flags, startId ); // oncreat lai khi bi ngat //stopSelf(); //dung service luon String thangCoder = null; if(intent!= null){ thangCoder = intent.getStringExtra(MainActivity.THANGCODER); } // Toast.makeText(this, "onStartCommand: "+thangCoder, Toast.LENGTH_SHORT).show(); return START_REDELIVER_INTENT; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "onDestroy", Toast.LENGTH_LONG).show(); } }
[ "=" ]
=
7c5e1d50b60ab8dfb5a89d14c9943f263d9afb05
fb1b922cf5e9897dc1bff8ff83e07028ccd45ef3
/java/src/demos/dlineage/dataflow/model/RelationElement.java
2f6bf98679d9ff3ab7f2aa86a7bfb54c24f77893
[]
no_license
sqlparser/gsp_demo
77397646a81306ad3b0f67a54057e9a6ed71c262
6831e3608389745ae9371d28ba289785b1630e96
refs/heads/master
2020-04-10T20:03:16.241846
2019-10-08T08:42:05
2019-10-08T08:42:05
161,255,427
21
15
null
null
null
null
UTF-8
Java
false
false
109
java
package demos.dlineage.dataflow.model; public interface RelationElement<T> { public T getElement(); }
56d66deb336529cc1f4c08d0caf42ce16d62007b
9efa33d09511c488a78164d61580894d33f79f34
/src/main/java/com/my/base/BaseQueryModel.java
66a15bf940b60b19270d68ba32e31b3d97e81892
[]
no_license
whm-project/baseFrame
3b56f648cb8f94486bcf388429645779755c6079
97438a2f91aa40dbb28e08d4bac39a46964fc3fd
refs/heads/master
2023-03-31T17:01:01.202437
2021-04-02T08:02:07
2021-04-02T08:02:07
343,329,960
0
0
null
null
null
null
UTF-8
Java
false
false
1,052
java
package com.my.base; import java.io.Serializable; /** * @author whm * @date 2018/6/8 */ public class BaseQueryModel implements Serializable { /** * 页数 */ private int pageNumber = 0; /** * 每页条数 */ private int pageSize = 10; /** * 排序 */ private String order = ""; /** * 当前用户所属组织机构 */ private String currentOrgCd; public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getCurrentOrgCd() { return currentOrgCd; } public void setCurrentOrgCd(String currentOrgCd) { this.currentOrgCd = currentOrgCd; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } }
e0420263ee45d7168cc6d26942c6c7fb1d5f8997
fe88e6850326cab829870863781bb9b9bf57c2ff
/JAX-WS_1/client/src/ru/javacourse/webservice/Main.java
8b4854a3f07222a2e98bfc363526ddefbc30b89e
[]
no_license
VitaliiMaltsev/JAX-RS-jAX-WS
a729d9917740b89cdb719d9a5aa70a49d0b279fc
ee18e4e43a324727b91175d1d91fefa030c3a7aa
refs/heads/master
2020-03-25T00:01:02.766965
2018-08-01T19:41:16
2018-08-01T19:41:16
143,165,428
0
0
null
null
null
null
UTF-8
Java
false
false
411
java
package ru.javacourse.webservice; /** * Created by Georgy Gobozov on 10.02.2015. */ public class Main { public static void main(String[] args) { SayHelloServiceService service = new SayHelloServiceService(); SayHelloService port = service.getSayHelloServicePort(); String response = port.sayHello("Georgy!"); System.out.println("response = " + response); } }
dcae175b47fcc0e7bf4fbc39d917c26d82bd00e6
92b55033aabbfc89bb9ad84e35d9d2ce37f4ccd4
/ReBuildTree.java
10d58fd99853b7975d89de8d721e288273b1168e
[]
no_license
liusiyu579/Java
2c8c728a1dedd40dbe6964bd9cb61dbaa022bb8e
b549e1cab63c4cc61e737bf692bef11a7939b2c5
refs/heads/master
2020-08-21T15:53:05.288634
2020-03-19T08:39:40
2020-03-19T08:39:40
216,192,738
0
0
null
null
null
null
UTF-8
Java
false
false
1,025
java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class ReBuildTree { public TreeNode buildTree(int[] inorder, int[] postorder) { return reBuildTree(inorder,postorder,0,postorder.length,postorder.length); } public TreeNode reBuildTree(int[] inorder, int[] postorder,int inStart,int postEnd,int postLength) { if(postLength == 0) { return null; } int root = postorder[postEnd-1]; TreeNode node = new TreeNode(root); if(postLength == 1) { return node; } for(int i = 0;i < postLength;i++) { if(root == inorder[inStart+i]) { node.left = reBuildTree(inorder,postorder,inStart,postEnd-postLength+i,i); node.right = reBuildTree(inorder,postorder,inStart+i+1,postEnd-1,postLength-i-1); break; } } return node; } }
61388f6c7a5d3bc604e6a2d46980408acdb8646e
5f8f06170bda6fe5e52aba172715a554c19fa6b5
/Domino/src/domino/IU/Main.java
9f21b9dfc6864340eca4eee1b40a90f301b0294c
[]
no_license
JuanCastroR/Domino
249d53dccb14d3d433252a1b6f2fa527e777ef3c
5fa7133fa86ef2c86fc184d21670665e6502f51a
refs/heads/main
2023-08-26T02:35:59.565004
2021-10-17T10:20:03
2021-10-17T10:20:03
418,090,702
0
0
null
null
null
null
UTF-8
Java
false
false
440
java
/* * 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 domino.IU; import static domino.IU.Domino.inicioPartida; /** * * @author Rosalia */ public class Main { public static void main(String[] args) { inicioPartida(); } }
e160ee1b7eba225b815337dc140744e80a3eba7c
72387693c65b0eb00773a7eb1823b76a0ced059f
/android/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/androidx/legacy/coreui/R.java
fa8eba3659b345b5989f56afe1f8877930a2a072
[ "MIT" ]
permissive
klakshman318/covid-19-info-app
4a475c24010fbeba8dc15243a93f4f2f54aae4b5
44c150d40b2f3b357da849bd387d4a13f99d65e7
refs/heads/master
2023-04-26T17:19:56.964356
2021-05-21T18:58:01
2021-05-21T18:58:01
280,132,139
3
0
MIT
2021-05-21T18:58:02
2020-07-16T11:07:01
Java
UTF-8
Java
false
false
12,395
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.legacy.coreui; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f03002a; public static final int coordinatorLayoutStyle = 0x7f0300a6; public static final int font = 0x7f0300e3; public static final int fontProviderAuthority = 0x7f0300e5; public static final int fontProviderCerts = 0x7f0300e6; public static final int fontProviderFetchStrategy = 0x7f0300e7; public static final int fontProviderFetchTimeout = 0x7f0300e8; public static final int fontProviderPackage = 0x7f0300e9; public static final int fontProviderQuery = 0x7f0300ea; public static final int fontStyle = 0x7f0300eb; public static final int fontVariationSettings = 0x7f0300ec; public static final int fontWeight = 0x7f0300ed; public static final int keylines = 0x7f03011b; public static final int layout_anchor = 0x7f030120; public static final int layout_anchorGravity = 0x7f030121; public static final int layout_behavior = 0x7f030122; public static final int layout_dodgeInsetEdges = 0x7f030125; public static final int layout_insetEdge = 0x7f030126; public static final int layout_keyline = 0x7f030127; public static final int statusBarBackground = 0x7f03019e; public static final int ttcIndex = 0x7f030201; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050077; public static final int notification_icon_bg_color = 0x7f050078; public static final int ripple_material_light = 0x7f050083; public static final int secondary_text_default_material_light = 0x7f050085; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f060053; public static final int compat_button_inset_vertical_material = 0x7f060054; public static final int compat_button_padding_horizontal_material = 0x7f060055; public static final int compat_button_padding_vertical_material = 0x7f060056; public static final int compat_control_corner_material = 0x7f060057; public static final int compat_notification_large_icon_max_height = 0x7f060058; public static final int compat_notification_large_icon_max_width = 0x7f060059; public static final int notification_action_icon_size = 0x7f0600c5; public static final int notification_action_text_size = 0x7f0600c6; public static final int notification_big_circle_margin = 0x7f0600c7; public static final int notification_content_margin_start = 0x7f0600c8; public static final int notification_large_icon_height = 0x7f0600c9; public static final int notification_large_icon_width = 0x7f0600ca; public static final int notification_main_column_padding_top = 0x7f0600cb; public static final int notification_media_narrow_margin = 0x7f0600cc; public static final int notification_right_icon_size = 0x7f0600cd; public static final int notification_right_side_padding_top = 0x7f0600ce; public static final int notification_small_icon_background_padding = 0x7f0600cf; public static final int notification_small_icon_size_as_large = 0x7f0600d0; public static final int notification_subtext_size = 0x7f0600d1; public static final int notification_top_pad = 0x7f0600d2; public static final int notification_top_pad_large_text = 0x7f0600d3; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f07008f; public static final int notification_bg = 0x7f070090; public static final int notification_bg_low = 0x7f070091; public static final int notification_bg_low_normal = 0x7f070092; public static final int notification_bg_low_pressed = 0x7f070093; public static final int notification_bg_normal = 0x7f070094; public static final int notification_bg_normal_pressed = 0x7f070095; public static final int notification_icon_background = 0x7f070096; public static final int notification_template_icon_bg = 0x7f070097; public static final int notification_template_icon_low_bg = 0x7f070098; public static final int notification_tile_bg = 0x7f070099; public static final int notify_panel_notification_icon_bg = 0x7f07009a; } public static final class id { private id() {} public static final int action_container = 0x7f080035; public static final int action_divider = 0x7f080037; public static final int action_image = 0x7f080038; public static final int action_text = 0x7f08003e; public static final int actions = 0x7f08003f; public static final int async = 0x7f080047; public static final int blocking = 0x7f08004a; public static final int bottom = 0x7f08004b; public static final int chronometer = 0x7f08005b; public static final int end = 0x7f080070; public static final int forever = 0x7f080082; public static final int icon = 0x7f08008a; public static final int icon_group = 0x7f08008b; public static final int info = 0x7f08008f; public static final int italic = 0x7f080090; public static final int left = 0x7f080094; public static final int line1 = 0x7f080096; public static final int line3 = 0x7f080097; public static final int none = 0x7f0800a4; public static final int normal = 0x7f0800a5; public static final int notification_background = 0x7f0800a6; public static final int notification_main_column = 0x7f0800a7; public static final int notification_main_column_container = 0x7f0800a8; public static final int right = 0x7f0800b4; public static final int right_icon = 0x7f0800b5; public static final int right_side = 0x7f0800b6; public static final int start = 0x7f0800e3; public static final int tag_transition_group = 0x7f0800ee; public static final int tag_unhandled_key_event_manager = 0x7f0800ef; public static final int tag_unhandled_key_listeners = 0x7f0800f0; public static final int text = 0x7f0800f1; public static final int text2 = 0x7f0800f2; public static final int time = 0x7f0800fa; public static final int title = 0x7f0800fb; public static final int top = 0x7f0800fe; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f090011; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b0031; public static final int notification_action_tombstone = 0x7f0b0032; public static final int notification_template_custom_big = 0x7f0b0039; public static final int notification_template_icon_group = 0x7f0b003a; public static final int notification_template_part_chronometer = 0x7f0b003e; public static final int notification_template_part_time = 0x7f0b003f; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e006d; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f0121; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0122; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0124; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f0127; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f0129; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01db; public static final int Widget_Compat_NotificationActionText = 0x7f0f01dc; public static final int Widget_Support_CoordinatorLayout = 0x7f0f020b; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f03002a }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] CoordinatorLayout = { 0x7f03011b, 0x7f03019e }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f030120, 0x7f030121, 0x7f030122, 0x7f030125, 0x7f030126, 0x7f030127 }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0300e5, 0x7f0300e6, 0x7f0300e7, 0x7f0300e8, 0x7f0300e9, 0x7f0300ea }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300e3, 0x7f0300eb, 0x7f0300ec, 0x7f0300ed, 0x7f030201 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
b6839bf7403ed494da55642a8944de2a1192ad12
94f87406b6b80a3b1654a776fce7d0d80172e7e6
/src/main/java/multiThreads/ProducerConsumer_V2.java
2b1cbaffd95c178b04133505282da36295488117
[]
no_license
EinSamstorch/Study
c7a6e7a15bb78e4b227fda3173e419ff4783ecc1
a1549bb41fee028e20843d05f0ea5e979b8276b9
refs/heads/master
2023-06-26T15:29:17.274800
2021-07-23T06:51:03
2021-07-23T06:51:03
368,532,466
0
0
null
null
null
null
UTF-8
Java
false
false
2,579
java
package multiThreads; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author <a href="mailto:[email protected]">Liqun_Wang</a> * @date: 2021/5/15 10:17 */ class ShareData { private int number = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public void increment() throws Exception { lock.lock(); try { while (number != 0) { //等待,不能生产 condition.await(); } number++; System.out.println(Thread.currentThread().getName() + "\t" + number); condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void decrement() throws Exception { lock.lock(); try { while (number == 0) { //等待,不能消费 condition.await(); } number--; System.out.println(Thread.currentThread().getName() + "\t" + number); condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public class ProducerConsumer_V2{ public static void main(String[] args) { ShareData shareData = new ShareData(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.increment(); } catch (Exception e) { e.printStackTrace(); } } }, "AA").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.decrement(); } catch (Exception e) { e.printStackTrace(); } } }, "BB").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.increment(); } catch (Exception e) { e.printStackTrace(); } } }, "CC").start(); new Thread(()->{ for (int i = 0; i < 5; i++) { try { shareData.decrement(); } catch (Exception e) { e.printStackTrace(); } } }, "DD").start(); } }
bad91b2c4267a15ecd50534b92bb4a9ba84d0a12
03f6f5d5dea61513531ac8624a5312c8b5993979
/Task/TODD/android/src/main/java/by/todd/android/app/Success.java
f4f7758803f50ee18d6909a860616ddf3017220d
[]
no_license
deniotokiari/JMP-2014-Mikhail-Ivanou-Group-2
a757447460497992724adac5bbce4f8ced9b1e16
18fcb6d9acdff44ff7d87b20e83feef1df354261
refs/heads/master
2021-01-14T12:45:23.962013
2015-01-11T15:30:25
2015-01-11T15:30:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
137
java
package by.todd.android.app; /** * Created by sergey on 24.11.2014. */ public interface Success { void success(String content); }
8d0fec4b618dd8933408f18dc91e6e6a14e500c7
867dde84a4d7aa224035a646691cadc3a2ec5676
/Solar/src/model/FuncaoAvaliador.java
fe1c5926486737b0da1c316d0d02d2d39e99a17f
[]
no_license
faelfv/Solarr
cb54ab990a21671be49f67e453cfb885f4ed1e27
4273696536e036073c83c1fe0c374a2a7d44de44
refs/heads/master
2020-12-30T12:10:49.536081
2017-05-16T21:42:10
2017-05-16T21:42:10
91,507,369
0
0
null
null
null
null
UTF-8
Java
false
false
1,404
java
package model; import java.io.Serializable; public class FuncaoAvaliador implements Serializable { private static final long serialVersionUID = 1L; private String login, nome, senha; private int setor; public FuncaoAvaliador() { } public String getLogin(){ return login; } public int getSetor(){ return setor; } public String getNome(){ return nome; } public String getSenha(){ return senha; } public void setLogin(String login){ this.login = login; } public void setSetor(int setor){ this.setor = setor; } public void setNome(String nome){ this.nome = nome; } public void setSenha(String senha){ this.senha = senha; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FuncaoAvaliador other = (FuncaoAvaliador) obj; if (senha == null) { if (other.senha != null) return false; } else if (!senha.equals(other.senha)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (login != other.login) return false; if (setor != other.setor) { return false; } return true; } }
6e25978b21978acd314047dc4e2bb95a852f6230
4831f6defb09339993abc2d974e0dccbddb3adfb
/src/URI018.java
347b76ba5b489e325cb0caa25f4748b01832cfda
[]
no_license
ThaiDelgado/Logica_Programacao_JAVA
05987b4b62386460e9e9a967817ad0cd1df582ea
3fb31e9acfa1ffde10eaf74b7bb67870e86339a8
refs/heads/master
2023-06-27T07:13:03.214669
2021-07-06T20:33:19
2021-07-06T20:33:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,004
java
import java.util.Scanner; public class URI018 { public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int valor = sc.nextInt(); int n100, n50, n20, n10, n5, n1; int r100, r50, r20, r10, r5; n100 = valor / 100; // n100 vai receber o valor da divisão r100 = valor % 100; // r100 vai receber o resto da divisão n50 = r100 / 50; r50 = r100 % 50; n20 = r50 / 20; r20 = r50 % 20; n10 = r20 / 10; r10 = r20 % 10; n5 = r10 / 5; r5 = r10 % 5; n1 = r5 / 1; System.out.println(valor); System.out.println("Cedulas de 100 = " + n100); System.out.println("Cedulas de 50 = " + n50); System.out.println("Cedulas de 20 = " + n20); System.out.println("Cedulas de 10 = " + n10); System.out.println("Cedulas de 5 = " + n5); System.out.println("Cedulas de 1 = " + n1); sc.close(); } }
77a5f34b1a694ce36f410c0672a6d30653009788
c06b386813d8916990e6d51753b5fc03623f4414
/miltiplescreen/app/src/main/java/com/example/android/miltiplescreen/MainActivity.java
42d523ae4013bde950b225e48bd89d91a51d089b
[]
no_license
ManikandanRajamanickam12/Android-App
428c62b82ca280cae053ba61463a33c48cafa791
4d4c9d5c1097644d3ce4cbdf7eef4374acd10f94
refs/heads/main
2023-08-23T17:18:42.312044
2021-10-09T05:59:22
2021-10-09T05:59:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,260
java
package com.example.android.miltiplescreen; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.example.android.miltiplescreen.FamilyActivity; import com.example.android.miltiplescreen.NumberActivity; import com.example.android.miltiplescreen.R; import com.example.android.miltiplescreen.colorActivity; import com.example.android.miltiplescreen.phraseActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void openNumberList(View view){ Intent in = new Intent(this, NumberActivity.class); startActivity(in); } public void openfamilyList(View view){ Intent in = new Intent(this, FamilyActivity.class); startActivity(in); } public void opencolorList(View view){ Intent in = new Intent(this, colorActivity.class); startActivity(in); } public void openphraseList(View view){ Intent in = new Intent(this, phraseActivity.class); startActivity(in); } }
5bd6ebb708302eb9766190baee55123d2d85a74f
17d42506db7331e8ca0b7962d28067078e70bad8
/src/MainPackage/GuideMain.java
b1959058fbabc5e35359494b44b2115e20b6f98b
[]
no_license
velevatanas/GeoGuide
9add6b7f6594b7ed0341c7eb6f70e54a200e0674
a89780e6bf3042ea7167f7e4edec37708a55d980
refs/heads/master
2020-03-17T15:38:58.621329
2018-05-17T07:48:05
2018-05-17T07:48:05
133,714,209
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package MainPackage; import ContinentsPackage.Asia; public class GuideMain { public static void main(String[] args) { Application app = new Application(); app.start(); } }
b8ca250afe36f981637a9236b746cff83e1e54dc
a60578fd7ed02db6ce69db4b7cfb23f5d097b45d
/app/src/main/java/com/briup/pgc/anew/base/impl/VipPager.java
5c78b512d69f6461e93f3a97c9710fbedba14afb
[]
no_license
ainiyibeizi/Demo1
6f1c6a07f45fcadafa716d6051b13bf8e6633b83
a3b518565d4bb36bee4e4578ee6ff270a39633b3
refs/heads/master
2020-03-26T13:03:36.206906
2018-09-05T07:07:35
2018-09-05T07:07:35
144,920,965
0
0
null
null
null
null
UTF-8
Java
false
false
693
java
package com.briup.pgc.anew.base.impl; import android.app.Activity; import android.graphics.Color; import android.view.Gravity; import android.widget.TextView; import com.briup.pgc.anew.base.BasePager; public class VipPager extends BasePager { public VipPager(Activity activity) { super(activity); } @Override public void initData() { //要给帧布局填充对象 TextView view=new TextView(mActivity); view.setText("VIP"); view.setTextColor(Color.RED); view.setTextSize(22); view.setGravity(Gravity.CENTER); flContent.addView(view); //修改页面标题 tv_title.setText("VIP标题"); } }
f6e81a4c1a55551546c3be9bac2e189b964d05eb
138ee8645681022e8493f97047bd072459831696
/src/main/java/com/lazynessmind/horsemodifiers/HorseModifiers.java
dc8e3dc12675092342ad08eb3c36d752be927453
[ "MIT" ]
permissive
naqaden/HorseModifiers-1.12.2
70cc0f13da6e830815bd673d279a8e3b4b054f74
8edea95278f3bc4252c5d9c269dc200c7ee6fd42
refs/heads/master
2020-09-08T16:06:44.642204
2019-11-12T09:43:26
2019-11-12T09:43:26
221,159,912
0
0
MIT
2019-11-12T07:48:41
2019-11-12T07:48:37
null
UTF-8
Java
false
false
1,131
java
package com.lazynessmind.horsemodifiers; import com.lazynessmind.horsemodifiers.configs.Configs; import com.lazynessmind.horsemodifiers.proxy.CommonProxy; import com.lazynessmind.horsemodifiers.tab.Tabs; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Const.MOD_ID, name = Const.NAME, version = Const.VERSION, updateJSON = Const.UPDATE_JSON, guiFactory = Const.GUI_FACTORY) public class HorseModifiers { @Mod.Instance public static HorseModifiers instance; @SidedProxy(clientSide = Const.CLIENT_PROXY, serverSide = Const.COMMON_PROXY) public static CommonProxy common; public static Tabs tabs = new Tabs(); @EventHandler public void preInit(FMLPreInitializationEvent event) { Configs.preInit(); } @EventHandler public void init(FMLInitializationEvent event) { Configs.preInit(); Configs.clientPreInit(); } }
26c37629d805fb903c37015c06f04e2aa7ea444a
0c399254a070fa89bd15ffd4c62552e215dd7751
/cloud-rocksdb-server/src/main/java/cloud/rocksdb/server/state/ShardMasterListener.java
75c69bf42a98672c540e042b21d7b3156bb0ad94
[]
no_license
aronica/cloud-rocksdb
ef4d5d0ec03b000e3ae5f0f3b6816b11710fc1e5
4d69192219709f154ad27063778be495ad759417
refs/heads/master
2021-01-23T11:21:11.790290
2017-10-09T06:28:20
2017-10-09T06:28:20
93,133,299
1
0
null
null
null
null
UTF-8
Java
false
false
204
java
package cloud.rocksdb.server.state; /** * Created by fafu on 2017/6/14. */ public interface ShardMasterListener { public default void becomeMaster() {}; public default void loseMaster() {}; }
2eb4070609ed886357013383ddece2c5c27dfab5
8a98577c5995449677ede2cbe1cc408c324efacc
/Big_Clone_Bench_files_used/bcb_reduced/3/selected/96313.java
f665e58251deb335f5ccb8179cc4dbd8a49a2b58
[ "MIT" ]
permissive
pombredanne/lsh-for-source-code
9363cc0c9a8ddf16550ae4764859fa60186351dd
fac9adfbd98a4d73122a8fc1a0e0cc4f45e9dcd4
refs/heads/master
2020-08-05T02:28:55.370949
2017-10-18T23:57:08
2017-10-18T23:57:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,583
java
package edu.vt.middleware.crypt.signature; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import edu.vt.middleware.crypt.CryptException; import edu.vt.middleware.crypt.digest.DigestAlgorithm; import edu.vt.middleware.crypt.digest.SHA1; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.DSASigner; /** * Implements the DSA signature algorithm. * * @author Middleware Services * @version $Revision: 3 $ */ public class DSASignature extends SignatureAlgorithm { /** Signature algorithm name. */ private static final String ALGORITHM = "DSA"; /** Computes DSA signatures on hashed messages. */ private final DSASigner signer = new DSASigner(); /** * Creates a new DSA signature class that uses a SHA-1 for message digest * computation. This is the conventional DSA signature configuration. */ public DSASignature() { this(new SHA1()); } /** * Creates a new DSA signature class that uses the given digest algorithm for * message digest computation. * * @param d Message digest algorithm. */ public DSASignature(final DigestAlgorithm d) { super(ALGORITHM); digest = d; } /** {@inheritDoc} */ public void setSignKey(final PrivateKey key) { if (!DSAPrivateKey.class.isInstance(key)) { throw new IllegalArgumentException("DSA private key required."); } super.setSignKey(key); } /** {@inheritDoc} */ public void setVerifyKey(final PublicKey key) { if (!DSAPublicKey.class.isInstance(key)) { throw new IllegalArgumentException("DSA public key required."); } super.setVerifyKey(key); } /** {@inheritDoc} */ public void initSign() { if (signKey == null) { throw new IllegalStateException("Sign key must be set prior to initialization."); } final DSAPrivateKey privKey = (DSAPrivateKey) signKey; final DSAParams params = privKey.getParams(); final DSAPrivateKeyParameters bcParams = new DSAPrivateKeyParameters(privKey.getX(), new DSAParameters(params.getP(), params.getQ(), params.getG())); init(true, bcParams); } /** {@inheritDoc} */ public void initVerify() { if (verifyKey == null) { throw new IllegalStateException("Verify key must be set prior to initialization."); } final DSAPublicKey pubKey = (DSAPublicKey) verifyKey; final DSAParams params = pubKey.getParams(); final DSAPublicKeyParameters bcParams = new DSAPublicKeyParameters(pubKey.getY(), new DSAParameters(params.getP(), params.getQ(), params.getG())); init(false, bcParams); } /** {@inheritDoc} */ public byte[] sign(final byte[] data) throws CryptException { final BigInteger[] out = signer.generateSignature(digest.digest(data)); return encode(out[0], out[1]); } /** {@inheritDoc} */ public byte[] sign(final InputStream in) throws CryptException, IOException { final BigInteger[] out = signer.generateSignature(digest.digest(in)); return encode(out[0], out[1]); } /** {@inheritDoc} */ public boolean verify(final byte[] data, final byte[] signature) throws CryptException { final BigInteger[] sig = decode(signature); return signer.verifySignature(digest.digest(data), sig[0], sig[1]); } /** {@inheritDoc} */ public boolean verify(final InputStream in, final byte[] signature) throws CryptException, IOException { final BigInteger[] sig = decode(signature); return signer.verifySignature(digest.digest(in), sig[0], sig[1]); } /** * Initialize the signer. * * @param forSigning Whether to initialize signer for the sign operation. * @param params BC cipher parameters. */ protected void init(final boolean forSigning, final CipherParameters params) { if (forSigning && randomProvider != null) { signer.init(forSigning, new ParametersWithRandom(params, randomProvider)); } else { signer.init(forSigning, params); } } /** * Produces DER-encoded byte array output from the raw DSA signature output * parameters, r and s. * * @param r DSA signature output integer r. * @param s DSA signature output integer s. * * @return DER-encoded concatenation of byte representations of r and s. * * @throws CryptException On cryptographic errors. */ protected byte[] encode(final BigInteger r, final BigInteger s) throws CryptException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERInteger(r)); v.add(new DERInteger(s)); try { new DEROutputStream(out).writeObject(new DERSequence(v)); } catch (IOException e) { throw new CryptException("Error encoding DSA signature.", e); } return out.toByteArray(); } /** * Produces the r,s integer pair of a DSA signature from a DER-encoded byte * representation. * * @param in DER-encoded concatenation of byte representation of r and s. * * @return DSA signature output parameters (r,s). * * @throws CryptException On cryptographic errors. */ protected BigInteger[] decode(final byte[] in) throws CryptException { ASN1Sequence s; try { s = (ASN1Sequence) new ASN1InputStream(in).readObject(); } catch (IOException e) { throw new CryptException("Error decoding DSA signature.", e); } return new BigInteger[] { ((DERInteger) s.getObjectAt(0)).getValue(), ((DERInteger) s.getObjectAt(1)).getValue() }; } }
5b9f497e86e13092b7584c81cc2f7773460fdabe
4a9f3aa3f2b05ff290e159e64e305bc4ffb45e59
/src/prestation/composition/VoyageAvecDP.java
58d193ff798b032e862b24c924627e9764762ae1
[]
no_license
LOOS-A/TP_2_MOCI
a7b35fe9428ae95e0d5b28f2d76693daee85e8a9
d4e204fedc0003e7b1ff74b173dbefe10e660322
refs/heads/master
2020-09-24T19:46:10.508617
2019-12-04T14:13:48
2019-12-04T14:13:48
225,828,960
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package prestation.composition; public class VoyageAvecDP extends Voyage { public VoyageAvecDP(double prix, int nbA, int nbE) { super(prix, nbA, nbE); } @Override public double getPrix() { return super.getPrix(); } }
05f457b3e0a666e7bb6f37dacdf6c12e8cec3c16
90978588f73dae363217683f723f1096356dca9c
/EmployeeDataManagment/src/org/jsp/employeedatamanagement/execution/SoftwareCompany.java
efbb381fd4e31f96485f31bbcc19704a99f81ca5
[]
no_license
amit9473/JavaProject
707fa84d0fe1f47d831aa5cd7f4c5a4de9ec0ffd
7e2111f1cc7bfa17676386b4e6f4ceba3dede8d1
refs/heads/master
2020-07-13T01:55:05.447751
2019-08-28T15:28:23
2019-08-28T15:28:23
204,962,746
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
package org.jsp.employeedatamanagement.execution; //import org.jsp.employeedatamanagement.databaseconnectivity.DatabaseConnectivityPrepared; //import org.jsp.employeedatamanagement.databaseconnectivity.DatabaseConnectivityStatement; public class SoftwareCompany { public static void main(String[] args) { //DatabaseConnectivityStatement.updateUpdate(); Execute e = new Execute(); e.start(); /* DatabaseExecute databaseExecute = new DatabaseExecute(); databaseExecute.run(); */ } }
11744325a0556adfc90e10ea020c2b2c9ceec973
cb9992fd8a8005056a67c783aa46086c8e55290f
/hudi-common/src/test/java/org/apache/hudi/common/util/hash/TestHashID.java
3bf316cc4c18af3a657a8749368a51b6aa3433c9
[ "CC0-1.0", "MIT", "JSON", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
apache/hudi
cb3f365f40570357777e9d6e83b93c554f50e707
0e50d7586a7719eab870c8d83e3566bb549d64b6
refs/heads/master
2023-09-02T14:55:11.040855
2023-09-02T11:06:37
2023-09-02T11:06:37
76,474,200
3,615
1,833
Apache-2.0
2023-09-14T19:03:11
2016-12-14T15:53:41
Java
UTF-8
Java
false
false
4,829
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hudi.common.util.hash; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import javax.xml.bind.DatatypeConverter; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests {@link HashID}. */ public class TestHashID { /** * Test HashID of all sizes for ByteArray type input message. */ @ParameterizedTest @EnumSource(HashID.Size.class) public void testHashForByteInput(HashID.Size size) { final int count = 8; Random random = new Random(); for (int i = 0; i < count; i++) { final String message = random.ints(50, 120) .filter(j -> (j <= 57 || j >= 65) && (j <= 90 || j >= 97)) .limit((32 + (i * 4))) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); final byte[] originalData = message.getBytes(StandardCharsets.UTF_8); final byte[] hashBytes = HashID.hash(originalData, size); assertEquals(hashBytes.length, size.byteSize()); } } /** * Test HashID of all sizes for String type input message. */ @ParameterizedTest @EnumSource(HashID.Size.class) public void testHashForStringInput(HashID.Size size) { final int count = 8; Random random = new Random(); for (int i = 0; i < count; i++) { final String message = random.ints(50, 120) .filter(j -> (j <= 57 || j >= 65) && (j <= 90 || j >= 97)) .limit((32 + (i * 4))) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); final byte[] hashBytes = HashID.hash(message, size); assertEquals(hashBytes.length, size.byteSize()); } } /** * Test expected hash values for all bit sizes. */ @Test public void testHashValues() { Map<HashID.Size, Map<String, String>> expectedValuesMap = new HashMap<HashID.Size, Map<String, String>>(); Map<String, String> hash32ExpectedValues = new HashMap<String, String>() { { put("Hudi", "FB6A3F92"); put("Data lake", "99913A4D"); put("Data Lake", "6F7DAD6A"); put("Col1", "B4393B9A"); put("A", "CDD946CE"); put("2021/10/28/", "BBD4FDB2"); } }; expectedValuesMap.put(HashID.Size.BITS_32, hash32ExpectedValues); Map<String, String> hash64ExpectedValues = new HashMap<String, String>() { { put("Hudi", "F7727B9A28379071"); put("Data lake", "52BC72D592EBCAE5"); put("Data Lake", "5ED19AF9FD746E3E"); put("Col1", "22FB1DD2F4784D31"); put("A", "EBF88350484B5AA7"); put("2021/10/28/", "2A9399AF6E7C8B12"); } }; expectedValuesMap.put(HashID.Size.BITS_128, hash64ExpectedValues); Map<String, String> hash128ExpectedValues = new HashMap<String, String>() { { put("Hudi", "09DAB749F255311C1C9EF6DD7B790170"); put("Data lake", "7F2FC1EA445FC81F67CAA25EC9089C08"); put("Data Lake", "9D2CEF0D61B02848C528A070ED75C570"); put("Col1", "EC0FFE21E704DE2A580661C59A81D453"); put("A", "7FC56270E7A70FA81A5935B72EACBE29"); put("2021/10/28/", "1BAE8F04F44CB7ACF2458EF5219742DC"); } }; expectedValuesMap.put(HashID.Size.BITS_128, hash128ExpectedValues); for (Map.Entry<HashID.Size, Map<String, String>> allSizeEntries : expectedValuesMap.entrySet()) { for (Map.Entry<String, String> sizeEntry : allSizeEntries.getValue().entrySet()) { final byte[] actualHashBytes = HashID.hash(sizeEntry.getKey(), allSizeEntries.getKey()); final byte[] expectedHashBytes = DatatypeConverter.parseHexBinary(sizeEntry.getValue()); assertTrue(Arrays.equals(expectedHashBytes, actualHashBytes)); } } } }
add21153b7bc55b568c9be6ecd80514a54d0efa2
bf2966abae57885c29e70852243a22abc8ba8eb0
/aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/DescribeEventTypesResult.java
6baae81dafd0e891f284429023f6d8c675e540ca
[ "Apache-2.0" ]
permissive
kmbotts/aws-sdk-java
ae20b3244131d52b9687eb026b9c620da8b49935
388f6427e00fb1c2f211abda5bad3a75d29eef62
refs/heads/master
2021-12-23T14:39:26.369661
2021-07-26T20:09:07
2021-07-26T20:09:07
246,296,939
0
0
Apache-2.0
2020-03-10T12:37:34
2020-03-10T12:37:33
null
UTF-8
Java
false
false
12,454
java
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.health.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/health-2016-08-04/DescribeEventTypes" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeEventTypesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, <code>EC2</code>, * <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the format * <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * </p> */ private java.util.List<EventType> eventTypes; /** * <p> * If the results of a search are large, only a portion of the results are returned, and a <code>nextToken</code> * pagination token is returned in the response. To retrieve the next batch of results, reissue the search request * and include the returned token. When all results have been returned, the response does not contain a pagination * token value. * </p> */ private String nextToken; /** * <p> * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, <code>EC2</code>, * <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the format * <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * </p> * * @return A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, * <code>EC2</code>, <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the * format <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, * <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). */ public java.util.List<EventType> getEventTypes() { return eventTypes; } /** * <p> * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, <code>EC2</code>, * <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the format * <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * </p> * * @param eventTypes * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, * <code>EC2</code>, <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the * format <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, * <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). */ public void setEventTypes(java.util.Collection<EventType> eventTypes) { if (eventTypes == null) { this.eventTypes = null; return; } this.eventTypes = new java.util.ArrayList<EventType>(eventTypes); } /** * <p> * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, <code>EC2</code>, * <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the format * <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setEventTypes(java.util.Collection)} or {@link #withEventTypes(java.util.Collection)} if you want to * override the existing values. * </p> * * @param eventTypes * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, * <code>EC2</code>, <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the * format <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, * <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeEventTypesResult withEventTypes(EventType... eventTypes) { if (this.eventTypes == null) { setEventTypes(new java.util.ArrayList<EventType>(eventTypes.length)); } for (EventType ele : eventTypes) { this.eventTypes.add(ele); } return this; } /** * <p> * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, <code>EC2</code>, * <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the format * <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * </p> * * @param eventTypes * A list of event types that match the filter criteria. Event types have a category (<code>issue</code>, * <code>accountNotification</code>, or <code>scheduledChange</code>), a service (for example, * <code>EC2</code>, <code>RDS</code>, <code>DATAPIPELINE</code>, <code>BILLING</code>), and a code (in the * format <code>AWS_<i>SERVICE</i>_<i>DESCRIPTION</i> </code>; for example, * <code>AWS_EC2_SYSTEM_MAINTENANCE_EVENT</code>). * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeEventTypesResult withEventTypes(java.util.Collection<EventType> eventTypes) { setEventTypes(eventTypes); return this; } /** * <p> * If the results of a search are large, only a portion of the results are returned, and a <code>nextToken</code> * pagination token is returned in the response. To retrieve the next batch of results, reissue the search request * and include the returned token. When all results have been returned, the response does not contain a pagination * token value. * </p> * * @param nextToken * If the results of a search are large, only a portion of the results are returned, and a * <code>nextToken</code> pagination token is returned in the response. To retrieve the next batch of * results, reissue the search request and include the returned token. When all results have been returned, * the response does not contain a pagination token value. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * If the results of a search are large, only a portion of the results are returned, and a <code>nextToken</code> * pagination token is returned in the response. To retrieve the next batch of results, reissue the search request * and include the returned token. When all results have been returned, the response does not contain a pagination * token value. * </p> * * @return If the results of a search are large, only a portion of the results are returned, and a * <code>nextToken</code> pagination token is returned in the response. To retrieve the next batch of * results, reissue the search request and include the returned token. When all results have been returned, * the response does not contain a pagination token value. */ public String getNextToken() { return this.nextToken; } /** * <p> * If the results of a search are large, only a portion of the results are returned, and a <code>nextToken</code> * pagination token is returned in the response. To retrieve the next batch of results, reissue the search request * and include the returned token. When all results have been returned, the response does not contain a pagination * token value. * </p> * * @param nextToken * If the results of a search are large, only a portion of the results are returned, and a * <code>nextToken</code> pagination token is returned in the response. To retrieve the next batch of * results, reissue the search request and include the returned token. When all results have been returned, * the response does not contain a pagination token value. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeEventTypesResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEventTypes() != null) sb.append("EventTypes: ").append(getEventTypes()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeEventTypesResult == false) return false; DescribeEventTypesResult other = (DescribeEventTypesResult) obj; if (other.getEventTypes() == null ^ this.getEventTypes() == null) return false; if (other.getEventTypes() != null && other.getEventTypes().equals(this.getEventTypes()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEventTypes() == null) ? 0 : getEventTypes().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public DescribeEventTypesResult clone() { try { return (DescribeEventTypesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
fc6ef1de3bf105572e6104ab8295efcba9104da2
3b0ffacd22ebd56698be46d4c0d22053377be050
/src/75.颜色分类.java
211b4fbb99cdb5a1e03ef51cd2f631e5a4f54658
[]
no_license
kimehwa/leetcode
a585db4bfa726c6e600e5abb7a6f44c6ad5dd522
ad34f85c1948c585bcaeb95e13146e495a768423
refs/heads/master
2023-01-31T22:33:03.459979
2020-12-20T04:41:00
2020-12-20T04:41:00
255,772,312
0
0
null
null
null
null
UTF-8
Java
false
false
801
java
/* * @lc app=leetcode.cn id=75 lang=java * * [75] 颜色分类 */ // @lc code=start class Solution { public void sortColors(int[] nums) { // 这个题就是荷兰国旗问题 哪里又有问题了 if (nums == null || nums.length < 2) return; int left = -1, right = nums.length, i = 0; while (i < right) {//这里出了问题,左一定跟右碰不到啊不是left<right if (nums[i]== 2) { swap(nums, i, --right); } else if (nums[i] == 0) { swap(nums, i++, ++left); } else { i++; } } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } // @lc code=end
737696bdee7c94eee76d866e1e511f7ed4f29ace
5c7717f9abbffbadd5450d4127cec3ce423da51e
/app/src/main/java/ua/com/vendetta8247/f1news/ArticleParser.java
8691ca3dfab226d7d8c09614400f31c19cb5bd43
[]
no_license
Vendetta8247/F1News
822dabd301b1d2cc05269ee7adf7a4833d43c637
3226521aa9c4905cefb3a32203c44a07d3bfead5
refs/heads/master
2021-01-22T02:21:03.778578
2017-05-25T01:52:58
2017-05-25T01:52:58
92,353,674
0
0
null
null
null
null
UTF-8
Java
false
false
14,194
java
package ua.com.vendetta8247.f1news; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Entities; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Created by Y500 on 26.04.2015. */ public class ArticleParser { String articleUrl; String articleName; TextView textView; TextView deleteTextView; Context context; String siteName; String innerHtml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; public ArticleParser(String articleName, String articleUrl, TextView textView, TextView deleteTextView , Context context) { this.articleName = articleName; this.articleUrl = articleUrl; this.textView = textView; this.context = context; this.deleteTextView = deleteTextView; } public ArticleParser(String articleName, String articleUrl, String siteName, Context context) { this.articleName = articleName; this.articleUrl = articleUrl; this.context = context; this.siteName = siteName; } public ArticleParser(NewCard card, String siteName) { this.articleName = card.header; this.articleUrl = card.articleLink; this.context = ContextGetter.getAppContext(); this.siteName = siteName; } public void start() { System.out.println("SITENAME " + siteName); if(siteName == "f1news") new AsyncF1Parser().execute(); else if(siteName == "formulanews") new AsyncFormulaNewsParser().execute(); else if(siteName == "euronews") { new AsyncEuronewsParser().execute(); System.out.println("Euronews parser called"); } else if(siteName == "planetf1") { new AsyncPlanetf1Parser().execute(); System.out.println("PlanetF1 parser called"); } else if(siteName == "crash") { new AsyncCrashParser().execute(); System.out.println("Crash parser called"); } } class AsyncCrashParser extends AsyncTask<Void, Void, Void> { String tmp = ""; @Override protected Void doInBackground(Void... params) { try { System.out.println("Crash article URL = " + articleUrl); Document doc = Jsoup.connect(articleUrl).get(); Document.OutputSettings settings = doc.outputSettings(); settings.prettyPrint(true); settings.escapeMode(Entities.EscapeMode.extended); settings.charset("ASCII"); tmp += "<h2>" + articleName + "</h2>"; tmp += "<br>"; Elements toRemove = doc.select("img"); toRemove.remove(); toRemove = doc.select("iframe"); toRemove.remove(); Element articleText = doc.getElementById("art-text"); tmp += articleText.html(); innerHtml = tmp; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { String filename = context.getFilesDir() + "/Crash.net/" + (articleName); System.out.println(filename); File f = new File(context.getFilesDir() + "/Crash.net"); if(!f.exists() || !f.isDirectory()) { System.out.println(f + " не существует"); f.mkdir(); } FileOutputStream outputStream; try { File file = new File(filename); outputStream = new FileOutputStream(file); outputStream.write(innerHtml.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } class AsyncPlanetf1Parser extends AsyncTask<Void, Void, Void> { String tmp = ""; @Override protected Void doInBackground(Void... params) { try { System.out.println("PlanetF1 article URL = " + articleUrl); Document doc = Jsoup.connect(articleUrl).get(); Document.OutputSettings settings = doc.outputSettings(); settings.prettyPrint(true); settings.escapeMode(Entities.EscapeMode.extended); settings.charset("ASCII"); tmp += "<h2>" + articleName + "</h2>"; tmp += "<br>"; Elements toRemove = doc.select("img"); toRemove.remove(); toRemove = doc.select("iframe"); toRemove.remove(); Element articleText = doc.getElementsByClass("article__body").first(); tmp += articleText.html(); innerHtml = tmp; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { String filename = context.getFilesDir() + "/PlanetF1.com/" + (articleName); System.out.println(filename); File f = new File(context.getFilesDir() + "/PlanetF1.com"); if(!f.exists() || !f.isDirectory()) { System.out.println(f + " не существует"); f.mkdir(); } FileOutputStream outputStream; try { File file = new File(filename); outputStream = new FileOutputStream(file); outputStream.write(innerHtml.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } class AsyncEuronewsParser extends AsyncTask<Void, Void, Void> { String tmp = ""; @Override protected Void doInBackground(Void... params) { try { Document doc = Jsoup.connect(articleUrl).get(); Document.OutputSettings settings = doc.outputSettings(); settings.prettyPrint(true); settings.escapeMode(Entities.EscapeMode.extended); settings.charset("ASCII"); tmp += "<h2>" + articleName + "</h2>"; tmp += "<br>"; Elements toRemove = doc.select("img"); toRemove.remove(); toRemove = doc.select("iframe"); toRemove.remove(); Element articleText = doc.getElementById("articleTranscript"); tmp+=articleText.text(); innerHtml = tmp; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { String filename = context.getFilesDir() + "/Euronews.com/" + (articleName); System.out.println(filename); File f = new File(context.getFilesDir() + "/Euronews.com"); if(!f.exists() || !f.isDirectory()) { System.out.println(f + " не существует"); f.mkdir(); } //String filename = "/storage/emulated/0/F1News/" + TextHelper.toTranslit(articleName) + ".html"; FileOutputStream outputStream; try { File file = new File(filename); outputStream = new FileOutputStream(file); outputStream.write(innerHtml.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } class AsyncFormulaNewsParser extends AsyncTask<Void, Void, Void> { String tmp = ""; @Override protected Void doInBackground(Void... params) { try { Document doc = Jsoup.connect(articleUrl).get(); Document.OutputSettings settings = doc.outputSettings(); settings.prettyPrint(true); settings.escapeMode(Entities.EscapeMode.extended); settings.charset("ASCII"); tmp += "<h2>" + articleName + "</h2>"; tmp += "<br>"; Elements toRemove = doc.select("img"); toRemove.remove(); toRemove = doc.select("iframe"); toRemove.remove(); Elements collection = doc.select("div.block.article"); for(Element el : collection) { Elements paragraphs = el.getElementsByTag("p"); for(Element element:paragraphs) { if(!element.className().equals("new-data")) { Log.i("", element.className()); tmp += element.html(); tmp += "<br/><br/>"; } } } innerHtml = tmp; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { String filename = context.getFilesDir() + "/Formula-News.com/" + (articleName); System.out.println(filename); File f = new File(context.getFilesDir() + "/Formula-News.com"); if(!f.exists() || !f.isDirectory()) System.out.println(f + " не существует"); f.mkdir(); //String filename = "/storage/emulated/0/F1News/" + TextHelper.toTranslit(articleName) + ".html"; FileOutputStream outputStream; try { File file = new File(filename); outputStream = new FileOutputStream(file); outputStream.write(innerHtml.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } class AsyncF1Parser extends AsyncTask<Void, Void, Void> { String tmp = ""; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { try { Document doc = Jsoup.connect(articleUrl).get(); Document.OutputSettings settings = doc.outputSettings(); settings.prettyPrint(true); settings.escapeMode(Entities.EscapeMode.extended); settings.charset("ASCII"); try { if (articleUrl.contains("gallery")) { innerHtml = new String(innerHtml + "<br><br>Загрузка изображений отключена. <a href = \"" + articleUrl + "\"> Посмотреть галерею на сайте </a>"); } else { Elements toRemove = doc.select("img"); toRemove.remove(); toRemove = doc.select("iframe"); toRemove.remove(); for (Element link : doc.select("a")) { if (!link.attr("href").toLowerCase().startsWith("http")) { link.attr("href", "http://www.f1news.ru" + link.attr("href")); } } Elements elements = doc.getElementsByClass("post_body").first().getElementsByTag("p"); tmp += "<h2>" + articleName + "</h2>"; for (Element element : elements) { tmp += element.html(); tmp += "<br><br>"; } innerHtml = tmp; innerHtml += "<a href = \"" + articleUrl + "\">Посмотреть статью на сайте</a>"; } } catch (NullPointerException ex) { cancel(true); } //tmp = elements.html(); } catch (IOException e) { e.printStackTrace(); } return null; } protected void onPostExecute(Void params) { if(textView != null) { textView.setText("Скачано"); textView.setEnabled(false); textView.setBackgroundColor(0xFFEEEEEE); } //else //Toast.makeText(context,"Скачано", Toast.LENGTH_SHORT).show(); if(deleteTextView != null) { deleteTextView.setEnabled(true); deleteTextView.setBackgroundColor(0xFFFFFFFF); } String filename = context.getFilesDir() + "/F1News.ru/" + (articleName); File f = new File(context.getFilesDir() + "/F1News.ru"); if(!f.exists() || !f.isDirectory()) f.mkdir(); //String filename = "/storage/emulated/0/F1News/" + TextHelper.toTranslit(articleName) + ".html"; FileOutputStream outputStream; try { File file = new File(filename); outputStream = new FileOutputStream(file); outputStream.write(innerHtml.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } }
17f3d3ccf3a59630bb71e5236ddffa53853593b2
6a67de9df3338bf00081d06a8af3a901b33c03a4
/KoguryoEmpire/src/main/java/com/km/service/GuildAttackPhotoServiceImpl.java
9d75cdb9b440fa382d52101880ef1fd687a89b7b
[]
no_license
hwanam1111/Spring_KoguryoEmpire
8b1f1d07e3387e48fb68a12f73d21f1497b8cd1a
a78c95cf3925d40a1fc9ce0b14b0bae2dcd96040
refs/heads/master
2020-03-08T08:18:16.546357
2018-08-20T07:09:11
2018-08-20T07:09:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
291
java
package com.km.service; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.km.dao.GuildAttackPhotoDao; @Service public class GuildAttackPhotoServiceImpl implements GuildAttackPhotoService { @Inject private GuildAttackPhotoDao dao; }
0723209a6dc4258ea3b6aa678a325513d396cce2
2df1e437ed420f7062c2cfa8a7780f8309f3ba04
/src/main/java/com/github/manolo8/darkbot/config/actions/conditions/EqualCondition.java
de1f90ae2a104123d398188f60ef137aca204cf7
[]
no_license
dm94/DarkBot
61614f18bc58811c136fc8f0a8e8db5f73bfc6ed
d0300bc5f7ddc39a3e7581f62936a8b54a3621b7
refs/heads/master
2023-08-07T20:48:46.449129
2023-07-30T17:25:44
2023-07-30T17:25:44
187,385,483
0
0
null
2019-05-18T17:17:11
2019-05-18T17:17:11
null
UTF-8
Java
false
false
2,501
java
package com.github.manolo8.darkbot.config.actions.conditions; import com.github.manolo8.darkbot.Main; import com.github.manolo8.darkbot.config.actions.Condition; import com.github.manolo8.darkbot.config.actions.Parser; import com.github.manolo8.darkbot.config.actions.SyntaxException; import com.github.manolo8.darkbot.config.actions.Value; import com.github.manolo8.darkbot.config.actions.ValueData; import com.github.manolo8.darkbot.config.actions.parser.ParseResult; import com.github.manolo8.darkbot.config.actions.parser.ParseUtil; import com.github.manolo8.darkbot.config.actions.parser.ValueParser; import com.github.manolo8.darkbot.utils.ReflectionUtils; import org.jetbrains.annotations.NotNull; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @ValueData(name = "equal", description = "Returns true if both parameters are the same", example = "equal(a, b)") public class EqualCondition implements Condition, Parser { private Boolean isComparable; private Value<?> a, b; @Override public @NotNull Result get(Main main) { Object objA = Value.get(a, main), objB = Value.get(b, main); if (objA == null || objB == null) return Result.ABSTAIN; if (isComparable == null) isComparable = isComparable(objA, objB); if (isComparable) //noinspection unchecked return Result.fromBoolean(((Comparable<Object>) objA).compareTo(objB) == 0); return Result.fromBoolean(objA.equals(objB)); } @Override public String toString() { return "equal(" + a + ", " + b + ")"; } private boolean isComparable(Object a, Object b) { if (!(a instanceof Comparable)) return false; Type t = ReflectionUtils.findGenericParameters(a.getClass(), Comparable.class)[0]; if (t instanceof Class) return ((Class<?>) t).isInstance(b); if (t instanceof ParameterizedType) { Type raw = ((ParameterizedType) t).getRawType(); return raw instanceof Class && ((Class<?>) raw).isInstance(b); } return false; } @Override public String parse(String str) throws SyntaxException { ParseResult<?> prA = ValueParser.parse(str); a = prA.value; str = ParseUtil.separate(prA.leftover.trim(), getClass(), ","); ParseResult<?> prB = ValueParser.parse(str, prA.type); b = prB.value; isComparable = null; return ParseUtil.separate(prB.leftover.trim(), getClass(), ")"); } }
6d9bff436a9808969fed206204297375ba447c95
5b6a9d81075109421d99b8df2fa2cd6c2a6447b6
/ProjectPersistance/src/main/java/src/entities/StateMe.java
c73fa0fcc8a2eb2b70020a5df84588993f76a387
[]
no_license
amaanusa/WSPersistance
348bc332fc3aa90eae414a712a0c601091f7a292
48f94489bfe330971a1625c3802c7e086ceb5df0
refs/heads/master
2021-01-20T04:32:37.926337
2015-09-11T18:52:46
2015-09-11T18:52:46
42,315,783
0
0
null
null
null
null
UTF-8
Java
false
false
21,253
java
/* * 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 src.entities; import java.io.Serializable; import java.math.BigInteger; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author imranadmin */ @Entity @Table(name = "state_me") @XmlRootElement @NamedQueries({ @NamedQuery(name = "StateMe.findAll", query = "SELECT s FROM StateMe s"), @NamedQuery(name = "StateMe.findByCompanyName", query = "SELECT s FROM StateMe s WHERE s.companyName = :companyName"), @NamedQuery(name = "StateMe.findByMailingAddress", query = "SELECT s FROM StateMe s WHERE s.mailingAddress = :mailingAddress"), @NamedQuery(name = "StateMe.findByCity", query = "SELECT s FROM StateMe s WHERE s.city = :city"), @NamedQuery(name = "StateMe.findByState", query = "SELECT s FROM StateMe s WHERE s.state = :state"), @NamedQuery(name = "StateMe.findByZipCode", query = "SELECT s FROM StateMe s WHERE s.zipCode = :zipCode"), @NamedQuery(name = "StateMe.findByMailingCarrierRoute", query = "SELECT s FROM StateMe s WHERE s.mailingCarrierRoute = :mailingCarrierRoute"), @NamedQuery(name = "StateMe.findByMailingDeliveryPointBarCode", query = "SELECT s FROM StateMe s WHERE s.mailingDeliveryPointBarCode = :mailingDeliveryPointBarCode"), @NamedQuery(name = "StateMe.findByStreetAddress", query = "SELECT s FROM StateMe s WHERE s.streetAddress = :streetAddress"), @NamedQuery(name = "StateMe.findByStreetAddressCity", query = "SELECT s FROM StateMe s WHERE s.streetAddressCity = :streetAddressCity"), @NamedQuery(name = "StateMe.findByStreetAddressState", query = "SELECT s FROM StateMe s WHERE s.streetAddressState = :streetAddressState"), @NamedQuery(name = "StateMe.findByStreetAddressZip", query = "SELECT s FROM StateMe s WHERE s.streetAddressZip = :streetAddressZip"), @NamedQuery(name = "StateMe.findByStreetAddressDeliveryPointBarCode", query = "SELECT s FROM StateMe s WHERE s.streetAddressDeliveryPointBarCode = :streetAddressDeliveryPointBarCode"), @NamedQuery(name = "StateMe.findByStreetAddressCarrierRoute", query = "SELECT s FROM StateMe s WHERE s.streetAddressCarrierRoute = :streetAddressCarrierRoute"), @NamedQuery(name = "StateMe.findByCounty", query = "SELECT s FROM StateMe s WHERE s.county = :county"), @NamedQuery(name = "StateMe.findByPhoneNumber", query = "SELECT s FROM StateMe s WHERE s.phoneNumber = :phoneNumber"), @NamedQuery(name = "StateMe.findByFaxNumber", query = "SELECT s FROM StateMe s WHERE s.faxNumber = :faxNumber"), @NamedQuery(name = "StateMe.findByWebAddress", query = "SELECT s FROM StateMe s WHERE s.webAddress = :webAddress"), @NamedQuery(name = "StateMe.findByLastName", query = "SELECT s FROM StateMe s WHERE s.lastName = :lastName"), @NamedQuery(name = "StateMe.findByFirstName", query = "SELECT s FROM StateMe s WHERE s.firstName = :firstName"), @NamedQuery(name = "StateMe.findByContactTitle", query = "SELECT s FROM StateMe s WHERE s.contactTitle = :contactTitle"), @NamedQuery(name = "StateMe.findByContactGender", query = "SELECT s FROM StateMe s WHERE s.contactGender = :contactGender"), @NamedQuery(name = "StateMe.findByActualEmployeeSize", query = "SELECT s FROM StateMe s WHERE s.actualEmployeeSize = :actualEmployeeSize"), @NamedQuery(name = "StateMe.findByEmployeeSizeRange", query = "SELECT s FROM StateMe s WHERE s.employeeSizeRange = :employeeSizeRange"), @NamedQuery(name = "StateMe.findByActualSalesVolume", query = "SELECT s FROM StateMe s WHERE s.actualSalesVolume = :actualSalesVolume"), @NamedQuery(name = "StateMe.findBySalesVolumeRange", query = "SELECT s FROM StateMe s WHERE s.salesVolumeRange = :salesVolumeRange"), @NamedQuery(name = "StateMe.findByPrimarySic", query = "SELECT s FROM StateMe s WHERE s.primarySic = :primarySic"), @NamedQuery(name = "StateMe.findByPrimarySicDescription", query = "SELECT s FROM StateMe s WHERE s.primarySicDescription = :primarySicDescription"), @NamedQuery(name = "StateMe.findBySecondarySic1", query = "SELECT s FROM StateMe s WHERE s.secondarySic1 = :secondarySic1"), @NamedQuery(name = "StateMe.findBySecondarySicDescription1", query = "SELECT s FROM StateMe s WHERE s.secondarySicDescription1 = :secondarySicDescription1"), @NamedQuery(name = "StateMe.findBySecondarySic2", query = "SELECT s FROM StateMe s WHERE s.secondarySic2 = :secondarySic2"), @NamedQuery(name = "StateMe.findBySecondarySicDescription2", query = "SELECT s FROM StateMe s WHERE s.secondarySicDescription2 = :secondarySicDescription2"), @NamedQuery(name = "StateMe.findByCreditAlphaScore", query = "SELECT s FROM StateMe s WHERE s.creditAlphaScore = :creditAlphaScore"), @NamedQuery(name = "StateMe.findByCreditNumericScore", query = "SELECT s FROM StateMe s WHERE s.creditNumericScore = :creditNumericScore"), @NamedQuery(name = "StateMe.findByHeadquartersbranch", query = "SELECT s FROM StateMe s WHERE s.headquartersbranch = :headquartersbranch"), @NamedQuery(name = "StateMe.findByOfficeSize", query = "SELECT s FROM StateMe s WHERE s.officeSize = :officeSize"), @NamedQuery(name = "StateMe.findBySquareFootage", query = "SELECT s FROM StateMe s WHERE s.squareFootage = :squareFootage"), @NamedQuery(name = "StateMe.findByFirmindividual", query = "SELECT s FROM StateMe s WHERE s.firmindividual = :firmindividual"), @NamedQuery(name = "StateMe.findByPublicprivateFlag", query = "SELECT s FROM StateMe s WHERE s.publicprivateFlag = :publicprivateFlag"), @NamedQuery(name = "StateMe.findByPcCode", query = "SELECT s FROM StateMe s WHERE s.pcCode = :pcCode"), @NamedQuery(name = "StateMe.findByFranchisespecialty1", query = "SELECT s FROM StateMe s WHERE s.franchisespecialty1 = :franchisespecialty1"), @NamedQuery(name = "StateMe.findByFranchisespecialty2", query = "SELECT s FROM StateMe s WHERE s.franchisespecialty2 = :franchisespecialty2"), @NamedQuery(name = "StateMe.findByIndustrySpecificCodes", query = "SELECT s FROM StateMe s WHERE s.industrySpecificCodes = :industrySpecificCodes"), @NamedQuery(name = "StateMe.findByAdsizeInYellowPages", query = "SELECT s FROM StateMe s WHERE s.adsizeInYellowPages = :adsizeInYellowPages"), @NamedQuery(name = "StateMe.findByMetroArea", query = "SELECT s FROM StateMe s WHERE s.metroArea = :metroArea"), @NamedQuery(name = "StateMe.findByRownum", query = "SELECT s FROM StateMe s WHERE s.rownum = :rownum")}) public class StateMe implements Serializable { private static final long serialVersionUID = 1L; @Size(max = 100) @Column(name = "company_name", length = 100) private String companyName; @Size(max = 155) @Column(name = "mailing_address", length = 155) private String mailingAddress; @Size(max = 75) @Column(length = 75) private String city; @Size(max = 5) @Column(length = 5) private String state; @Size(max = 20) @Column(name = "zip_code", length = 20) private String zipCode; @Size(max = 10) @Column(name = "mailing_carrier_route", length = 10) private String mailingCarrierRoute; @Size(max = 15) @Column(name = "mailing_delivery_point_bar_code", length = 15) private String mailingDeliveryPointBarCode; @Size(max = 255) @Column(name = "street_address", length = 255) private String streetAddress; @Size(max = 75) @Column(name = "street_address_city", length = 75) private String streetAddressCity; @Size(max = 5) @Column(name = "street_address_state", length = 5) private String streetAddressState; @Size(max = 20) @Column(name = "street_address_zip", length = 20) private String streetAddressZip; @Column(name = "street_address_delivery_point_bar_code") private BigInteger streetAddressDeliveryPointBarCode; @Size(max = 20) @Column(name = "street_address_carrier_route", length = 20) private String streetAddressCarrierRoute; @Size(max = 25) @Column(length = 25) private String county; @Size(max = 12) @Column(name = "phone_number", length = 12) private String phoneNumber; @Size(max = 15) @Column(name = "fax_number", length = 15) private String faxNumber; @Size(max = 95) @Column(name = "web_address", length = 95) private String webAddress; @Size(max = 65) @Column(name = "last_name", length = 65) private String lastName; @Size(max = 65) @Column(name = "first_name", length = 65) private String firstName; @Size(max = 65) @Column(name = "contact_title", length = 65) private String contactTitle; @Size(max = 20) @Column(name = "contact_gender", length = 20) private String contactGender; @Column(name = "actual_employee_size") private BigInteger actualEmployeeSize; @Size(max = 65) @Column(name = "employee_size_range", length = 65) private String employeeSizeRange; @Column(name = "actual_sales_volume") private BigInteger actualSalesVolume; @Size(max = 65) @Column(name = "sales_volume_range", length = 65) private String salesVolumeRange; @Column(name = "primary_sic") private BigInteger primarySic; @Size(max = 95) @Column(name = "primary_sic_description", length = 95) private String primarySicDescription; @Column(name = "secondary_sic_1") private BigInteger secondarySic1; @Size(max = 95) @Column(name = "secondary_sic_description_1", length = 95) private String secondarySicDescription1; @Column(name = "secondary_sic_2") private BigInteger secondarySic2; @Size(max = 95) @Column(name = "secondary_sic_description_2", length = 95) private String secondarySicDescription2; @Size(max = 5) @Column(name = "credit_alpha_score", length = 5) private String creditAlphaScore; @Column(name = "credit_numeric_score") private BigInteger creditNumericScore; @Size(max = 45) @Column(length = 45) private String headquartersbranch; @Size(max = 45) @Column(name = "office_size", length = 45) private String officeSize; @Size(max = 45) @Column(name = "square_footage", length = 45) private String squareFootage; @Size(max = 45) @Column(length = 45) private String firmindividual; @Size(max = 5) @Column(name = "publicprivate_flag", length = 5) private String publicprivateFlag; @Size(max = 45) @Column(name = "pc_code", length = 45) private String pcCode; @Size(max = 95) @Column(name = "franchisespecialty_1", length = 95) private String franchisespecialty1; @Size(max = 95) @Column(name = "franchisespecialty_2", length = 95) private String franchisespecialty2; @Size(max = 45) @Column(name = "industry_specific_codes", length = 45) private String industrySpecificCodes; @Size(max = 15) @Column(name = "adsize_in_yellow_pages", length = 15) private String adsizeInYellowPages; @Size(max = 45) @Column(name = "metro_area", length = 45) private String metroArea; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(nullable = false) private Long rownum; public StateMe() { } public StateMe(Long rownum) { this.rownum = rownum; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getMailingAddress() { return mailingAddress; } public void setMailingAddress(String mailingAddress) { this.mailingAddress = mailingAddress; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getMailingCarrierRoute() { return mailingCarrierRoute; } public void setMailingCarrierRoute(String mailingCarrierRoute) { this.mailingCarrierRoute = mailingCarrierRoute; } public String getMailingDeliveryPointBarCode() { return mailingDeliveryPointBarCode; } public void setMailingDeliveryPointBarCode(String mailingDeliveryPointBarCode) { this.mailingDeliveryPointBarCode = mailingDeliveryPointBarCode; } public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getStreetAddressCity() { return streetAddressCity; } public void setStreetAddressCity(String streetAddressCity) { this.streetAddressCity = streetAddressCity; } public String getStreetAddressState() { return streetAddressState; } public void setStreetAddressState(String streetAddressState) { this.streetAddressState = streetAddressState; } public String getStreetAddressZip() { return streetAddressZip; } public void setStreetAddressZip(String streetAddressZip) { this.streetAddressZip = streetAddressZip; } public BigInteger getStreetAddressDeliveryPointBarCode() { return streetAddressDeliveryPointBarCode; } public void setStreetAddressDeliveryPointBarCode(BigInteger streetAddressDeliveryPointBarCode) { this.streetAddressDeliveryPointBarCode = streetAddressDeliveryPointBarCode; } public String getStreetAddressCarrierRoute() { return streetAddressCarrierRoute; } public void setStreetAddressCarrierRoute(String streetAddressCarrierRoute) { this.streetAddressCarrierRoute = streetAddressCarrierRoute; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getFaxNumber() { return faxNumber; } public void setFaxNumber(String faxNumber) { this.faxNumber = faxNumber; } public String getWebAddress() { return webAddress; } public void setWebAddress(String webAddress) { this.webAddress = webAddress; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getContactTitle() { return contactTitle; } public void setContactTitle(String contactTitle) { this.contactTitle = contactTitle; } public String getContactGender() { return contactGender; } public void setContactGender(String contactGender) { this.contactGender = contactGender; } public BigInteger getActualEmployeeSize() { return actualEmployeeSize; } public void setActualEmployeeSize(BigInteger actualEmployeeSize) { this.actualEmployeeSize = actualEmployeeSize; } public String getEmployeeSizeRange() { return employeeSizeRange; } public void setEmployeeSizeRange(String employeeSizeRange) { this.employeeSizeRange = employeeSizeRange; } public BigInteger getActualSalesVolume() { return actualSalesVolume; } public void setActualSalesVolume(BigInteger actualSalesVolume) { this.actualSalesVolume = actualSalesVolume; } public String getSalesVolumeRange() { return salesVolumeRange; } public void setSalesVolumeRange(String salesVolumeRange) { this.salesVolumeRange = salesVolumeRange; } public BigInteger getPrimarySic() { return primarySic; } public void setPrimarySic(BigInteger primarySic) { this.primarySic = primarySic; } public String getPrimarySicDescription() { return primarySicDescription; } public void setPrimarySicDescription(String primarySicDescription) { this.primarySicDescription = primarySicDescription; } public BigInteger getSecondarySic1() { return secondarySic1; } public void setSecondarySic1(BigInteger secondarySic1) { this.secondarySic1 = secondarySic1; } public String getSecondarySicDescription1() { return secondarySicDescription1; } public void setSecondarySicDescription1(String secondarySicDescription1) { this.secondarySicDescription1 = secondarySicDescription1; } public BigInteger getSecondarySic2() { return secondarySic2; } public void setSecondarySic2(BigInteger secondarySic2) { this.secondarySic2 = secondarySic2; } public String getSecondarySicDescription2() { return secondarySicDescription2; } public void setSecondarySicDescription2(String secondarySicDescription2) { this.secondarySicDescription2 = secondarySicDescription2; } public String getCreditAlphaScore() { return creditAlphaScore; } public void setCreditAlphaScore(String creditAlphaScore) { this.creditAlphaScore = creditAlphaScore; } public BigInteger getCreditNumericScore() { return creditNumericScore; } public void setCreditNumericScore(BigInteger creditNumericScore) { this.creditNumericScore = creditNumericScore; } public String getHeadquartersbranch() { return headquartersbranch; } public void setHeadquartersbranch(String headquartersbranch) { this.headquartersbranch = headquartersbranch; } public String getOfficeSize() { return officeSize; } public void setOfficeSize(String officeSize) { this.officeSize = officeSize; } public String getSquareFootage() { return squareFootage; } public void setSquareFootage(String squareFootage) { this.squareFootage = squareFootage; } public String getFirmindividual() { return firmindividual; } public void setFirmindividual(String firmindividual) { this.firmindividual = firmindividual; } public String getPublicprivateFlag() { return publicprivateFlag; } public void setPublicprivateFlag(String publicprivateFlag) { this.publicprivateFlag = publicprivateFlag; } public String getPcCode() { return pcCode; } public void setPcCode(String pcCode) { this.pcCode = pcCode; } public String getFranchisespecialty1() { return franchisespecialty1; } public void setFranchisespecialty1(String franchisespecialty1) { this.franchisespecialty1 = franchisespecialty1; } public String getFranchisespecialty2() { return franchisespecialty2; } public void setFranchisespecialty2(String franchisespecialty2) { this.franchisespecialty2 = franchisespecialty2; } public String getIndustrySpecificCodes() { return industrySpecificCodes; } public void setIndustrySpecificCodes(String industrySpecificCodes) { this.industrySpecificCodes = industrySpecificCodes; } public String getAdsizeInYellowPages() { return adsizeInYellowPages; } public void setAdsizeInYellowPages(String adsizeInYellowPages) { this.adsizeInYellowPages = adsizeInYellowPages; } public String getMetroArea() { return metroArea; } public void setMetroArea(String metroArea) { this.metroArea = metroArea; } public Long getRownum() { return rownum; } public void setRownum(Long rownum) { this.rownum = rownum; } @Override public int hashCode() { int hash = 0; hash += (rownum != null ? rownum.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof StateMe)) { return false; } StateMe other = (StateMe) object; if ((this.rownum == null && other.rownum != null) || (this.rownum != null && !this.rownum.equals(other.rownum))) { return false; } return true; } @Override public String toString() { return "src.entities.StateMe[ rownum=" + rownum + " ]"; } }
[ "Sg5NHsD7" ]
Sg5NHsD7
a5335d01092a0915ee59ce11bbafd48afb436272
b7fa9e2eccf76230aa45fccc9bd40fefba297f70
/demo/src/test/java/org/challenge/demo/DemoApplicationTests.java
2b7c3bd4a6fe7f192fdffd2db3936e9a25ac6571
[]
no_license
belemkaddem/belemkadem
42bdb10014aa31dfff1dc7131143d5f7a70a6aad
f3f1add681e8f5805d2452bf4043b4a7ce5b384c
refs/heads/master
2021-08-23T09:19:33.901619
2017-12-04T13:26:03
2017-12-04T13:26:03
111,923,637
0
0
null
null
null
null
UTF-8
Java
false
false
333
java
package org.challenge.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Test public void contextLoads() { } }
409e6039b5cd84e683d475b383b457270bf1b86b
8ed94a885b9dd023175b122b136c3ca46d0ba134
/JPMCodingProblem/src/com/jpm/coding/problem/Test/DailyTradingTest.java
d1fda03230bc44062c1957dfe0f471e050db2a23
[]
no_license
shandier/JPM-Trading-Assignmnent
ea1000ccced607c06226dac06a7c4fea505ad4bc
6664cf7bb466d48247950d8d79b7a2ec813eb087
refs/heads/master
2020-03-24T22:50:06.889529
2018-08-01T11:52:06
2018-08-01T11:52:06
143,105,059
0
0
null
null
null
null
UTF-8
Java
false
false
4,036
java
package com.jpm.coding.problem.Test; import static org.junit.Assert.assertEquals; import java.time.LocalDate; import java.util.ArrayList; import java.util.Currency; import java.util.List; import org.junit.Before; import org.junit.Test; import com.jpm.coding.problem.helper.InstructionUtil; import com.jpm.coding.problem.helper.TradeUtil; import com.jpm.coding.problem.model.TradeInstruction; import com.jpm.coding.problem.model.TradeType; import com.jpm.coding.problem.services.InstructionManager; import com.jpm.coding.problem.services.InstructionManagerImpl; public class DailyTradingTest { private InstructionManager instructionManager = new InstructionManagerImpl(); private List<TradeInstruction> tradingInstrunctions = new ArrayList<TradeInstruction>(); @Before public void buildTestData() { TradeInstruction inst1 = new TradeInstruction("foo", 0.50F, Currency.getInstance("SGD"), LocalDate.parse("2018-08-01"), LocalDate.parse("2018-08-04"), 200, 100.25, TradeType.BUY); TradeInstruction inst2 = new TradeInstruction("bar", 0.22F, Currency.getInstance("AED"), LocalDate.parse("2018-02-02"), LocalDate.parse("2018-08-03"), 450, 150.5, TradeType.SELL); TradeInstruction inst3 = new TradeInstruction("foo", 0.30F, Currency.getInstance("INR"), LocalDate.parse("2018-08-01"), LocalDate.parse("2018-08-04"), 100, 130.25, TradeType.SELL); TradeInstruction inst4 = new TradeInstruction("bar", 0.42F, Currency.getInstance("INR"), LocalDate.parse("2016-01-05"), LocalDate.parse("2016-01-07"), 400, 135.5, TradeType.BUY); TradeInstruction inst5 = new TradeInstruction("foo", 0.20F, Currency.getInstance("SGD"), LocalDate.parse("2016-01-01"), LocalDate.parse("2018-08-04"), 140, 112.25, TradeType.BUY); tradingInstrunctions.add(inst1); tradingInstrunctions.add(inst2); tradingInstrunctions.add(inst3); tradingInstrunctions.add(inst4); tradingInstrunctions.add(inst5); } @Test public void testsettleInstructionsWithNullAndEmptyList() { assertEquals(null, instructionManager.settleInstructions(null)); assertEquals(true, instructionManager.settleInstructions(new ArrayList<TradeInstruction>()).isEmpty()); } @Test public void testGetWorkingSettlementDate() { // Currency with weekend as Friday and Saturday Currency currency = Currency.getInstance("AED"); // Currency with weekend as Saturday and Sunday Currency regularWeekendCurrency = Currency.getInstance("SGD"); LocalDate weekDayFriday = LocalDate.parse("2018-08-03"); LocalDate weekDaySunday = LocalDate.parse("2018-08-05"); LocalDate nextWorkingDate = TradeUtil.getWorkingSettlementDate(currency, weekDayFriday); assertEquals(nextWorkingDate, weekDayFriday.plusDays(2)); LocalDate nextWorkingDate2 = TradeUtil.getWorkingSettlementDate(regularWeekendCurrency, weekDayFriday); assertEquals(nextWorkingDate2, weekDayFriday); LocalDate nextWorkingDate3 = TradeUtil.getWorkingSettlementDate(regularWeekendCurrency, weekDaySunday); assertEquals(nextWorkingDate3, weekDaySunday.plusDays(1)); } @Test(expected = IllegalArgumentException.class) public void testNegativeGetWorkingSettlementDate() { LocalDate nextWorkingDate = TradeUtil.getWorkingSettlementDate(null, null); assertEquals(nextWorkingDate, LocalDate.now()); LocalDate nextWorkingDate1 = TradeUtil.getWorkingSettlementDate(Currency.getInstance("fgd"), LocalDate.parse("2018-08-05")); assertEquals(nextWorkingDate1, LocalDate.now()); } @Test public void TestFilterInstructionsbySettlementDateAndTradeType() { List<TradeInstruction> fillteredInstructionForBuy = InstructionUtil .filterInstructionsbySettlementDateAndTradeType(tradingInstrunctions, LocalDate.parse("2018-08-04"), TradeType.BUY); List<TradeInstruction> fillteredInstructionsForSell = InstructionUtil .filterInstructionsbySettlementDateAndTradeType(tradingInstrunctions, LocalDate.parse("2018-08-04"), TradeType.SELL); assertEquals(fillteredInstructionForBuy.size(), 2); assertEquals(fillteredInstructionsForSell.size(), 1); } }
17359a9d6c21393ca4ca600037369b7b4da3ca6f
9fb7d94ddf4a75794de62986cb338fd63d120dfe
/food-tracker-micronaut/src/main/java/org/acme/supplier/SupplierService.java
0c4e5cb867d50608da0b9bc317ae174ed18e9aef
[]
no_license
khengsdijk/test-projecten-graalvm
6889775d243d3080b28a46b90c7a95632123f982
efa16cea854d3f5deeed4f91654ad84cd903d524
refs/heads/master
2022-11-28T05:34:27.978716
2020-08-10T11:12:25
2020-08-10T11:12:25
286,442,938
0
0
null
null
null
null
UTF-8
Java
false
false
1,222
java
package org.acme.supplier; import javax.inject.Singleton; @Singleton public class SupplierService { private final SupplierRepository repository; public SupplierService(SupplierRepository repository){ this.repository = repository; } public Iterable<Supplier> findAll(){ return repository.findAll(); } public Supplier findById( Long id){ return repository.findById(id).orElseThrow(() -> new SupplierNotfoundException(id)); } public Supplier saveSupplier(Supplier supplier){ return repository.save(supplier); } public Supplier updateSupplier(Supplier newSupplier, Long id){ return repository.findById(id) .map(supplier -> { supplier.setCountry(newSupplier.getCountry()); supplier.setName(newSupplier.getName()); supplier.setType(newSupplier.getType()); return repository.save(supplier); }).orElseGet(() -> { newSupplier.setId(id); return repository.save(newSupplier); }); } public void deleteSupplier(Long id){ repository.deleteById(id); } }
2d141d0498b02631cab374f1de1432162d074de0
a988f267ff9c32ec6eaed50c2bb4a989e1291834
/app/src/main/java/com/upv/rosiebelt/safefit/utility/Constants.java
504dd9bb645427219552d5d6ad783a3dac50bfc7
[]
no_license
beltjun26/safeAndFit
d515c28deac771fd27f0cad008ece0326ef8ee30
611f0e8acd50ce538a5a287d3169edc51fbae99c
refs/heads/master
2021-04-12T10:37:08.629749
2018-05-03T04:53:49
2018-05-03T04:53:49
126,222,981
0
0
null
null
null
null
UTF-8
Java
false
false
307
java
package com.upv.rosiebelt.safefit.utility; /** * Created by root on 3/26/18. */ public class Constants { public static final String BROADCAST_DETECTED_ACTIVITY = "activity_intent"; static final long DETECTION_INTERVAL_IN_MILLISECONDS = 2 * 1000; public static final int CONFIDENCE = 70; }
9591c9ed790b03e8d0c67e622cc5217d90a2b6d0
10c5610f3f7023ede49efa91ff3b04272fcd2581
/src/main/java/com/qnowapp/web/rest/errors/EmailAlreadyUsedException.java
b50e1301f520e09f172070ed1a2419018f926ffc
[]
no_license
lksmangai/PMOJava-development
20a024500fa2bb3e91da22cef185014265a8e8c0
a39f8933ff1a8a938087f81f5b3adc1b71428a54
refs/heads/master
2022-12-23T06:44:46.667535
2020-01-27T04:33:27
2020-01-27T04:33:27
233,754,527
0
0
null
2022-12-16T04:54:29
2020-01-14T04:13:09
HTML
UTF-8
Java
false
false
332
java
package com.qnowapp.web.rest.errors; public class EmailAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public EmailAlreadyUsedException() { super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); } }
13846205ddc7a485e430e72fc9d40820e228397c
12c3b27b08757ff85f1ad4e2732bcb0141bc1933
/src/JsonReader/main.java
ac94b25db0c64c1665224500952894bc7d1db969
[]
no_license
Marymaryam/HotelSimulatie-Maryam-develop
9d6367deb33b8281bc7822f2721e6243afe3d4a8
077ed959d5c8e88a554c6991f91a0df40ca7a2c9
refs/heads/master
2020-03-30T05:30:42.633000
2018-09-28T23:13:20
2018-09-28T23:13:20
150,803,320
0
0
null
null
null
null
UTF-8
Java
false
false
1,714
java
package JsonReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class main { private static final String filePath = "Hotel3.layout"; public static void main(String[] args) { try { // read the json file FileReader reader = new FileReader(filePath); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); // get an array from the JSON object JSONArray hotel= (JSONArray) jsonObject.get("Hotel"); // take the elements of the json array for(int i=0; i<hotel.size(); i++){ System.out.println("The " + i + " element of the array: "+hotel.get(i)); } // take each value from the json array separately for (Object aLang : hotel) { JSONObject innerObj = (JSONObject) aLang; System.out.println("AreaType " + innerObj.get("AreaType") + " Position " + innerObj.get("Position")); } // iterator Iterator it = hotel.iterator(); System.out.println("met iterator: "); while(it.hasNext()) System.out.println(it.next()); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
df465cc30259e2278c1916c2c24781f81fc3dbed
e77d6e036778b4ca0fd79c65201d9e75792a79d1
/coronavirus-tracker/src/test/java/com/patil/CoronavirusTrackerApplicationTests.java
2c7c2b8da0d6225a683a1caf4b9edfd723d8173b
[]
no_license
sjp28/corona-virus
eac228b24e412d8379057d7b8e7fea0861c8ba71
b8c56d8147368ce723861e03e264df67e28a9585
refs/heads/master
2022-12-15T00:45:42.264460
2020-09-18T07:24:44
2020-09-18T07:24:44
296,544,409
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package com.patil; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CoronavirusTrackerApplicationTests { @Test void contextLoads() { } }
e58519b1a3fb528ecf7db79f8e0f39e3d2b130df
040f897f6e5ffbbbf58012455ff86362e3051b1c
/src/main/java/io/lenar/examples/spring/model/Planet.java
a5e87038f6cd3f94fa07c0288ec3815f845ca1e1
[]
no_license
LenarBad/EasyLog-Spring-Example
6b7d69f4fc0f4b7140537162ceefc500b5320e47
3d237eb90a0c22c2378d2ccd92b7c59a28acd015
refs/heads/master
2020-03-21T23:39:04.808874
2018-10-03T15:32:25
2018-10-03T15:32:25
139,199,549
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package io.lenar.examples.spring.model; public class Planet { private String name; private boolean haveSatellites; public Planet(String name, boolean haveSatellites) { this.name = name; this.haveSatellites = haveSatellites; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isHaveSatellites() { return haveSatellites; } public void setHaveSatellites(boolean haveSatellites) { this.haveSatellites = haveSatellites; } }
b039a237068814caea03ef2b888b64ea81bb2af9
8b68ce9e4c3c75b9054473451c406bfbd60afb6a
/java/DecodeVideoFrame/src/com/dbr/decodevideoframe/DecodeVideoFrame.java
81f364e6d1d4f5788ad7a5f0a523ecc6bdbe4b5f
[]
no_license
dynamsoft-dbr/java-barcode-samples
a5607c19c7b84c815dfee25716f91675cd562dc0
aa811f0d635c0a969f89ca902c1577232f4a4b13
refs/heads/master
2022-12-15T15:31:22.498260
2020-09-09T03:22:00
2020-09-09T03:22:00
293,987,382
0
0
null
null
null
null
UTF-8
Java
false
false
4,391
java
package com.dbr.decodevideoframe; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.videoio.VideoCapture; import org.opencv.videoio.Videoio; import com.dynamsoft.barcode.BarcodeReader; import com.dynamsoft.barcode.BarcodeReaderException; import com.dynamsoft.barcode.EnumConflictMode; import com.dynamsoft.barcode.EnumImagePixelFormat; import com.dynamsoft.barcode.ErrorCallback; import com.dynamsoft.barcode.FrameDecodingParameters; import com.dynamsoft.barcode.TextResult; import com.dynamsoft.barcode.TextResultCallback; public class DecodeVideoFrame { static{ System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); } public static String ToHexString(String string) { String result = ""; for (int i = 0; i < string.length(); i++) { int ch = (int) string.charAt(i); String hex = Integer.toHexString(ch); result = result + hex; } return result; } public static void OutputResult(TextResult[] result) { if(result.length==0) { System.out.println("No barcode found."); } else { System.out.println("Total barcode(s) found:"+ result.length); for(int iIndex = 0; iIndex <result.length;iIndex++) { System.out.println("Barcode "+(iIndex+1)+":\n"); if(result[iIndex].barcodeFormat !=0 ) { System.out.println(" Type: "+result[iIndex].barcodeFormatString); } else { System.out.println(" Type: "+result[iIndex].barcodeFormatString_2); } System.out.println(" Value: "+result[iIndex].barcodeText); String hexString = ToHexString(result[iIndex].barcodeText); System.out.println(" Hex Value: "+hexString+"\n"); } } return; } public static void main(String[] args) { Mat frame = new Mat(); System.out.println("Opening camera..."); VideoCapture capture = new VideoCapture(); try { capture.open(0); } catch (Exception e) { System.out.println("ERROR: Can't initialize camera capture"); return; } if(!capture.isOpened()) { System.out.println("ERROR: Can't initialize camera capture"); return; } try { BarcodeReader reader = new BarcodeReader("t0068MgAAAKh+3x+Y3EFBqOMBGnRw9mTIc0hZOnBzJdCzjaUPgEAXqffqQhW5179bBIImwWKqpHhU0Gz1OM1fOAYCq32DT1Y="); reader.initRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_STATISTICS\"}]}}",EnumConflictMode.CM_OVERWRITE); reader.setTextResultCallback(new TextResultCallback() { @Override public void textResultCallback(int frameId, TextResult[] results, Object userData) { System.out.println("frame: "+frameId); OutputResult(results); } }, null); reader.setErrorCallback(new ErrorCallback() { @Override public void errorCallback(int frameId, int errorCode, Object userData) { System.out.println("frame: "+frameId); if(errorCode!=0) { System.out.println("error code: "+errorCode); } } }, null); capture.read(frame); FrameDecodingParameters parameters; parameters = reader.initFrameDecodingParameters(); parameters.width = (int) capture.get(Videoio.CAP_PROP_FRAME_WIDTH); parameters.height = (int) capture.get(Videoio.CAP_PROP_FRAME_HEIGHT); parameters.maxQueueLength = 30; parameters.maxResultQueueLength = 30; parameters.stride = (int) frame.step1(0); parameters.imagePixelFormat = EnumImagePixelFormat.IPF_RGB_888; parameters.region.regionMeasuredByPercentage = 1; parameters.region.regionTop = 0; parameters.region.regionBottom = 100; parameters.region.regionLeft = 0; parameters.region.regionRight = 100; parameters.threshold =(float) 0.01; parameters.fps = 0; reader.startFrameDecodingEx(parameters, ""); ImageGui gui = new ImageGui(frame,"Image"); gui.imshow(); for(;;) { capture.read(frame); if(frame.empty()) { System.out.println("ERROR: Can't grab camera frame."); break; } int length = (int)(frame.total()*frame.elemSize()); byte data[] = new byte[length]; frame.get(0, 0,data); reader.appendFrame(data); gui.Changeframe(frame); } reader.stopFrameDecoding(); } catch (BarcodeReaderException e) { System.out.println("init barcode reader failed, error code: "+e.getErrorCode()); return; } } }
aa9426af46f7a01fd0bfbe3725b5815bc38fd3fc
8ae7ec62a5bc59866ff8ca3d400cc5de142d6771
/src/main/java/com/lzwing/threadpool/AsyncHandler.java
a398a5a39ba8525828b4f512687a8899e8c026ea
[]
no_license
longzhiwuing/spring-boot-test
05880fe2b412a4e71f80ae9165e42016ae9f5842
f19b5567ff17574e23ff8404ed31669dc985a5d3
refs/heads/master
2020-03-16T17:41:21.107763
2018-09-10T08:33:02
2018-09-10T08:33:02
132,842,889
0
0
null
null
null
null
UTF-8
Java
false
false
315
java
package com.lzwing.threadpool; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component @Slf4j public class AsyncHandler { @Async public void doSync(String name) { log.info("AsyncTester:{}",name); } }
60dc26bb6839d1395ccee58f7f04fa47b1e424cd
4e4834be387cbe0e8c4261cdc3ef2166d5187d2c
/src/cn/mm2/evernote/ui/EvernoteInvoke.java
0433580474985b2bc2a4d40b66e329b1056d4fe2
[]
no_license
xinmeng2011/eatYourCode
4fed9ed04e8f566bf0c44d6f0a1e612d07c61857
fbc5c274c547314d805e9ae42b0406f069689be0
refs/heads/master
2021-01-23T18:59:08.846995
2014-02-25T01:48:01
2014-02-25T01:48:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,052
java
package cn.mm2.evernote.ui; import java.util.ArrayList; import java.util.List; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.notestore.NoteStore; import com.evernote.edam.type.Note; import com.evernote.edam.type.Notebook; import com.evernote.edam.userstore.UserStore; import com.evernote.thrift.TException; import com.evernote.thrift.protocol.TBinaryProtocol; import com.evernote.thrift.transport.THttpClient; import com.evernote.thrift.transport.TTransportException; public class EvernoteInvoke { private static String mToken = ""; private NoteStore.Client mNoteStore; private UserStore.Client mUserStore; private static EvernoteInvoke mSingle; private static final String NOTEBOOK_NAME= "Elephant eat your code"; public static void setToken(String token){ if(mToken.length() == 0){ mToken = token; } } static public EvernoteInvoke getSingle(){ if(mSingle != null){ return mSingle; }else{ mSingle = new EvernoteInvoke(mToken); } return mSingle; } private EvernoteInvoke(String token){ THttpClient userStoreTrans = null; try { userStoreTrans = new THttpClient(AccountUtil.getNoteStoreUrl()); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } //userStoreTrans.setCustomHeader("User-Agent", userAgent); TBinaryProtocol userStoreProt = new TBinaryProtocol(userStoreTrans); mUserStore = new UserStore.Client(userStoreProt, userStoreProt); String noteStoreUrl = ""; try { noteStoreUrl = mUserStore.getNoteStoreUrl(mToken); THttpClient noteStoreTrans = new THttpClient(noteStoreUrl); TBinaryProtocol noteStoreProt = new TBinaryProtocol(noteStoreTrans); mNoteStore = new NoteStore.Client(noteStoreProt, noteStoreProt); Notebook book = mNoteStore.getDefaultNotebook(mToken); } catch (EDAMUserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (EDAMSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void saveNote(String noteTitle, String noteBody, Notebook parentNotebook){ noteBody = noteBody.replace("\r\n", "</div><div>"); noteBody = "<div>" + noteBody +"</div>"; String nBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; nBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"; nBody += "<en-note>" + noteBody + "</en-note>"; // Create note object Note ourNote = new Note(); ourNote.setTitle(noteTitle); ourNote.setContent(nBody); // parentNotebook is optional; if omitted, default notebook is used if (parentNotebook != null && parentNotebook.isSetGuid()) { ourNote.setNotebookGuid(parentNotebook.getGuid()); } // Attempt to create note in Evernote account Note note = null; try { note = mNoteStore.createNote(mToken,ourNote); } catch (EDAMUserException edue) { // Something was wrong with the note data // See EDAMErrorCode enumeration for error code explanation // http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode System.out.println("EDAMUserException: " + edue); } catch (EDAMNotFoundException ednfe) { // Parent Notebook GUID doesn't correspond to an actual notebook System.out.println("EDAMNotFoundException: Invalid parent notebook GUID"); } catch (Exception e) { // Other unexpected exceptions e.printStackTrace(); } // Return created note object return ; } private Notebook getEYCNotebook(){ Notebook nb = new Notebook(); Notebook nbRemote = null; nb.setName(NOTEBOOK_NAME); try { nbRemote = mNoteStore.createNotebook(mToken, nb); } catch (EDAMUserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (EDAMSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } return nbRemote; } private Notebook findEYCNotebook(){ List<Notebook> nbs; try { nbs = mNoteStore.listNotebooks(mToken); if(nbs != null){ for (int i = 0; i < nbs.size(); i++) { Notebook item = nbs.get(i); if(item.getName().equals(NOTEBOOK_NAME)){ return item; } } } } catch (EDAMUserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (EDAMSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void saveNote(String title, String note){ Notebook nb = getEYCNotebook(); if(nb == null){ nb = findEYCNotebook(); } if(nb == null){ return; } saveNote(title, note, nb); } public void testbootstrap(){ } }
adae9c8e534794e134f89f886706c8d1bb578de8
20dfba714ddf8717f7b862833460b0dc1e0f1b10
/RemoveNthNodeFromEnd.java
4de69941f6af0033d9df83c59a51ed452e1fe1c7
[]
no_license
mahima95/Linked-List-1
4278db656a716a2edbfb81ec1128bc6044da4b5a
ae6a51637da6074d1f0394a6d8908459006cba35
refs/heads/master
2020-06-23T00:54:45.410743
2019-07-26T02:55:15
2019-07-26T02:55:15
198,451,691
0
0
null
2019-07-23T14:52:25
2019-07-23T14:52:24
null
UTF-8
Java
false
false
1,018
java
//Approach: Traverse till the sth node, //Create a sliding window between f and s , //When the f reaches null ,then make s.next = s.next.next //Run on Leetcode? Yes //Time Complexitiy:O(n) //Space Complexity: O(1) /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return null; else{ ListNode dummy = new ListNode(0); dummy.next = head; ListNode f = dummy; //head ListNode s = dummy; //head for(int i=1;i<=n+1;i++) f = f.next; //Go till 1,2,3,4,5 n positons : go till nth pass : there will be a sliding window while(f!=null){ //there is a sliding window between the two f = f.next; s = s.next; } s.next = s.next.next; return dummy.next; } }}
e2fb73234ca60f21543fad3edc38e2cb9cccfe50
d6cf992e3b50b809e2ee6f38e5fae0945a099556
/SpringRestExample/src/main/java/com/java/spring/dao/EmpDao.java
7e21c4a884bbf8e7175ede946a00d1c20dba4143
[]
no_license
prakashkoganti/RestAngular
638d32c8416d5fad177e86454de7bd8c39c54bda
8207013788e7c8fd879665aca8e9f6812bc2fd23
refs/heads/master
2021-01-12T06:34:58.583765
2016-12-26T14:18:12
2016-12-26T14:18:12
77,387,823
0
0
null
null
null
null
UTF-8
Java
false
false
201
java
package com.java.spring.dao; import com.java.spring.model.EmployeeDetails; public interface EmpDao { EmployeeDetails saveEmpData(EmployeeDetails empData); EmployeeDetails fetchEmpData(Long id); }
1eaa218f3e7a00c99beb2862e63a773d56d61ec1
c5250712b1e229c2155c57beceffedf09600ce59
/Vehicle_Reservation_System - Copy/src/com/pack/dao/EntityDaoImpl.java
032d4d38cc7d4950592dc4c3f867967eb9b95c9f
[]
no_license
pragyadas6/VRS1
09b100646b44ca6cbdd400d98a19f6175c50005d
a1ffe8dc7fe281c1786eee1723ea6f38d85d9d5e
refs/heads/master
2020-05-03T21:31:49.962056
2019-04-26T11:35:45
2019-04-26T11:35:45
178,825,477
0
0
null
null
null
null
UTF-8
Java
false
false
10,907
java
package com.pack.dao; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.pack.bean.AdminEntity; import com.pack.bean.LoginEntity; import com.pack.bean.VehicleEntity; @Repository public class EntityDaoImpl implements EntityDao { @Autowired private SessionFactory sessionFactory; @Override public void addVehicle(VehicleEntity vehicle) { this.sessionFactory.getCurrentSession().save(vehicle); } @Override public List<VehicleEntity> getAllVehicles() { return this.sessionFactory.getCurrentSession().createQuery("from Vehicle").list(); } @Override public void addAdmin(AdminEntity admin) { this.sessionFactory.getCurrentSession().save(admin); LoginEntity login = new LoginEntity(); login.setEmailId(admin.getEmailId()); login.setPassword(admin.getPassword()); login.setStatus(null); login.setAdminId(admin.getAdminId()); login.setResetToken(null); this.sessionFactory.getCurrentSession().save(login); } @Override public AdminEntity loginAdmin(LoginEntity login) { AdminEntity l1 = null; Session s = this.sessionFactory.openSession(); Transaction t = s.beginTransaction(); Query q = s.createQuery("from Admin l where l.adminId=:adminId and l.password=:password"); q.setParameter("adminId", login.getAdminId()); q.setParameter("password", login.getPassword()); l1 = (AdminEntity) q.uniqueResult(); return l1; } @Override public AdminEntity getAdminById(String adminId) { AdminEntity l1 = null; Session s = this.sessionFactory.openSession(); Transaction t = s.beginTransaction(); Query q = s.createQuery("from Admin l where l.adminId=:adminId"); q.setParameter("adminId", adminId); l1 = (AdminEntity) q.uniqueResult(); return l1; } @Override public void editAdmin(AdminEntity admin) { this.sessionFactory.getCurrentSession().update(admin); LoginEntity login = new LoginEntity(); login.setAdminId(admin.getAdminId()); login.setEmailId(admin.getEmailId()); login.setPassword(admin.getPassword()); login.setResetToken(""); login.setStatus(""); this.sessionFactory.getCurrentSession().update(login); } @Override public void deleteAdmin(String adminId) { AdminEntity admin = (AdminEntity) sessionFactory.getCurrentSession().load( AdminEntity.class, adminId); if (null != admin) { this.sessionFactory.getCurrentSession().delete(admin); } } @Override public void deleteVehicle(String vehicleNo) { VehicleEntity vehicle = (VehicleEntity) sessionFactory.getCurrentSession().load( VehicleEntity.class, vehicleNo); if (null != vehicle) { this.sessionFactory.getCurrentSession().delete(vehicle); } } @Override public VehicleEntity getVehicleById(String vehicleNo) { VehicleEntity v1 = null; Session s = this.sessionFactory.openSession(); Transaction t = s.beginTransaction(); Query q = s.createQuery("from Vehicle v where v.vehicleNo=:vehicleNo"); q.setParameter("vehicleNo", vehicleNo); v1 = (VehicleEntity) q.uniqueResult(); return v1; } @Override public void editVehicle(VehicleEntity vehicle) { this.sessionFactory.getCurrentSession().update(vehicle); } @Override public List<VehicleEntity> searchVehicle(VehicleEntity vehicle) { List<VehicleEntity> list = null; Session s = this.sessionFactory.getCurrentSession(); Query q = null; String qwry = "from Vehicle v where"; if(vehicle.getBranch() != null && !vehicle.getBranch().equals("")){ qwry += " branch= '"+String.valueOf(vehicle.getBranch()+"'"); } if(vehicle.getVehicleType() != null && !vehicle.getVehicleType().equals("")){ if(qwry.endsWith("where")) qwry += " vehicleType= '"+String.valueOf(vehicle.getVehicleType()+"'"); else qwry += " and vehicleType= '"+String.valueOf(vehicle.getVehicleType()+"'"); } if(vehicle.getServiceDueDate() != null && !vehicle.getServiceDueDate().equals("")){ if(qwry.endsWith("where")) qwry += " serviceDueDate like '_____"+String.valueOf(vehicle.getServiceDueDate()+"%'"); else qwry += " and serviceDueDate like '_____"+String.valueOf(vehicle.getServiceDueDate()+"%'"); } if(vehicle.getLastServiceDate() != null && !vehicle.getLastServiceDate().equals("")){ if(qwry.endsWith("where")) qwry += " lastServiceDate like '_____"+String.valueOf(vehicle.getLastServiceDate()+"%'"); else qwry += " and lastServiceDate like '_____"+String.valueOf(vehicle.getLastServiceDate()+"%'"); } q = s.createQuery(qwry); list = q.list(); return list; } @Override public void sendMailSSL(String email, VehicleEntity v1) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("ChoHelen1097","pass.1234"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Vehicle Registration System"); message.setText("Vehicle Number: "+v1.getVehicleNo()+" need to be updated !!!!!!!!!"+"\nThe service due date is "+v1.getServiceDueDate()+"\nThe insurance expiry date is "+v1.getInsuranceExpiryDate()); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } @Override public List<String> getAllMails(String branch) { List<AdminEntity> l = null; Query q = sessionFactory.getCurrentSession().createQuery("from Admin where branch=:branch"); q.setParameter("branch", branch); l=q.list(); List<String> l1 = new ArrayList<String>(); for(AdminEntity e: l) { if(e.getEmailId() != null) l1.add(e.getEmailId()); } return l1; } @Override public boolean checkAdminId(String adminId) { List<String> l = null; Session s = this.sessionFactory.openSession(); try{ String hql = "select l from Admin l where l.adminId=:adminId"; Query q = s.createQuery(hql); q.setParameter("adminId", adminId); l =q.list(); } catch(Exception e){ System.out.println("Error"); } s.close(); if(l.isEmpty()) return true; return false; } @Override public boolean checkVehicleNo(String vehicleNo) { List<String> l = null; Session s = this.sessionFactory.openSession(); try{ String hql = "select l from Vehicle l where l.vehicleNo=:vehicleNo"; Query q = s.createQuery(hql); q.setParameter("vehicleNo", vehicleNo); l = q.list(); } catch(Exception e){ System.out.println("Error"); } s.close(); if(l.isEmpty()) return true; return false; } @Override public boolean checkEmailId(String emailId) { AdminEntity l = null; Session s = this.sessionFactory.openSession(); try{ String hql = "from Admin l where l.emailId=:emailId"; Query q = s.createQuery(hql); q.setParameter("emailId", emailId); l = (AdminEntity)q.uniqueResult(); } catch(Exception e){ System.out.println("Error"); } s.close(); if(l == null) return true; return false; } @Override public List<String> getAllVehicleType() { List<String> allVehicleType = null; Session s = this.sessionFactory.openSession(); String qry = "select distinct v.vehicleType from Vehicle v"; Query q = s.createQuery(qry); allVehicleType = q.list(); return allVehicleType; } @Override public List<String> getAllBranch() { List<String> allBranch = null; Session s = this.sessionFactory.openSession(); String qry = "select distinct v.branch from Vehicle v"; Query q = s.createQuery(qry); allBranch = q.list(); return allBranch; } @Override public void updateToken(LoginEntity login) { String hql = "UPDATE Login set resetToken=:resetToken " + "WHERE emailId = :emailId"; Query query = this.sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("resetToken", login.getResetToken()); query.setParameter("emailId", login.getEmailId()); int result = query.executeUpdate(); } @Override public String findUserByToken(String token) { List<String> list=null; Session s=this.sessionFactory.openSession(); Transaction t=s.beginTransaction(); try{ String hql = "SELECT emailId from Login l WHERE l.resetToken LIKE ?"; Query q = s.createQuery(hql); q.setParameter(0, token); list = q.list(); } catch (Exception e) { System.out.println("Error"); } s.close(); if(list.isEmpty()) return null; else return list.get(0); } @Override public void resetPassword(String emailId, String password) { String hql = "UPDATE Login set password = :password,resetToken=:resetToken "+ "WHERE emailId = :emailId"; String hql1 = "UPDATE Admin set password = :password"+ "WHERE emailId = :emailId"; Query query = this.sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("password", password); query.setParameter("resetToken",""); query.setParameter("emailId", emailId); int result = query.executeUpdate(); Query query1 = this.sessionFactory.getCurrentSession().createQuery("UPDATE Admin set password = :password WHERE emailId = :emailId"); query1.setParameter("password", password); query1.setParameter("emailId", emailId); int result1 = query1.executeUpdate(); } @Override public boolean checkEmail(String emailId) { List<String> list=null; Session s=this.sessionFactory.openSession(); Transaction t=s.beginTransaction(); try{ String hql = "SELECT emailId from Login l WHERE l.emailId LIKE ?"; Query q = s.createQuery(hql); q.setParameter(0, emailId); list = q.list(); } catch (Exception e) { System.out.println("Error"); } s.close(); if(list.isEmpty()) return false; else return true; } }
48637e8c105016bc94838ecbb28296a1397efc74
53c8d56fc88c2e1a788dd50418e265cbf37ec8f1
/mq/rabbitmq/src/main/java/com/cloud/rabbitmq/api/consumer/Consumer5.java
610b729c4e62da3a5c91211816cfe8837239004f
[]
no_license
huangweixun/spring-cloud-master
a780d9ae07ba3c1b03b321d1e7784697a84d250f
242697cdcea24003415350a54d643d4fa90a94f1
refs/heads/master
2022-06-23T18:32:46.434061
2020-01-16T10:01:20
2020-01-16T10:01:20
159,179,475
1
0
null
null
null
null
UTF-8
Java
false
false
1,630
java
package com.cloud.rabbitmq.api.consumer; import com.rabbitmq.client.*; /** * confirm消息确认机制 * 消息的确认是指生产者投递消息后,如果Broker接收到消息,则会给生产者一个应答。 * 生产者进行接收应答,用来确认这条消息是否正常的发送到Broker,这种方式也是消息可靠性投递的核心保障 */ public class Consumer5 { private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("134.175.52.58"); factory.setPort(5672); factory.setVirtualHost("/root"); factory.setPassword("root"); factory.setUsername("root"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicQos(0,1,false); //申明队列 channel.queueDeclare(QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received '" + message + "'"); System.out.println(System.currentTimeMillis()); channel.basicNack(delivery.getEnvelope().getDeliveryTag(),false,true); }; //回调 队列名、是否自动确认信息、回调 channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { }); } }
489a5dcd61d954f2bc4083c0cc2eb3250b26deff
1aaeae6ca0cceabeb8f2aa71fc5fb409f838e227
/xjcloud-provider/xjcloud-provider-audit/src/main/java/gov/pbc/xjcloud/provider/contract/controller/file/ResourceController.java
5f16f3e4dc945b4cbf2f95c28056d799730da1ed
[]
no_license
lizxGitHub/xjcloud-master
e03d7079bd0d262ba8b6f964b2f560589421e1a8
d73c5553c94e6ac133bd1e0b80277ffa34f80dc3
refs/heads/master
2023-06-21T20:40:54.854381
2021-05-31T14:18:40
2021-05-31T14:18:40
231,402,466
0
1
null
2023-06-20T18:32:04
2020-01-02T14:52:34
Java
UTF-8
Java
false
false
3,589
java
package gov.pbc.xjcloud.provider.contract.controller.file; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @RestController @RequestMapping("/${audit.file.uploadPrefix}") @Slf4j public class ResourceController { @Value("${audit.file.uploadFolder}") private String fileRootPath; private int BUFFER_LENGTH=1024; /* 采用SPEL方式来表达路径,以消除不能获取文件扩展名的问题 */ @RequestMapping("/{bizKey}/{name:.+}") public void DownloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable("name") String fileName, @PathVariable("bizKey") String bizKey) { log.debug("the URL is "+request.getRequestURL()); if (isFileValid(bizKey,fileName)) { String downloadFile=fileRootPath+File.separator+bizKey+File.separator+fileName; response.setContentType("application/force-download"); try { response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } FileInputStream inStream=null; BufferedInputStream bufferInStream=null; try { ServletOutputStream outStream=response.getOutputStream(); inStream=new FileInputStream(downloadFile); bufferInStream=new BufferedInputStream(inStream); byte[] buffer=new byte[BUFFER_LENGTH]; int len=-1; while ( (len=bufferInStream.read(buffer))>0) { outStream.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferInStream!=null) { try { bufferInStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (inStream!=null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }else { try { ServletOutputStream outputStream = response.getOutputStream(); response.setHeader("content-Type","text/html;charset=UTF-8"); outputStream.write(new String("文件不存在").getBytes("utf-8")); outputStream.close(); }catch (Exception e){ e.printStackTrace(); } } } protected boolean isFileValid(String bizKey,String fileName) { if (fileName.isEmpty() || fileName==null || fileName.compareTo("")==0) return false; String downloadFile=fileRootPath+File.separator+bizKey+File.separator+fileName; File file = new File(downloadFile); if (file.exists()) return true; else return false; } }
2987a3200c0c3a53ac55e1e763b18efe226ee895
2ab053242399929cca47d682da2f8ea7f773e780
/hetfirsdk/hetwslogsdk/src/main/java/com/het/ws/server/WebSoketServer.java
d2a84d7b717febd25536707b9d13a8448516a7f6
[]
no_license
szhittech/pubcode
73e4743e3c468f3e3beed68c56e175d820646044
cdc274e5f084274776cda066fae63b065938e5ce
refs/heads/master
2020-09-23T16:20:24.845985
2020-04-17T02:23:02
2020-04-17T02:23:02
225,539,574
0
0
null
null
null
null
UTF-8
Java
false
false
3,984
java
package com.het.ws.server; import com.het.ws.util.Logc; import com.het.ws.util.Utils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.InetAddress; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okio.ByteString; public class WebSoketServer { private MockWebServer mockWebServer; private IWebSocketServerState webSocketServerState; public WebSoketServer() { mockWebServer = new MockWebServer(); mockWebServer.enqueue(withWebSocketUpgrade()); mockWebServer.enqueue(withWebSocketUpgrade()); } public void setWebSocketServerState(IWebSocketServerState webSocketServerState) { this.webSocketServerState = webSocketServerState; } public void start(int port) { try { InetAddress ipAddr = Utils.getLocalIpAddress(); mockWebServer.start(ipAddr, port); Logc.i("ws://" + mockWebServer.getHostName() + ":" + mockWebServer.getPort()); } catch (IOException e) { e.printStackTrace(); } } public void start() { start(8081); } private MockResponse withWebSocketUpgrade() { MockResponse response = new MockResponse(); response.withWebSocketUpgrade(new WebSocketListener() { @Override public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { super.onClosed(webSocket, code, reason); Logc.i("onClosed code:" + code + " reason:" + reason); WebSocketClients.getInstance().unregister(webSocket); mockWebServer.enqueue(withWebSocketUpgrade()); if (webSocketServerState != null && !WebSocketClients.getInstance().hasClient()) { webSocketServerState.onClientEmpty(); } } @Override public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { super.onClosing(webSocket, code, reason); Logc.i("onClosing code:" + code + " reason:" + reason); onClosed(webSocket, 1, reason); } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { super.onFailure(webSocket, t, response); Logc.i("throwable:" + t); Logc.i("onFailure response:" + response); onClosed(webSocket, 1, t.getMessage()); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { super.onMessage(webSocket, text); Logc.i("server onMessage"); Logc.i("message:" + text); } @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) { super.onMessage(webSocket, bytes); Logc.i("message:" + bytes.toString()); } @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); Logc.i("onOpen response:" + response); if (webSocketServerState != null && !WebSocketClients.getInstance().hasClient()) { webSocketServerState.onClientTiger(); } WebSocketClients.getInstance().register(webSocket); } }); return response; } public void stop() { if (mockWebServer != null) { try { mockWebServer.close(); } catch (IOException e) { e.printStackTrace(); } mockWebServer = null; } } }
b64244576f9edc182b8091e6354ff02fc458e807
426adf1902b01ce46e46dc275bf259242866ff19
/L4DC_Sem2_DDOOCP/Inheritance/src/inheritance/Result.java
0945f96db6031ece13239714a0a4765769c31092
[]
no_license
BijuAle/softwarica_labs
8381957b0e7de39a47c1c2fc922d0042bbbd71dc
7c6a7065edf825f0793100c3032ef0b5e361c8fd
refs/heads/master
2022-12-24T01:39:14.454602
2020-04-06T12:39:10
2020-04-06T12:39:10
156,977,314
0
0
null
2022-12-10T13:00:13
2018-11-10T12:05:59
Java
UTF-8
Java
false
false
462
java
/* * 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 inheritance; /** * * @author Biju Ale */ public class Result { public static void main(String[] args) { Employee john = new Employee(); john.assignInfo("John", "Kathmandu", 20000); john.displayInfo(); } }
063cfe561242d9743602c185acb7a6f1bb6f69dc
dba87418d2286ce141d81deb947305a0eaf9824f
/sources/kotlinx/coroutines/internal/MissingMainCoroutineDispatcher.java
b9bd6961a4d166eba7ed1e8533a8f2453a402d3d
[]
no_license
Sluckson/copyOavct
1f73f47ce94bb08df44f2ba9f698f2e8589b5cf6
d20597e14411e8607d1d6e93b632d0cd2e8af8cb
refs/heads/main
2023-03-09T12:14:38.824373
2021-02-26T01:38:16
2021-02-26T01:38:16
341,292,450
0
1
null
null
null
null
UTF-8
Java
false
false
7,059
java
package kotlinx.coroutines.internal; import com.lowagie.text.html.Markup; import kotlin.Metadata; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.CoroutineContext; import kotlin.jvm.internal.Intrinsics; import kotlinx.coroutines.CancellableContinuation; import kotlinx.coroutines.Delay; import kotlinx.coroutines.DisposableHandle; import kotlinx.coroutines.MainCoroutineDispatcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Metadata(mo66931bv = {1, 0, 3}, mo66932d1 = {"\u0000X\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0003\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0005\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\t\n\u0002\b\u0002\n\u0002\u0010\u0001\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0002\b\u0002\u0018\u00002\u00020\u00012\u00020\u0002B\u001b\u0012\b\u0010\u0003\u001a\u0004\u0018\u00010\u0004\u0012\n\b\u0002\u0010\u0005\u001a\u0004\u0018\u00010\u0006¢\u0006\u0002\u0010\u0007J\u0019\u0010\u000b\u001a\u00020\f2\u0006\u0010\r\u001a\u00020\u000eH–@ø\u0001\u0000¢\u0006\u0002\u0010\u000fJ\u001c\u0010\u0010\u001a\u00020\u00112\u0006\u0010\u0012\u001a\u00020\u00132\n\u0010\u0014\u001a\u00060\u0015j\u0002`\u0016H\u0016J\u001c\u0010\u0017\u001a\u00020\u00182\u0006\u0010\u0019\u001a\u00020\u000e2\n\u0010\u0014\u001a\u00060\u0015j\u0002`\u0016H\u0016J\u0010\u0010\u001a\u001a\u00020\u001b2\u0006\u0010\u0012\u001a\u00020\u0013H\u0016J\b\u0010\u001c\u001a\u00020\u0011H\u0002J\u001e\u0010\u001d\u001a\u00020\u00112\u0006\u0010\u0019\u001a\u00020\u000e2\f\u0010\u001e\u001a\b\u0012\u0004\u0012\u00020\f0\u001fH\u0016J\b\u0010 \u001a\u00020\u0006H\u0016R\u0010\u0010\u0003\u001a\u0004\u0018\u00010\u0004X‚\u0004¢\u0006\u0002\n\u0000R\u0010\u0010\u0005\u001a\u0004\u0018\u00010\u0006X‚\u0004¢\u0006\u0002\n\u0000R\u0014\u0010\b\u001a\u00020\u00018VX–\u0004¢\u0006\u0006\u001a\u0004\b\t\u0010\n‚\u0002\u0004\n\u0002\b\u0019¨\u0006!"}, mo66933d2 = {"Lkotlinx/coroutines/internal/MissingMainCoroutineDispatcher;", "Lkotlinx/coroutines/MainCoroutineDispatcher;", "Lkotlinx/coroutines/Delay;", "cause", "", "errorHint", "", "(Ljava/lang/Throwable;Ljava/lang/String;)V", "immediate", "getImmediate", "()Lkotlinx/coroutines/MainCoroutineDispatcher;", "delay", "", "time", "", "(JLkotlin/coroutines/Continuation;)Ljava/lang/Object;", "dispatch", "", "context", "Lkotlin/coroutines/CoroutineContext;", "block", "Ljava/lang/Runnable;", "Lkotlinx/coroutines/Runnable;", "invokeOnTimeout", "Lkotlinx/coroutines/DisposableHandle;", "timeMillis", "isDispatchNeeded", "", "missing", "scheduleResumeAfterDelay", "continuation", "Lkotlinx/coroutines/CancellableContinuation;", "toString", "kotlinx-coroutines-core"}, mo66934k = 1, mo66935mv = {1, 1, 15}) /* compiled from: MainDispatchers.kt */ final class MissingMainCoroutineDispatcher extends MainCoroutineDispatcher implements Delay { private final Throwable cause; private final String errorHint; /* JADX INFO: this call moved to the top of the method (can break code semantics) */ public /* synthetic */ MissingMainCoroutineDispatcher(Throwable th, String str, int i, DefaultConstructorMarker defaultConstructorMarker) { this(th, (i & 2) != 0 ? null : str); } public MissingMainCoroutineDispatcher(@Nullable Throwable th, @Nullable String str) { this.cause = th; this.errorHint = str; } @NotNull public MainCoroutineDispatcher getImmediate() { return this; } public boolean isDispatchNeeded(@NotNull CoroutineContext coroutineContext) { Intrinsics.checkParameterIsNotNull(coroutineContext, "context"); missing(); throw null; } @Nullable public Object delay(long j, @NotNull Continuation<? super Unit> continuation) { missing(); throw null; } @NotNull public DisposableHandle invokeOnTimeout(long j, @NotNull Runnable runnable) { Intrinsics.checkParameterIsNotNull(runnable, Markup.CSS_VALUE_BLOCK); missing(); throw null; } @NotNull public Void dispatch(@NotNull CoroutineContext coroutineContext, @NotNull Runnable runnable) { Intrinsics.checkParameterIsNotNull(coroutineContext, "context"); Intrinsics.checkParameterIsNotNull(runnable, Markup.CSS_VALUE_BLOCK); missing(); throw null; } @NotNull public Void scheduleResumeAfterDelay(long j, @NotNull CancellableContinuation<? super Unit> cancellableContinuation) { Intrinsics.checkParameterIsNotNull(cancellableContinuation, "continuation"); missing(); throw null; } /* JADX WARNING: Code restructure failed: missing block: B:5:0x0023, code lost: if (r1 != null) goto L_0x0028; */ /* Code decompiled incorrectly, please refer to instructions dump. */ private final java.lang.Void missing() { /* r4 = this; java.lang.Throwable r0 = r4.cause if (r0 == 0) goto L_0x0039 java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() java.lang.String r1 = "Module with the Main dispatcher had failed to initialize" r0.append(r1) java.lang.String r1 = r4.errorHint if (r1 == 0) goto L_0x0026 java.lang.StringBuilder r2 = new java.lang.StringBuilder r2.<init>() java.lang.String r3 = ". " r2.append(r3) r2.append(r1) java.lang.String r1 = r2.toString() if (r1 == 0) goto L_0x0026 goto L_0x0028 L_0x0026: java.lang.String r1 = "" L_0x0028: r0.append(r1) java.lang.String r0 = r0.toString() java.lang.IllegalStateException r1 = new java.lang.IllegalStateException java.lang.Throwable r2 = r4.cause r1.<init>(r0, r2) java.lang.Throwable r1 = (java.lang.Throwable) r1 throw r1 L_0x0039: java.lang.IllegalStateException r0 = new java.lang.IllegalStateException java.lang.String r1 = "Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'" r0.<init>(r1) java.lang.Throwable r0 = (java.lang.Throwable) r0 throw r0 */ throw new UnsupportedOperationException("Method not decompiled: kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing():java.lang.Void"); } @NotNull public String toString() { String str; StringBuilder sb = new StringBuilder(); sb.append("Main[missing"); if (this.cause != null) { str = ", cause=" + this.cause; } else { str = ""; } sb.append(str); sb.append(']'); return sb.toString(); } }
3da3e6f5958b83e8c7c467ea9e941fce6d52bccc
b16ad5c27d52acae46db64ba83b07176003b1919
/smart-admin-service/smart-admin-api/src/main/java/net/lab1024/smartadmin/module/system/datascope/strategy/DataScopePowerStrategy.java
d12cbf15bf61753c28977cb90ef72a61da5bc1f7
[ "MIT" ]
permissive
zifeiyu0531/smart-admin
ffb9fea1194daee8d634fa8451737a66b6ad83d7
9fb2da648ff1dd1ec284b84571a74f23b339bccc
refs/heads/master
2023-07-31T09:46:22.195122
2021-09-22T11:19:55
2021-09-22T11:19:55
388,366,509
0
0
MIT
2021-09-22T11:19:56
2021-07-22T07:20:22
null
UTF-8
Java
false
false
842
java
package net.lab1024.smartadmin.module.system.datascope.strategy; import net.lab1024.smartadmin.module.system.datascope.constant.DataScopeViewTypeEnum; import net.lab1024.smartadmin.module.system.datascope.domain.dto.DataScopeSqlConfigDTO; /** * [ 数据范围策略 ,使用DataScopeWhereInTypeEnum.CUSTOM_STRATEGY类型,DataScope注解的joinSql属性无用] * * @author yandanyang * @version 1.0 * @company 1024lab.net * @copyright (c) 2018 1024lab.netInc. All rights reserved. * @date 2020/11/28 0008 下午 16:00 * @since JDK1.8 */ public abstract class DataScopePowerStrategy { /** * 获取joinsql 字符串 * @param viewTypeEnum 查看的类型 * @param sqlConfigDTO * @return */ public abstract String getCondition(DataScopeViewTypeEnum viewTypeEnum, DataScopeSqlConfigDTO sqlConfigDTO); }
6c757563885bf45b8776dd5e850767d96cc4cd41
c717554b49b82fc1986f8e4d5963ec33932476ee
/src/main/java/com/backend/contacts/BackEndContactsApplication.java
d37023e35c9e9db05ef720476fc1f77381897a66
[]
no_license
elizondo1288/backEndSpring
a58cd50056bb5849463c53b5a3cf6c2b28a7f3c6
b2faf9d141793f9c5a66f68524d7e48d54967596
refs/heads/master
2016-09-06T01:23:47.508594
2015-06-16T19:51:17
2015-06-16T19:51:17
37,291,312
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.backend.contacts; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackEndContactsApplication { public static void main(String[] args) { SpringApplication.run(BackEndContactsApplication.class, args); } }
0f04f744f089617f05f3c13d1ba0a78819197eeb
1bebb1ae0f503b1befe253978f2d7002253e85d7
/saripaar/src/main/java/commons/validator/routines/UrlValidator.java
4bbaf43f999d3c44103cccf9c559fbef67955bee
[ "Apache-2.0" ]
permissive
bayan1987/android-saripaar
85d2d9b6e405c7c3e2d8afea2aa4b53c3cc63f3e
bf6ef53b4d7037ae4b1f6626480a725792f49ab2
refs/heads/master
2021-01-24T15:33:11.761587
2014-12-09T08:00:46
2014-12-09T08:00:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,727
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package commons.validator.routines; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p><b>URL Validation</b> routines.</p> * Behavior of validation is modified by passing in options: * <li>ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path * component.</li> * <li>NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is * included then fragments are flagged as illegal.</li> * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are * considered valid schemes. Enabling this option will let any scheme pass validation.</li> * <p/> * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02, * http://javascript.internet.com. However, this validation now bears little resemblance * to the php original.</p> * <pre> * Example of usage: * Construct a UrlValidator with valid schemes of "http", and "https". * * String[] schemes = {"http","https"}. * UrlValidator urlValidator = new UrlValidator(schemes); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { * System.out.println("url is invalid"); * } * * prints "url is invalid" * If instead the default constructor is used. * * UrlValidator urlValidator = new UrlValidator(); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { * System.out.println("url is invalid"); * } * * prints out "url is valid" * </pre> * * @see <a href="http://www.ietf.org/rfc/rfc2396.txt"> * Uniform Resource Identifiers (URI): Generic Syntax * </a> * @since Validator 1.4 */ public class UrlValidator { /** * Allows all validly formatted schemes to pass validation instead of * supplying a set of valid schemes. */ public static final long ALLOW_ALL_SCHEMES = 1 << 0; /** * Allow two slashes in the path component of the URL. */ public static final long ALLOW_2_SLASHES = 1 << 1; /** * Enabling this options disallows any URL fragments. */ public static final long NO_FRAGMENTS = 1 << 2; /** * Allow local URLs, such as http://localhost/ or http://machine/ . * This enables a broad-brush check, for complex local machine name * validation requirements you should create your validator with * a {@link RegexValidator} instead ({@link #UrlValidator(RegexValidator, long)}) */ public static final long ALLOW_LOCAL_URLS = 1 << 3; // Drop numeric, and "+-." for now private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\."; /** * This expression derived/taken from the BNF for URI (RFC2396). */ private static final String URL_REGEX = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"; // 12 3 4 5 6 7 8 9 private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); /** * Schema/Protocol (ie. http:, ftp:, file:, etc). */ private static final int PARSE_URL_SCHEME = 2; /** * Includes hostname/ip and port number. */ private static final int PARSE_URL_AUTHORITY = 4; private static final int PARSE_URL_PATH = 5; private static final int PARSE_URL_QUERY = 7; private static final int PARSE_URL_FRAGMENT = 9; /** * Protocol (ie. http:, ftp:,https:). */ private static final String SCHEME_REGEX = "^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*"; private static final Pattern SCHEME_PATTERN = Pattern.compile(SCHEME_REGEX); private static final String AUTHORITY_REGEX = "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?"; // 1 2 3 4 private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX); private static final int PARSE_AUTHORITY_HOST_IP = 1; private static final int PARSE_AUTHORITY_PORT = 2; /** * Should always be empty. */ private static final int PARSE_AUTHORITY_EXTRA = 3; private static final String PATH_REGEX = "^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$"; private static final Pattern PATH_PATTERN = Pattern.compile(PATH_REGEX); private static final String QUERY_REGEX = "^(.*)$"; private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX); private static final String LEGAL_ASCII_REGEX = "^\\p{ASCII}+$"; private static final Pattern ASCII_PATTERN = Pattern.compile(LEGAL_ASCII_REGEX); private static final String PORT_REGEX = "^:(\\d{1,5})$"; private static final Pattern PORT_PATTERN = Pattern.compile(PORT_REGEX); /** * Holds the set of current validation options. */ private final long options; /** * The set of schemes that are allowed to be in a URL. */ private final Set allowedSchemes; /** * Regular expressions used to manually validate authorities if IANA * domain name validation isn't desired. */ private final RegexValidator authorityValidator; /** * If no schemes are provided, default to this set. */ private static final String[] DEFAULT_SCHEMES = {"http", "https", "ftp"}; /** * Singleton instance of this class with default schemes and options. */ private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator(); /** * Returns the singleton instance of this class with default schemes and options. * * @return singleton instance with default schemes and options */ public static UrlValidator getInstance() { return DEFAULT_URL_VALIDATOR; } /** * Create a UrlValidator with default properties. */ public UrlValidator() { this(null); } /** * Behavior of validation is modified by passing in several strings options: * * @param schemes Pass in one or more url schemes to consider valid, passing in * a null will default to "http,https,ftp" being valid. * If a non-null schemes is specified then all valid schemes must * be specified. Setting the ALLOW_ALL_SCHEMES option will * ignore the contents of schemes. */ public UrlValidator(String[] schemes) { this(schemes, 0L); } /** * Initialize a UrlValidator with the given validation options. * * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(long options) { this(null, null, options); } /** * Behavior of validation is modified by passing in options: * * @param schemes The set of valid schemes. * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(String[] schemes, long options) { this(schemes, null, options); } /** * Initialize a UrlValidator with the given validation options. * * @param authorityValidator Regular expression validator used to validate the authority part * @param options Validation options. Set using the public constants of this class. * To set multiple options, simply add them together: * <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p> * enables both of those options. */ public UrlValidator(RegexValidator authorityValidator, long options) { this(null, authorityValidator, options); } /** * Customizable constructor. Validation behavior is modifed by passing in options. * * @param schemes the set of valid schemes * @param authorityValidator Regular expression validator used to validate the authority part * @param options Validation options. Set using the public constants of this class. * To set multiple options, simply add them together: * <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p> * enables both of those options. */ public UrlValidator(String[] schemes, RegexValidator authorityValidator, long options) { this.options = options; if (isOn(ALLOW_ALL_SCHEMES)) { this.allowedSchemes = Collections.EMPTY_SET; } else { if (schemes == null) { schemes = DEFAULT_SCHEMES; } this.allowedSchemes = new HashSet(); this.allowedSchemes.addAll(Arrays.asList(schemes)); } this.authorityValidator = authorityValidator; } /** * <p>Checks if a field has a valid url address.</p> * * @param value The value validation is being performed on. A <code>null</code> * value is considered invalid. * @return true if the url is valid. */ public boolean isValid(String value) { if (value == null) { return false; } if (!ASCII_PATTERN.matcher(value).matches()) { return false; } // Check the whole url address structure Matcher urlMatcher = URL_PATTERN.matcher(value); if (!urlMatcher.matches()) { return false; } String scheme = urlMatcher.group(PARSE_URL_SCHEME); if (!isValidScheme(scheme)) { return false; } String authority = urlMatcher.group(PARSE_URL_AUTHORITY); if ("file".equals(scheme) && "".equals(authority)) { // Special case - file: allows an empty authority } else { // Validate the authority if (!isValidAuthority(authority)) { return false; } } if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) { return false; } if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) { return false; } if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) { return false; } return true; } /** * Validate scheme. If schemes[] was initialized to a non null, * then only those scheme's are allowed. Note this is slightly different * than for the constructor. * * @param scheme The scheme to validate. A <code>null</code> value is considered * invalid. * @return true if valid. */ protected boolean isValidScheme(String scheme) { if (scheme == null) { return false; } if (!SCHEME_PATTERN.matcher(scheme).matches()) { return false; } if (isOff(ALLOW_ALL_SCHEMES)) { if (!this.allowedSchemes.contains(scheme)) { return false; } } return true; } /** * Returns true if the authority is properly formatted. An authority is the combination * of hostname and port. A <code>null</code> authority value is considered invalid. * * @param authority Authority value to validate. * @return true if authority (hostname and port) is valid. */ protected boolean isValidAuthority(String authority) { if (authority == null) { return false; } // check manual authority validation if specified if (authorityValidator != null) { if (authorityValidator.isValid(authority)) { return true; } } Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority); if (!authorityMatcher.matches()) { return false; } String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP); // check if authority is hostname or IP address: // try a hostname first since that's much more likely DomainValidator domainValidator = DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS)); if (!domainValidator.isValid(hostLocation)) { // try an IP address InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); if (!inetAddressValidator.isValid(hostLocation)) { // isn't either one, so the URL is invalid return false; } } String port = authorityMatcher.group(PARSE_AUTHORITY_PORT); if (port != null) { if (!PORT_PATTERN.matcher(port).matches()) { return false; } } String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA); if (extra != null && extra.trim().length() > 0) { return false; } return true; } /** * Returns true if the path is valid. A <code>null</code> value is considered invalid. * * @param path Path value to validate. * @return true if path is valid. */ protected boolean isValidPath(String path) { if (path == null) { return false; } if (!PATH_PATTERN.matcher(path).matches()) { return false; } int slash2Count = countToken("//", path); if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) { return false; } int slashCount = countToken("/", path); int dot2Count = countToken("..", path); if (dot2Count > 0) { if ((slashCount - slash2Count - 1) <= dot2Count) { return false; } } return true; } /** * Returns true if the query is null or it's a properly formatted query string. * * @param query Query value to validate. * @return true if query is valid. */ protected boolean isValidQuery(String query) { if (query == null) { return true; } return QUERY_PATTERN.matcher(query).matches(); } /** * Returns true if the given fragment is null or fragments are allowed. * * @param fragment Fragment value to validate. * @return true if fragment is valid. */ protected boolean isValidFragment(String fragment) { if (fragment == null) { return true; } return isOff(NO_FRAGMENTS); } /** * Returns the number of times the token appears in the target. * * @param token Token value to be counted. * @param target Target value to count tokens in. * @return the number of tokens. */ protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; } /** * Tests whether the given flag is on. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is on. * * @param flag Flag value to check. * @return whether the specified flag value is on. */ private boolean isOn(long flag) { return (this.options & flag) > 0; } /** * Tests whether the given flag is off. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is off. * * @param flag Flag value to check. * @return whether the specified flag value is off. */ private boolean isOff(long flag) { return (this.options & flag) == 0; } }
58a82f71007891b7261a654c68874efd5e9175b0
571ce46236afb5d836b713c5f3cc165db5d2ae77
/packages/apps/PrizeGalleryV8/src/com/prize/sticker/Utils.java
9430565ae09d32738add8697408272cdd12734f2
[]
no_license
sengeiou/prize
d6f56746ba82e0bbdaa47b5bea493ceddb0abd0c
e27911e194c604bf651f7bed0f5f9ce8f7dc8d4d
refs/heads/master
2020-04-28T04:45:42.207852
2018-11-23T13:50:20
2018-11-23T13:50:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,376
java
/*** * function:watermark * author: wanzhijuan * date: 2016-1-21 */ package com.prize.sticker; import android.app.Activity; import android.content.Context; import android.graphics.Point; import android.view.WindowManager; /** * Created by yangchen on 15-9-10. */ public class Utils { private static Point point = null; public static Point getDisplayWidthPixels(Context context) { if (point != null) { return point; } WindowManager wm = ((Activity)context).getWindowManager(); point = new Point(); wm.getDefaultDisplay().getSize(point); return point; } /** * 计算两点之间的距离 * @param x1 * @param y1 * @param x2 * @param y2 * @return */ public static double lineSpace(double x1, double y1, double x2, double y2) { double lineLength = 0; double x, y; x = x1 - x2; y = y1 - y2; lineLength = Math.sqrt(x * x + y * y); return lineLength; } /** * 获取线段中点坐标 * @param x1 * @param y1 * @param x2 * @param y2 * @return */ public static PointD getMidpointCoordinate(double x1, double y1, double x2, double y2) { PointD midpoint = new PointD(); midpoint.set((x1 + x2) / 2, (y1 + y2) / 2); return midpoint; } }
48175e9d1895eec73ce2f470485f633c71434684
ffe0abd3105cd91c676f0cd404ffcb58ed862fae
/src/main/java/com/sachin/cricket/dao/MatchDAO.java
d677fbf39d91a232722eee878b81eed1bbb27ed9
[]
no_license
Ksachin1997/cricket_backend
3d0718b40af8382c397f3643bfe22d80d063beb1
f90e1d91e4bc3b869e5fddbe987c57a348cbd299
refs/heads/master
2023-01-12T07:54:30.673612
2020-11-16T19:26:48
2020-11-16T19:26:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
211
java
package com.sachin.cricket.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.sachin.cricket.entities.Matches; public interface MatchDAO extends JpaRepository<Matches, Integer>{ }
bcd170f3a52aa1b9ef0a6ee46e4bca44ae1f7a9f
a4c8d21c22f7eec1fc28c4815f7a783cf7b66aba
/InputCode/InputCode.java
028b5ffe4f9a653e6a23f8bdf389ca3f773a5233
[]
no_license
WangxiOpenSourceTeam/workspace_java
ae06794408ba236b1eae6e50bbd52435786667be
d1e1fa9301a96dfbc6eb02eb86d13586112812e8
refs/heads/master
2021-07-11T21:34:54.309409
2021-04-01T09:59:56
2021-04-01T09:59:56
231,689,388
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
import java.util.Scanner; public class InputCode { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); String line = scanner.nextLine(); System.out.println("你输入的是" + line); } }
9aa173d7007e1e7ccaebe8cee391846586fe310d
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5706278382862336_1/java/AlexTolstov/A.java
9727c93bed12d345021ac75791b624945971de74
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Java
false
false
1,651
java
import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class A { private static final String path = "/home/tolstov.a.a/codejam/a/"; private static final String problem = "A-large"; Scanner in; PrintWriter out; long gcd(long a, long b) { if (a % b == 0) { return b; } else { return gcd(b, a % b); } } void solveOne() { String str = in.next(); long first = Long.parseLong(str.substring(0, str.indexOf('/'))); long second = Long.parseLong(str.substring(str.indexOf('/') + 1)); if (second == 0 && first == 0) { out.print("impossible"); return; } long div = gcd(first, second); first /= div; second /= div; boolean isGood = false; for (long p = 0; p <= 62; p++) { if (second == (1L << p)) { isGood = true; break; } } if (!isGood || first > second) { out.print("impossible"); return; } int level = 1; while (first * 2L < second) { first *= 2L; level++; } if (level > 40) { out.println("impossible"); return; } out.print(level); } void solve() { int nTests = in.nextInt(); for (int i = 1; i <= nTests; i++) { out.print("Case #" + i + ": "); solveOne(); out.println(); } } void run() { try { in = new Scanner(new FileReader(path + problem + ".in")); out = new PrintWriter(path + problem + ".out1"); } catch (IOException e) { in = new Scanner(System.in); out = new PrintWriter(System.out); out.println("cmd>"); out.flush(); } try { solve(); } finally { out.close(); } } public static void main(String[] args) { new A().run(); } }
4f3ca8cc0a29103df049dd03e279ae155f89654a
8ac74b2c9786a8a4377899c7bd8bc9585334d7aa
/src/main/java/com/mgrapp/GrzegorzDawidek/mgrapp/web/UserRegistrationController.java
4dc630407d465e35a4265a20beddf8b2a0bef749
[]
no_license
GrzegorzDawidek/Wypozyczalnia
76fe3dd835a342f44ba2645eb8116201de5186f9
d52686eb3b2ef3931f3e49fe900fd0048e740824
refs/heads/master
2023-02-09T05:46:56.848020
2021-01-07T16:10:58
2021-01-07T16:10:58
327,662,037
0
0
null
null
null
null
UTF-8
Java
false
false
1,180
java
package com.mgrapp.GrzegorzDawidek.mgrapp.web; import com.mgrapp.GrzegorzDawidek.mgrapp.model.dto.UserRegistrationDto; import com.mgrapp.GrzegorzDawidek.mgrapp.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/registration") public class UserRegistrationController { private UserService userService; public UserRegistrationController(UserService userService) { super(); this.userService = userService; } @ModelAttribute("user") public UserRegistrationDto userRegistrationDto() { return new UserRegistrationDto(); } @GetMapping public String showRegistrationForm() { return "registration"; } @PostMapping public String registerUserAccount(@ModelAttribute("user") UserRegistrationDto registrationDto) { userService.save(registrationDto); return "redirect:/registration?success"; } }
a0fec80b0c018c7d121a3cb91a24780d182f6277
9630c7c54e36bf6f1e5f6921f0890f9725f972b9
/src/main/java/com/jxf/pay/service/impl/WxPayServiceImpl.java
92a4ea1d9c1b93252be9e3f93b3e39b3084e53c2
[]
no_license
happyjianguo/wyjt
df1539f6227ff38b7b7990fb0c56d20105d9c0b1
a5de0f17db2e5e7baf25ea72159e100c656920ea
refs/heads/master
2022-11-18T01:16:29.783973
2020-07-14T10:32:42
2020-07-14T10:32:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,144
java
/** * @文件名称: WXPayServiceImpl.java * @类路径: com.jxf.pay.service.impl * @描述: TODO * @作者:李新 * @时间:2016年8月10日 上午10:18:59 * @版本:V1.0 */ package com.jxf.pay.service.impl; import java.net.ConnectException; import java.text.ParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jxf.pay.entity.UnifiedOrder; import com.jxf.pay.service.WxPayService; import com.jxf.payment.entity.Payment; import com.jxf.payment.entity.Payment.Status; import com.jxf.payment.service.PaymentService; import com.jxf.svc.config.Global; import com.jxf.svc.plugin.PluginConfig; import com.jxf.svc.plugin.weixinPayment.WxPaymentPlugin; import com.jxf.svc.utils.DateUtils; import com.jxf.svc.utils.HttpsRequest; import com.jxf.svc.utils.MD5Code; import com.jxf.svc.utils.StringUtils; import com.jxf.svc.utils.XMLParser; import com.jxf.wx.account.entity.WxAccount; /** * 支付相关API * * @author lixin * @since 1.2 */ @Service("wxPayService") public class WxPayServiceImpl implements WxPayService { @Autowired private PaymentService paymentService; @Autowired private WxPaymentPlugin wxPaymentPlugin; protected Logger log = LoggerFactory.getLogger(getClass()); /** * 统一下单 * * @param payment 支付对象 * @return 调用结果 */ @Override public Map<String, String> payUnifiedOrder(Payment payment,WxAccount wxAccount) { log.debug("微信统一支付接口....."); Map<String, String> paySignMap=new HashMap<>(); try { String unifiedOrderRsp = new HttpsRequest().sendPost(payment.getRequestUrl(),UnifiedOrderReqXmlObj(payment,wxAccount),payment.getMchId(),Global.getConfig("cert.key")); Map<String, String> unifiedOrderRspMap = XMLParser.readStringXmlOut(unifiedOrderRsp); log.debug("微信统一支付接口返回:{}",unifiedOrderRspMap.toString()); String return_code = unifiedOrderRspMap.get("return_code"); if(StringUtils.isNotBlank(return_code) && return_code.equals("SUCCESS")){ String result_code = unifiedOrderRspMap.get("result_code"); if(StringUtils.isNotBlank(result_code) && StringUtils.equals(result_code, "SUCCESS")) { log.debug("微信统一支付提交成功、生成JS签名数据"); paySignMap = unifiedOrderToJsPaySignInfo(unifiedOrderRspMap,wxAccount,payment.getKey()); payment.setPayId(unifiedOrderRspMap.get("prepay_id")); }else { String err_code = unifiedOrderRspMap.get("err_code"); String err_code_des = unifiedOrderRspMap.get("err_code_des"); log.error("paymentId:{},微信支付单预支付请求:result_code:{},error_code:{},err_code_des:{}",payment.getId(),result_code,err_code,err_code_des); paySignMap.put("result_code", result_code); paySignMap.put("err_code", err_code); paySignMap.put("err_code_des", err_code_des); } }else{ log.error("微信统一支付提交出错{}!",return_code); } } catch (ConnectException ce) { log.error("连接超时:"+ce.getMessage()); } catch (Exception e) { log.error("https请求异常:"+e.getMessage()); } return paySignMap; } //统一下单参数整理 private UnifiedOrder UnifiedOrderReqXmlObj(Payment payment,WxAccount wxAccount) { UnifiedOrder unifiedOrder =new UnifiedOrder(); String appId = wxAccount.getAppid(); String appName = wxAccount.getName(); log.info("/////////////////////-APPID-////////////////:" + appId); log.info("/////////////////////-openid-////////////////:" + payment.getOpenID()); unifiedOrder.setAppid(appId); unifiedOrder.setMch_id(payment.getMchId()); unifiedOrder.setNonce_str(StringUtils.getRandomStringByLength(32)); unifiedOrder.setBody(appName+"-微信支付"); unifiedOrder.setOut_trade_no(payment.getPaymentNo()); unifiedOrder.setTotal_fee(StringUtils.StrTOInt(payment.getPaymentAmount().toString())); unifiedOrder.setSpbill_create_ip(payment.getRemoteAddr()); unifiedOrder.setNotify_url(payment.getNotifyUrl()); unifiedOrder.setTrade_type("JSAPI"); unifiedOrder.setOpenid(payment.getOpenID()); //签名 String signTemp = "appid="+unifiedOrder.getAppid() +"&body="+unifiedOrder.getBody() +"&mch_id="+unifiedOrder.getMch_id() +"&nonce_str="+unifiedOrder.getNonce_str() +"&notify_url="+unifiedOrder.getNotify_url() +"&openid="+unifiedOrder.getOpenid() +"&out_trade_no="+unifiedOrder.getOut_trade_no() +"&spbill_create_ip="+unifiedOrder.getSpbill_create_ip() +"&total_fee="+unifiedOrder.getTotal_fee() +"&trade_type="+unifiedOrder.getTrade_type() +"&key="+payment.getKey(); //商户号对应的秘钥 log.debug("签名字符串={}",signTemp); String characterEncoding = "UTF-8"; String sign=MD5Code.MD5Encode(signTemp, characterEncoding).toUpperCase(); log.debug("签名后的值"+sign); unifiedOrder.setSign(sign); return unifiedOrder; } //统一支付结果转JS支付签名信息 private Map<String, String> unifiedOrderToJsPaySignInfo(Map<String, String> unifiedOrderRspMap,WxAccount wxAccount,String key) throws ParseException { Map<String, String> paySignMap = new HashMap<>(); String appId = wxAccount.getAppid(); paySignMap.put("appId", appId); paySignMap.put("timeStamp", DateUtils.calLastedTime()+""); paySignMap.put("nonceStr", StringUtils.getRandomStringByLength(32)); paySignMap.put("package", "prepay_id="+unifiedOrderRspMap.get("prepay_id")); paySignMap.put("signType", "MD5"); //签名 String signTemp = "appId="+paySignMap.get("appId") +"&nonceStr="+paySignMap.get("nonceStr") +"&package="+paySignMap.get("package") +"&signType=MD5" +"&timeStamp="+paySignMap.get("timeStamp") +"&key="+key; //商户号对应的秘钥 log.debug("签名字符串={}",signTemp); String paySign=MD5Code.MD5Encode(signTemp, "UTF-8").toUpperCase(); log.debug("签名后的值"+paySign); paySignMap.put("paySign", paySign); return paySignMap; } //微信支付结果回调方法 @Override public boolean wxNotifyProcess(HttpServletRequest request) { log.info("============微信支付异步返回==========="); // 获取微信POST过来反馈信息 String inputLine; String notityXml = ""; try { while ((inputLine = request.getReader().readLine()) != null) { notityXml += inputLine; } request.getReader().close(); } catch (Exception e) { log.error("xml获取失败:" + e); } log.debug("收到微信异步回调:{}",notityXml); if(StringUtils.isEmpty(notityXml)){ log.error("xml为空:"); } Map<String, String> result = new HashMap<>(); result = XMLParser.readStringXmlOut(notityXml); String paymentNo = result.get("out_trade_no"); String thirdPaymentNo = result.get("transaction_id"); String respCode = result.get("return_code"); String respMsg = result.get("return_msg"); String resultCode = result.get("result_code"); log.info("响应支付单:[{}]",paymentNo); log.info("respCode:[{}]",respCode); log.info("respMsg:[{}]",respMsg); Payment payment= paymentService.getByPaymentNo(paymentNo); if(Payment.Status.success.equals(payment.getStatus())){//去重处理 log.info("=========该支付单已经成功========"); return true; } if(StringUtils.equals("SUCCESS", respCode)){ log.info("=========微信支付通讯成功========="); if(checkIsSignValidFromResponse(wxPaymentPlugin,result)) { log.info("=========签名验证成功========="); if(StringUtils.equals("SUCCESS", resultCode)){ log.info("=========交易结果验证成功========="); payment.setStatus(Payment.Status.success); payment.setRespCode(respCode); payment.setRespMsg(respMsg); payment.setThirdPaymentNo(thirdPaymentNo); paymentService.payFinishProcess(payment); return true; }else { tradeProcessByFailureStatus(Payment.Status.failure,payment,respCode,respMsg); log.error("=========微信支付交易失败========="); return false; } }else { tradeProcessByFailureStatus(Payment.Status.failure,payment,respCode,respMsg); log.error("=========微信支付签名不合法========="); return false; } }else{ tradeProcessByFailureStatus(Payment.Status.failure,payment,respCode,respMsg); log.error("=========微信支付通讯失败========="); return false; } } /** * 微信支付失败 统一处理 * @param failure * @param payment * @param respCode * @param respMsg */ private void tradeProcessByFailureStatus(Status failure, Payment payment, String respCode, String respMsg) { payment.setStatus(Payment.Status.failure); payment.setRespCode(respCode); payment.setRespMsg(respMsg); paymentService.payFinishProcess(payment); } /** * 验证签名 * @param wxPaymentPlugin * @param payment * @param result * @return 验证通过返回true */ private boolean checkIsSignValidFromResponse(WxPaymentPlugin wxPaymentPlugin, Map<String, String> result) { //获取商户秘钥 PluginConfig config = wxPaymentPlugin.getPluginConfig(); Map<String,String> configAttr = config.getAttributeMap(); String key = configAttr.get(WxPaymentPlugin.PAYMENT_KEY_ATTRIBUTE_NAME); if (!(result instanceof SortedMap<?,?>)) { result = new TreeMap<String, String>(result); } //服务端按照签名方式生成签名与返回签名进行比对 StringBuffer signTemp = new StringBuffer(); Iterator<String> it = result.keySet().iterator(); while(it.hasNext()) { String paramName = it.next(); String paramValue = result.get(paramName); if(paramValue!=null&&!"".equals(paramValue)&&!"sign".equals(paramName)) { signTemp.append(paramName+"="+paramValue+"&"); } } signTemp.append("key="+key); log.debug("签名字符串={}",signTemp); String characterEncoding = "UTF-8"; String sign=MD5Code.MD5Encode(signTemp.toString(), characterEncoding).toUpperCase(); log.debug("服务端生成的签名========"+sign); String returnSign = result.get("sign"); log.debug("返回的签名========"+returnSign); return sign.equals(returnSign); } }
0d78cae8d427e290643f6cd1853b7a09200779fc
17fa67968a156d574815723f649a06ee2b654741
/src/main/java/com/springbootproject/test/controller/BookController_3.java
9651acede88e079b3256662c885f90cf99b4b614
[]
no_license
coolshadan786/SpringBoot-Project1
9e09fd0470d628e11bf8d8124a6ae3ee27e3e408
f9906369e6088d79e2188d5d96074ca806901b27
refs/heads/main
2023-03-04T08:59:48.503917
2021-02-16T13:24:04
2021-02-16T13:24:04
339,404,109
0
0
null
null
null
null
UTF-8
Java
false
false
4,503
java
package com.springbootproject.test.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.springbootproject.test.entities.Book_3; import com.springbootproject.test.services.BookServices_3; @RestController public class BookController_3 { @Autowired private BookServices_3 bookServices_3; // @RequestMapping(value = "/books", method = RequestMethod.GET) // @ResponseBody //Use if we have a String type value in controller @GetMapping("/bAA") // Use as same as like but it has @RequestMapping by default get method Https type for sending data public String getBooks() { return "This is testing book.first"; } /* * //get All books handler //Using Simple return Book obj without try/catch and * ResponseEntity<T> * * @GetMapping("/books1") // Use as same as like but it has @RequestMapping by * public List<Book_3> getBooks1() { * * return this.bookServices_3.getAllBooks(); } */ // get All books handler //Using return ResponseEntity<Book> obj with try/catch // block data for error handling @GetMapping("/booksAA") // Use as same as like but it has @RequestMapping by public ResponseEntity<List<Book_3>> getBooks1() { List<Book_3> list = this.bookServices_3.getAllBooks(); if (list.size() <= 0) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } return ResponseEntity.status(HttpStatus.CREATED).body(list); } /* * //get single books handler //Using Simple return Book obj without try/catch * and ResponseEntity<T> * * @GetMapping("/bookas/{id}") public Book getSingleBook(@PathVariable("id") int * id) { return bookServices_2.getBookByID(id); } */ // get single books handler @GetMapping("/bookCC/{id}") // Using return ResponseEntity<Book> obj with try/catch block data for error handling public ResponseEntity<Book_3> getSingleBook(@PathVariable("id") int id) { Book_3 book = bookServices_3.getBookByID(id); if (book == null) { return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).build(); } return ResponseEntity.of(Optional.of(book)); } // Add new book handler @PostMapping("/booksDD") // Using return ResponseEntity<Book> obj with try/catch block data for error handling public ResponseEntity<Book_3> addBook(@RequestBody Book_3 book) { Book_3 b = null; try { b = this.bookServices_3.addBook(book); System.out.println(book); return ResponseEntity.of(Optional.of(b)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } // Delete new book handler @DeleteMapping("/bookEE/{bookId}") // Using return ResponseEntity<Book> obj with try/catch block data for error handling public ResponseEntity<Void> deleteBook(@PathVariable("bookId") int bookId) { try { this.bookServices_3.deleteBook(bookId); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } /* * /Update book handler //Using Simple return Book obj without try/catch and * ResponseEntity<T> * * @PutMapping("/bookFF/{bookId}") /public Book_2 * updateBook(@PathVariable("bookId") int bookId, @RequestBody Book_2 book) { * this.bookServices_3.updateBook(book, bookId); return book; } */ // Update book handler @PutMapping("/bookGG/{bookId}") // Using return ResponseEntity<Book> obj with try/catch block data for error handling public ResponseEntity<Book_3> updateBook(@PathVariable("bookId") int bookId, @RequestBody Book_3 book) { try { this.bookServices_3.updateBook(book, bookId); return ResponseEntity.ok().body(book); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
7e74828fa3b5dbfbbbe8e6e4358e13e30975f58f
75f067d7d62a56f78ddc3f3feb862de968bad6ed
/ICINBank/src/main/java/com/servlets/DepositServlet.java
7eee8ae559b6a7d8140fc882bc6f15744e81eb69
[]
no_license
preethigaM/ICINBank
636899b34dbe023bcb3141134cb37528c9cb2b95
8646d5964916c231a207f7b18dc56583ae10e296
refs/heads/master
2023-04-23T06:42:33.288189
2021-05-14T15:09:07
2021-05-14T15:09:07
367,397,959
0
0
null
null
null
null
UTF-8
Java
false
false
2,975
java
package com.servlets; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.connector.Connector; public class DepositServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = (String)(request.getParameter("username")); long millis=System.currentTimeMillis(); java.sql.Date date=new java.sql.Date(millis); String accNo = (String)(request.getParameter("accountNo")); String type = (String)(request.getParameter("type")); int amount = Integer.parseInt(request.getParameter("amount")); String balance1="0"; if(type.equals("primary")) { try{ Connection con = Connector.getCon(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select primaryBalance from icinbank.users where username = '"+username+"'"); while(rs.next()) { balance1 = rs.getString(1); System.out.println(balance1); } } catch(Exception e) { System.out.println(e); } } else if(type.equals("savings")) { try{ Connection con = Connector.getCon(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select savingsBalance from icinbank.users where username = '"+username+"'"); while(rs.next()) { balance1 = rs.getString(1); System.out.println(balance1); } } catch(Exception e) { System.out.println(e); } } int balance = Integer.parseInt(balance1); balance += amount; String sql = "insert into icinbank.transaction(username, date, payeeAccNo, accountType, debit, credit, balance) values(?,?,?,?,?,?,?)"; try { Connection con = Connector.getCon(); PreparedStatement st = con.prepareStatement(sql); st.setString(1, username); st.setDate(2, date); st.setString(3, accNo); st.setString(4, type); st.setInt(5, 0); st.setInt(6, amount); st.setInt(7, balance); st.executeUpdate(); if(type.equals("primary")) st.executeUpdate("update users set primaryBalance = '"+balance+"' where username = '"+username+"'"); if(type.equals("savings")) st.executeUpdate("update users set savingsBalance = '"+balance+"' where username = '"+username+"'"); st.close(); response.sendRedirect("deposit.jsp?msg=done"); } catch(Exception e) { response.sendRedirect("deposit.jsp?msg=error"); System.out.print(e); } } }
[ "Muralidharan@LAPTOP-HOUQ98C1" ]
Muralidharan@LAPTOP-HOUQ98C1
0fe2e228a2e4ab0d096eb90c49542f1429405630
8c818abbf228050ae3e531a609705433ab7f01c1
/src/com/useful/useful/UsefulCommandExecutor.java
5129d0e1152de903832315602c16aa71a29dfb47
[]
no_license
storm345dev/useful
9c013c739a15c671d1283433f600a5fc0dd3f381
304813f4ba9593d28c91f9628dfe43df7b0adacf
refs/heads/master
2021-01-10T20:32:14.720038
2013-11-25T19:36:49
2013-11-25T19:36:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
220,321
java
package com.useful.useful; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.management.ManagementFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect.Type; import org.bukkit.GameMode; import org.bukkit.Instrument; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Note; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.NoteBlock; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.conversations.Conversation; import org.bukkit.conversations.ConversationFactory; import org.bukkit.conversations.Prompt; import org.bukkit.conversations.StringPrompt; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.potion.Potion; import org.bukkit.potion.PotionType; import org.bukkit.util.ChatPaginator; import org.bukkit.util.ChatPaginator.ChatPage; import com.useful.useful.utils.Builder; import com.useful.useful.utils.ClosestFace; import com.useful.useful.utils.ColoredLogger; import com.useful.useful.utils.Copier; import com.useful.useful.utils.Entities; import com.useful.useful.utils.ItemRename; import com.useful.useful.utils.JailInfo; import com.useful.useful.utils.ListStore; import com.useful.useful.utils.Performance; import com.useful.useful.utils.Potions; import com.useful.useful.utils.TeleportRequest; import com.useful.useful.utils.TpaReq; import com.useful.useful.utils.UConnectDataRequest; import com.useful.useful.utils.UConnectProfile; import com.useful.useful.utils.UConnectRank; import com.useful.useful.utils.getColor; import com.useful.useful.utils.getEnchant; public class UsefulCommandExecutor implements CommandExecutor { static useful plugin; public static String pluginFolder; public int number; public int numberorig; FileConfiguration config = useful.config; private String pluginAuth = ""; public UsefulCommandExecutor(useful instance, String pluginAuthentication){ plugin = useful.plugin; this.pluginAuth = pluginAuthentication; } public void showAd(CommandSender sender){ try { sender.sendMessage(ChatColor.DARK_GREEN+""+ChatColor.BOLD+"[Advertisement:]"); List<String> ads = plugin.uconnectAds.values; int size = ads.size(); int index = 0 + (int)(Math.random() * (((size-1) - 0) + 1)); String advert = useful.colorise(ads.get(index)); String[] lines = advert.split("%n"); for(String line:lines){ sender.sendMessage(ChatColor.GOLD+line); } } catch (Exception e) { } return; } @Override public boolean onCommand(final CommandSender sender, Command cmd, String commandLabel, String[] args){ String disabledmessage = useful.config.getString("general.disabledmessage"); Player player = null; String cmdname = commandLabel; if (sender instanceof Player) { player = (Player) sender; } if(cmd.getName().equalsIgnoreCase("test")){ // If the player typed /basic then do the following... sender.sendMessage("The useful plugin is working! - coded by storm345"); return true; } else if(cmd.getName().equalsIgnoreCase("worlds")){ // If the player typed /basic then do the following... @SuppressWarnings("rawtypes") List world = plugin.getServer().getWorlds(); Object[] worlds = world.toArray(); String message = "Worlds on the server:"; for (Object s : worlds) { String wname = ((World) s).getName(); message = message + " " + wname + ","; } sender.sendMessage(plugin.colors.getInfo() + message); return true; } else if(cmd.getName().equalsIgnoreCase("craft")){ if(player == null){ sender.sendMessage(plugin.colors.getError() + "This command is for players!"); return true; } BlockFace face = ClosestFace.getClosestFace(player.getLocation().getYaw()); Block toPlaceAt = player.getLocation().getBlock().getRelative(face); boolean changed = false; Location spawnAt = toPlaceAt.getLocation(); Boolean canBuild = Builder.canBuild(player, spawnAt); if(!canBuild){ sender.sendMessage(plugin.colors.getError() + "You cannot build here"); return true; } if(toPlaceAt.getType() != Material.AIR){ sender.sendMessage(plugin.colors.getError() + "Nowhere to place the crafting table!"); return true; } Block above = toPlaceAt.getRelative(BlockFace.UP); if(above.getType() != Material.AIR && !changed){ spawnAt = toPlaceAt.getLocation(); changed = true; } Block above2 = above.getRelative(BlockFace.UP); if(above2.getType() != Material.AIR && !changed){ spawnAt = above.getLocation(); changed = true; } Block above3 = above2.getRelative(BlockFace.UP); if(above3.getType() != Material.AIR && !changed){ spawnAt = above2.getLocation(); changed = true; } Block above4 = above3.getRelative(BlockFace.UP); if(above4.getType() != Material.AIR && !changed){ spawnAt = above3.getLocation(); changed = true; } else{ if(!changed){ spawnAt = above4.getLocation(); } } spawnAt.getWorld().spawnFallingBlock(spawnAt, Material.WORKBENCH, Byte.parseByte("0")); sender.sendMessage(plugin.colors.getSuccess() + "Successfully given you a crafting table."); return true; } else if(cmd.getName().equalsIgnoreCase("world")){ // If the player typed /basic then do the following... if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } if (args.length < 1){ sender.sendMessage("Usage /world ([Player]) [World-Name]"); return true; } String wname = "world"; if (args.length > 1){ wname = args[1]; } else { wname = args[0]; } World world = plugin.getServer().getWorld(wname); if (world == null){ sender.sendMessage(plugin.colors.getError() + "World not found! Do /worlds for a list."); return true; } Location loc = world.getSpawnLocation(); Player target = ((Player) sender); if (args.length > 1){ target = plugin.getServer().getPlayer(args[0]); target.sendMessage(plugin.colors.getSuccess() + "Teleporting you to world " + world.getName() + " courtesy of " + sender.getName()); } else { sender.sendMessage(plugin.colors.getSuccess() + "Teleporting you to world " + world.getName()); } try{ target.teleport(loc); } catch(Exception e){ sender.sendMessage(plugin.colors.getError() + "World not found! Do /worlds for a list."); } return true; } else if(cmd.getName().equalsIgnoreCase("firework")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "This command is for players"); return true; } if(args.length < 5){ return false; } String height = args[0]; String col1 = args[1]; String col2 = args[2]; String fade = args[3]; String fade2 = args[4]; String type = args[5]; String flicker = args[6]; String trail = args[7]; boolean doFlicker = false; boolean doTrail = false; if(flicker.equalsIgnoreCase("true")){ doFlicker = true; } else if(flicker.equalsIgnoreCase("false")){ doFlicker = false; } else{ return false; } if(trail.equalsIgnoreCase("true")){ doTrail = true; } else if(trail.equalsIgnoreCase("false")){ doTrail = false; } else{ return false; } int amount = 0; try { amount = Integer.parseInt(args[8]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "The amount specified is not an integer."); return true; } ItemStack item = new ItemStack(Material.FIREWORK, 1); FireworkMeta fmeta = (FireworkMeta) item.getItemMeta(); if(height.equalsIgnoreCase("1")){ fmeta.setPower(1); } else if(height.equalsIgnoreCase("2")){ fmeta.setPower(2); } else if(height.equalsIgnoreCase("3")){ fmeta.setPower(3); } else{ sender.sendMessage(plugin.colors.getError() + "The firework height must be either 1, 2 or 3"); return true; } //Set the height org.bukkit.FireworkEffect.Builder effect = FireworkEffect.builder(); if(type.equalsIgnoreCase("small")){ Type effectType = FireworkEffect.Type.BALL; effect.with(effectType); } else if(type.equalsIgnoreCase("big")){ effect.with(FireworkEffect.Type.BALL_LARGE); } else if(type.equalsIgnoreCase("burst")){ effect.with(FireworkEffect.Type.BURST); } else if(type.equalsIgnoreCase("creeper")){ effect.with(FireworkEffect.Type.CREEPER); } else if(type.equalsIgnoreCase("star")){ effect.with(FireworkEffect.Type.STAR); } else if(type.equalsIgnoreCase("epic_creeper")){ org.bukkit.FireworkEffect.Builder Epiceffect = FireworkEffect.builder(); Epiceffect.flicker(true); Epiceffect.trail(true); Epiceffect.withColor(Color.RED, Color.YELLOW, Color.ORANGE); Epiceffect.with(Type.STAR); FireworkEffect explosion = Epiceffect.build(); fmeta.addEffect(explosion); effect.with(FireworkEffect.Type.CREEPER); } else{ sender.sendMessage(plugin.colors.getError() + "Invalid type - Valid types are: small, big, burst, creeper, epic_creeper, star"); return true; } if(doFlicker){ effect.withFlicker(); } if(doTrail){ effect.withTrail(); } Color color1 = getColor.getColorFromString(col1); if(color1 == null){ sender.sendMessage(plugin.colors.getError() + "Error: invalid first color." + ChatColor.RESET + " Valid colors are: aqua, black, blue, fuchsia, grey, green, lime, maroon, navy, olive, orange, pink, purple, red, silver, teal, white and yellow"); return true; } Color color2 = getColor.getColorFromString(col2); if(color2 == null){ sender.sendMessage(plugin.colors.getError() + "Error: invalid second color." + ChatColor.RESET + " Valid colors are: aqua, black, blue, fuchsia, grey, green, lime, maroon, navy, olive, orange, pink, purple, red, silver, teal, white and yellow"); return true; } Color fader = getColor.getColorFromString(fade); if(fader == null){ sender.sendMessage(plugin.colors.getError() + "Error: invalid first fade color." + ChatColor.RESET + " Valid colors are: aqua, black, blue, fuchsia, grey, green, lime, maroon, navy, olive, orange, pink, purple, red, silver, teal, white and yellow"); return true; } Color fader2 = getColor.getColorFromString(fade2); if(fader2 == null){ sender.sendMessage(plugin.colors.getError() + "Error: invalid second fade color." + ChatColor.RESET + " Valid colors are: aqua, black, blue, fuchsia, grey, green, lime, maroon, navy, olive, orange, pink, purple, red, silver, teal, white and yellow"); return true; } effect.withFade(fader, fader2); effect.withColor(color1, color2); FireworkEffect teffect = effect.build(); fmeta.addEffect(teffect); item.setItemMeta(fmeta); item.setAmount(amount); sender.sendMessage(plugin.colors.getSuccess() + "Created firework"); player.getInventory().addItem(item); return true; } else if(cmd.getName().equalsIgnoreCase("uconnect")){ String[] usage = {ChatColor.GREEN + "" + ChatColor.BOLD + "UConnect help:",ChatColor.DARK_AQUA + "Sections:", ChatColor.DARK_RED + "/"+cmdname+ChatColor.YELLOW+" msg", ChatColor.DARK_RED + "/"+cmdname+ChatColor.YELLOW+" profile", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" setprofile", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" news (page)", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" createnews", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" deletenews", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" servers", ChatColor.DARK_RED+"/"+cmdname+ChatColor.YELLOW+" friends"}; if(args.length <1){ for(String line:usage){ sender.sendMessage(line); } return true; } String program = args[0]; if(program.equalsIgnoreCase("message") || program.equalsIgnoreCase("msg")){ String[] msgUsage = {ChatColor.GREEN + "" + ChatColor.BOLD + "UConnect help:",ChatColor.DARK_AQUA + "Sections:", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"send <Player> <Msg>", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"clear", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"read (Page)", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"block <Player>", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"unblock <Player>", ChatColor.DARK_RED + "/"+cmdname+" msg "+ChatColor.YELLOW+"blocked (Page)"}; if(player == null){ sender.sendMessage(plugin.colors.getError() + "Only players can use the messaging part of uconnect."); return true; } if(args.length <2){ for(String line:msgUsage){ sender.sendMessage(line); } return true; } String action = args[1]; if(action.equalsIgnoreCase("read")){ UConnectProfile profile = new UConnectProfile(player.getName()); String page = "1"; if(args.length > 2){ page = args[2]; } sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.getMessages(profile,page,sender,pluginAuth); return true; } else if(action.equalsIgnoreCase("clear")){ UConnectProfile profile = new UConnectProfile(player.getName()); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.clearMessages(profile, sender,pluginAuth); return true; } else if(action.equalsIgnoreCase("send")){ if(args.length < 4){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" msg"+ChatColor.YELLOW + " send <Player> <Msg>"); return true; } String playerName = args[2]; sender.sendMessage(plugin.colors.getError() + "WARNING: Player names are CaSe SenSitIvE"); String message = args[3]; for(int i = 4; i<args.length;i++){ message = message + " " + args[i]; } sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.message(new UConnectProfile(playerName), new UConnectProfile(player.getName()), message, sender,pluginAuth); return true; } else if(action.equalsIgnoreCase("block")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" msg"+ChatColor.YELLOW + " block <Player>"); return true; } String name = args[2]; sender.sendMessage(plugin.colors.getError() + "WARNING: Player names are CaSe SenSitIvE"); List<Object> uargs = new ArrayList<Object>(); uargs.add(name); UConnectDataRequest request = new UConnectDataRequest("block", uargs.toArray(), player,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.load(request); return true; } else if(action.equalsIgnoreCase("unblock")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" msg"+ChatColor.YELLOW + " unblock <Player>"); return true; } String name = args[2]; sender.sendMessage(plugin.colors.getError() + "WARNING: Player names are CaSe SenSitIvE"); List<Object> uargs = new ArrayList<Object>(); uargs.add(name); UConnectDataRequest request = new UConnectDataRequest("unblock", uargs.toArray(), player,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.load(request); return true; } else if(action.equalsIgnoreCase("blocked")){ String page = "1"; if(args.length > 2){ page = args[2]; } List<Object> uargs = new ArrayList<Object>(); uargs.add(page); UConnectDataRequest request = new UConnectDataRequest("blocked", uargs.toArray(), player,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.load(request); return true; } else{ for(String line:msgUsage){ sender.sendMessage(line); } return true; } } else if(program.equalsIgnoreCase("profile")){ if(args.length < 2){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" profile"+ChatColor.YELLOW + " <Player>"); return true; } String pName = args[1]; List<Object> uargs = new ArrayList<Object>(); uargs.add(pName); UConnectDataRequest request = new UConnectDataRequest("loadProfile", uargs.toArray(), sender,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); plugin.uconnect.loadProfile(pName, request, sender); return true; } else if(program.equalsIgnoreCase("setprofile")){ String[] msgUsage = {ChatColor.GREEN + "" + ChatColor.BOLD + "UConnect help:",ChatColor.DARK_AQUA + "Sections:", ChatColor.DARK_RED + "/"+cmdname+" setprofile "+ChatColor.YELLOW+"About <Value>", ChatColor.DARK_RED + "/"+cmdname+" setprofile "+ChatColor.YELLOW+"Contact <Value>", ChatColor.DARK_RED + "/"+cmdname+" setprofile "+ChatColor.YELLOW+"Favserer <Value>"}; if(player == null){ sender.sendMessage(plugin.colors.getError() + "This part of uConnect is for players"); return true; } if(args.length < 3){ for(String line:msgUsage){ sender.sendMessage(line); } return true; } String action = args[1]; if(action.equalsIgnoreCase("contact")){ String contactInfo = args[2]; for(int i=3;i<args.length;i++){ contactInfo = contactInfo + " " + args[i]; } List<Object> uargs = new ArrayList<Object>(); uargs.add(player.getName()); uargs.add(contactInfo); UConnectDataRequest request = new UConnectDataRequest("setProfileContact", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfile(player.getName(), request, sender); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("about")){ String contactInfo = args[2]; for(int i=3;i<args.length;i++){ contactInfo = contactInfo + " " + args[i]; } List<Object> uargs = new ArrayList<Object>(); uargs.add(player.getName()); uargs.add(contactInfo); UConnectDataRequest request = new UConnectDataRequest("setProfileAbout", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfile(player.getName(), request, sender); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("favserver")){ String contactInfo = args[2]; for(int i=3;i<args.length;i++){ contactInfo = contactInfo + " " + args[i]; } List<Object> uargs = new ArrayList<Object>(); uargs.add(player.getName()); uargs.add(contactInfo); UConnectDataRequest request = new UConnectDataRequest("setProfileFavServer", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfile(player.getName(), request, sender); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else{ for(String line:msgUsage){ sender.sendMessage(line); } return true; } } else if(program.equalsIgnoreCase("news")){ int page = 1; if(args.length > 1){ try { page = Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number!"); return true; } if(page < 1){ sender.sendMessage(plugin.colors.getError() + "Invalid page number!"); return true; } } Object[] uargs = {page}; UConnectDataRequest request = new UConnectDataRequest("showNews", uargs, sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(program.equalsIgnoreCase("createnews")){ UConnectProfile profile = new UConnectProfile(sender.getName()); if(profile.getRank() != UConnectRank.CREATOR && profile.getRank() != UConnectRank.DEVELOPER){ sender.sendMessage(plugin.colors.getError() + "You don't have permission to do this"); return true; } if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" createnews"+ChatColor.YELLOW + " <Article> <Story>"); return true; } String article = args[1]; String story = args[2]; for(int i=4;i<args.length;i++){ story = story + " " + args[i]; } String toPut = "&2&l"+article+"abcd&r&e"+story; List<Object> uargs = new ArrayList<Object>(); uargs.add(toPut); UConnectDataRequest request = new UConnectDataRequest("createNews", uargs.toArray(), sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(program.equalsIgnoreCase("deleteNews")){ UConnectProfile profile = new UConnectProfile(sender.getName()); if(profile.getRank() != UConnectRank.CREATOR && profile.getRank() != UConnectRank.DEVELOPER){ sender.sendMessage(plugin.colors.getError() + "You don't have permission to do this"); return true; } if(args.length < 2){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" deleteNews"+ChatColor.YELLOW + " <Article>"); return true; } String article = args[1]; List<Object> uargs = new ArrayList<Object>(); uargs.add(article); UConnectDataRequest request = new UConnectDataRequest("deleteNews", uargs.toArray(), sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(program.equalsIgnoreCase("servers")){ String[] msgUsage = {ChatColor.GREEN + "" + ChatColor.BOLD + "UConnect help:",ChatColor.DARK_AQUA + "Sections:", ChatColor.DARK_RED + "/"+cmdname+" servers "+ChatColor.YELLOW+"list (Page)", ChatColor.DARK_RED + "/"+cmdname+" servers "+ChatColor.YELLOW+"add <Ip> <About>", ChatColor.DARK_RED + "/"+cmdname+" servers "+ChatColor.YELLOW+"delete <Ip>"}; if(args.length < 2){ for(String line:msgUsage){ sender.sendMessage(line); } return true; } String action = args[1]; if(action.equalsIgnoreCase("add")){ if(args.length < 4){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" servers"+ChatColor.YELLOW + " add <Ip> <About>"); return true; } String ip = args[2]; String about = args[3]; for(int i=4;i<args.length;i++){ about = about + " " + args[i]; } List<Object> uargs = new ArrayList<Object>(); uargs.add(ip); uargs.add(about); UConnectDataRequest request = new UConnectDataRequest("addServer", uargs.toArray(), sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("delete")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" servers"+ChatColor.YELLOW + " delete <Ip>"); return true; } String ip = args[2]; List<Object> uargs = new ArrayList<Object>(); uargs.add(ip); UConnectDataRequest request = new UConnectDataRequest("deleteServer", uargs.toArray(), sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("list")){ int page = 1; if(args.length > 2){ String pag = args[2]; try { page = Integer.parseInt(pag); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError()+"Invalid page number"); return true; } } if(page < 1){ page = 1; } List<Object> uargs = new ArrayList<Object>(); uargs.add(page); UConnectDataRequest request = new UConnectDataRequest("listServer", uargs.toArray(), sender,pluginAuth); plugin.uconnect.load(request); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else{ if(args.length <1){ for(String line:usage){ sender.sendMessage(line); } return true; } } } else if(program.equalsIgnoreCase("friends")){ // /uc friends: add, view, remove, list, overview/over if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "This part of uconnect is for players!"); return true; } String[] msgUsage = {ChatColor.GREEN + "" + ChatColor.BOLD + "UConnect help:",ChatColor.DARK_AQUA + "Sections:", ChatColor.DARK_RED + "/"+cmdname+" Friends "+ChatColor.YELLOW+"Add <Name>", ChatColor.DARK_RED + "/"+cmdname+" Friends "+ChatColor.YELLOW+"Remove <Name>", ChatColor.DARK_RED + "/"+cmdname+" Friends "+ChatColor.YELLOW+"View <Name>", ChatColor.DARK_RED + "/"+cmdname+" Friends "+ChatColor.YELLOW+"List (Page)", ChatColor.DARK_RED + "/"+cmdname+" Friends "+ChatColor.YELLOW+"Overview/Over (Page)"}; if(args.length < 2){ for(String msg:msgUsage){ sender.sendMessage(msg); } return true; } String action = args[1]; if(action.equalsIgnoreCase("add")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" friends"+ChatColor.YELLOW + " add <Name>"); return true; } String name = args[2]; List<Object> uargs = new ArrayList<Object>(); uargs.add(name); UConnectDataRequest request = new UConnectDataRequest("addFriend", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfiles(request,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("view")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" friends"+ChatColor.YELLOW + " view <Name>"); return true; } String name = args[2]; List<Object> uargs = new ArrayList<Object>(); uargs.add(name); UConnectDataRequest request = new UConnectDataRequest("viewFriend", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfiles(request,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("remove")){ if(args.length < 3){ sender.sendMessage(ChatColor.GREEN+"Usage: "+ChatColor.DARK_RED+"/"+cmdname+" friends"+ChatColor.YELLOW + " remove <Name>"); return true; } String name = args[2]; List<Object> uargs = new ArrayList<Object>(); uargs.add(name); UConnectDataRequest request = new UConnectDataRequest("removeFriend", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfiles(request,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("list")){ int page = 1; if(args.length > 2){ try { page = Integer.parseInt(args[2]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number!"); return true; } } List<Object> uargs = new ArrayList<Object>(); uargs.add(page); UConnectDataRequest request = new UConnectDataRequest("listFriend", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfiles(request,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else if(action.equalsIgnoreCase("over")||action.equalsIgnoreCase("overview")){ int page = 1; if(args.length > 2){ try { page = Integer.parseInt(args[2]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number!"); return true; } } List<Object> uargs = new ArrayList<Object>(); uargs.add(page); UConnectDataRequest request = new UConnectDataRequest("overviewFriend", uargs.toArray(), sender,pluginAuth); plugin.uconnect.loadProfiles(request,pluginAuth); sender.sendMessage(ChatColor.GRAY + "Loading..."); showAd(sender); return true; } else{ for(String msg:msgUsage){ sender.sendMessage(msg); } } return true; } for(String line:usage){ sender.sendMessage(line); } return true; } else if(cmd.getName().equalsIgnoreCase("needauth")){ if(args.length < 2){ return false; } useful.authed.put(args[0], false); if(plugin.auths.contains(args[0] + " " + args[1].toLowerCase())){ sender.sendMessage(plugin.colors.getError() + args[0] + " was already on the authentication list!"); return true; } plugin.auths.add(args[0] + " " + args[1].toLowerCase()); plugin.auths.save(); sender.sendMessage(plugin.colors.getSuccess() + args[0] + " is now on the authentication list with the password: " + args[1].toLowerCase()); return true; } else if(cmd.getName().equalsIgnoreCase("notneedauth")){ if(args.length < 1){ return false; } plugin.auths.load(); Object[] authVal = plugin.auths.values.toArray(); String tval = "&&unknown**name&&"; for(int i=0;i<authVal.length;i++){ String val = (String) authVal[i]; if(val.startsWith(args[0])){ tval = val; plugin.auths.remove(val); plugin.auths.remove((String)authVal[i]); } } if(tval == "&&unknown**name&&"){ sender.sendMessage(plugin.colors.getError() + "Player is not on the authentication list (Player names are case sensitive)!)"); return true; } plugin.auths.remove(tval); plugin.auths.save(); plugin.auths.load(); useful.authed.remove(args[0]); sender.sendMessage(plugin.colors.getSuccess() + args[0] + " is now not on the authentication list."); return true; } else if(cmd.getName().equalsIgnoreCase("login")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "Non players don't need authentication!"); return true; } if(args.length < 1){ return false; } if(!useful.authed.containsKey(sender.getName())){ sender.sendMessage(plugin.colors.getError() + "You do not need to be logged in!"); return true; } String tval = player.getName() + " " + args[0].toLowerCase(); if(plugin.auths.contains(tval)){ //They are logged in! if(useful.authed.get(player.getName())){ sender.sendMessage(plugin.colors.getError() + "Already logged in!!"); return true; } useful.authed.put(player.getName(), true); sender.sendMessage(plugin.colors.getSuccess() + "Password accepted!"); return true; } else{ sender.sendMessage(plugin.colors.getError() + "Password incorrect!"); } return true; } else if(cmd.getName().equalsIgnoreCase("shelter")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "You need to be a player to use this command."); return true; } if(args.length < 1){ return false; } String rank = ""; if(args[0].equalsIgnoreCase("1")){ rank = "1"; } Block start = player.getLocation().add(0, -1, 0).getBlock(); Block floorMiddle = player.getLocation().add(0, -1, 0).getBlock(); //BEGIN FLOOR Builder.build(player, floorMiddle, Material.WOOD); // middle of floor Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH), Material.WOOD); //north floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH), Material.WOOD); //south floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST), Material.WOOD); //east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST), Material.WOOD); //west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_EAST), Material.WOOD); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_EAST), Material.WOOD); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_WEST), Material.WOOD); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_WEST), Material.WOOD); //north west floor block //END FLOOR //BEGIN NORTH WALL Block wallCenter = start.getRelative(BlockFace.NORTH, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); //wall block under window Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.STEP); //ENG NORTH WALL //BEGIN EAST WALL wallCenter = start.getRelative(BlockFace.EAST, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.STEP); //ENG EAST WALL //BEGIN WEST WALL wallCenter = start.getRelative(BlockFace.WEST, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.STEP); //ENG WEST WALL //BEGIN SOUTH WALL wallCenter = start.getRelative(BlockFace.SOUTH, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter.getRelative(BlockFace.UP), Material.AIR); Builder.build(player, wallCenter.getRelative(BlockFace.UP, 2), Material.AIR); Builder.build(player, wallCenter.getRelative(BlockFace.DOWN), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.DOWN).getRelative(BlockFace.SOUTH), Material.WOOD); Builder.buildById(player, wallCenter.getRelative(BlockFace.UP), "64:8"); Builder.buildById(player, wallCenter, "64:3"); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getRelative(BlockFace.EAST), Material.TORCH); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP).getRelative(BlockFace.WEST), Material.TORCH); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.STEP); //ENG SOUTH WALL //BEGIN INTERIOR AIR & torches Block levelMid = floorMiddle.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.AIR); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.AIR); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.AIR); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.AIR); //west block Builder.buildById(player, levelMid.getRelative(BlockFace.WEST), "26:2"); Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block Builder.buildById(player, levelMid.getRelative(BlockFace.NORTH_WEST), "26:10"); levelMid = levelMid.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.AIR); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.AIR); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.AIR); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.AIR); //west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block levelMid = levelMid.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.TORCH); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.TORCH); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.TORCH); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.TORCH); //west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block //END INTERIOR AIR //BEGIN ROOF floorMiddle = levelMid.getRelative(BlockFace.UP); //BEGIN FLOOR Builder.build(player, floorMiddle, Material.WOOD); // middle of floor Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH), Material.WOOD); //north floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH), Material.WOOD); //south floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST), Material.WOOD); //east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST), Material.WOOD); //west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_EAST), Material.WOOD); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_EAST), Material.WOOD); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_WEST), Material.WOOD); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_WEST), Material.WOOD); //north west floor block //END ROOF if(args[0].equalsIgnoreCase("2")){ rank = "2"; start = player.getLocation().add(0, 3, 0).getBlock(); floorMiddle = player.getLocation().add(0, 3, 0).getBlock(); //BEGIN FLOOR Builder.build(player, floorMiddle, Material.WOOD); // middle of floor Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH), Material.AIR); //north floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH), Material.WOOD); //south floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST), Material.AIR); //east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST), Material.WOOD); //west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_EAST), Material.WOOD); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_WEST), Material.WOOD); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_WEST), Material.WOOD); //north west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH, 2), Material.DOUBLE_STEP); //north floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH,2 ), Material.DOUBLE_STEP); //south floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST, 2), Material.DOUBLE_STEP); //east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST, 2), Material.DOUBLE_STEP); //west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_EAST, 2), Material.DOUBLE_STEP); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_EAST, 2), Material.DOUBLE_STEP); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_WEST, 2), Material.DOUBLE_STEP); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_WEST, 2), Material.DOUBLE_STEP); //north west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_NORTH_EAST), Material.DOUBLE_STEP); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_SOUTH_EAST), Material.DOUBLE_STEP); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_SOUTH_WEST), Material.DOUBLE_STEP); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_NORTH_WEST), Material.DOUBLE_STEP); //north west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST_NORTH_EAST), Material.DOUBLE_STEP); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST_SOUTH_EAST), Material.DOUBLE_STEP); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST_SOUTH_WEST), Material.DOUBLE_STEP); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST_NORTH_WEST), Material.DOUBLE_STEP); //north west floor block //END FLOOR //BEGIN NORTH WALL wallCenter = start.getRelative(BlockFace.NORTH, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); //wall block under window Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.DOWN, 4), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.STEP); //ENG NORTH WALL //BEGIN EAST WALL wallCenter = start.getRelative(BlockFace.EAST, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.STEP); //ENG EAST WALL //BEGIN WEST WALL wallCenter = start.getRelative(BlockFace.WEST, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.SOUTH, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.NORTH, 2), Material.STEP); //ENG WEST WALL //BEGIN SOUTH WALL wallCenter = start.getRelative(BlockFace.SOUTH, 2).getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); //wall block under window Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.GLASS); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.WOOD); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.LOG); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.LOG); wallCenter = wallCenter.getRelative(BlockFace.UP); Builder.build(player, wallCenter, Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.EAST, 2), Material.STEP); Builder.build(player, wallCenter.getRelative(BlockFace.WEST, 2), Material.STEP); //ENG SOUTH WALL //BEGIN INTERIOR AIR & torches levelMid = floorMiddle.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.AIR); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.AIR); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.AIR); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.AIR); //west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block levelMid = levelMid.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.AIR); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.AIR); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.AIR); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.AIR); //west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block levelMid = levelMid.getRelative(BlockFace.UP); Builder.build(player, levelMid, Material.AIR); Builder.build(player, levelMid.getRelative(BlockFace.NORTH), Material.AIR); //north block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH), Material.TORCH); //south block Builder.build(player, levelMid.getRelative(BlockFace.EAST), Material.TORCH); //east block Builder.build(player, levelMid.getRelative(BlockFace.WEST), Material.TORCH); //west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_EAST), Material.AIR); //north east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_EAST), Material.AIR); //south east block Builder.build(player, levelMid.getRelative(BlockFace.SOUTH_WEST), Material.AIR); //south west block Builder.build(player, levelMid.getRelative(BlockFace.NORTH_WEST), Material.AIR); //north west block //END INTERIOR AIR //START STAIRS levelMid = floorMiddle.getRelative(BlockFace.DOWN, 3); Builder.buildById(player, levelMid.getRelative(BlockFace.EAST), "53:3"); //west block levelMid = levelMid.getRelative(BlockFace.UP); Builder.buildById(player, levelMid.getRelative(BlockFace.NORTH_EAST), "53:3"); //north west block levelMid = levelMid.getRelative(BlockFace.UP); Builder.buildById(player, levelMid.getRelative(BlockFace.NORTH), "53:1"); //north block Builder.buildById(player, levelMid.getRelative(BlockFace.UP).getRelative(BlockFace.NORTH_WEST), "53:1"); //north east block //END STAIRS //BEGIN ROOF floorMiddle = levelMid.getRelative(BlockFace.UP, 5); //BEGIN FLOOR Builder.build(player, floorMiddle, Material.WOOD); // middle of floor Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH), Material.WOOD); //north floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH), Material.WOOD); //south floor block Builder.build(player, floorMiddle.getRelative(BlockFace.EAST), Material.WOOD); //east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.WEST), Material.WOOD); //west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_EAST), Material.WOOD); //north east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_EAST), Material.WOOD); //south east floor block Builder.build(player, floorMiddle.getRelative(BlockFace.SOUTH_WEST), Material.WOOD); //south west floor block Builder.build(player, floorMiddle.getRelative(BlockFace.NORTH_WEST), Material.WOOD); //north west floor block //END ROOF } player.sendMessage(plugin.colors.getSuccess() + "Built an instant shelter size " + rank + "!"); return true; } else if(cmd.getName().equalsIgnoreCase("mobtypes")){ // If the player typed /basic then do the following... sender.sendMessage(plugin.colors.getInfo() + "Available mob types: cow, chicken, blaze, cave-spider, creeper, enderdragon, " + "enderman, xp, ghast, giant, irongolem, magmacube, mushroomcow, ocelot, pig, pigzombie, silverfish, " + "sheep, skeleton, slime, snowman, spider, squid, villager, wolf, zombie, bat, witch, wither, wither_skull, firework"); return true; } else if(cmd.getName().equalsIgnoreCase("mobset")){ // If the player typed /basic then do the following... if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } boolean isenabled = useful.config.getBoolean("general.mobset.enable"); if (isenabled == false){ sender.sendMessage(disabledmessage); return true; } if (args.length < 1){ sender.sendMessage("Usage /mobset [Type] - do /mobtypes for a list"); return true; } Block block = plugin.getServer().getPlayer(sender.getName()).getTargetBlock(null, 10); //Block block = loc.getBlock(); if (block.getTypeId() == 52){ //change type of spawner BlockState isSpawner = block.getState(); CreatureSpawner spawner = (CreatureSpawner) isSpawner; EntityType type = Entities.getEntityTypeByName(args[0], sender); if (type == null){ return true; } spawner.setSpawnedType(type); sender.sendMessage(plugin.colors.getSuccess() + "Spawner type set!"); } else { sender.sendMessage(plugin.colors.getError() + "You must be looking at a mob spawner to use this command."); return true; } return true; } else if(cmd.getName().equalsIgnoreCase("spawnmob")){ // If the player typed /basic then do the following... if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } boolean isenabled = useful.config.getBoolean("general.spawnmob.enable"); if (isenabled == false){ sender.sendMessage(disabledmessage); return true; } if (args.length < 2){ sender.sendMessage("Usage /" + cmdname + " [Type] [Amount] - do /mobtypes for a list"); return true; } //Block block = plugin.getServer().getPlayer(sender.getName()).getTargetBlock(null, 10); //Block block = loc.getBlock(); EntityType type = Entities.getEntityTypeByName(args[0], sender); if (type == null){ return true; } Location loc = ((Player )sender).getLocation(); int number = 0; try { number = Integer.parseInt(args[1]); } catch (Exception e) { sender.sendMessage("Usage /" + cmdname + " [Type] [Amount] - do /mobtypes for a list"); return true; } while (number > 0){ ((Player )sender).getWorld().spawnEntity(loc, type); number--; } if (number <= 0){ sender.sendMessage(plugin.colors.getSuccess() + "Successfully spawned " + args[1] + " " + args[0] + "'s!"); return true; } //((Player )sender).getWorld().spawnEntity(loc, type); return true; } else if(cmd.getName().equalsIgnoreCase("hat")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.hat.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ //no arguments given Player target = (Player) sender; PlayerInventory inv = target.getInventory(); if (inv.getHelmet() != null && inv.getHelmet() != new ItemStack(0)){ ItemStack helmet = inv.getHelmet(); inv.setHelmet(new ItemStack(0)); if (helmet.getTypeId() != 0){ inv.addItem(helmet); } } int item = target.getItemInHand().getTypeId(); inv.setHelmet(new ItemStack(item)); target.setItemInHand(new ItemStack(0)); sender.sendMessage(plugin.colors.getSuccess() + "Hat set!"); } else { Player target = (Player) sender; PlayerInventory inv = target.getInventory(); int item = 0; if (inv.getHelmet() != null && inv.getHelmet() != new ItemStack(0)){ ItemStack helmet = inv.getHelmet(); inv.setHelmet(new ItemStack(item)); if (helmet.getTypeId() != 0){ inv.addItem(helmet); } } sender.sendMessage(plugin.colors.getError() + "Hat taken off!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("kick")){ // If the player typed /basic then do the following... if (args.length < 1){ sender.sendMessage("Usage /kick [Name] [Reason]"); } else if (args.length == 1){ // kick [name] Player bad = plugin.getServer().getPlayer(args[0]); if (bad == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } bad.kickPlayer("You were kicked from the server :("); Bukkit.broadcastMessage(plugin.colors.getInfo() + bad.getName() + " was kicked from the server by " + sender.getName()); } else { //kick [name] [reason] Player bad = plugin.getServer().getPlayer(args[0]); if (bad == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } StringBuilder msg = new StringBuilder(); for (int i = 1; i < args.length; i++) { if (i != 0) msg.append(" "); msg.append(args[i]); } bad.kickPlayer("Kicked: " + msg); Bukkit.broadcastMessage(plugin.colors.getInfo() + bad.getName() + " was kicked from the server by " + sender.getName() + " for " + msg); } return true; } else if(cmd.getName().equalsIgnoreCase("ban")){ // If the player typed /basic then do the following... if (args.length < 1){ sender.sendMessage("Usage /ban [Name] [Reason]"); } else if (args.length == 1){ // kick [name] OfflinePlayer bad = getServer().getOfflinePlayer(args[0]); Player online = getServer().getPlayer(args[0]); if (bad == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } if (online != null){ online.kickPlayer("You were banned from the server :("); } bad.setBanned(true); Bukkit.broadcastMessage(plugin.colors.getInfo() + bad.getName() + " was banned from the server by " + sender.getName()); } else { //kick [name] [reason] OfflinePlayer bad = getServer().getOfflinePlayer(args[0]); Player online = getServer().getPlayer(args[0]); if (bad == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } StringBuilder msg = new StringBuilder(); for (int i = 1; i < args.length; i++) { if (i != 0) msg.append(" "); msg.append(args[i]); } if (online != null){ online.kickPlayer("Banned: " + msg); } bad.setBanned(true); Bukkit.broadcastMessage(plugin.colors.getInfo() + bad.getName() + " was banned from the server by " + sender.getName() + " for " + msg); } return true; } else if(cmd.getName().equalsIgnoreCase("unban")){ // If the player typed /basic then do the following... if (args.length < 1){ sender.sendMessage("Usage /" + cmdname + " [Name]"); } else { //kick [name] [reason] Set<OfflinePlayer> banned = getServer().getBannedPlayers(); Object[] ban = banned.toArray(); String name = "Unknown"; OfflinePlayer theplayer = null; boolean found = false; for (int i = 0; i < ban.length; i++) { if(((OfflinePlayer) ban[i]).getName().equalsIgnoreCase(args[0])){ theplayer = (OfflinePlayer) ban[i]; found = true; name = ((OfflinePlayer) ban[i]).getName(); } } if(found == false){ sender.sendMessage(plugin.colors.getError() + "Player not found on ban list!"); return true; } theplayer.setBanned(false); Bukkit.broadcastMessage(plugin.colors.getInfo() + name + " was unbanned from the server by " + sender.getName()); } return true; } else if(cmd.getName().equalsIgnoreCase("backup")){ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable(){ public void run(){ DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //get current date time with Date() java.util.Date dateTime = new java.util.Date(); String date = dateFormat.format(dateTime); sender.sendMessage(plugin.colors.getSuccess() + "Starting backup procedure..."); getLogger().info(sender.getName() + " Ran a backup"); List<World> worlds = plugin.getServer().getWorlds(); Object[] theWorlds = worlds.toArray(); String path = new File(".").getAbsolutePath(); for(int i=0;i<theWorlds.length; i++){ World w = (World) theWorlds[i]; try { w.save(); } catch (Exception e1) { getLogger().info("Failed to save world. Proceeding on assumption it is already done automatically..."); } String wNam = w.getName(); File srcFolder = new File(path + File.separator + wNam); File destFolder = new File(plugin.getDataFolder().getAbsolutePath() + File.separator + "World Backups" + File.separator + date + File.separator + wNam); destFolder.mkdirs(); //make sure source exists if(!srcFolder.exists()){ sender.sendMessage(plugin.colors.getError() + "Failed to find world " + wNam); }else{ try{ Copier.copyFolder(srcFolder,destFolder); }catch(IOException e){ sender.sendMessage(plugin.colors.getError() + "Error copying world " + wNam); } } } sender.sendMessage(plugin.colors.getSuccess() + "Backup procedure complete!"); } }); return true; } else if(cmd.getName().equalsIgnoreCase("canfly")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "This command is for players!"); return true; } if(player.getAllowFlight()){ player.setAllowFlight(false); player.sendMessage(plugin.colors.getSuccess() + "Fly mode disabled!"); } else if(!player.getAllowFlight()){ player.setAllowFlight(true); player.sendMessage(plugin.colors.getSuccess() + "Fly mode enabled!"); } return true; } else if(cmd.getName().equalsIgnoreCase("rename")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "This command is for players!"); return true; } if(args.length<1){ return false; } String raw = args[0]; for(int i=1;i<args.length;i++){ raw = raw + " " + args[i]; } String newName = ChatColor.RESET + raw; newName = useful.colorise(newName); ItemStack toName = player.getItemInHand(); if(toName.getTypeId() == 0){ sender.sendMessage(plugin.colors.getError() + "Cannot rename air!"); return true; } ItemRename manager = new ItemRename(plugin); manager.rename(toName, newName); sender.sendMessage(plugin.colors.getSuccess() + "Successfully renamed the item in hand to " + newName); return true; } else if(cmd.getName().equalsIgnoreCase("useful")){ // If the player typed /basic then do the following... if (args.length < 1){ sender.sendMessage("The useful plugin version " + config.getDouble("version.current") + " is working! - coded by storm345 - do /useful reload to reload the config."); return true; } else if(args[0].equalsIgnoreCase("changelog")){ sender.sendMessage(plugin.colors.getTitle() + "Changelog:"); Object[] changes = plugin.changelog.values.toArray(); for(int i=0;i<changes.length;i++){ String change = (String) changes[i]; sender.sendMessage(ChatColor.BOLD + plugin.colors.getInfo() + change); } return true; } else if(args[0].equalsIgnoreCase("reload")){ try{ plugin.getServer().getPluginManager().getPlugin("useful").reloadConfig(); plugin.getServer().getPluginManager().getPlugin("useful").reloadConfig(); sender.sendMessage(plugin.colors.getSuccess() + "Useful config successfully reloaded!"); plugin.colLogger.info("Useful config reloaded by " + sender.getName()); } catch(Exception e){ sender.sendMessage(plugin.colors.getError() + "Useful config reload was unsuccessful"); plugin.colLogger.log(Level.SEVERE, "Useful config was attempting to reload and caused an error:"); e.printStackTrace(); plugin.colLogger.log(Level.SEVERE, "Useful is attempting to disable itself to avoid errors:.."); Plugin me = plugin.getServer().getPluginManager().getPlugin("useful"); plugin.getServer().getPluginManager().disablePlugin(me); } } return true; } else if(cmd.getName().equalsIgnoreCase("head")){ if(args.length < 1){ //If they didnt mention a name return false; //Show them the usage } if(!(sender instanceof Player)){ //If not a player sender.sendMessage(plugin.colors.getError() + "Not a player!"); //Tell them return true; //return } String playerName = args[0]; //Make a string of the inputted name! //Put ur code here ItemStack itemStack = new ItemStack(Material.SKULL_ITEM); itemStack.setDurability((short) 3); SkullMeta data = (SkullMeta) itemStack.getItemMeta(); data.setOwner(playerName); itemStack.setItemMeta(data); player.sendMessage(plugin.colors.getSuccess() + "Made a skull of " + playerName + "'s face (Place to see it!)!"); player.getInventory().addItem(itemStack); return true; } else if(cmd.getName().equalsIgnoreCase("potion")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "This command is for players!"); return true; } if(args.length < 4){ return false; } Potions manager = new Potions(useful.plugin); PotionType type = manager.potionTypeFromString(args[0]); if(type == null){ sender.sendMessage(plugin.colors.getTitle() + "Valid potion types:"); sender.sendMessage(plugin.colors.getInfo() + "fire_resistance, instant_damage, instant_heal, invisibility, night_vision, poison, regen, slowness, speed, strength, water, weakness"); return true; } int level = 0; try { level = Integer.parseInt(args[1]); } catch (NumberFormatException e) { return false; } if(level < 1){ sender.sendMessage(plugin.colors.getError() + "Level must be bigger than 0"); return true; } //type and level set boolean splash = false; if(args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("yes")){ splash = true; } //nearly... int amount = 0; try { amount = Integer.parseInt(args[3]); } catch (NumberFormatException e) { return false; } if(amount < 1){ sender.sendMessage(plugin.colors.getError() + "Amount must be bigger than 0"); return true; } //All set! Potion potion; try { potion = new Potion(type, level); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Potion is invalid (Level too high?)"); return true; } if(splash){ potion.splash(); } if(args.length == 5){ boolean extended = false; if(args[4].equalsIgnoreCase("yes") || args[4].equalsIgnoreCase("true")){ extended = true; } potion.setHasExtendedDuration(extended); } ItemStack potions = potion.toItemStack(amount); player.getInventory().addItem(potions); player.sendMessage(plugin.colors.getSuccess() + "Successfully created potion!"); return true; } else if(cmd.getName().equalsIgnoreCase("timeget")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.timeget.enable"); if(isenabled == false){ sender.sendMessage(disabledmessage); return true; } if(sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "This command can only be used by players."); return true; } Location loc = ((Entity) sender).getLocation(); long current = loc.getWorld().getTime(); long time = current; double realtime = time + 6000; realtime = realtime / 1000; realtime = (double)Math.round(realtime * 100) / 100; if (realtime > 24){ realtime = realtime - 24; } realtime = (double)Math.round(realtime * 100) / 100; String r = realtime + ""; r = r.replace(".", ":"); String[] re = r.split(":"); String re1 = re[0]; String re2 = re[1]; if (re1.length() < 2){ re1 = "0" + re1; } Double re2dbl = Double.parseDouble(re2); re2dbl = re2dbl / 100; re2dbl = re2dbl * 60; re2dbl = (double)Math.round(re2dbl * 1) / 1; if (number > 59){ number = 59; } int number=(int)Math.floor(re2dbl); if (number > 59){ number = 59; } re2 = number + ""; if (re2.length() < 2){ if (number < 10){ re2 = "0" + re2; } else { re2 = re2 + "0"; } } r = re1 + ":" + re2; sender.sendMessage(plugin.colors.getInfo() + "The time is " + time + " or " + r + " in world " + loc.getWorld().getName() + "."); return true; } else if(cmd.getName().equalsIgnoreCase("gm")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.gamemode.enable"); if(isenabled == false){ sender.sendMessage(disabledmessage); return true; } if (args.length < 1){ if(sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "This command can only be used by players. Or setting another players gamemode"); return true; } Player check = (Player) sender; GameMode gm = check.getGameMode(); GameMode CREATIVE = GameMode.CREATIVE; GameMode SURVIVAL = GameMode.SURVIVAL; //GameMode ADVENTURE = GameMode.ADVENTURE; if (gm == SURVIVAL){ check.setGameMode(CREATIVE); check.sendMessage(plugin.colors.getInfo() + "Gamemode set to CREATIVE"); plugin.colLogger.info(check.getName() + "'s gamemode was changed to creative by themself"); } /* //for next update if (gm == CREATIVE){ check.setGameMode(ADVENTURE); check.sendMessage(plugin.colors.getInfo() + "Gamemode set to ADVENTURE"); getLogger().info(check.getName() + "'s gamemode was changed to adventure by themself"); } */ //in next update change creative to adventure below. if (gm == CREATIVE){ check.setGameMode(SURVIVAL); check.sendMessage(plugin.colors.getInfo() + "Gamemode set to SURVIVAL"); plugin.colLogger.info(check.getName() + "'s gamemode was changed to survival by themself"); } return true; } String pname = args[0]; Player check = Bukkit.getPlayer(pname); if (check != null){ //do command for player check GameMode gm = check.getGameMode(); GameMode CREATIVE = GameMode.CREATIVE; GameMode SURVIVAL = GameMode.SURVIVAL; //GameMode ADVENTURE = GameMode.ADVENTURE; if (gm == SURVIVAL){ check.setGameMode(CREATIVE); if (sender instanceof Player && sender.hasPermission("useful.gamemode.others")){ check.sendMessage(plugin.colors.getInfo() + "Gamemode set to CREATIVE by " + sender.getName()); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in creative mode."); plugin.colLogger.info(check.getName() + " is now in creative mode and changed by " + sender.getName()); return true; } check.sendMessage(plugin.colors.getInfo() + "Gamemode set to CREATIVE"); plugin.colLogger.info(check.getName() + "'s gamemode was changed to creative"); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in creative mode."); } /* //for next update if (gm == CREATIVE){ check.setGameMode(ADVENTURE); if (sender instanceof Player){ check.sendMessage(plugin.colors.getInfo() + "Gamemode set to ADVENTURE by " + sender.getName()); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in adventure mode."); getLogger().info(check.getName() + " is now in adventure mode and changed by " + sender.getName()); return true; } check.sendMessage(plugin.colors.getInfo() + "Gamemode set to ADVENTURE"); getLogger().info(check.getName() + "'s gamemode was changed to adventure"); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in adventure mode."); } */ //in next update change creative to adventure below. if (gm == CREATIVE){ check.setGameMode(SURVIVAL); if (sender instanceof Player && sender.hasPermission("useful.gamemode.others")){ check.sendMessage(plugin.colors.getInfo() + "Gamemode set to SURVIVAL by " + sender.getName()); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in survival mode."); plugin.colLogger.info(check.getName() + " is now in survival mode and changed by " + sender.getName()); return true; } check.sendMessage(plugin.colors.getInfo() + "Gamemode set to SURVIVAL"); plugin.colLogger.info(check.getName() + "'s gamemode was changed to survival"); sender.sendMessage(plugin.colors.getSuccess() + check.getName() + " is now in survival mode."); } } else { sender.sendMessage(plugin.colors.getError() + "Player not found."); } return true; } else if(cmd.getName().equalsIgnoreCase("time")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.time.enable"); if (isenabled == true){ if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "Only a player can use this command."); return true; } if (args.length < 1){ sender.sendMessage("Usage: /" + cmdname + " [day/night/early/late/set/add] (if set/add[Number])"); return true; } long time = 0; Location loc = ((Entity) sender).getLocation(); if (args[0].equalsIgnoreCase("day")){ time = 1500; sender.sendMessage(plugin.colors.getInfo() + "Time set to day or 7:30 AM in world " + loc.getWorld().getName() + "."); } else if (args[0].equalsIgnoreCase("midday")){ time = 6000; sender.sendMessage(plugin.colors.getInfo() + "Time set to midday or 12:00 PM in world " + loc.getWorld().getName() + "."); } else if (args[0].equalsIgnoreCase("night")){ time = 15000; sender.sendMessage(plugin.colors.getInfo() + "Time set to night or 9:00 PM in world " + loc.getWorld().getName() + "."); } else if (args[0].equalsIgnoreCase("early")){ time = -1000; sender.sendMessage(plugin.colors.getInfo() + "The time is early or 5:00 AM in world " + loc.getWorld().getName() + "."); } else if (args[0].equalsIgnoreCase("late")){ time = 12500; sender.sendMessage(plugin.colors.getInfo() + "The time is late or 6:30 PM in world " + loc.getWorld().getName() + "."); } else if (args[0].equalsIgnoreCase("set")){ if (args.length < 2){ sender.sendMessage("Usage: /" + cmdname + " [day/night/early/late/set/add] (if set/add[Number])"); return true; } try { time = Long.parseLong(args[1]); double realtime = time + 6000; realtime = realtime / 1000; realtime = (double)Math.round(realtime * 100) / 100; if (realtime > 24){ realtime = realtime - 24; } realtime = (double)Math.round(realtime * 100) / 100; String r = realtime + ""; r = r.replace(".", ":"); String[] re = r.split(":"); String re1 = re[0]; String re2 = re[1]; if (re1.length() < 2){ re1 = "0" + re1; } Double re2dbl = Double.parseDouble(re2); re2dbl = re2dbl / 100; re2dbl = re2dbl * 60; re2dbl = (double)Math.round(re2dbl * 1) / 1; int number=(int)Math.floor(re2dbl); if (number > 59){ number = 59; } re2 = number + ""; if (re2.length() < 2){ if (number < 10){ re2 = "0" + re2; } else { re2 = re2 + "0"; } } r = re1 + ":" + re2; sender.sendMessage(plugin.colors.getInfo() + "Time set to " + time + " or " + r + " in world " + loc.getWorld().getName() + "."); } catch (Exception e){ sender.sendMessage(plugin.colors.getError() + args[1] + " is not a number."); return true; } } else if (args[0].equalsIgnoreCase("add")){ if (args.length < 2){ sender.sendMessage("Usage: /" + cmdname + " [day/night/early/late/set/add] (if set/add[Number])"); return true; } try { Long add = Long.parseLong(args[1]); long current = loc.getWorld().getTime(); time = current + add; double realtime = time + 6000; realtime = realtime / 1000; realtime = (double)Math.round(realtime * 100) / 100; if (realtime > 24){ realtime = realtime - 24; } realtime = (double)Math.round(realtime * 100) / 100; String r = realtime + ""; r = r.replace(".", ":"); String[] re = r.split(":"); String re1 = re[0]; String re2 = re[1]; if (re1.length() < 2){ re1 = "0" + re1; } Double re2dbl = Double.parseDouble(re2); re2dbl = re2dbl / 100; re2dbl = re2dbl * 60; re2dbl = (double)Math.round(re2dbl * 1) / 1; int number=(int)Math.floor(re2dbl); if (number > 59){ number = 59; } re2 = number + ""; if (re2.length() < 2){ re2 = re2 + "0"; } r = re1 + ":" + re2; sender.sendMessage(plugin.colors.getInfo() + "Time increased by " + add + " and now is " + r + " in world " + loc.getWorld().getName() + "."); } catch (Exception e){ sender.sendMessage(plugin.colors.getError() + args[2] + " is not a number."); return true; } } else { sender.sendMessage(plugin.colors.getError() + "Invalid time argument. Setting time to default..."); time = 1500; sender.sendMessage(plugin.colors.getInfo() + "Time set to day."); } loc.getWorld().setTime(time); } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("jail")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ if(args.length < 3) { //Not enough arguments given! sender.sendMessage("Usage: /jail [Jailname] [Name] [Time(minutes)] [Reason]"); } else{ String jailname = args[0].toLowerCase(); Location jail = null; String locWorld = null; double locX; double locY; double locZ; float locPitch; float locYaw; try { String query = "SELECT DISTINCT * FROM jails WHERE jailname='"+jailname+"' ORDER BY jailname"; ResultSet rs = plugin.sqlite.query(query); try { locWorld = rs.getString("locWorld"); locX = Double.parseDouble(rs.getString("locX")); locY = Double.parseDouble(rs.getString("locY")); locZ = Double.parseDouble(rs.getString("locZ")); locPitch = Float.parseFloat((rs.getString("locPitch"))); locYaw = Float.parseFloat((rs.getString("locYaw"))); jail = new Location(getServer().getWorld(locWorld), locX, locY, locZ, locPitch, locYaw); rs.close(); } catch (Exception e) { e.printStackTrace(); return true; } } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Jail not found! Do /jails for a list of them"); return true; } /* int timeset = Integer.parseInt(args[2]); if(timeset < 1){ sender.sendMessage(plugin.colors.getError() + "Player must be jailed for at least a minute."); return true; } */ double timeold = 0; try { timeold = Double.parseDouble(args[2]); } catch (Exception e) { sender.sendMessage("Usage: /jail [Jailname] [Name] [Time(minutes] [Reason]"); return true; } double time = System.currentTimeMillis() + (timeold * 60000); String jailee = args[1]; Boolean contains = useful.jailed.containsKey(jailee); if (contains == false){ if (jail != null){ ArrayList<String> jailinfo = new ArrayList<String>(); String sentence = "" + time; StringBuilder messagetosend = new StringBuilder(); for (int i = 3; i < args.length; i++) { if (i != 0) messagetosend.append(" "); messagetosend.append(args[i]); } String cause = "" + messagetosend + ""; jailinfo.add(sentence); jailinfo.add(jailname); jailinfo.add(cause); useful.jailed.put(jailee, jailinfo); plugin.saveHashMap(useful.jailed, plugin.getDataFolder() + File.separator + "jailed.bin"); //sender.sendMessage(plugin.colors.getSuccess() + "Player jailed!"); if (plugin.getServer().getPlayer(jailee) != null && plugin.getServer().getPlayer(jailee).isOnline()){ plugin.getServer().getPlayer(jailee).sendMessage(plugin.colors.getError() + "You have been jailed for " + timeold + " minutes because" + cause); PlayerInventory inv = plugin.getServer().getPlayer(jailee).getInventory(); inv.clear(); plugin.getServer().getPlayer(jailee).setGameMode(GameMode.SURVIVAL); plugin.getServer().getPlayer(jailee).teleport(jail); Bukkit.broadcastMessage(jailee + " has been jailed for " + timeold + " minutes because " + cause); plugin.colLogger.info(plugin.colors.getInfo() + jailee + " has been jailed for " + timeold + " minutes because" + cause); } else{ sender.sendMessage(plugin.colors.getError() + "Player is offline!"); } } } else { sender.sendMessage(plugin.colors.getError() + "Player already jailed!"); return true; } //close player not already jailed //sender.sendMessage("" + jailed + ""); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("setjail")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage("Usage /setjail [Name]"); } else { if (sender instanceof Player){ String query = "SELECT jailname FROM jails"; boolean shouldReturn = false; try { ResultSet rs = plugin.sqlite.query(query); if(rs == null){ sender.sendMessage(plugin.colors.getError() + "Error saving jail."); plugin.colLogger.log(Level.SEVERE, "[Useful] - error saving a new jail."); return true; } while(rs.next() && shouldReturn == false){ if(rs.getString("jailname").equalsIgnoreCase(args[0].toLowerCase())){ sender.sendMessage(plugin.colors.getError() + "Jail already exists! Use /deljail to remove it."); shouldReturn = true; } } rs.close(); } catch (SQLException e) { e.printStackTrace(); return true; } if(shouldReturn){ return true; } Location loc = ((Entity) sender).getLocation(); String world; double x; double y; double z; double yaw; double pitch; world = loc.getWorld().getName(); x = loc.getX(); y = loc.getY(); z = loc.getZ(); yaw = loc.getYaw(); pitch = loc.getPitch(); //We now have all the location details set! String theData = "INSERT INTO jails VALUES('"+args[0].toLowerCase()+"', '"+world+"', "+x+", "+y+", "+z+", "+yaw+", "+pitch+");"; try { ResultSet rsi = plugin.sqlite.query(theData); rsi.close(); } catch (SQLException e) { sender.sendMessage(plugin.colors.getError() + "Error saving jail."); plugin.colLogger.log(Level.SEVERE, "[Useful] - error saving a new jail."); e.printStackTrace(); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Jail saved as " + args[0]); plugin.colLogger.info("Jail created called " + args[0].toLowerCase() + " by " + sender.getName()); } else { sender.sendMessage("Command only available to players."); } } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("mail")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.mail.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage("Usage /mail [send/read/clear/clearall] (name) (msg)"); return true; } else if (args.length > 1 && args[0].equalsIgnoreCase("send")){ String name = args[1].toLowerCase(); StringBuilder msg = new StringBuilder(); for (int i = 2; i < args.length; i++) { if (i != 0) msg.append(" "); msg.append(args[i]); } ArrayList<String> array = new ArrayList<String>(); if (useful.mail.containsKey(name)){ array = useful.mail.get(name); } array.add("From " + sender.getName() + ": " + msg); useful.mail.put(name, array); plugin.saveHashMap(useful.mail, plugin.getDataFolder() + File.separator + "mail.bin"); sender.sendMessage(ChatColor.GOLD + "Mail sent!"); if (plugin.getServer().getPlayer(args[1]) != null){ plugin.getServer().getPlayer(args[1]).sendMessage(ChatColor.GOLD + "You have recieved a message from " + sender.getName() + " type /mail read to view it!"); } } else if (args.length == 1 && args[0].equalsIgnoreCase("read")){ String name = sender.getName().toLowerCase(); ArrayList<String> array = new ArrayList<String>(); if (useful.mail.containsKey(name)){ array = useful.mail.get(name); } else { sender.sendMessage(ChatColor.GOLD + "Your mail:"); return true; } sender.sendMessage(ChatColor.GOLD + "Your mail: (type /mail clear to clear your inbox)"); String listString = ""; //String newLine = System.getProperty("line.separator"); for (String s : array) { listString += s + " %n"; } //sender.sendMessage(playerName + " " + listString); String[] message = listString.split("%n"); // Split everytime the "\n" into a new array value for(int x=0 ; x<message.length ; x++) { sender.sendMessage(plugin.colors.getSuccess() + "- " + message[x]); // Send each argument in the message } } else if (args.length == 1 && args[0].equalsIgnoreCase("clear")){ ArrayList<String> array = new ArrayList<String>(); useful.mail.put(sender.getName(), array); useful.mail.remove(sender.getName()); plugin.saveHashMap(useful.mail, plugin.getDataFolder() + File.separator + "mail.bin"); sender.sendMessage(ChatColor.GOLD + "Mail deleted!"); } else if (args.length == 1 && args[0].equalsIgnoreCase("clearall")){ if (sender.hasPermission("useful.mail.clearall")){ useful.mail = new HashMap<String, ArrayList<String>>(); plugin.saveHashMap(useful.mail, plugin.getDataFolder() + File.separator + "mail.bin"); sender.sendMessage(ChatColor.GOLD + "All server mail deleted!"); } } else { sender.sendMessage("Usage /mail [send/read/clear/clearall] (name) (msg)"); } } else { sender.sendMessage(disabledmessage); return true; } return true; } else if(cmd.getName().equalsIgnoreCase("deljail")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage("Usage /deljail [Name]"); } else { if (sender instanceof Player){ boolean found = false; boolean del = false; String query = "SELECT * FROM jails"; try { ResultSet rs = plugin.sqlite.query(query); while(rs.next()){ if(rs.getString("jailname").equalsIgnoreCase(args[0].toLowerCase())){ found = true; } if(found == true){ del = true; } } if(!found){ sender.sendMessage(plugin.colors.getError() + "Jail not found!"); } rs.close(); } catch (SQLException e1) { e1.printStackTrace(); return true; } if(!del){ return true; } //Delete the warp String delquery = "DELETE FROM jails WHERE jailname='"+args[0].toLowerCase()+"'"; try { ResultSet delete = plugin.sqlite.query(delquery); delete.close(); } catch (SQLException e) { e.printStackTrace(); sender.sendMessage(plugin.colors.getError() + "Error deleting jail."); plugin.colLogger.log(Level.SEVERE, "[Useful] - error deleting a jail."); return true; } if (found == true){ sender.sendMessage(plugin.colors.getSuccess() + "Jail deleted"); plugin.colLogger.info("Jail deleted called " + args[0] + " by " + sender.getName()); } else { sender.sendMessage(plugin.colors.getError() + "Jail not found."); } } else { sender.sendMessage("Command only available to players."); } } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("delwarp")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.warps.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage("Usage /delwarp [Name]"); } else { if (sender instanceof Player){ boolean found = false; boolean isOwner = true; boolean del = false; String query = "SELECT * FROM warps"; try { ResultSet rs = plugin.sqlite.query(query); while(rs.next()){ if(rs.getString("warpname").equalsIgnoreCase(args[0].toLowerCase())){ found = true; if(rs.getString("playername") != sender.getName()){ if(sender.hasPermission("useful.delwarp.others") == false){ isOwner = false; } } } if(found == true && isOwner == true){ del = true; } } if(!found){ sender.sendMessage(plugin.colors.getError() + "Warp not found!"); } if(!isOwner){ sender.sendMessage(plugin.colors.getError() + "You do not have permission to delete the warps of others (useful.delwarp.others)"); } rs.close(); } catch (SQLException e1) { e1.printStackTrace(); return true; } if(!del){ return true; } //Delete the warp String delquery = "DELETE FROM warps WHERE warpname='"+args[0].toLowerCase()+"'"; try { ResultSet delete = plugin.sqlite.query(delquery); delete.close(); } catch (SQLException e) { e.printStackTrace(); sender.sendMessage(plugin.colors.getError() + "Error"); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Warp deleted!"); return true; } else { sender.sendMessage("Command only available to players."); } } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("compass")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "Error: not a player"); return true; } Location loc = player.getLocation(); float yaw = loc.getYaw(); BlockFace face = ClosestFace.getClosestFace(yaw); if(face == BlockFace.DOWN){ sender.sendMessage(plugin.colors.getInfo() + "You are looking down."); } else if(face == BlockFace.UP){ sender.sendMessage(plugin.colors.getInfo() + "You are looking up."); } else if(face == BlockFace.NORTH){ sender.sendMessage(plugin.colors.getInfo() + "You are looking north."); } else if(face == BlockFace.NORTH_EAST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking north east."); } else if(face == BlockFace.EAST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking east."); } else if(face == BlockFace.SOUTH_EAST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking south east."); } else if(face == BlockFace.SOUTH){ sender.sendMessage(plugin.colors.getInfo() + "You are looking south."); } else if(face == BlockFace.SOUTH_WEST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking south west."); } else if(face == BlockFace.WEST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking west."); } else if(face == BlockFace.NORTH_WEST){ sender.sendMessage(plugin.colors.getInfo() + "You are looking north west."); } else if(face == BlockFace.SELF){ sender.sendMessage(plugin.colors.getInfo() + "You are looking at the block your feet are on."); } else{ sender.sendMessage(plugin.colors.getError() + "Error"); } return true; } else if(cmd.getName().equalsIgnoreCase("worldgm")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "You are not a player"); return true; } if(args.length < 1){ return false; } String mode = "survival"; if(args[0].equalsIgnoreCase("creative")){ mode = "creative"; } else if(args[0].equalsIgnoreCase("survival")){ mode = "survival"; } else if(args[0].equalsIgnoreCase("adventure")){ mode = "adventure"; } else if(args[0].equalsIgnoreCase("none")){ //remove it from list mode = "none"; String wname = player.getLocation().getWorld().getName(); String delquery = "DELETE FROM worldgm WHERE world='"+wname+"'"; try { ResultSet delete = plugin.sqlite.query(delquery); delete.close(); } catch (SQLException e) { e.printStackTrace(); sender.sendMessage(plugin.colors.getError() + "Error"); return true; } sender.sendMessage(plugin.colors.getSuccess() + "The default gamemode for this world set to " + mode + " override with the permission: 'useful.worldgm.bypass'"); return true; } else{ return false; } //store it in worldgm sqlite table String query = "SELECT world FROM worldgm"; String wname = player.getLocation().getWorld().getName(); boolean shouldReturn = false; try { ResultSet rs = plugin.sqlite.query(query); while(rs.next()){ if(rs.getString("world") == wname){ shouldReturn = true; } } rs.close(); } catch (SQLException e) { e.printStackTrace(); return true; } if(shouldReturn){ //remove it from list String delquery = "DELETE FROM worldgm WHERE world='"+wname+"'"; try { ResultSet delete = plugin.sqlite.query(delquery); delete.close(); } catch (SQLException e) { e.printStackTrace(); sender.sendMessage(plugin.colors.getError() + "Error"); return true; } } //add it to list String theData = "INSERT INTO worldgm VALUES('"+wname+"', '"+mode+"');"; try { ResultSet rsi = plugin.sqlite.query(theData); rsi.close(); } catch (SQLException e) { e.printStackTrace(); return true; } sender.sendMessage(plugin.colors.getSuccess() + "The default gamemode for this world set to " + mode + " override with the permission: 'useful.worldgm.bypass'"); return true; } else if(cmd.getName().equalsIgnoreCase("jailtime")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ if (sender instanceof Player){ if (args.length < 1){ String name = sender.getName(); if (useful.jailed.containsKey(name)){ long currentTime = System.currentTimeMillis(); ArrayList<String> array = JailInfo.getPlayerJailInfo(name); //ArrayList<String> array = useful.jailed.get(name); String time = array.get(0); double time2 = Double.parseDouble(time); double sentence = currentTime - time2; sentence = sentence / 60000; sentence = sentence - sentence - sentence; sentence = (double)Math.round(sentence * 10) / 10; String reason = array.get(2); sender.sendMessage(plugin.colors.getError() + "You were jailed for:" + reason + " and have " + sentence + " minutes left in jail."); } else { sender.sendMessage(plugin.colors.getSuccess() + "You are not in jail!"); } return true; } String name = args[0]; if (useful.jailed.containsKey(name)){ long currentTime = System.currentTimeMillis(); ArrayList<String> array = useful.jailed.get(name); String time = array.get(0); double time2 = Double.parseDouble(time); double sentence = currentTime - time2; sentence = sentence / 60000; sentence = sentence - sentence - sentence; sentence = (double)Math.round(sentence * 10) / 10; String reason = array.get(2); sender.sendMessage(plugin.colors.getError() + name + " has " + sentence + " minutes left in jail and was jailed for " + reason); } else { sender.sendMessage(plugin.colors.getSuccess() + name + " is not in jail!"); } } else { sender.sendMessage("Command only available to players."); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("unjail")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage(plugin.colors.getError() + "Usage: /unjail [Name]"); return true; } String name = args[0]; if (useful.jailed.containsKey(name)){ try { Player p = plugin.getServer().getPlayer(args[0]); useful.jailed.remove(name); plugin.saveHashMap(useful.jailed, plugin.getDataFolder() + File.separator + "jailed.bin"); String path = plugin.getDataFolder() + File.separator + "jailed.bin"; File file = new File(path); if(file.exists()){ // check if file exists before loading to avoid errors! useful.jailed = plugin.load(path); } if(!p.isOnline()){ sender.sendMessage(plugin.colors.getError() + "Player is not online!"); return true; } Location spawn = p.getWorld().getSpawnLocation(); p.teleport(spawn); plugin.colLogger.info(name + " has been unjailed."); p.sendMessage(plugin.colors.getSuccess() + "You have been unjailed."); sender.sendMessage(plugin.colors.getSuccess() + name + " has been unjailed!"); } catch (Exception ex) { // Should never happen ex.printStackTrace(); } } else { sender.sendMessage(plugin.colors.getSuccess() + name + " is not in jail!"); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("jails")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ ArrayList<String> jailnames = new ArrayList<String>(); try { ResultSet jails = plugin.sqlite.query("SELECT DISTINCT jailname FROM jails ORDER BY jailname"); while(jails.next()){ String name = jails.getString("jailname"); jailnames.add(name); } jails.close(); } catch (SQLException e) { sender.sendMessage(plugin.colors.getError() + "Errow listing jails from stored data!"); getLogger().log(Level.SEVERE, "Errow listing jails from stored data!", e); } Object[] ver = jailnames.toArray(); StringBuilder messagetosend = new StringBuilder(); for (int i=0;i<ver.length;i++) { //output.add(v); String v = (String) ver[i]; messagetosend.append(" "); messagetosend.append(v); messagetosend.append(","); } int page = 1; if(args.length > 0){ try { page = Integer.parseInt(args[0]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number"); return true; } } ChatPage tPage = ChatPaginator.paginate("" + messagetosend, page); sender.sendMessage(plugin.colors.getTitle() + "Jails: [" + tPage.getPageNumber() + "/" + tPage.getTotalPages() + "]"); String[] lines = tPage.getLines(); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + lines[i]); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("warps")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.warps.enable"); if(isenabled == true){ ArrayList<String> warpnames = new ArrayList<String>(); try { ResultSet warps = plugin.sqlite.query("SELECT DISTINCT warpname FROM warps ORDER BY warpname"); while(warps.next()){ String warpname = warps.getString("warpname"); warpnames.add(warpname); } warps.close(); } catch (SQLException e) { sender.sendMessage(plugin.colors.getError() + "Errow listing warps from stored data!"); getLogger().log(Level.SEVERE, "Errow listing warps from stored data!", e); } Object[] ver = warpnames.toArray(); StringBuilder messagetosend = new StringBuilder(); for (int i=0;i<ver.length;i++) { //output.add(v); String v = (String) ver[i]; messagetosend.append(" "); messagetosend.append(v); messagetosend.append(","); } int pageNumber = 1; if(args.length > 0){ try { pageNumber = Integer.parseInt(args[0]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Is an invalid page number"); return true; } } ChatPage page = ChatPaginator.paginate("" + messagetosend, pageNumber); String[] lines = page.getLines(); sender.sendMessage(plugin.colors.getInfo() + "Warps: Page[" + page.getPageNumber() + "/" + page.getTotalPages() + "]"); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + lines[i]); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("warp")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.warps.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); return true; } if (args.length < 1){ sender.sendMessage("Usage /" + cmdname + " [Warp-Name]"); return true; } String warpname = args[0].toLowerCase(); Location warp = null; String locWorld = null; double locX; double locY; double locZ; float locPitch; float locYaw; try { String query = "SELECT DISTINCT * FROM warps WHERE warpname='"+warpname+"' ORDER BY warpname"; ResultSet wrs = plugin.sqlite.query(query); try { try { locWorld = wrs.getString("locWorld"); locX = Double.parseDouble(wrs.getString("locX")); locY = Double.parseDouble(wrs.getString("locY")); locZ = Double.parseDouble(wrs.getString("locZ")); locPitch = Float.parseFloat((wrs.getString("locPitch"))); locYaw = Float.parseFloat((wrs.getString("locYaw"))); warp = new Location(getServer().getWorld(locWorld), locX, locY, locZ, locPitch, locYaw); } catch (Exception e) { } wrs.close(); } catch (Exception e) { e.printStackTrace(); return true; } ((LivingEntity) sender).teleport(warp); player.getWorld().playSound(player.getLocation(), Sound.NOTE_PLING, 1, 1); sender.sendMessage(plugin.colors.getInfo() + "Warping..."); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Warp not found! Do /warps for a list of them"); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("jailed")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.jail.enable"); if(isenabled == true){ Set<String> ver = useful.jailed.keySet(); StringBuilder messagetosend = new StringBuilder(); for (String v : ver) { //output.add(v); messagetosend.append(" "); messagetosend.append(v); messagetosend.append(","); } int page = 1; if(args.length > 0){ try { page = Integer.parseInt(args[0]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number"); return true; } } ChatPage tPage = ChatPaginator.paginate("" + messagetosend, page); sender.sendMessage(plugin.colors.getTitle() + "Jailed players: ["+tPage.getPageNumber() + "/" + tPage.getTotalPages() + "]"); String[] lines = tPage.getLines(); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + lines[i]); } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("count")){ // If the player typed /basic then do the following... boolean isenabled = useful.config.getBoolean("general.count.enable"); if(isenabled == true){ if(args.length < 1) { //No arguments given! sender.sendMessage("Usage: /" + cmdname + " [up/down] [number]"); } else{ String direction = args[0]; try { number = Integer.parseInt(args[1]); numberorig = Integer.parseInt(args[1]); } catch (Exception e) { sender.sendMessage("Usage: /" + cmdname + " [up/down] [number]"); return true; } if (direction.equalsIgnoreCase("down")){ Bukkit.broadcastMessage(plugin.colors.getSuccess() + "Countdown started by " + sender.getName()); this.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable(){ public void run(){ while (number > -1){ Bukkit.broadcastMessage(ChatColor.AQUA + "" + number); number = number - 1; try { Thread.sleep(1000); } catch (Exception e) { sender.sendMessage("An error occured."); } if (number < 0){ Bukkit.broadcastMessage(plugin.colors.getSuccess() + sender.getName() + "'s countdown has ended!"); return; } } } }); } else if (direction.equalsIgnoreCase("up")){ Bukkit.broadcastMessage(plugin.colors.getSuccess() + "Countup started by " + sender.getName()); this.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable(){ public void run(){ int number2 = 1; while (number2 <= numberorig){ Bukkit.broadcastMessage(ChatColor.AQUA + "" + number2); number2 = number2 + 1; try { Thread.sleep(1000); } catch (Exception e) { sender.sendMessage("An error occured."); } if (number2 > numberorig){ Bukkit.broadcastMessage(plugin.colors.getSuccess() + sender.getName() + "'s countup has ended!"); return; } } } }); } /* while (number > -1){ sender.sendMessage("" + number); number = number - 1; try { Thread.sleep(1000); } catch (Exception e) { sender.sendMessage("An error occured."); } } } else if (direction.equalsIgnoreCase("up")){ int number2 = 0; while (number2 <= numberorig){ sender.sendMessage("" + number2); number2 = number2 + 1; try { Thread.sleep(1000); } catch (Exception e) { sender.sendMessage("An error occured."); } } } */ else { sender.sendMessage("Usage: /count [up/down] [number]"); return true; } } } else { sender.sendMessage(disabledmessage); } return true; } /* boolean isenabled = config.getBoolean("general.burn.enable"); if(isenabled == true){ } else { sender.sendMessage(disabledmessage); } */ else if (cmd.getName().equalsIgnoreCase("eat")){ // If the player typed /eat then do the following... boolean isenabled = useful.config.getBoolean("general.eat.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if(args.length < 1){ ((Player) sender).setFoodLevel(21); player.playSound(player.getLocation(), Sound.EAT, 15, 1); sender.sendMessage(plugin.colors.getSuccess() + "You have been fed!"); return true; } else { if(sender.hasPermission("useful.eat.others") == false){ sender.sendMessage(plugin.colors.getError() + "You don't have the permission useful.eat.others."); return true; } Player p = getServer().getPlayer(args[0]); if(p != null){ p.setFoodLevel(20); p.getWorld().playSound(p.getLocation(), Sound.EAT, 15, 1); p.sendMessage(plugin.colors.getSuccess() + sender.getName() + " fed you!"); sender.sendMessage(plugin.colors.getSuccess() + "Successfully fed " + p.getName()); } else { sender.sendMessage(plugin.colors.getError() + "Player not found!"); } } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("feast")){ // If the player typed /eat then do the following... boolean isenabled = useful.config.getBoolean("general.feast.enable"); if(isenabled == true){ Player[] players = getServer().getOnlinePlayers(); sender.sendMessage(plugin.colors.getSuccess() + "Let the feast begin!"); for(int i = 0; i<players.length; i++){ Player p = players[i]; p.setFoodLevel(21); p.playSound(player.getLocation(), Sound.EAT, 15, 1); p.sendMessage(plugin.colors.getSuccess() + "You were fed in a feast courtesy of " + sender.getName()); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("murder")){ // If the player typed /eat then do the following... boolean isenabled = useful.config.getBoolean("general.murder.enable"); if(isenabled == true){ if(args.length < 1){ return false; } Player p = getServer().getPlayer(args[0]); if(p != null){ p.setHealth(0); p.sendMessage(plugin.colors.getError() + "Murdered by " + sender.getName()); sender.sendMessage(plugin.colors.getSuccess() + p.getName() + " was successfully murdered!"); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("genocide")){ // If the player typed /eat then do the following... boolean isenabled = useful.config.getBoolean("general.genocide.enable"); if(isenabled == true){ Player[] players = getServer().getOnlinePlayers(); sender.sendMessage(plugin.colors.getSuccess() + "Murdered everyone on the server!"); for(int i = 0; i<players.length; i++){ players[i].sendMessage(plugin.colors.getError() + "Killed in a genocide created by " + sender.getName()); players[i].setHealth(0); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("smite")){ // If the player typed /eat then do the following... boolean isenabled = useful.config.getBoolean("general.smite.enable"); if(isenabled == true){ if (args.length < 1){ sender.sendMessage("Usage /smite [Name]"); return true; } String pName = args[0]; if (getServer().getPlayer(pName) == null){ sender.sendMessage(plugin.colors.getError() + "Player not found."); return true; } Location loc = getServer().getPlayer(pName).getLocation(); boolean damage = config.getBoolean("general.smite.damage"); if (damage){ getServer().getPlayer(pName).getWorld().strikeLightning(loc); } else { getServer().getPlayer(pName).getWorld().strikeLightningEffect(loc); } sender.sendMessage(plugin.colors.getSuccess() + "Player has been smited"); getServer().getPlayer(pName).sendMessage(plugin.colors.getSuccess() + "You have been smited"); plugin.colLogger.info(sender.getName() + " has smited " + pName); } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("setwarp")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.warps.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ sender.sendMessage("Usage /setwarp [Name]"); return true; } String query = "SELECT warpname FROM warps"; boolean shouldReturn = false; try { ResultSet rs = plugin.sqlite.query(query); while(rs.next() && shouldReturn == false){ if(rs.getString("warpname").equalsIgnoreCase(args[0].toLowerCase())){ sender.sendMessage(plugin.colors.getError() + "Warp already exists! Use /delwarp to remove it."); shouldReturn = true; } } rs.close(); } catch (SQLException e) { e.printStackTrace(); return true; } if(shouldReturn){ return true; } Location loc = ((Entity) sender).getLocation(); String owner = sender.getName(); String world; double x; double y; double z; double yaw; double pitch; world = loc.getWorld().getName(); x = loc.getX(); y = loc.getY(); z = loc.getZ(); yaw = loc.getYaw(); pitch = loc.getPitch(); //We now have all the location details set! String theData = "INSERT INTO warps VALUES('"+owner+"', '"+args[0].toLowerCase()+"', '"+world+"', "+x+", "+y+", "+z+", "+yaw+", "+pitch+");"; try { ResultSet rsi = plugin.sqlite.query(theData); rsi.close(); } catch (SQLException e) { e.printStackTrace(); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Successfully set warp!"); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("setspawn")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.setspawn.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { Location loc = ((Entity) sender).getLocation(); double xd = loc.getX(); double yd = loc.getY(); double zd = loc.getZ(); int x = (int)Math.floor(xd); int y = (int)Math.floor(yd); int z = (int)Math.floor(zd); ((Entity) sender).getWorld().setSpawnLocation(x, y, z); sender.sendMessage(plugin.colors.getSuccess() + "World spawn point set!"); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("spawn")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.spawn.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { Location sp = ((Entity) sender).getWorld().getSpawnLocation(); sender.sendMessage(plugin.colors.getSuccess() + "Teleported to world's spawn location!"); ((Entity) sender).teleport(sp); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("tp")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.tp.enable"); if(isenabled == true){ if (!isenabled) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ sender.sendMessage("Usage: /" + cmdname + " [name] ([Name]) or... ([Name]) [x] [y] [z]"); } else if (args.length == 2){ if (player == null) { sender.sendMessage("This command can only be used by a player"); return true; } Player target = this.getServer().getPlayer(args[1]); Player telepoertee = this.getServer().getPlayer(args[0]); if (target != null && telepoertee != null){ telepoertee.sendMessage(plugin.colors.getTp() + "Teleporting you to " + target.getName() + " courtesy of " + sender.getName() + "..."); sender.sendMessage(plugin.colors.getTp() + "Teleporting..."); ((LivingEntity) telepoertee).teleport(target); target.sendMessage(plugin.colors.getTp() + telepoertee.getName() + " was teleported to your location by " + sender.getName() + "!"); } else { sender.sendMessage(plugin.colors.getError() + "Player not found."); } } else if (args.length == 3){ if (player == null) { sender.sendMessage("This command can only be used by a player"); return true; } Player p = getServer().getPlayer(sender.getName()); Location sendloc = p.getLocation(); World world = sendloc.getWorld(); double x = 0; double y = 0; double z = 0; try{ x = Double.parseDouble(args[0]); y = Double.parseDouble(args[1]); z = Double.parseDouble(args[2]); } catch(Exception e){ sender.sendMessage(plugin.colors.getError() + "Your coordinates were not recognised as numbers!"); return true; } Location loc = new Location(world, x, y, z); sender.sendMessage(plugin.colors.getTp() + "Teleporting..."); ((LivingEntity) sender).teleport(loc); } else if (args.length == 4){ Player p = getServer().getPlayer(args[0]); if (p == null){ sender.sendMessage(plugin.colors.getError() + "Player not found."); return true; } Location sendloc = p.getLocation(); World world = sendloc.getWorld(); double x = 0; double y = 0; double z = 0; try{ x = Double.parseDouble(args[1]); y = Double.parseDouble(args[2]); z = Double.parseDouble(args[3]); } catch(Exception e){ sender.sendMessage(plugin.colors.getError() + "Your coordinates were not recognised as numbers!"); return true; } Location loc = new Location(world, x, y, z); sender.sendMessage(plugin.colors.getTp() + "Teleporting..."); p.sendMessage(plugin.colors.getTp() + "Teleporting courtesy of " + sender.getName() + "..."); ((LivingEntity) p).teleport(loc); } else { if (player == null) { sender.sendMessage("This command can only be used by a player"); return true; } Player target = this.getServer().getPlayer(args[0]); if (target != null){ sender.sendMessage(plugin.colors.getTp() + "Teleporting..."); ((LivingEntity) sender).teleport(target); target.sendMessage(plugin.colors.getTp() + sender.getName() + " teleported to your location!"); } else { sender.sendMessage(plugin.colors.getError() + "Player not found."); } } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("tpa")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.tpa.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ sender.sendMessage("Usage: /" + cmdname + " [Name]"); return true; } Location loc = getServer().getPlayer(args[0]).getLocation(); Player target = getServer().getPlayer(args[0]); if(loc != null && target != null){ //initiate request long reqTime = System.currentTimeMillis() + 60000; TpaReq req = new TpaReq(player.getName(), target.getName(), reqTime, true); TeleportRequest.addTeleportRequest(player, req); sender.sendMessage(plugin.colors.getSuccess() + "Request sent!"); } else{ sender.sendMessage(plugin.colors.getError() + "Player not found!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("tpahere")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.tpa.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ sender.sendMessage("Usage: /" + cmdname + " [Name]"); return true; } Location loc = getServer().getPlayer(args[0]).getLocation(); Player target = getServer().getPlayer(args[0]); if(loc != null && target != null){ //initiate request long reqTime = System.currentTimeMillis() + 60000; TpaReq req = new TpaReq(player.getName(), target.getName(), reqTime, false); TeleportRequest.addTeleportRequest(player, req); sender.sendMessage(plugin.colors.getSuccess() + "Request sent!"); } else{ sender.sendMessage(plugin.colors.getError() + "Player not found!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("tpaccept")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.tpa.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { TpaReq req = TeleportRequest.getTeleportRequest(player); if(req == null){ sender.sendMessage(plugin.colors.getError() + "You don't have any teleport requests!"); return true; } String requester; requester = req.getRequester(); Player target = null; try { target = plugin.getServer().getPlayer(requester); } catch (Exception e) { sender.sendMessage("An error occured"); return true; } if(target == null){ sender.sendMessage(plugin.colors.getError() + "You don't have any teleport requests!"); return true; } Player[] players = getServer().getOnlinePlayers(); boolean online = false; for(int i = 0; i < players.length; i++){ if(players[i] == target){ online = true; } } if(online == false){ TeleportRequest.requests.remove(player); sender.sendMessage(plugin.colors.getError() + "You don't have any teleport requests!"); return true; } boolean timeout = req.getTimedOut(System.currentTimeMillis()); if(timeout){ TeleportRequest.requests.remove(player); sender.sendMessage(plugin.colors.getError() + "Request timeout: Answer sooner."); return true; } boolean tpa = req.getTpa(); if(tpa){ player.sendMessage(plugin.colors.getSuccess() + "Teleporting " + target.getName() + " to you!"); target.sendMessage(plugin.colors.getSuccess() + player.getName() + " Accepted your request!"); target.teleport(player); } else { player.sendMessage(plugin.colors.getSuccess() + "Teleporting you to " + target.getName() + "!"); target.sendMessage(plugin.colors.getSuccess() + player.getName() + " Accepted your request!"); player.teleport(target); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("tphere")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.tphere.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ sender.sendMessage("Usage: /" + cmdname + " [name]"); } else { Player target = this.getServer().getPlayer(args[0]); String sendername = sender.getName(); Player sender2 = this.getServer().getPlayer(sendername); if (target != null){ sender.sendMessage(plugin.colors.getTp() + "Teleporting..."); ((LivingEntity) target).teleport(sender2); target.sendMessage(plugin.colors.getTp() + sender.getName() + " teleported you to their location!"); } else { sender.sendMessage(plugin.colors.getError() + "Player not found."); } } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("levelup")){ // If the player typed /eat then do the following... boolean isenabled = config.getBoolean("general.levelup.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { ((Player) sender).setLevel(((Player) sender).getLevel() + 1); sender.sendMessage(plugin.colors.getSuccess() + "You have been levelled up!"); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("killmobs")){ // If the player typed /eat then do the following... //Fixed perm glitch!!!!! In plugin.yml!!! boolean isenabled = config.getBoolean("general.killmobs.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if (args.length < 1){ Entity senderent = ((Entity) sender); Location loc = senderent.getLocation(); List<Entity> entities = ((Location) loc).getWorld().getEntities(); int killed = 0; Object[] entarray = entities.toArray(); Entity listent; for (Object s : entarray) { boolean playerfound = false; listent = (Entity) s; EntityType type = listent.getType(); if (listent instanceof Player){ playerfound = true; } else if (listent instanceof LivingEntity && playerfound == false && type.toString() != "WOLF" && type.toString() != "OCELOT" && type.toString() != "SHEEP" && type.toString() != "COW" && type.toString() != "CHICKEN" && type.toString() != "SQUID" && type.toString() != "VILLAGER" && type.toString() != "MOOSHROOM" && type.toString() != "PIG" && type.toString() != "WITCH" && type.toString() != "BAT" && type.toString() != "ITEM_FRAME"){ listent.remove(); killed++; } } sender.sendMessage(plugin.colors.getInfo() + "" + killed + " Monsters's killed in the whole world."); } else { int radius = 0; try { radius = Integer.parseInt(args[0]); } catch (Exception e) { sender.sendMessage("Your radius was not recognised as a number!"); return true; } Entity senderent = ((Entity) sender); Double x = (double) radius; Double y = (double) radius; Double z = (double) radius; List<Entity> near = senderent.getNearbyEntities(x, y, z); int killed = 0; Object[] entarray = near.toArray(); Entity listent; for (Object s : entarray) { boolean playerfound = false; listent = (Entity) s; EntityType type = listent.getType(); if (listent instanceof Player){ playerfound = true; } else if (listent instanceof LivingEntity && playerfound == false && type.toString() != "WOLF" && type.toString() != "OCELOT" && type.toString() != "SHEEP" && type.toString() != "COW" && type.toString() != "CHICKEN" && type.toString() != "SQUID" && type.toString() != "VILLAGER" && type.toString() != "MOOSHROOM" && type.toString() != "PIG" && type.toString() != "WITCH" && type.toString() != "BAT" && type.toString() != "ITEM_FRAME"){ listent.remove(); killed++; } } sender.sendMessage(plugin.colors.getInfo() + "" + killed + " Monsters's killed in the radius of " + radius + "."); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("setlevel")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.setlevel.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if(args.length < 1) { //No arguments given! sender.sendMessage("Usage: /" + cmdname + " [Level]"); return true; } else{ int level = 0; try { level = Integer.parseInt(args[0]); } catch (Exception e) { sender.sendMessage("Usage: /" + cmdname + " [Level]"); return true; } ((Player) sender).setLevel(level); sender.sendMessage(plugin.colors.getSuccess() + "You have been levelled up!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("getid")){ // If the player typed /getid then do the following... boolean isenabled = config.getBoolean("general.getid.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { ItemStack itemslot = ((HumanEntity) sender).getInventory().getItemInHand(); int itemid = itemslot.getType().getId(); MaterialData itemname = itemslot.getData(); String name = itemname.getItemType().name(); short newitemdata = itemslot.getDurability(); String theitemname = name;//itemname.toString(); //Scanner in = new Scanner(theitemdata).useDelimiter("[^0-9]+"); //int itemdataint = in.nextInt(); String newitemname = theitemname.replaceAll("[0-9]", ""); String neweritemname = newitemname.replace(")", ""); String newestitemname = neweritemname.replace("(", ""); newestitemname = newestitemname.toLowerCase(); newestitemname = newestitemname.replaceAll("facing", ""); newestitemname = newestitemname.replaceAll("null", ""); //int itemdataint = Integer.parseInt(itemdataext); String id = Integer.toString(itemid); //String data = Integer.toString(itemdataint); if (newitemdata < 1){ String message = id; sender.sendMessage(plugin.colors.getInfo() + "The item in hand is " + newestitemname + " id:" + plugin.colors.getSuccess() + message); } else { String message = id + ":"+ newitemdata; sender.sendMessage(plugin.colors.getInfo() + "The item in hand is " + newestitemname + " id:" + plugin.colors.getSuccess() + message); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("look")){ // If the player typed /getid then do the following... boolean isenabled = config.getBoolean("general.getid.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { Block itemslot = player.getTargetBlock(null, 5); int itemid = itemslot.getType().getId(); MaterialData itemname = itemslot.getState().getData(); String name = itemname.getItemType().name(); int newitemdata = itemslot.getState().getRawData(); String theitemname = name;//itemname.toString(); //Scanner in = new Scanner(theitemdata).useDelimiter("[^0-9]+"); //int itemdataint = in.nextInt(); String newitemname = theitemname.replaceAll("[0-9]", ""); String neweritemname = newitemname.replace(")", ""); String newestitemname = neweritemname.replace("(", ""); newestitemname = newestitemname.toLowerCase(); newestitemname = newestitemname.replaceAll("facing", ""); newestitemname = newestitemname.replaceAll("null", ""); //int itemdataint = Integer.parseInt(itemdataext); String id = Integer.toString(itemid); //String data = Integer.toString(itemdataint); if (newitemdata < 1){ String message = id; sender.sendMessage(plugin.colors.getInfo() + "The block you are looking at is " + newestitemname + " id:" + plugin.colors.getSuccess() + message); } else { String message = id + ":"+ newitemdata; sender.sendMessage(plugin.colors.getInfo() + "The block you are looking at is " + newestitemname + " id:" + plugin.colors.getSuccess() + message); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("burn")){ // If the player typed /burn then do the following... if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if(args.length < 1) { //No arguments given! sender.sendMessage("You forgot to mention who to burn!"); } else{ Player s = (Player) sender; Player check = Bukkit.getPlayer(args[0]); Player target = s.getServer().getPlayer(args[0]); // Gets the player who was typed in the command. // For instance, if the command was "/ignite notch", then the player would be just "notch". // Note: The first argument starts with [0], not [1]. So arg[0] will get the player typed. if(check != null){ boolean isenabled = config.getBoolean("general.burn.enable"); if(isenabled == true){ target.setFireTicks(10000); sender.sendMessage("That player is on fire! (If they are in survival)"); } else { sender.sendMessage(disabledmessage); } } else { s.sendMessage(plugin.colors.getError() + "Player not found!"); } } } return true; } else if (cmd.getName().equalsIgnoreCase("message")){ // If the player typed /burn then do the following... boolean isenabled = config.getBoolean("general.message.enable"); if(isenabled == true){ if(args.length < 1) { //No arguments given! sender.sendMessage("Usage: /" + cmdname + " [Name] [Message]"); } else{ StringBuilder messagetosend = new StringBuilder(); for (int i = 1; i < args.length; i++) { if (i != 0) messagetosend.append(" "); messagetosend.append(args[i]); } Player check = Bukkit.getPlayer(args[0]); Player target = getServer().getPlayer(args[0]); // Gets the player who was typed in the command. // For instance, if the command was "/ignite notch", then the player would be just "notch". // Note: The first argument starts with [0], not [1]. So arg[0] will get the player typed. if(check != null){ target.sendMessage(plugin.colors.getTitle() + "from " + plugin.colors.getSuccess() + sender.getName() + ": " + plugin.colors.getInfo() + messagetosend); getLogger().info("from " + sender.getName() + " to " + args[0] + " -message:-" + messagetosend); sender.sendMessage(plugin.colors.getTitle() + "to " + plugin.colors.getSuccess() + target.getName() + ": " + plugin.colors.getInfo() + messagetosend); } else { sender.sendMessage(plugin.colors.getError() + "Player not found!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("warn")){ // If the player typed /burn then do the following... boolean isenabled = config.getBoolean("general.warning.enable"); if(isenabled == true){ if(args.length < 1) { //No arguments given! sender.sendMessage("Usage: " + cmdname + " [Player] [Reason]"); } else{ StringBuilder warnmsg = new StringBuilder(); for (int i = 1; i < args.length; i++) { if (i != 0) warnmsg.append(" "); warnmsg.append(args[i]); } Player check = Bukkit.getPlayer(args[0]); Player target = getServer().getPlayer(args[0]); // Gets the player who was typed in the command. // For instance, if the command was "/ignite notch", then the player would be just "notch". // Note: The first argument starts with [0], not [1]. So arg[0] will get the player typed. if(check != null){ target.sendMessage(plugin.colors.getError() + "You have been warned by " + sender.getName() + " " + plugin.colors.getInfo() + "for" + warnmsg); getLogger().info(plugin.colors.getError() + target.getName() + " has been warned by " + sender.getName() + " " + plugin.colors.getInfo() + "for" + warnmsg); sender.sendMessage("Warning sent!"); boolean sendtoall = config.getBoolean("general.warning.sendtoall"); if (sendtoall == true) { getServer().broadcastMessage(plugin.colors.getError() + target.getName() + " has been warned by " + sender.getName() + " " + plugin.colors.getInfo() + "for" + warnmsg); plugin.warns.add("" + target.getName() + " has been warned by " + sender.getName() + " for" + warnmsg); plugin.warns.save(); String pluginFolder = plugin.getDataFolder().getAbsolutePath(); plugin.warnsplayer = new ListStore(new File(pluginFolder + File.separator + "warns" + File.separator + target.getName() + ".txt")); plugin.warnsplayer.load(); plugin.warnsplayer.add("* Warned by " + sender.getName() + " for" + warnmsg); plugin.warnsplayer.save(); } else { } } else { sender.sendMessage(plugin.colors.getError() + "Player not found!"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("hero")){ // If the player typed /burn then do the following... boolean isenabled = config.getBoolean("general.hero.enable"); if(isenabled == true){ if (args.length < 1){ //no arguments given if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { String heroName = sender.getName(); if (plugin.heros.contains(heroName) == false){ plugin.heros.add(heroName); plugin.heros.save(); Player hero = (Player) sender; PlayerInventory heroinv = hero.getInventory(); if (heroinv.getHelmet() != null && heroinv.getHelmet() != new ItemStack(0)){ ItemStack helmet = heroinv.getHelmet(); heroinv.setHelmet(new ItemStack(0)); if (helmet.getTypeId() != 0){ heroinv.addItem(helmet); } } if (heroinv.getBoots() != null && heroinv.getBoots() != new ItemStack(0)){ ItemStack boots = heroinv.getBoots(); heroinv.setBoots(new ItemStack(0)); if (boots.getTypeId() != 0){ heroinv.addItem(boots); } } if (heroinv.getChestplate() != null && heroinv.getChestplate() != new ItemStack(0)){ ItemStack chest = heroinv.getChestplate(); heroinv.setChestplate(new ItemStack(0)); if (chest.getTypeId() != 0){ heroinv.addItem(chest); } } if (heroinv.getLeggings() != null && heroinv.getLeggings() != new ItemStack(0)){ ItemStack legs = heroinv.getLeggings(); heroinv.setLeggings(new ItemStack(0)); if (legs.getTypeId() != 0){ heroinv.addItem(legs); } } heroinv.addItem(new ItemStack(276)); heroinv.setBoots(new ItemStack(313)); heroinv.setChestplate(new ItemStack(311)); heroinv.setHelmet(new ItemStack(20)); heroinv.setLeggings(new ItemStack(312)); ((LivingEntity) sender).setHealth(20); ((Player) sender).setFoodLevel(21); sender.sendMessage(plugin.colors.getTitle() + "[HERO MODE]" + plugin.colors.getSuccess() + "Hero mode enabled."); this.getLogger().info("Hero mode enabled for " + sender.getName()); } else { plugin.heros.remove(heroName); plugin.heros.save(); Player hero = (Player) sender; PlayerInventory heroinv = hero.getInventory(); heroinv.removeItem(new ItemStack(276)); if (heroinv.getHelmet() != null && heroinv.getHelmet() != new ItemStack(0)){ ItemStack helmet = heroinv.getHelmet(); heroinv.setHelmet(new ItemStack(0)); if (helmet.getTypeId() != 0){ heroinv.addItem(helmet); } } if (heroinv.getBoots() != null && heroinv.getBoots() != new ItemStack(0)){ ItemStack boots = heroinv.getBoots(); heroinv.setBoots(new ItemStack(0)); if (boots.getTypeId() != 0){ heroinv.addItem(boots); } } if (heroinv.getChestplate() != null && heroinv.getChestplate() != new ItemStack(0)){ ItemStack chest = heroinv.getChestplate(); heroinv.setChestplate(new ItemStack(0)); if (chest.getTypeId() != 0){ heroinv.addItem(chest); } } if (heroinv.getLeggings() != null && heroinv.getLeggings() != new ItemStack(0)){ ItemStack legs = heroinv.getLeggings(); heroinv.setLeggings(new ItemStack(0)); if (legs.getTypeId() != 0){ heroinv.addItem(legs); } } heroinv.removeItem(new ItemStack(313)); heroinv.removeItem(new ItemStack(20)); heroinv.removeItem(new ItemStack(311)); heroinv.removeItem(new ItemStack(312)); //heroinv.setBoots(new ItemStack(0)); //heroinv.setChestplate(new ItemStack(0)); //heroinv.setHelmet(new ItemStack(0)); //heroinv.setLeggings(new ItemStack(0)); sender.sendMessage(plugin.colors.getTitle() + "[HERO MODE]" + plugin.colors.getError() + "Hero mode disabled."); this.getLogger().info("Hero mode disabled for " + sender.getName()); } } } else{ // Gets the player who was typed in the command. // For instance, if the command was "/ignite notch", then the player would be just "notch". // Note: The first argument starts with [0], not [1]. So arg[0] will get the player typed. sender.sendMessage("Usage /hero"); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("delete-warns")){ // If the player typed /view-warns then do the following... boolean isenabled = config.getBoolean("general.warning.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if(args.length < 1) { //No arguments given! sender.sendMessage("Usage /" + cmdname + " [name]"); } else{ String playerName = args[0]; String pluginFolder = plugin.getDataFolder().getAbsolutePath(); new File(pluginFolder + File.separator + "warns" + File.separator + playerName + ".txt").delete(); sender.sendMessage(plugin.colors.getSuccess() + playerName + "'s warning's have been deleted."); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("view-warns")){ // If the player typed /view-warns then do the following... boolean isenabled = config.getBoolean("general.warning.enable"); if(isenabled == true){ if(args.length < 1) { //No arguments given! sender.sendMessage("Usage /" + cmdname + " [name]"); } else{ String playerName = args[0]; String pluginFolder = plugin.getDataFolder().getAbsolutePath(); plugin.warnsplayer = new ListStore(new File(pluginFolder + File.separator + "warns" + File.separator + playerName + ".txt")); plugin.warnsplayer.load(); ArrayList<String> warnlist = plugin.warnsplayer.getValues(); String listString = ""; //String newLine = System.getProperty("line.separator"); for (String s : warnlist) { listString += s + " %n"; } //sender.sendMessage(playerName + " " + listString); int page = 1; if(args.length > 1){ try { page = Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number"); return true; } } ChatPage tPage = ChatPaginator.paginate("" + listString, page); sender.sendMessage(plugin.colors.getTitle() + playerName + "'s warnings: ["+tPage.getPageNumber() + "/" + tPage.getTotalPages() + "]"); String[] lines = tPage.getLines(); String list = plugin.colors.getInfo() + ""; for(int i=0;i<lines.length;i++){ list = plugin.colors.getInfo() + list + plugin.colors.getInfo() + ChatColor.stripColor(lines[i]) + " "; } String[] message = list.split("%n"); // Split everytime the "\n" into a new array value for(int x=0 ; x<message.length ; x++) { sender.sendMessage(plugin.colors.getInfo() + ChatColor.stripColor(message[x])); // Send each argument in the message } plugin.warnsplayer.save(); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("warnslog")){ // If the player typed /view-warns then do the following... boolean isenabled = config.getBoolean("general.warning.enable"); if(isenabled == true){ if(args.length < 1) { //No arguments given! ArrayList<String> warnlist = plugin.warns.getValues(); sender.sendMessage(plugin.colors.getTitle() + "Log of warnings:"); String listString = ""; //String newLine = System.getProperty("line.separator"); for (String s : warnlist) { listString += s + " %n"; } //sender.sendMessage(playerName + " " + listString); String[] message = listString.split("%n"); // Split everytime the "\n" into a new array value for(int x=0 ; x<message.length ; x++) { sender.sendMessage(plugin.colors.getError() + message[x]); // Send each argument in the message } } else{ String action = args[0]; if (action.equalsIgnoreCase("clear")){ String pluginFolder = plugin.getDataFolder().getAbsolutePath(); new File(pluginFolder + File.separator + "warns.log").delete(); plugin.warns = new ListStore(new File(pluginFolder + File.separator +"warns.log")); plugin.warns.load(); sender.sendMessage(plugin.colors.getSuccess() + "The warning's log has been cleared."); plugin.warns.save(); } else { sender.sendMessage("Usage /warnslog ([Nothing, clear])"); } } } else { sender.sendMessage(disabledmessage); } return true; } else if(cmd.getName().equalsIgnoreCase("rules")){ ArrayList<String> rules = plugin.rules.getValues(); sender.sendMessage(plugin.colors.getTitle() + "Server rules:"); String listString = ""; //String newLine = System.getProperty("line.separator"); for (String s : rules) { listString += s + " %n"; } //sender.sendMessage(playerName + " " + listString); String[] message = listString.split("%n"); // Split everytime the "\n" into a new array value for(int x=0 ; x<message.length ; x++) { sender.sendMessage(plugin.colors.getInfo() + "[" + (x+1) + "]" + plugin.colors.getInfo() + useful.colorise(message[x])); // Send each argument in the message } return true; } else if(cmd.getName().equalsIgnoreCase("information")){ ArrayList<String> info = plugin.info.getValues(); String listString = ""; //String newLine = System.getProperty("line.separator"); for (String s : info) { listString += s + " %n"; } //sender.sendMessage(playerName + " " + listString); int page = 1; if(args.length > 0){ try { page = Integer.parseInt(args[0]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Invalid page number"); return true; } } ChatPage tPage = ChatPaginator.paginate("" + listString, page); sender.sendMessage(plugin.colors.getTitle() + "Server info: ["+tPage.getPageNumber() + "/" + tPage.getTotalPages() + "]"); String[] lines = tPage.getLines(); String list = plugin.colors.getInfo() + ""; for(int i=0;i<lines.length;i++){ list = plugin.colors.getInfo() + list + plugin.colors.getInfo() + lines[i] + " "; } String[] message = list.split("%n"); // Split everytime the "\n" into a new array value for(int x=0 ; x<message.length ; x++) { sender.sendMessage(plugin.colors.getInfo() + useful.colorise(message[x])); // Send each argument in the message } return true; } else if (cmd.getName().equalsIgnoreCase("magicmessage")){ // If the player typed /burn then do the following... boolean isenabled = config.getBoolean("general.magicmessage.enable"); if(isenabled == true){ if (player == null) { sender.sendMessage("This command can only be used by a player"); } else { if(args.length < 1) { //No arguments given! sender.sendMessage("Usage: /" + cmdname + " [Message]"); } else{ StringBuilder messagetosender = new StringBuilder(); for (int i = 0; i < args.length; i++) { if (i != 0) messagetosender.append(" "); messagetosender.append(args[i]); } // Gets the player who was typed in the command. // For instance, if the command was "/ignite notch", then the player would be just "notch". // Note: The first argument starts with [0], not [1]. So arg[0] will get the player typed. getServer().broadcastMessage(plugin.colors.getInfo() + "<" + sender.getName() + ">" + ChatColor.MAGIC + "" + messagetosender); } } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("listplayers")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.listplayers.enable"); if(isenabled == true){ OfflinePlayer[] allplayers = getServer().getOfflinePlayers(); StringBuilder playerslist = new StringBuilder(); for (int i = 0; i < allplayers.length; i++) { if (i != 0) playerslist.append(" "); playerslist.append(allplayers[i].getName()); playerslist.append(", "); } sender.sendMessage("All the players that have been on this server are: " + playerslist); } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("ci")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.ci.enable"); if(isenabled == true){ if (args.length < 1){ //No args given - clear sender inv if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command. Or do /ci [Name]"); return true; } PlayerInventory inv = ((Player )sender).getInventory(); inv.clear(); inv.setChestplate(new ItemStack(0)); inv.setHelmet(new ItemStack(0)); inv.setLeggings(new ItemStack(0)); inv.setBoots(new ItemStack(0)); sender.sendMessage(plugin.colors.getSuccess() + "Inventory has been cleared!"); } else { //player name given if (sender instanceof Player && sender.hasPermission("useful.ci.others") == false){ if (sender.getName().equalsIgnoreCase(args[0])){ } else { sender.sendMessage(plugin.colors.getError() + "You are not allowed to clear other's inventories."); return true; } } Player target = getServer().getPlayer(args[0]); if (target == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } PlayerInventory inv = target.getInventory(); inv.clear(); inv.setChestplate(new ItemStack(0)); inv.setHelmet(new ItemStack(0)); inv.setLeggings(new ItemStack(0)); inv.setBoots(new ItemStack(0)); sender.sendMessage(plugin.colors.getSuccess() + "Inventory has been cleared!"); target.sendMessage(plugin.colors.getInfo() + "Your inventory has been cleared by " + sender.getName()); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("invsee")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.invsee.enable"); if(isenabled == true){ if (args.length < 1){ //No args given - clear sender inv sender.sendMessage(plugin.colors.getInfo() + "Usage /" + cmdname + " [Name]"); } else { //player name given if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } Player target = getServer().getPlayer(args[0]); if (target == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } Inventory inv = target.getInventory(); HumanEntity ent = player; useful.invsee.add(sender.getName()); player.getWorld().playSound(player.getLocation(), Sound.CHEST_OPEN, 1, 1); ent.openInventory(inv); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("creative")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.creativecommand.enable"); if(isenabled == true){ if (args.length < 1){ if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } //No args given - clear sender inv player.setGameMode(GameMode.CREATIVE); player.getWorld().playSound(player.getLocation(), Sound.FIZZ, 1, 10); sender.sendMessage(plugin.colors.getSuccess() + "Your gamemode was set to creative"); getLogger().info(sender.getName() + "'s gamemode was set to creative by themselves"); } else { //player name given if (sender.hasPermission("useful.gamemode.others") == false){ sender.sendMessage(plugin.colors.getError() + "You don't have permission to change others gamemodes (useful.gamemode.others)"); return true; } Player target = getServer().getPlayer(args[0]); if (target == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } target.setGameMode(GameMode.CREATIVE); target.getWorld().playSound(target.getLocation(), Sound.FIZZ, 1, 10); sender.sendMessage(plugin.colors.getSuccess() + target.getName() + "'s gamemode was set to creative!"); target.sendMessage(plugin.colors.getSuccess() + sender.getName() + " set your gamemode to creative!"); getLogger().info(target.getName() + "'s gamemode was set to creative by " + sender.getName()); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("survival")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.survivalcommand.enable"); if(isenabled == true){ if (args.length < 1){ if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } //No args given - clear sender inv player.setGameMode(GameMode.SURVIVAL); player.getWorld().playSound(player.getLocation(), Sound.FIZZ, 1, 10); sender.sendMessage(plugin.colors.getSuccess() + "Your gamemode was set to survival"); getLogger().info(sender.getName() + "'s gamemode was set to survival by themselves"); } else { //player name given if (sender.hasPermission("useful.gamemode.others") == false){ sender.sendMessage(plugin.colors.getError() + "You don't have permission to change others gamemodes (useful.gamemode.others)"); return true; } Player target = getServer().getPlayer(args[0]); if (target == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } target.getWorld().playSound(target.getLocation(), Sound.FIZZ, 1, 10); target.setGameMode(GameMode.SURVIVAL); sender.sendMessage(plugin.colors.getSuccess() + target.getName() + "'s gamemode was set to survival!"); target.sendMessage(plugin.colors.getSuccess() + sender.getName() + " set your gamemode to survival!"); getLogger().info(target.getName() + "'s gamemode was set to survival by " + sender.getName()); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("adventure")){ // If the player typed /setlevel then do the following... boolean isenabled = config.getBoolean("general.adventurecommand.enable"); if(isenabled == true){ if (args.length < 1){ if (sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "You must be a player to use this command."); return true; } //No args given - clear sender inv player.setGameMode(GameMode.ADVENTURE); player.getWorld().playSound(player.getLocation(), Sound.FIZZ, 1, 10); sender.sendMessage(plugin.colors.getSuccess() + "Your gamemode was set to adventure"); getLogger().info(sender.getName() + "'s gamemode was set to adventure by themselves"); } else { //player name given if (sender.hasPermission("useful.gamemode.others") == false){ sender.sendMessage(plugin.colors.getError() + "You don't have permission to change others gamemodes (useful.gamemode.others)"); return true; } Player target = getServer().getPlayer(args[0]); if (target == null){ sender.sendMessage(plugin.colors.getError() + "Player not found!"); return true; } target.setGameMode(GameMode.ADVENTURE); target.getWorld().playSound(target.getLocation(), Sound.FIZZ, 1, 10); sender.sendMessage(plugin.colors.getSuccess() + target.getName() + "'s gamemode was set to adventure!"); target.sendMessage(plugin.colors.getSuccess() + sender.getName() + " set your gamemode to adventure!"); getLogger().info(target.getName() + "'s gamemode was set to adventure by " + sender.getName()); } } else { sender.sendMessage(disabledmessage); } return true; } else if (cmd.getName().equalsIgnoreCase("ucommands")){ // If the player typed /setlevel then do the following... PluginDescriptionFile desc = getServer().getPluginManager().getPlugin("useful").getDescription(); Map<String, Map<String, Object>> cmds = desc.getCommands(); Set<String> keys = cmds.keySet(); Object[] commandsavailable = keys.toArray(); int displayed = 0; int page = 1; if (args.length < 1){ page = 1; } else { try { page = Integer.parseInt(args[0]); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Given page number is not a number!"); return true; } } int startpoint = (page - 1) * 3; double tot = keys.size() / 3; double total = (double)Math.round(tot * 1) / 1; total += 1; if (page > total || page < 1){ sender.sendMessage(plugin.colors.getError() + "Invalid page number!"); return true; } int totalpages = (int) total; sender.sendMessage(ChatColor.DARK_GREEN + "Page: [" + page + "/" + totalpages + "]"); for(int i = startpoint; displayed < 3; i++) { String v; try { v = commandsavailable[i].toString(); } catch (Exception e) { return true; } Map<String, Object> vmap = cmds.get(v); @SuppressWarnings("unused") Set<String> commandInfo = vmap.keySet(); String usage = vmap.get("usage").toString(); String description = vmap.get("description").toString(); String perm = vmap.get("permission").toString(); @SuppressWarnings("unchecked") List<String> aliases = (List<String>) vmap.get("aliases"); usage = usage.replaceAll("<command>", v); sender.sendMessage(ChatColor.BOLD + "" + ChatColor.GREEN + usage + plugin.colors.getTitle() + " Description: " + plugin.colors.getInfo() + description); sender.sendMessage(plugin.colors.getTitle() + " Aliases: " + plugin.colors.getInfo() + aliases); sender.sendMessage(plugin.colors.getTitle() + " Permission: " + plugin.colors.getInfo() + perm); displayed++; } int next = page + 1; if (next < total + 1){ sender.sendMessage(ChatColor.DARK_GREEN+ "Do /ucommands " + next + " for the next page of commands!"); } return true; } else if (cmd.getName().equalsIgnoreCase("ucommand")){ // If the player typed /setlevel then do the following... if (args.length < 1){ sender.sendMessage("Usage /ucommand [Command]"); return true; } String thecmd = args[0]; PluginDescriptionFile desc = getServer().getPluginManager().getPlugin("useful").getDescription(); Map<String, Map<String, Object>> cmds = desc.getCommands(); String v = thecmd; try { Map<String, Object> vmap = cmds.get(v); if (vmap == null) { sender.sendMessage(plugin.colors.getError() + "Command not found!"); return true; } @SuppressWarnings("unused") Set<String> commandInfo = vmap.keySet(); String usage = vmap.get("usage").toString(); String description = vmap.get("description").toString(); String perm = vmap.get("permission").toString(); @SuppressWarnings("unchecked") List<String> aliases = (List<String>) vmap.get("aliases"); usage = usage.replaceAll("<command>", v); sender.sendMessage(ChatColor.BOLD + "" + ChatColor.GREEN + usage + plugin.colors.getTitle() + " Description: " + plugin.colors.getInfo() + description); sender.sendMessage(plugin.colors.getTitle() + " Aliases: " + plugin.colors.getInfo() + aliases); sender.sendMessage(plugin.colors.getTitle() + " Permission: " + plugin.colors.getInfo() + perm); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Command not found!"); return true; } return true; } else if(cmd.getName().equalsIgnoreCase("back")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "You are not a player"); return true; } String pname = player.getName(); Location prev; String pluginFolder = plugin.getDataFolder().getAbsolutePath(); File pFile = new File(pluginFolder + File.separator + "player-data" + File.separator + pname + ".yml"); //Should create is doesn't exist? FileConfiguration pData = new YamlConfiguration(); try { pData.load(pFile); } catch (FileNotFoundException e) { try { pFile.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { pFile.delete(); sender.sendMessage(plugin.colors.getError() + "Error"); return true; } if(!(pData.contains("data.previous-location.world"))){ sender.sendMessage(plugin.colors.getError() + "Error: previous location wasn't saved!"); return true; } World world = null; try { world = getServer().getWorld(pData.getString("data.previous-location.world")); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Error: Invalid world"); } try { double x = pData.getDouble("data.previous-location.x"); double y = pData.getDouble("data.previous-location.y"); double z = pData.getDouble("data.previous-location.z"); float yaw = Float.parseFloat(pData.getString("data.previous-location.yaw")); float pitch = Float.parseFloat(pData.getString("data.previous-location.pitch")); prev = new Location(world, x, y, z, yaw, pitch); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Error - pitch and yaw incorrectly formatted"); return true; } player.teleport(prev); sender.sendMessage(plugin.colors.getSuccess() + "Returned to previous location!"); player.getWorld().playSound(player.getLocation(), Sound.NOTE_PLING, 1, 1); return true; } else if(cmd.getName().equalsIgnoreCase("enchant")){ if(!(sender instanceof Player)){ sender.sendMessage(plugin.colors.getError() + "Not a player"); return true; } if(args.length < 2){ return false; } String enchantmentStr = args[0]; int enchantmentLvl = 0; try { enchantmentLvl = Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Expected a number but got " + args[1]); return true; } if(enchantmentLvl < 1){ sender.sendMessage(plugin.colors.getError() + "Level must be higher than 1"); return true; } Enchantment toEnchant = getEnchant.getEnchantFromString(enchantmentStr); if(toEnchant == null){ sender.sendMessage(plugin.colors.getError() + "Invalid enchantment!" + ChatColor.RESET + plugin.colors.getTitle() + " Valid enchantments are:" + ChatColor.RESET + plugin.colors.getInfo() + "arrow_damage, " + "arrow_fire, arrow_infinite, arrow_knockback, damage_all, damage_spiders, damage_zombies, haste, durability, fire_aspect, knockback, loot_bonus_blocks, loot_bonus_mobs, oxygen, environmental_protection, " + "explosion_protection, fall_protection, fire_protection, arrow_protection, silk_touch, thorns, water_worker"); return true; } ItemStack item = player.getItemInHand(); if(item.getTypeId() == 0){ sender.sendMessage(plugin.colors.getError() + "Cannot enchant air!"); } try { item.addUnsafeEnchantment(toEnchant, enchantmentLvl); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Enchantment invalid! (Level is too high/item is invalid for that enchantment)"); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Successfully enchanted to level " + enchantmentLvl); return true; } else if (cmd.getName().equalsIgnoreCase("uhost")){ // If the player typed /setlevel then do the following... if (args.length < 1){ //do summin return false; } if(player != null){ //is a player player.getWorld().playSound(player.getLocation(), Sound.CLICK, 1, 10); } String version = getServer().getBukkitVersion(); int maxplayers = getServer().getMaxPlayers(); String motd = getServer().getMotd(); String name = getServer().getServerName(); int port = getServer().getPort(); @SuppressWarnings("rawtypes") List world = getServer().getWorlds(); Object[] worlds = world.toArray(); String worldnames = ""; for (Object s : worlds) { String wname = ((World) s).getName(); worldnames = worldnames + " " + wname + ","; } String flight = "false"; boolean doflight = getServer().getAllowFlight(); if (doflight){ flight = "true"; } OfflinePlayer[] players = getServer().getOfflinePlayers(); int playerCount = players.length; OfflinePlayer[] playerso = getServer().getOnlinePlayers(); int online = playerso.length; boolean nether = getServer().getAllowNether(); boolean end = getServer().getAllowEnd(); int animalSpawnLimit = getServer().getAnimalSpawnLimit(); int monsterSpawnLimit = getServer().getMonsterSpawnLimit(); int spawnRadius = getServer().getSpawnRadius(); int WaterSpawnLimit = getServer().getWaterAnimalSpawnLimit(); long startTime = ManagementFactory.getRuntimeMXBean().getStartTime(); long runningTime = ((startTime - System.currentTimeMillis()) / 1000) / 60; String runTime = "" + runningTime; runTime = runTime.replaceAll("-", ""); double runningTimeHr = Math.round((Double.parseDouble(runTime) / 60) * 10) / 10; String runTimeHr = "" + runningTimeHr; runTimeHr = runTimeHr.replaceAll("-", ""); double time = Double.parseDouble(runTime); String DD = Math.round((time/24/60)*1)/1 + ""; String HH = Math.round((time/60%24)*1)/1 + ""; String MM = Math.round((time%60)*1)/1 + ""; if (DD.length() < 2){ DD = "0" + DD; } if (HH.length() < 2){ HH = "0" + HH; } if (MM.length() < 2){ MM = "0" + MM; } String theTime = DD + ":" + HH + ':' + MM; long totMem = Runtime.getRuntime().totalMemory() / 1024 / 1024;// Allocated memory MB long freMem = Runtime.getRuntime().freeMemory() / 1024 / 1024;//Free memory MB long usedMem = totMem - freMem;//Used memory MB if (args[0].equalsIgnoreCase("stats")){ //show stats sender.sendMessage(plugin.colors.getSuccess() + "" + ChatColor.BOLD + "Server stats:"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server name: " + ChatColor.RESET + "" + plugin.colors.getInfo() + name); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server run time: " + ChatColor.RESET + "" + plugin.colors.getInfo() + "(Days:Hours:Minutes) " + theTime); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server version: " + ChatColor.RESET + "" + plugin.colors.getInfo() + version); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Player count: " + ChatColor.RESET + "" + plugin.colors.getInfo() + playerCount); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Online players: " + ChatColor.RESET + "" + plugin.colors.getInfo() + online); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server worlds: " + ChatColor.RESET + "" + plugin.colors.getInfo() + worldnames); return true; } else if(args[0].equalsIgnoreCase("ram")|| args[0].equalsIgnoreCase("memory")){ sender.sendMessage(plugin.colors.getSuccess() + "" + ChatColor.BOLD + "Server memory/RAM:"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server allocated memory: " + ChatColor.RESET + "" + plugin.colors.getInfo() + totMem + "MB"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server free memory: " + ChatColor.RESET + "" + plugin.colors.getInfo() + freMem + "MB"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server memory usage: " + ChatColor.RESET + "" + plugin.colors.getInfo() + usedMem + "MB"); return true; } else if(args[0].equalsIgnoreCase("clean")|| args[0].equalsIgnoreCase("optimise")||args[0].equals("gc")){ sender.sendMessage(plugin.colors.getSuccess() + "The server memory has been purged of all unused objects to free up memory/ram"); System.gc(); return true; } else if(args[0].equalsIgnoreCase("system")){ Properties props = System.getProperties(); //user.language user.timezome java.runtime.name user.country java.runtime.version String server_lang; String server_timezone; String server_script; String server_country; String java_version; try { server_lang = props.getProperty("user.language"); server_timezone = props.getProperty("user.timezone"); server_script = props.getProperty("java.runtime.name"); server_country = props.getProperty("user.country"); java_version = props.getProperty("java.runtime.version"); } catch (Exception e) { sender.sendMessage("Error has occurred while obtaining system information"); return true; } sender.sendMessage(plugin.colors.getSuccess() + "" + ChatColor.BOLD + "Server system information:"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server default language: " + ChatColor.RESET + "" + plugin.colors.getInfo() + server_lang); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server default timezone: " + ChatColor.RESET + "" + plugin.colors.getInfo() + server_timezone); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server script language: " + ChatColor.RESET + "" + plugin.colors.getInfo() + server_script); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server country: " + ChatColor.RESET + "" + plugin.colors.getInfo() + server_country); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server reccomended java version to use: " + ChatColor.RESET + "" + plugin.colors.getInfo() + java_version); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Useful plugin version: " + config.getDouble("version.current")); return true; } else if(args[0].equalsIgnoreCase("properties")){ sender.sendMessage(plugin.colors.getSuccess() + "" + ChatColor.BOLD + "Server properties:"); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server name: " + ChatColor.RESET + "" + plugin.colors.getInfo() + name); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server MOTD: " + ChatColor.RESET + "" + plugin.colors.getInfo() + motd); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Maximum players: " + ChatColor.RESET + "" + plugin.colors.getInfo() + maxplayers); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server port: " + ChatColor.RESET + "" + plugin.colors.getInfo() + port); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server allow flight: " + ChatColor.RESET + "" + plugin.colors.getInfo() + flight); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server allow nether: " + ChatColor.RESET + "" + plugin.colors.getInfo() + nether); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Server allow end: " + ChatColor.RESET + "" + plugin.colors.getInfo() + end); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Animal spawn limit: " + ChatColor.RESET + "" + plugin.colors.getInfo() + animalSpawnLimit); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Monster spawn limit: " + ChatColor.RESET + "" + plugin.colors.getInfo() + monsterSpawnLimit); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Water Creature spawn limit: " + ChatColor.RESET + "" + plugin.colors.getInfo() + WaterSpawnLimit); sender.sendMessage(plugin.colors.getTitle() + "" + ChatColor.BOLD + "Spawn protection radius: " + ChatColor.RESET + "" + plugin.colors.getInfo() + spawnRadius); return true; } else if(args[0].equalsIgnoreCase("performance")){ //performance stuff if(useful.uhost_settings.get("performance") != null && useful.uhost_settings.get("performance") == true){ sender.sendMessage(plugin.colors.getSuccess() + "Performance mode disabled!"); useful.uhost_settings.put("performance", false); Performance.performanceMode(false); } else { //enable performance sender.sendMessage(plugin.colors.getSuccess() + "Performance mode enabled!"); useful.uhost_settings.put("performance", true); Performance.performanceMode(true); } plugin.saveHashMapBoolean(useful.uhost_settings, plugin.getDataFolder() + File.separator + "uhost_settings.bin"); return true; } else if(args[0].equalsIgnoreCase("logger")){ if(sender instanceof Player == false){ sender.sendMessage(plugin.colors.getError() + "Only players can use this subcommand"); return true; } if(plugin.commandViewers.contains(sender.getName()) == false){ plugin.commandViewers.add(sender.getName()); sender.sendMessage(plugin.colors.getSuccess() + "Logger mode enabled!"); plugin.commandViewers.save(); } else if(plugin.commandViewers.contains(sender.getName())){ plugin.commandViewers.remove(sender.getName()); plugin.commandViewers.save(); sender.sendMessage(plugin.colors.getSuccess() + "Logger mode disabled!"); } plugin.commandViewers.save(); return true; } else if(args[0].equalsIgnoreCase("dplugin")){ //disable plugin args[1] if(args.length < 2){ return false; } Plugin[] plugins = getServer().getPluginManager().getPlugins(); boolean exists = false; Plugin thepl = null; for (int i = 0; i < plugins.length; i++) { if(plugins[i].getName().equalsIgnoreCase(args[1])){ exists = true; thepl = plugins[i]; } } if(exists == false){ sender.sendMessage(plugin.colors.getError() + "Plugin not found!"); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Plugin disabled!"); getServer().getPluginManager().disablePlugin(thepl); return true; } else if(args[0].equalsIgnoreCase("config")){ /* if(args.length < 5){ // 1 = this, 2 = plugin, 3 = node, 4 = setting sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]]"); return true; } */ if(args.length < 2){ sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]] [View [Plugin] [Node]]"); return true; } String action = args[1]; if(action.equalsIgnoreCase("set")){ if(args.length < 5){ sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]] [View [Plugin] [Node]]"); return true; } String pname = args[2]; Plugin[] plugins = plugin.getServer().getPluginManager().getPlugins(); boolean found = false; Plugin tPlugin = null; for(int i = 0;i<plugins.length;i++){ Plugin test = plugins[i]; if(test.getName().equalsIgnoreCase(pname)){ tPlugin = test; found = true; } } if(plugin == null || found == false){ sender.sendMessage(plugin.colors.getError() + "Plugin not found! Do /plugins for a list!"); return true; } String type = "unknown"; FileConfiguration config = tPlugin.getConfig(); String node = args[3]; String setting = args[4]; float num = 0; try { num = Float.parseFloat(setting); type = "number"; } catch (NumberFormatException e) { type = "unknown"; } boolean bool = false; if(setting.equalsIgnoreCase("true")){ bool = true; type = "boolean"; } else if(setting.equalsIgnoreCase("false")){ bool = false; type = "boolean"; } if(type == "unknown"){ //It is a string for(int i = 5; i< args.length;i++){ setting = setting + " " + args[i]; } config.set(node, setting); } else if(type == "number"){ //It is a number config.set(node, num); } else if(type == "boolean"){ //It is a boolean config.set(node, bool); } try { tPlugin.saveConfig(); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Unable to find config file for the plugin " + tPlugin.getName()); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Successfully created/set the node: " + node + " to " + setting + " in " + tPlugin.getName() + " reload for it to take effect!"); return true; } else if(action.equalsIgnoreCase("unset")){ if(args.length < 4){ sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]] [View [Plugin] [Node]]"); return true; } String pname = args[2]; String node = args[3]; Plugin[] plugins = plugin.getServer().getPluginManager().getPlugins(); boolean found = false; Plugin tPlugin = null; for(int i = 0;i<plugins.length;i++){ Plugin test = plugins[i]; if(test.getName().equalsIgnoreCase(pname)){ tPlugin = test; found = true; } } if(plugin == null || found == false){ sender.sendMessage(plugin.colors.getError() + "Plugin not found! Do /plugins for a list!"); return true; } //String type = "unknown"; FileConfiguration config = tPlugin.getConfig(); config.set(node, null); try { tPlugin.saveConfig(); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Unable to find config file for the plugin " + tPlugin.getName()); return true; } sender.sendMessage(plugin.colors.getSuccess() + "Successfully removed the node: " + node + " in " + tPlugin.getName() + " reload for it to take effect!"); return true; } else if(action.equalsIgnoreCase("list")){ if(args.length < 4){ sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]] [View [Plugin] [Node]]"); return true; } String pname = args[2]; String page = args[3]; int pnum = 0; try { pnum = Integer.parseInt(page); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Page number is incorrect!"); return true; } Plugin[] plugins = plugin.getServer().getPluginManager().getPlugins(); boolean found = false; Plugin tPlugin = null; for(int i = 0;i<plugins.length;i++){ Plugin test = plugins[i]; if(test.getName().equalsIgnoreCase(pname)){ tPlugin = test; found = true; } } if(plugin == null || found == false){ sender.sendMessage(plugin.colors.getError() + "Plugin not found! Do /plugins for a list!"); return true; } //String type = "unknown"; FileConfiguration config = tPlugin.getConfig(); Set<String> keys = config.getKeys(true); Object[] nodes = keys.toArray(); List<String> listNodes = new ArrayList<String>(); if(tPlugin.getName().equalsIgnoreCase("useful")){ for(int i=0;i<nodes.length;i++){ listNodes.add((String) nodes[i]); } for(int i=0;i<listNodes.size();i++){ String node = listNodes.get(i); if((node).contains("description") && tPlugin.getName().equalsIgnoreCase("useful")){ listNodes.remove(node); } } nodes = listNodes.toArray(); } int totalPages = nodes.length / 15; totalPages += 1; sender.sendMessage(plugin.colors.getTitle() + "Valid nodes for " + tPlugin.getName() + ":" + plugin.colors.getInfo() + "(Page: " + pnum + "/"+totalPages+")"); int displayed = 0; int start = pnum - 1; start = start * 15; for(int i = start;i<nodes.length && displayed < 15;i++){ String v = (String) nodes[i]; if(!(v.contains("."))){ sender.sendMessage(plugin.colors.getTitle() + v); } else{ String[] nodeParts = v.split("\\."); if(nodeParts.length < 3 && nodeParts.length > 1){ nodeParts[0] = ChatColor.RED + nodeParts[0]; nodeParts[1] = ChatColor.YELLOW + nodeParts[1]; v = nodeParts[0] + "." + nodeParts[1]; } if(nodeParts.length > 2){ nodeParts[0] = ChatColor.RED + nodeParts[0]; nodeParts[1] = ChatColor.YELLOW + nodeParts[1]; v = nodeParts[0] + "." + nodeParts[1]; for(int o=2;o<nodeParts.length;o++){ v = v + "." + ChatColor.BLUE + nodeParts[o]; } } sender.sendMessage(plugin.colors.getInfo() + v); } displayed++; } } else if(action.equalsIgnoreCase("view")){ String pname = args[2]; Plugin[] plugins = plugin.getServer().getPluginManager().getPlugins(); boolean found = false; Plugin tPlugin = null; for(int i = 0;i<plugins.length;i++){ Plugin test = plugins[i]; if(test.getName().equalsIgnoreCase(pname)){ tPlugin = test; found = true; } } if(plugin == null || found == false){ sender.sendMessage(plugin.colors.getError() + "Plugin not found! Do /plugins for a list!"); return true; } FileConfiguration config = tPlugin.getConfig(); String node = args[3]; Object result = config.get(node); sender.sendMessage(plugin.colors.getSuccess() + "Value of " + node + " in " + tPlugin.getName() + " is: " + result); return true; } else{ sender.sendMessage("Usage: /" + cmdname + " config [Set [Plugin] [Node] [Setting]] [Unset [Plugin] [Node]] [List [Plugin] [Page number]] [View [Plugin] [Node]]"); return true; } return true; } else if(args[0].equalsIgnoreCase("perms")){ if(!(useful.config.getBoolean("uperms.enable"))){ sender.sendMessage(plugin.colors.getError() + "Uperms is not enabled in the config!"); return true; } if(args.length < 2){ sender.sendMessage("Usage: /" + cmdname + " perms [Group/Player/Reload]"); return true; } if(args[1].equalsIgnoreCase("reload")){ useful.uperms = new YamlConfiguration(); useful.uperms.options().pathSeparator('/'); plugin.loadYamls(); Player[] onlineP = plugin.getServer().getOnlinePlayers(); for(int i=0;i<onlineP.length;i++){ plugin.permManager.unLoadPerms(onlineP[i].getName()); plugin.permManager.refreshPerms(onlineP[i]); } sender.sendMessage(plugin.colors.getSuccess() + "Successfully refreshed server permissions to match currently loaded file!"); return true; } if(args[1].equalsIgnoreCase("group")){ if(args.length < 3){ sender.sendMessage("Usage: /" + cmdname + " <Perms> <Group> [<SetPerm> <Name> <Perm> <Value>], [<UnsetPerm> <Name> <Perm>], [<Create> <Name> <Inheritance>], [<Delete> <Name>], [<List>], [<View> <Group> <Page>]"); return true; } String action = args[2]; boolean valid = true; if(action.equalsIgnoreCase("setperm")){ String gname = ""; if(args.length < 6){ valid = false; } if(valid){ gname = args[3]; String gperm = args[4]; String gval = args[5]; Boolean Val; try { Val = Boolean.parseBoolean(gval); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Value must be true or false!"); return true; } gname = plugin.permManager.groupExists(gname); if(gname == "^^error^^"){ sender.sendMessage(plugin.colors.getError() + "Group doesn't exist!"); return true; } String path = "groups/"+gname+"/permissions"; gperm = gperm.replaceAll(":", ""); plugin.permManager.setPerm(path, gperm, Val); } if(valid){ sender.sendMessage(plugin.colors.getSuccess() + "Successfully set perm for "+gname+"!"); } } else if(action.equalsIgnoreCase("unsetperm")){ String gname = ""; if(args.length < 5){ valid = false; } if(valid){ gname = args[3]; String gperm = args[4]; gname = plugin.permManager.groupExists(gname); if(gname == "^^error^^"){ sender.sendMessage(plugin.colors.getError() + "Group doesn't exist!"); return true; } String path = "groups/"+gname+"/permissions"; plugin.permManager.setPerm(path, gperm, null); } if(valid){ sender.sendMessage(plugin.colors.getSuccess() + "Successfully unset perm for "+gname+"!"); } } else if(action.equalsIgnoreCase("create")){ if(args.length < 5){ valid = false; } if(valid){ String gname = args[3]; List<String> inherited = new ArrayList<String>(); for(int i=4;i<args.length;i++){ inherited.add(args[i]); } plugin.permManager.createGroup(gname, inherited); sender.sendMessage(plugin.colors.getSuccess() + "Successfully created the group " + gname); } } else if(action.equalsIgnoreCase("delete")){ if(args.length < 4){ valid = false; } String gname = args[3]; gname = plugin.permManager.groupExists(gname); if(gname == "^^error^^"){ sender.sendMessage(plugin.colors.getError() + "Group doesn't exist!"); return true; } plugin.permManager.removeGroup(gname); sender.sendMessage(plugin.colors.getSuccess() + "Successfully deleted the group " + gname); } else if(action.equalsIgnoreCase("list")){ List<String> groups = plugin.permManager.listGroups(); Object[] array = groups.toArray(); String result = "**start**"; for(int i=0;i<array.length;i++){ if(result == "**start**"){ result = (String) array[i]; } else{ result = result + "," + array[i]; } } sender.sendMessage(plugin.colors.getTitle() + "Groups: " + plugin.colors.getInfo() + result); } else if(action.equalsIgnoreCase("view")){ if(args.length < 5){ valid = false; } if(valid){ String gname = args[3]; gname = plugin.permManager.groupExists(gname); if(gname == "^^error^^"){ sender.sendMessage(plugin.colors.getError() + "Group doesn't exist!"); return true; } int page = 1; try { page = Integer.parseInt(args[4]); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Page number incorrect"); return true; } ConfigurationSection validGroups = plugin.permManager.getConfig().getConfigurationSection("groups"); Map<String, Object> perms = new HashMap<String, Object>(); if(validGroups.contains(gname)){ perms = plugin.permManager.viewPerms("groups/"+gname); } Set<String> keys = perms.keySet(); String result = ""; for(String v:keys){ result = result + v + ":" + perms.get(v) + ", "; } String msg = result; ChatPaginator.ChatPage tpage = ChatPaginator.paginate(msg, page); int total = tpage.getTotalPages(); int current = tpage.getPageNumber(); String[] lines = tpage.getLines(); sender.sendMessage(plugin.colors.getTp()+"Page number: [" +current+"/"+total+"]"); sender.sendMessage(plugin.colors.getTitle() + "Permissions for " + gname + " = "); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + ChatColor.stripColor(lines[i])); } } } else{ valid = false; } if(!valid){ sender.sendMessage("Usage: /" + cmdname + " <Perms> <Group> [<SetPerm> <Name> <Perm> <Value>], [<UnsetPerm> <Name> <Perm>], [<Create> <Name> <Inheritance>], [<Delete> <Name>], [<List>], [<View> <Group> <Page>]"); return true; } } else if(args[1].equalsIgnoreCase("player")){ boolean valid = true; String usage = "Usage: /" + cmdname + " <Perms> <Player> [<Setgroups> <Player> <Groups>], [<Setperm> <Player> <Node> <value>], [<Unsetperm> <Player> <Node>], [<View> <Player>], [<viewPersonalPerms> <Player> (Page)], [<ViewAllPerms> <Player> (Page)]"; if(args.length < 3){ sender.sendMessage(usage); return true; } String action = args[2]; if(action.equalsIgnoreCase("setgroups")){ if(args.length < 5){ sender.sendMessage(usage); return true; } List<String> groups = new ArrayList<String>(); for(int i=4;i<args.length;i++){ groups.add(args[i]); } String playerName = args[3]; if(plugin.getServer().getOfflinePlayer(playerName)!= null){ playerName = plugin.getServer().getOfflinePlayer(playerName).getName(); } for(int i=0;i<groups.size();i++){ String Group = groups.get(i); Group = plugin.permManager.groupExists(Group); if(Group == "^^error^^"){ sender.sendMessage(plugin.colors.getError() + "Group "+groups.get(i)+" doesn't exist!"); return true; } } plugin.permManager.setGroups(playerName, groups); sender.sendMessage(plugin.colors.getSuccess() + playerName + " is now in groups "+ groups); } else if(action.equalsIgnoreCase("setperm")){ String gname = ""; if(args.length < 6){ valid = false; } if(valid){ gname = args[3]; String gperm = args[4]; String gval = args[5]; Boolean Val; try { Val = Boolean.parseBoolean(gval); } catch (Exception e) { sender.sendMessage(plugin.colors.getError() + "Value must be true or false!"); return true; } OfflinePlayer[] allPlay = plugin.getServer().getOfflinePlayers(); for(int i=0;i<allPlay.length;i++){ OfflinePlayer play = allPlay[i]; if(play.getName().equalsIgnoreCase(gname)){ gname = play.getName(); } } String path = "users/"+gname+"/permissions"; gperm = gperm.replaceAll(":", ""); plugin.permManager.setPerm(path, gperm, Val); } if(valid){ sender.sendMessage(plugin.colors.getSuccess() + "Successfully set perm for "+gname+"!"); } } else if(action.equalsIgnoreCase("unsetperm")){ String gname = ""; if(args.length < 5){ valid = false; } if(valid){ gname = args[3]; String gperm = args[4]; OfflinePlayer[] allPlay = plugin.getServer().getOfflinePlayers(); for(int i=0;i<allPlay.length;i++){ OfflinePlayer play = allPlay[i]; if(play.getName().equalsIgnoreCase(gname)){ gname = play.getName(); } } String path = "users/"+gname+"/permissions"; plugin.permManager.setPerm(path, gperm, null); } if(valid){ sender.sendMessage(plugin.colors.getSuccess() + "Successfully unset perm for "+gname+"!"); } } else if(action.equalsIgnoreCase("view")){ if(args.length < 4){ valid = false; } if(valid){ String pname = args[3]; OfflinePlayer[] allPlay = plugin.getServer().getOfflinePlayers(); for(int i=0;i<allPlay.length;i++){ OfflinePlayer play = allPlay[i]; if(play.getName().equalsIgnoreCase(pname)){ pname = play.getName(); } } if(plugin.permManager.getConfig().contains("users/"+pname+"/groups")){ List<String> list = plugin.permManager.getConfig().getStringList("users/"+pname+"/groups"); if(list.size() < 1){ sender.sendMessage(plugin.colors.getError() + pname + " is not in a group"); return true; } String toSend = list.get(0); for(int i=1;i<list.size();i++){ String groupName = list.get(i); toSend = toSend + ", " + groupName; } sender.sendMessage(plugin.colors.getTitle() + pname+" is in the groups: " + plugin.colors.getInfo() + toSend); return true; } else{ sender.sendMessage(plugin.colors.getError() + pname + " is not in a group"); return true; } } } else if(action.equalsIgnoreCase("viewPersonalPerms")){ if(args.length < 4){ valid = false; } int page = 0; if(args.length < 5){ page = 1; } else { String pagRaw = args[4]; try { page = Integer.parseInt(pagRaw); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Page number invalid"); return true; } } String pname = args[3]; OfflinePlayer[] allPlay = plugin.getServer().getOfflinePlayers(); for(int i=0;i<allPlay.length;i++){ OfflinePlayer play = allPlay[i]; if(play.getName().equalsIgnoreCase(pname)){ pname = play.getName(); } } String personalPath = "users/"+pname+"/permissions"; if(!plugin.permManager.getConfig().getConfigurationSection("users").getKeys(false).contains(pname)){ sender.sendMessage(plugin.colors.getInfo() + pname + " does not have any personal permissions set"); return true; } else if(!plugin.permManager.getConfig().getConfigurationSection("users/" + pname).getKeys(false).contains("permissions")){ sender.sendMessage(plugin.colors.getInfo() + pname + " does not have any personal permissions set"); return true; } ConfigurationSection perms = plugin.permManager.getConfig().getConfigurationSection(personalPath); Set<String> permsKeys = perms.getKeys(false); String permsToSend = ""; for(String key:permsKeys){ sender.sendMessage("."); boolean value = false; try { value = perms.getBoolean(key); } catch (Exception e) { value = true; } permsToSend = permsToSend + key + " : " + value + ", "; } ChatPage toSend = ChatPaginator.paginate(permsToSend, page); int total = toSend.getTotalPages(); sender.sendMessage(plugin.colors.getTp() + "Page: ["+toSend.getPageNumber()+"/"+total+"]"); String[] lines = toSend.getLines(); sender.sendMessage(plugin.colors.getTitle() + "Permissions for " + pname + ":"); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + lines[i]); } return true; } else if(action.equalsIgnoreCase("viewAllPerms")){ if(args.length < 4){ valid = false; } int page = 0; if(args.length < 5){ page = 1; } else { String pagRaw = args[4]; try { page = Integer.parseInt(pagRaw); } catch (NumberFormatException e) { sender.sendMessage(plugin.colors.getError() + "Page number invalid"); return true; } } String pname = args[3]; OfflinePlayer[] allPlay = plugin.getServer().getOfflinePlayers(); for(int i=0;i<allPlay.length;i++){ OfflinePlayer play = allPlay[i]; if(play.getName().equalsIgnoreCase(pname)){ pname = play.getName(); } } String personalPath = "users/"+pname; if(!plugin.permManager.getConfig().getConfigurationSection("users").getKeys(false).contains(pname)){ sender.sendMessage(plugin.colors.getInfo() + pname + " does not have any permissions set"); return true; } Map<String, Object> perms = plugin.permManager.viewPerms(personalPath); if(plugin.permManager.getConfig().getConfigurationSection("users/"+pname).getKeys(false).contains("groups")){ List<String> allGroups = plugin.permManager.getConfig().getStringList("users/"+pname+"/groups"); for(String gname:allGroups){ gname = plugin.permManager.groupExists(gname); if(gname != "^^error^^"){ Map<String, Object> permsToAdd = plugin.permManager.viewPerms("groups/"+gname); Set<String> keysPerms = permsToAdd.keySet(); for(String keyPerm:keysPerms){ perms.put(keyPerm, permsToAdd.get(keyPerm)); } } } } Set<String> permsKeys = perms.keySet(); String permsToSend = ""; for(String key:permsKeys){ sender.sendMessage("."); Object value = false; try { value = perms.get(key); } catch (Exception e) { value = true; } permsToSend = plugin.colors.getInfo() + permsToSend + plugin.colors.getInfo() + key + " : " + value + ", "; } ChatPage toSend = ChatPaginator.paginate(permsToSend, page); int total = toSend.getTotalPages(); sender.sendMessage(plugin.colors.getTp() + "Page: ["+toSend.getPageNumber()+"/"+total+"]"); String[] lines = toSend.getLines(); sender.sendMessage(plugin.colors.getTitle() + "All permissions for " + pname + ":"); for(int i=0;i<lines.length;i++){ sender.sendMessage(plugin.colors.getInfo() + lines[i]); } return true; } else{ sender.sendMessage(usage); return true; } if(!valid){ sender.sendMessage(usage); return true; } } else{ sender.sendMessage("Usage: /" + cmdname + " perms [Group/Player]"); return true; } return true; } else{ return false; } } //If this has happened the function will break and return true. if this hasn't happened the a value of false will be returned. return false; } Server getServer() { return plugin.getServer(); } ColoredLogger getLogger() { return plugin.colLogger; } }
fb12d31b13551786e3b96acfda058e319bf3ed4d
0e8bb849f92902f9213bfe93b6b86d0c322284d2
/modules/core/src/main/java/org/apache/ignite/internal/processors/metastorage/persistence/NotAvailableDistributedMetaStorageBridge.java
d5be56c26e587e9b6425347f4e91e56fdc733f8c
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0" ]
permissive
nobitlost/ignite
c6168dba2a16fc26fc518ff9351cf809a23c1487
8a0aa2a824c7170321be8d5f8708a064cf7c5f00
refs/heads/master
2021-06-21T20:49:18.740657
2019-05-17T15:44:40
2019-05-17T15:44:40
126,074,245
5
0
Apache-2.0
2019-05-05T18:33:36
2018-03-20T19:52:08
Java
UTF-8
Java
false
false
2,130
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.metastorage.persistence; import java.io.Serializable; import java.util.function.BiConsumer; /** */ class NotAvailableDistributedMetaStorageBridge implements DistributedMetaStorageBridge { /** {@inheritDoc} */ @Override public Serializable read(String globalKey, boolean unmarshal) { throw new UnsupportedOperationException("read"); } /** {@inheritDoc} */ @Override public void iterate( String globalKeyPre, BiConsumer<String, ? super Serializable> cb, boolean unmarshal ) { throw new UnsupportedOperationException("iterate"); } /** {@inheritDoc} */ @Override public void write(String globalKey, byte[] valBytes) { throw new UnsupportedOperationException("write"); } /** {@inheritDoc} */ @Override public void onUpdateMessage(DistributedMetaStorageHistoryItem histItem) { throw new UnsupportedOperationException("onUpdateMessage"); } /** {@inheritDoc} */ @Override public void removeHistoryItem(long ver) { throw new UnsupportedOperationException("removeHistoryItem"); } /** {@inheritDoc} */ @Override public DistributedMetaStorageKeyValuePair[] localFullData() { throw new UnsupportedOperationException("localFullData"); } }
df7697b94c96d1ac95e5a59e8cd5649e36e2e7f5
01024e7ad4ebf70944bdef04aa9fa45dfdd248bb
/src/main/java/com/kutayyaman/footballListCase/api/FootballTeamController.java
419b94dbcfcc7cf73030c6545825509293c4c3bc
[]
no_license
kutayyaman/footballListCaseWithSpringBoot
c6eaff5300061ac42f8a29250e93c025ea798b78
d3e8fa67d0b00ecffd3e1ff6690a4af37fc58d90
refs/heads/master
2023-08-22T11:22:19.991697
2021-10-17T15:02:22
2021-10-17T15:02:22
381,333,840
0
0
null
null
null
null
UTF-8
Java
false
false
1,308
java
package com.kutayyaman.footballListCase.api; import com.kutayyaman.footballListCase.dto.DeleteFootballTeamDTO; import com.kutayyaman.footballListCase.dto.FootballTeamDTO; import com.kutayyaman.footballListCase.service.IFootballTeamService; import com.kutayyaman.footballListCase.util.ApiPaths; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(ApiPaths.FootballTeamCtrl.CTRL) // /api/footballTeam public class FootballTeamController { private final IFootballTeamService footballTeamService; public FootballTeamController(IFootballTeamService footballTeamService) { this.footballTeamService = footballTeamService; } @GetMapping() public List<FootballTeamDTO> findAllFootballTeam() { return footballTeamService.findAllFootballTeam(); } @DeleteMapping() public ResponseEntity<?> deleteFootballTeamById(@RequestBody DeleteFootballTeamDTO deleteFootballTeamDTO) { return footballTeamService.deleteFootballTeamById(deleteFootballTeamDTO.getId()); } @PutMapping() public ResponseEntity<?> updateFootballTeam(@RequestBody FootballTeamDTO footballTeamDTO) { return footballTeamService.updateFootballTeam(footballTeamDTO); } }
e89eb7388f684b48b7ac6ac400db9c45305c88da
2ad3c30b2c36a3a4d7b7eb2d8e371f83049a6a8a
/javabt/javabt/Basic1/src/cauHOIphongvan/Student.java
5748872095c8153ccef0f5769c4ab15abf886ef8
[]
no_license
khoale22/LearnFullJava
85774d94df57afd2a4ee957410bf6222d1112f78
f6010e451a95f8c5e4f8c5cbc9ffd4a5a2c901a3
refs/heads/master
2022-12-21T20:27:02.215968
2020-07-07T14:09:04
2020-07-07T14:09:04
248,209,077
0
0
null
2022-12-16T03:16:17
2020-03-18T11:08:39
Rich Text Format
UTF-8
Java
false
false
1,355
java
/* * 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 cauHOIphongvan; import java.io.Serializable; /** * * @author maich */ import java.io.*; class Test implements Serializable{ int i = 124, j = 123; // Transient variables transient int k = 20; // khong bi anh huong boi transient transient static int l = 100; transient final int m = 900; final transient int b = 110; public static void main(String[] args) throws Exception { Test input = new Test(); // serialization FileOutputStream fos = new FileOutputStream("C:\\New folder\\student2.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(input); // de-serialization FileInputStream fis = new FileInputStream("C:\\New folder\\student2.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Test output = (Test)ois.readObject(); System.out.println("i = " + output.i); System.out.println("j = " + output.j); System.out.println("k = " + output.k); System.out.println("l = " + output.l); System.out.println("m = " + output.m); System.out.println("b = " + output.b); } }
6f8b0b41511ff3ea5aa22a0dd46b17ce75eacb73
11f638750f35b4d9d491a7f3071167e840263ebf
/teacherhelper/app/src/main/java/com/park61/teacherhelper/module/course/SubCourseVideoActivity.java
d49136b0781eb33bb3d091232f832b71585d1329
[]
no_license
shushucn2012/gohomeplay
a0a2ca0db1fd59228e23e464703ec16946fe07ff
6f9f25d7d6f17ad3f556ac26ed3a0208f9a5fb88
refs/heads/master
2020-05-31T06:12:06.489037
2019-07-11T15:49:03
2019-07-11T15:49:03
190,134,348
0
0
null
null
null
null
UTF-8
Java
false
false
41,065
java
package com.park61.teacherhelper.module.course; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Handler; import android.os.Message; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.aliyun.vodplayerview.utils.ScreenUtils; import com.aliyun.vodplayerview.widget.AliyunScreenMode; import com.aliyun.vodplayerview.widget.AliyunVodPlayerView; import com.lzy.okgo.OkGo; import com.lzy.okgo.model.Progress; import com.lzy.okgo.request.GetRequest; import com.lzy.okserver.OkDownload; import com.lzy.okserver.download.DownloadListener; import com.lzy.okserver.download.DownloadTask; import com.makeramen.roundedimageview.RoundedImageView; import com.park61.teacherhelper.CanBackWebViewActivity; import com.park61.teacherhelper.R; import com.park61.teacherhelper.VideoBaseActivity; import com.park61.teacherhelper.common.set.AppUrl; import com.park61.teacherhelper.common.set.GlobalParam; import com.park61.teacherhelper.common.set.ParamBuild; import com.park61.teacherhelper.common.tool.CommonMethod; import com.park61.teacherhelper.common.tool.FU; import com.park61.teacherhelper.common.tool.HtmlParserTool; import com.park61.teacherhelper.common.tool.ImageManager; import com.park61.teacherhelper.common.tool.UIUtil; import com.park61.teacherhelper.common.tool.ViewInitTool; import com.park61.teacherhelper.module.course.bean.SubCourseBean; import com.park61.teacherhelper.module.course.bean.SubCourseListBean; import com.park61.teacherhelper.module.home.CourseDetailsActivity; import com.park61.teacherhelper.module.home.FhDetailsCommtActivity; import com.park61.teacherhelper.module.home.adapter.ContentCommentListAdapter; import com.park61.teacherhelper.module.home.adapter.FileSourcesAdapter; import com.park61.teacherhelper.module.home.bean.CommentListBean; import com.park61.teacherhelper.module.home.bean.FileItemSource; import com.park61.teacherhelper.module.login.LoginActivity; import com.android.volley.Request; import com.park61.teacherhelper.module.okdownload.DownloadService; import com.park61.teacherhelper.module.okdownload.widget.FileModel; import com.park61.teacherhelper.net.request.SimpleRequestListener; import com.park61.teacherhelper.net.request.interfa.BaseRequestListener; import com.park61.teacherhelper.net.request.interfa.JsonRequestListener; import com.park61.teacherhelper.widget.listview.ObservableScrollView; import com.park61.teacherhelper.widget.webview.ShowImageWebView; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import okhttp3.HttpUrl; import tyrantgit.widget.HeartLayout; /** * 专家课程详情视频 * Created by shubei on 2017/8/16. */ public class SubCourseVideoActivity extends VideoBaseActivity { private int[] paopaoResArray = {R.mipmap.banana, R.mipmap.cherry, R.mipmap.nnut, R.mipmap.polo, R.mipmap.rraspberry, R.mipmap.cake, R.mipmap.devil, R.mipmap.love_heart, R.mipmap.moon_stars, R.mipmap.ttaxi, R.mipmap.advance, R.mipmap.gifts, R.mipmap.roles, R.mipmap.shanzu, R.mipmap.spring, R.mipmap.tiqing, R.mipmap.wen, R.mipmap.xiangshui, R.mipmap.yazi, R.mipmap.yule, R.mipmap.zuifan}; private ImageView img_back, img_sc, iv_whitestore; private RoundedImageView img_recom_one, img_recom_two; public View paly_backveiw, area_do_praise, area_recommend, area_commentsend, area_real_input, area_show_input, recom_area_one, recom_area_two; public RelativeLayout rl_contenttitle, area_top, rl_edit; public LinearLayout ll_textcoutent, ll_commentbottom; public ListView lv_comment, lv_files; private ShowImageWebView wvContent; private EditText et_commentwrite; private ContentCommentListAdapter contentCommentListAdapter; private ObservableScrollView sv; private ImageView iv_message, iv_attent; private TextView tv_course_titles, tv_titlename, tv_titletime, tv_messagecount, tv_attentcount, tv_title, tv_commentsend, recom_tv_one, recom_tv_two; private HeartLayout mHeartLayout; private String authInfo; private String videoId; private int subCourseId; public int courseContentId; private SubCourseBean subCourseBean; private SubCourseListBean recomOne, recomTwo; private int collect;//0 未收藏,1 已收藏 private boolean isPriseLimt; private int curPlayId;//当前播放资源id private int taskCalendarId;//学习任务id,可以判断是否记录学习时间 private long startTime, endTime;//开始时间 private boolean isShowed;//是否显示下载提示 private List<FileItemSource> fList = new ArrayList<>(); private FileSourcesAdapter fileSourcesAdapter; private List<FileItemSource> showFList = new ArrayList<>(); @Override public void setLayout() { //让布局向上移来显示软键盘 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); setContentView(R.layout.activity_subcourse_video); } @Override public void initView() { area_recommend = findViewById(R.id.area_recommend); recom_area_one = findViewById(R.id.recomm_area_one); recom_area_two = findViewById(R.id.recomm_area_two); tv_title = (TextView) findViewById(R.id.tv_title); wvContent = (ShowImageWebView) findViewById(R.id.wvContent); area_top = (RelativeLayout) findViewById(R.id.area_top); rl_contenttitle = (RelativeLayout) findViewById(R.id.rl_contenttitle); img_back = (ImageView) findViewById(R.id.img_back); img_sc = (ImageView) findViewById(R.id.img_sc); iv_whitestore = (ImageView) findViewById(R.id.iv_whitestore); paly_backveiw = findViewById(R.id.paly_backveiw); mAliyunVodPlayerView = (AliyunVodPlayerView) findViewById(R.id.video_view); mAliyunVodPlayerView.setTitleBarCanShow(false); mAliyunVodPlayerView.setControlBarCanShow(false); lv_comment = (ListView) findViewById(R.id.lv_comment); rl_edit = (RelativeLayout) findViewById(R.id.rl_edit); LinearLayoutManager manager = new LinearLayoutManager(mContext); manager.setOrientation(LinearLayout.HORIZONTAL); area_commentsend = findViewById(R.id.area_commentsend); ll_commentbottom = (LinearLayout) findViewById(R.id.ll_commentbottom); et_commentwrite = (EditText) findViewById(R.id.et_commentwrite); tv_commentsend = (TextView) findViewById(R.id.tv_commentsend); iv_message = (ImageView) findViewById(R.id.iv_message); img_recom_one = (RoundedImageView) findViewById(R.id.recomm_img_one); img_recom_two = (RoundedImageView) findViewById(R.id.recomm_img_two); tv_messagecount = (TextView) findViewById(R.id.tv_messagecount); tv_attentcount = (TextView) findViewById(R.id.tv_attentcount); recom_tv_one = (TextView) findViewById(R.id.recomm_tv_one); recom_tv_two = (TextView) findViewById(R.id.recomm_tv_two); iv_attent = (ImageView) findViewById(R.id.iv_attent); sv = (ObservableScrollView) findViewById(R.id.sv); tv_course_titles = (TextView) findViewById(R.id.tv_course_titles); tv_titlename = (TextView) findViewById(R.id.tv_titlename); tv_titletime = (TextView) findViewById(R.id.tv_titletime); ll_textcoutent = (LinearLayout) findViewById(R.id.ll_textcoutent); area_do_praise = findViewById(R.id.area_do_praise); mHeartLayout = (HeartLayout) findViewById(R.id.heart_layout); area_real_input = findViewById(R.id.area_real_input); area_show_input = findViewById(R.id.area_show_input); lv_files = (ListView) findViewById(R.id.lv_files); } @Override protected void onResume() { super.onResume(); startTime = System.currentTimeMillis(); } @Override public void initData() { taskCalendarId = getIntent().getIntExtra("taskCalendarId", -1); subCourseId = getIntent().getIntExtra("subCourseId", -1); fileSourcesAdapter = new FileSourcesAdapter(SubCourseVideoActivity.this, showFList); lv_files.setAdapter(fileSourcesAdapter); asyncGetSubCourse(); } @Override public void initListener() { findViewById(R.id.iv_redshre).setOnClickListener(v -> { ViewInitTool.AddStatistics(mContext, "contentshare"); showShareDialog("http://m.61park.cn/teach/#/expert/detail/" + subCourseId, subCourseBean.getCoverImg(), subCourseBean.getTitle(), subCourseBean.getSummary()); }); findViewById(R.id.iv_contentshare).setOnClickListener(v -> { ViewInitTool.AddStatistics(mContext, "contentshare"); showShareDialog("http://m.61park.cn/teach/#/expert/detail/" + subCourseId, subCourseBean.getCoverImg(), subCourseBean.getTitle(), subCourseBean.getSummary()); }); //返回 findViewById(R.id.iv_back).setOnClickListener(v -> { hideKeyboard(); finish(); }); iv_message.setOnClickListener(v -> { Intent it = new Intent(mContext, FhDetailsCommtActivity.class); it.putExtra("itemId", courseContentId); startActivity(it); }); img_back.setOnClickListener(v -> { int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED); } else { finish(); } }); iv_whitestore.setOnClickListener(view -> store()); img_sc.setOnClickListener(v -> store()); area_do_praise.setOnClickListener(v -> mHeartLayout.post(new Runnable() { @Override public void run() { mHeartLayout.addHeart(mContext.getResources().getColor(R.color.transparent), paopaoResArray[new Random().nextInt(20)], R.mipmap.icon_trans); admire(); } })); tv_commentsend.setOnClickListener(view -> { if (CommonMethod.checkUserLogin(mContext)) { if (TextUtils.isEmpty(et_commentwrite.getText().toString().trim())) { showShortToast("请输入评论内容"); return; } sedCommend(); } }); rl_edit.setOnClickListener(v -> { showComtArea(); }); sv.setScrollViewListener((x, y, oldx, oldy) -> { if (y == 0) { tran(area_top, 0, 0); tran(mAliyunVodPlayerView, 0, 0); } else { tran(area_top, -y, -oldy); tran(mAliyunVodPlayerView, -y, -oldy); } if (y > UIUtil.dp(mContext, 50)) { rl_contenttitle.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); } else { rl_contenttitle.setVisibility(View.GONE); } }); findViewById(R.id.area_to_download_all).setOnClickListener(v -> { if (!CommonMethod.checkUserLogin(mContext)) return; //下载全部 添加进度框 showDownLoadTip(); showDialog(); for (int i = 0; i < fList.size(); i++) { FileItemSource fileItemSource = fList.get(i); if (fileItemSource.getStatus() != -1 || HttpUrl.parse(fileItemSource.getSourceUrl()) == null) {//已经开始下载了就跳过 continue; } //下载附件 FileModel fileModel = new FileModel(); fileModel.setUrl(fileItemSource.getSourceUrl()); fileModel.setName(fileItemSource.getSourceName()); fileModel.setCreateTime(DownloadService.fomatCurrentTime()); fileModel.setPath(OkDownload.getInstance().getFolder() + fileItemSource.getSourceName()); fileModel.setSize(fileItemSource.getShowFileSize()); fileModel.setIconUrl(fileItemSource.getIconUrl()); GetRequest<File> request = OkGo.<File>get(fileModel.getUrl()); OkDownload.request(fileModel.getUrl(), request).extra1(fileModel).save(); if (OkDownload.getInstance().getTask(fileItemSource.getSourceUrl()) != null) { DownloadTask task = OkDownload.getInstance().getTask(fileItemSource.getSourceUrl()); task.register(new ListDownloadListener(fileItemSource)); } fileItemSource.setStatus(0);//未下载完成状态 fileItemSource.setTotalDownloadNum(FU.addDownLoadNumStr(fileItemSource.getTotalDownloadNum())); addDowLoadNum(fileItemSource.getId()); } fileSourcesAdapter.notifyDataSetChanged(); new Handler() { @Override public void handleMessage(Message msg) { OkDownload.getInstance().startAll(); dismissDialog(); } }.sendEmptyMessageDelayed(0, 1500); }); findViewById(R.id.area_see_all_files).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showFList.clear(); showFList.addAll(fList); fileSourcesAdapter.notifyDataSetChanged(); findViewById(R.id.area_see_all_files).setVisibility(View.GONE); } }); findViewById(R.id.area_how_to_save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(mContext, CanBackWebViewActivity.class); it.putExtra("url", "http://m.61park.cn/teach/#/servicedict/index/355"); startActivity(it); } }); } /** * 获取课时详情 */ private void asyncGetSubCourse() { ViewInitTool.AddStatistics(mContext, "contentdetails"); String wholeUrl = AppUrl.host + AppUrl.getSubCourseDetail; Map<String, Object> map = new HashMap<String, Object>(); map.put("trainerCourseId", subCourseId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, courselistener); } BaseRequestListener courselistener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); dDialog.showDialog("提示", errorMsg, "返回", "重试", v -> { dDialog.dismissDialog(); finish(); }, v -> { dDialog.dismissDialog(); asyncGetSubCourse(); }); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); sv.smoothScrollTo(0, 0); subCourseBean = gson.fromJson(jsonResult.toString(), SubCourseBean.class); if (subCourseBean != null) { fillData(); } } }; //收藏 public void store() { if (subCourseBean == null) { return; } if (GlobalParam.userToken == null) {// 没有登录则跳去登录 startActivity(new Intent(mContext, LoginActivity.class)); return; } if (collect == 1) { asyncCancelCollect(); } else { asyncAddCollect(); } } public void fillData() { // if (subCourseBean.getIsCollect()) { // img_sc.setImageResource(R.mipmap.corse_store); // iv_whitestore.setImageResource(R.mipmap.course_whitestor); // collect = 1; // } else { // img_sc.setImageResource(R.mipmap.content_redrestore); // iv_whitestore.setImageResource(R.mipmap.content_whit_restore); // collect = 0; // } // mAliyunVodPlayerView.setCoverUri(subCourseBean.getCoverImg()); rl_contenttitle.setVisibility(View.GONE); mAliyunVodPlayerView.setVisibility(View.VISIBLE); paly_backveiw.setVisibility(View.VISIBLE); area_top.setVisibility(View.VISIBLE); ViewInitTool.initShowimgWebview(wvContent); setWebData(); // tv_attentcount.setText(curCourseSectionBean.getPraiseNumDsc()); tv_title.setText(subCourseBean.getTitle()); tv_course_titles.setText(subCourseBean.getTitle()); tv_titletime.setText(subCourseBean.getLearningNum() + "人学习"); if (subCourseBean.getTrainerCourseResource() != null) { courseContentId = subCourseBean.getId(); //日期格式 tv_titlename.setText(subCourseBean.getTrainerCourseResource().getUpdateTime()); //播放 videoId = subCourseBean.getTrainerCourseResource().getUrl(); authInfo = subCourseBean.getTrainerCourseResource().getVideoPlayAuth(); initAliyunVodPlayerView(videoId, authInfo); if (GlobalParam.userToken != null) { ansycSavaStudyNum(); } } // ansycGetVideoAuth(); // asyncGetComment(); ansycGetFileList(); asynGetRecomment(); } /** * 获取附件列表 */ public void ansycGetFileList() { String wholeUrl = AppUrl.host + AppUrl.trainerCourseAttachmentList; Map<String, Object> map = new HashMap<String, Object>(); map.put("trainerCourseId", subCourseId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, flister); } BaseRequestListener flister = new JsonRequestListener() { @Override public void onStart(int requestId) { } @Override public void onError(int requestId, String errorCode, String errorMsg) { showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { JSONArray actJay = jsonResult.optJSONArray("list"); if (actJay == null || actJay.length() == 0) { findViewById(R.id.area_file_list).setVisibility(View.GONE); return; } findViewById(R.id.area_file_list).setVisibility(View.VISIBLE); fList.clear(); for (int i = 0; i < actJay.length(); i++) { JSONObject jot = actJay.optJSONObject(i); FileItemSource source = gson.fromJson(jot.toString(), FileItemSource.class); source.setStatus(ViewInitTool.getFilesItemDownLoadStatus(source.getSourceUrl()));//下载状态 fList.add(source); } ((TextView) findViewById(R.id.tv_files_num)).setText("相关课件(" + fList.size() + ")"); showFList.clear(); if (fList.size() > 3) { showFList.addAll(fList.subList(0, 3)); findViewById(R.id.area_see_all_files).setVisibility(View.VISIBLE); } else { showFList.addAll(fList); findViewById(R.id.area_see_all_files).setVisibility(View.GONE); } fileSourcesAdapter.notifyDataSetChanged(); fileSourcesAdapter.setOnDownLoadClickedLsner(index -> { if (!CommonMethod.checkUserLogin(mContext)) return; FileItemSource fileItemSource = fList.get(index); if (fileItemSource.getStatus() != -1) { return; } if (HttpUrl.parse(fileItemSource.getSourceUrl()) == null) { showShortToast("文件地址有误,无法下载"); return; } showDownLoadTip(); //下载附件 FileModel fileModel = new FileModel(); fileModel.setUrl(fileItemSource.getSourceUrl()); fileModel.setName(fileItemSource.getSourceName()); fileModel.setCreateTime(DownloadService.fomatCurrentTime()); fileModel.setPath(OkDownload.getInstance().getFolder() + fileItemSource.getSourceName()); fileModel.setSize(fileItemSource.getShowFileSize()); fileModel.setIconUrl(fileItemSource.getIconUrl()); GetRequest<File> request = OkGo.<File>get(fileModel.getUrl()); OkDownload.request(fileModel.getUrl(), request).extra1(fileModel).save().start(); if (OkDownload.getInstance().getTask(fileItemSource.getSourceUrl()) != null) { DownloadTask task = OkDownload.getInstance().getTask(fileItemSource.getSourceUrl()); task.register(new ListDownloadListener(fileItemSource)); } fileItemSource.setStatus(0);//未下载完成状态 fileItemSource.setTotalDownloadNum(FU.addDownLoadNumStr(fileItemSource.getTotalDownloadNum())); fileSourcesAdapter.notifyDataSetChanged(); addDowLoadNum(fileItemSource.getId()); }); } }; private class ListDownloadListener extends DownloadListener { public ListDownloadListener(Object tag) { super(tag); } @Override public void onStart(Progress progress) { } @Override public void onProgress(Progress progress) { } @Override public void onError(Progress progress) { Throwable throwable = progress.exception; if (throwable != null) throwable.printStackTrace(); } @Override public void onFinish(File file, Progress progress) { //更新列表 for (int i = 0; i < fList.size(); i++) { FileItemSource source = fList.get(i); if (source == tag) { source.setStatus(1); break; } } fileSourcesAdapter.notifyDataSetChanged(); } @Override public void onRemove(Progress progress) { } } /** * 获取视频播放权证 */ public void ansycGetVideoAuth() { String wholeUrl = AppUrl.host + AppUrl.videoPlayAuth; Map<String, Object> map = new HashMap<String, Object>(); map.put("id", courseContentId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, alister); } BaseRequestListener alister = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); videoId = jsonResult.optString("videoId"); authInfo = jsonResult.optString("videoPlayAuth"); initAliyunVodPlayerView(videoId, authInfo); if (GlobalParam.userToken != null) { ansycSavaStudyNum(); } } }; /** * 播放一次,保存学习记录 */ public void ansycSavaStudyNum() { String wholeUrl = AppUrl.host + AppUrl.saveStudyRecord; Map<String, Object> map = new HashMap<String, Object>(); map.put("trainerCourseId", subCourseId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, new SimpleRequestListener()); } private void asyncAddCollect() { String wholeUrl = AppUrl.host + AppUrl.teachMyCourse_add; Map<String, Object> map = new HashMap<String, Object>(); map.put("contentId", courseContentId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, listener); } BaseRequestListener listener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); //收藏,变成已收藏 collect = 1; img_sc.setImageResource(R.mipmap.corse_store); iv_whitestore.setImageResource(R.mipmap.course_whitestor); sendBroadcast(new Intent().setAction("ACTION_REFRESH_SKLIST")); Toast.makeText(SubCourseVideoActivity.this, "已收藏", Toast.LENGTH_LONG).show(); } }; private void asyncCancelCollect() { String wholeUrl = AppUrl.host + AppUrl.teachMyCourse_cancel; Map<String, Object> map = new HashMap<String, Object>(); map.put("contentId", courseContentId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, clistener); } BaseRequestListener clistener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); //取消收藏,变成未收藏 collect = 0; img_sc.setImageResource(R.mipmap.content_redrestore); iv_whitestore.setImageResource(R.mipmap.content_whit_restore); sendBroadcast(new Intent().setAction("ACTION_REFRESH_SKLIST")); Toast.makeText(SubCourseVideoActivity.this, "已取消收藏", Toast.LENGTH_LONG).show(); } }; public void asyncGetComment() { String wholeUrl = AppUrl.host + AppUrl.addContentComment; Map<String, Object> map = new HashMap<String, Object>(); map.put("itemId", courseContentId); map.put("sort", "create_date"); map.put("order", "desc"); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, commentlistener); } BaseRequestListener commentlistener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); CommentListBean commentListBean = gson.fromJson(jsonResult.toString(), CommentListBean.class); initCommentList(commentListBean); } }; public void initCommentList(CommentListBean commentListBean) { contentCommentListAdapter = new ContentCommentListAdapter(this, commentListBean.getRows()); lv_comment.setAdapter(contentCommentListAdapter); tv_messagecount.setText(commentListBean.getTotal() + ""); if (commentListBean.getRows().size() == 0) { ((TextView) findViewById(R.id.tv_newcommend)).setText("暂无评论"); findViewById(R.id.area_commt_empty).setVisibility(View.VISIBLE); } else { ((TextView) findViewById(R.id.tv_newcommend)).setText("最新评论"); findViewById(R.id.area_commt_empty).setVisibility(View.GONE); } } public void sedCommend() { String wholeUrl = AppUrl.host + AppUrl.addContentCommentSend; Map<String, Object> map = new HashMap<String, Object>(); map.put("itemId", courseContentId); map.put("content", et_commentwrite.getText().toString().trim()); map.put("parentId", ""); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, commentsedlistener); } BaseRequestListener commentsedlistener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); asyncGetComment(); area_show_input.setVisibility(View.VISIBLE); area_real_input.setVisibility(View.GONE); et_commentwrite.setText(""); showShortToast("评论成功"); } }; public void admire() { String wholeUrl = AppUrl.host + AppUrl.praise; Map<String, Object> map = new HashMap<String, Object>(); map.put("contentId", courseContentId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, admirelistener); } BaseRequestListener admirelistener = new JsonRequestListener() { @Override public void onStart(int requestId) { } @Override public void onError(int requestId, String errorCode, String errorMsg) { if (errorCode.equals("0000000004") && !isPriseLimt) { showShortToast(errorMsg); isPriseLimt = true; } } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); tv_attentcount.setText(jsonResult.optString("data")); } }; /** * 获取相关的推荐课程 */ public void asynGetRecomment() { String wholeUrl = AppUrl.host + AppUrl.getRecommendCourse; Map<String, Object> map = new HashMap<String, Object>(); map.put("trainerCourseId", subCourseId); map.put("trainerCourseSeriesId", subCourseBean.getTrainerCourseSeriesId()); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, recommendlistener); } BaseRequestListener recommendlistener = new JsonRequestListener() { @Override public void onStart(int requestId) { showDialog(); } @Override public void onError(int requestId, String errorCode, String errorMsg) { dismissDialog(); showShortToast(errorMsg); } @Override public void onSuccess(int requestId, String url, JSONObject jsonResult) { dismissDialog(); JSONArray arr = jsonResult.optJSONArray("list"); if (arr != null && (taskCalendarId < 0 || subCourseBean.getIsInterest() == 0)) {//不是行事历跳转过来或者不是兴趣课才显示推荐 area_recommend.setVisibility(View.VISIBLE); if (arr.length() > 0) { recom_area_one.setVisibility(View.VISIBLE); recomOne = gson.fromJson(arr.optJSONObject(0).toString(), SubCourseListBean.class); recom_area_one.setVisibility(View.VISIBLE); ImageManager.getInstance().displayImg(img_recom_one, recomOne.getCoverImg()); recom_tv_one.setText(recomOne.getTitle()); recom_area_one.setOnClickListener(v -> { if (recomOne.isBuyStatus() || recomOne.getIsProbation() == 1) { subCourseId = recomOne.getId(); asyncGetSubCourse(); } else { //不可试看 且未购买 showShortToast("请购买该课程"); } }); } if (arr.length() > 1) { recom_area_two.setVisibility(View.VISIBLE); recomTwo = gson.fromJson(arr.optJSONObject(1).toString(), SubCourseListBean.class); recom_area_two.setVisibility(View.VISIBLE); ImageManager.getInstance().displayImg(img_recom_two, recomTwo.getCoverImg()); recom_tv_two.setText(recomTwo.getTitle()); recom_area_two.setOnClickListener(v -> { if (recomTwo.isBuyStatus() || recomTwo.getIsProbation() == 1) { subCourseId = recomTwo.getId(); asyncGetSubCourse(); } else { //不可试看 且未购买 showShortToast("请购买该课程"); } }); } } else { area_recommend.setVisibility(View.GONE); } } }; private void setWebData() { String htmlDetailsStr = ""; try { String content = subCourseBean.getContent(); if (content.length() < 100) { for (int i = 0; i < 400; i++) { content = content + " &nbsp"; } } htmlDetailsStr = HtmlParserTool.replaceImgStr(content); } catch (Exception e) { e.printStackTrace(); } wvContent.loadDataWithBaseURL("file:///android_asset", htmlDetailsStr, "text/html", "UTF-8", ""); } public void tran(View view, float a, float b) { ObjectAnimator.ofFloat(view, "translationY", a, b) .setDuration(0)// 设置执行时间(1000ms) .start(); // 开始动画 } public void updatePlayerViewMode() { if (mAliyunVodPlayerView != null) { int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { //转为竖屏了。 // this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); showBar(); //设置view的布局,宽高之类 ViewGroup.LayoutParams aliVcVideoViewLayoutParams = (ViewGroup.LayoutParams) mAliyunVodPlayerView.getLayoutParams(); aliVcVideoViewLayoutParams.height = (int) (ScreenUtils.getWidth(this) * 9.0f / 16); aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; //设置为小屏状态 mAliyunVodPlayerView.changeScreenMode(AliyunScreenMode.Small); sv.setVisibility(View.VISIBLE); // area_commentsend.setVisibility(View.VISIBLE); } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) { //转到横屏了。 // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // | View.SYSTEM_UI_FLAG_FULLSCREEN // | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); hideBar(); //设置view的布局,宽高 ViewGroup.LayoutParams aliVcVideoViewLayoutParams = (ViewGroup.LayoutParams) mAliyunVodPlayerView.getLayoutParams(); aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; //设置为全屏状态 mAliyunVodPlayerView.changeScreenMode(AliyunScreenMode.Full); sv.setVisibility(View.GONE); // area_commentsend.setVisibility(View.GONE); tran(mAliyunVodPlayerView, 0, 0); tran(area_top, 0, 0); } } } /** * 点击评论按钮,显示评论输入框 */ public void showComtArea() { // 点击评论按钮,显示评论输入框 area_real_input.setVisibility(View.VISIBLE); area_show_input.setVisibility(View.GONE); et_commentwrite.requestFocus(); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.showSoftInput(et_commentwrite, 0); } /** * 监控点击按钮如果点击在评论输入框之外就关闭输入框,变回报名栏 */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = area_commentsend;// getCurrentFocus(); if (isShouldHideInput(v, ev)) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } area_show_input.setVisibility(View.VISIBLE); area_real_input.setVisibility(View.GONE); et_commentwrite.setText(""); } return super.dispatchTouchEvent(ev); } // 必不可少,否则所有的组件都不会有TouchEvent了 if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); } @Override protected void onPause() { super.onPause(); endTime = System.currentTimeMillis(); if (taskCalendarId > 0) studyTrainerCourse(); } /** * 记录学习记录 */ public void studyTrainerCourse() { String wholeUrl = AppUrl.host + AppUrl.studyTrainerCourse; Map<String, Object> map = new HashMap<String, Object>(); map.put("taskCalendarId", taskCalendarId); map.put("time", (endTime - startTime) / 1000); map.put("trainerCourseId", subCourseId); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, new SimpleRequestListener()); } /** * 增加下载次数 */ public void addDowLoadNum(int id) { String wholeUrl = AppUrl.host + AppUrl.addCourseDownLoadNum; Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); String requestBodyData = ParamBuild.buildParams(map); netRequest.startRequest(wholeUrl, Request.Method.POST, requestBodyData, 0, new SimpleRequestListener()); } /** * 显示下载提示 */ private void showDownLoadTip() { if (!isShowed) { showShortToast("已加入下载列表,可在我的-我的下载中查看"); isShowed = true; } } }