blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
313
7ac7423ed2decdcbeb0a481e48492e7a573b7ec4
17c5a088d4dbfdf986631bacc62ff417949ed78b
/CRM/src/main/java/workbench/entity/ContactsRemark.java
76a133a9db80b4fea82391569c30ccad810c72cf
[]
no_license
judy19981229/IdeaProjects
72e7755f2bf5891abc37f574e576317ce17fb1d4
d3df2db8675cd583126a7b1377f8a65314dd1d0b
refs/heads/master
2023-04-15T12:50:56.593891
2021-04-27T02:14:50
2021-04-27T02:14:50
356,805,074
0
0
null
null
null
null
UTF-8
Java
false
false
1,294
java
package workbench.entity; public class ContactsRemark { private String id; private String noteContent; private String createTime; private String createBy; private String editTime; private String editBy; private String editFlag; private String contactsId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNoteContent() { return noteContent; } public void setNoteContent(String noteContent) { this.noteContent = noteContent; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getEditTime() { return editTime; } public void setEditTime(String editTime) { this.editTime = editTime; } public String getEditBy() { return editBy; } public void setEditBy(String editBy) { this.editBy = editBy; } public String getEditFlag() { return editFlag; } public void setEditFlag(String editFlag) { this.editFlag = editFlag; } public String getContactsId() { return contactsId; } public void setContactsId(String contactsId) { this.contactsId = contactsId; } }
ca293754450d7f24a57227d9fcc9317da6e11f7b
51ecb0b59c48edb733f182a06a2933da5f241936
/Demo/IntStack.java
66e127678bd3199e4d8193c019244a37166dc800
[]
no_license
Praveenchowdaryy/BaseCamp-Mind
bc9ac028bd60d1d32787311b98970c66cbe3c330
d8a85e66073279da74cafe701b9ee5c72b18697a
refs/heads/main
2023-03-01T15:11:38.846687
2021-02-07T07:35:56
2021-02-07T07:35:56
336,729,041
0
0
null
null
null
null
UTF-8
Java
false
false
666
java
package com.mind.Demo; public class IntStack { private int max; private int top; private int array[]; public IntStack(int len) { this.max=len; array=new int[max]; this.top=-1; } public boolean push(int x) { if(top>=(max-1)) { System.out.println("Overflow"); return false; }else { top++; array[top]=x; return true; } } public int pop() { if(top<0) { System.out.println("UnderFlow"); return 0; }else { return array[top--]; } } public int topElem() { if(top<0) { System.out.println("Under Flow"); return 0; }else { return array[top]; } } }
2812c62afc87bfb3b2ed84334e0dd8a7027c8744
d03074416e5e6b6ed65311baeee1fd84ac4d3c95
/hw04-0036491099/src/main/java/hr/fer/zemris/optjava/dz4/algorithms/Main.java
bf8e05290c8cbe714399dfc0527f93fdb16f8c09
[]
no_license
Masperado/NENR-Project-FER-2019
f62a534deb4d727214d02e198f20972c44f0dc07
614b7aee13279a78802053093293014ea5c74f33
refs/heads/master
2020-04-24T21:32:37.031677
2019-02-24T01:10:44
2019-02-24T01:10:44
172,281,982
0
1
null
null
null
null
UTF-8
Java
false
false
3,278
java
package hr.fer.zemris.optjava.dz4.algorithms; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Random; import hr.fer.zemris.optjava.dz4.api.ICrossing; import hr.fer.zemris.optjava.dz4.api.IFunction; import hr.fer.zemris.optjava.dz4.api.IMutation; import hr.fer.zemris.optjava.dz4.api.ISelection; import hr.fer.zemris.optjava.dz4.impl.*; public class Main { // zad4-dataset1.txt 200 0.000001 1000 true 0.2 false // zad4-dataset2.txt 200 0.000001 1000 true 0.2 false // zad4-dataset1.txt 200 0.000001 1000 false 0.5 false // zad4-dataset2.txt 200 0.000001 1000 false 0.5 false // zad4-dataset1.txt 20 0.000001 10000 false 0.2 true // zad4-dataset2.txt 20 0.000001 10000 false 0.2 true public static void main(String[] args) throws IOException { if (args.length != 7) { System.out.println("Neispravan broj argumenta"); System.exit(1); } List<String> rows = Files.readAllLines(Paths.get(args[0])); double[] consts = new double[rows.size()]; double[][] inputs = new double[rows.size()][2]; for (int i = 0; i < rows.size(); i++) { String[] values = rows.get(i).split("\\s+"); for (int j = 0; j < values.length - 1; j++) { inputs[i][j] = Double.valueOf(values[j]); } consts[i] = Double.valueOf(values[values.length - 1]); } IFunction<double[]> function = new AFFunction(inputs, consts); int populationSize = Integer.valueOf(args[1]); double[][] startingPopulation = generatePopulation(populationSize); double minError = Double.valueOf(args[2]); int maxIterations = Integer.valueOf(args[3]); ISelection<double[]> selectionGeneration = new RouletteWheel(); ISelection<double[]> selectionElimination = new NTournamentDoubleArray(3); boolean elite = Boolean.valueOf(args[4]); double sigma = Double.valueOf(args[5]); IMutation<double[]> mutation = new SigmaMutation(sigma); ICrossing<double[]> crossing = new BLX(0.1); boolean elimination = Boolean.valueOf(args[6]); if (!elimination) { GenerationAlgorithm<double[]> algorithm = new GenerationAlgorithm<>(startingPopulation, function, crossing, mutation, selectionGeneration, elite, minError, maxIterations); algorithm.run(); } else { EliminationAlgorithm<double[]> algorithm = new EliminationAlgorithm<>(startingPopulation, function, crossing, mutation, selectionElimination, minError, maxIterations); algorithm.run(); } } private static double[][] generatePopulation(int populationSize) { double[][] population = new double[populationSize][6]; for (int i = 0; i < populationSize; i++) { population[i] = generateSolution(); } return population; } private static double[] generateSolution() { Random rand = new Random(); double[] solution = new double[5]; for (int i = 0; i < 5; i++) { solution[i] = -4 + rand.nextDouble() * 8; } return solution; } }
60283471f43d72fd32eab6074306cc03f98749a9
c8556e99c99ae77ed78732694771c1420b1ae75e
/common-tools/src/main/java/design/first/commons/tools/RSACoder.java
6238788d56503ffc34ef7e7d9be7dcf52397401e
[]
no_license
First2019/maven-cloud
6de7afdb15a6b1cc1a323b1f52b0935dbae46f87
f3913775fb5da9c61bbbf08fb0a8c3c23997867b
refs/heads/master
2023-03-18T19:34:20.057767
2021-03-18T06:12:06
2021-03-18T06:12:06
325,499,755
0
0
null
null
null
null
UTF-8
Java
false
false
8,107
java
package design.first.commons.tools; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; /** * 非对称加密算法RSA算法组件 * 非对称算法一般是用来传送对称加密算法的密钥来使用的,相对于DH算法,RSA算法只需要一方构造密钥,不需要 * 大费周章的构造各自本地的密钥对了。DH算法只能算非对称算法的底层实现。而RSA算法实现起来较为简单 */ public class RSACoder { //非对称密钥算法 public static final String KEY_ALGORITHM = "RSA"; /** * 密钥长度,DH算法的默认密钥长度是1024 * 密钥长度必须是64的倍数,在512到65536位之间 */ private static final int KEY_SIZE = 512; //公钥 private static final String PUBLIC_KEY = "RSAPublicKey"; //私钥 private static final String PRIVATE_KEY = "RSAPrivateKey"; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //初始化密钥 //生成密钥对 Map<String, Object> keyMap = initKey(); //公钥 byte[] publicKey =getPublicKey(keyMap); //私钥 byte[] privateKey = getPrivateKey(keyMap); System.out.println("byte公钥12:\n" + publicKey[5]); String s = Base64.encodeBase64String(publicKey); byte[] bytes = Base64.decodeBase64(s); System.out.println("byte公钥12:\n" + bytes[5]); System.out.println("Base64公钥:\n" + Base64.encodeBase64String(publicKey)); System.out.println("Base64私钥:\n" + Base64.encodeBase64String(privateKey)); System.out.println("================密钥对构造完毕,甲方将公钥公布给乙方,开始进行加密数据的传输============="); String str = "RSA密码交换算法"; System.out.println("\n===========甲方向乙方发送加密数据=============="); System.out.println("原文:" + str); //甲方进行数据的加密 byte[] code1 = encryptByPrivateKey(str.getBytes(), privateKey); System.out.println("加密后的数据:" + Base64.encodeBase64String(code1)); System.out.println("===========乙方使用甲方提供的公钥对数据进行解密=============="); //乙方进行数据的解密 byte[] decode1 = decryptByPublicKey(code1, publicKey); System.out.println("乙方解密后的数据:" + new String(decode1) + "\n\n"); System.out.println("===========反向进行操作,乙方向甲方发送数据==============\n\n"); str = "乙方向甲方发送数据RSA算法"; System.out.println("原文:" + str); //乙方使用公钥对数据进行加密 byte[] code2 = encryptByPublicKey(str.getBytes(), publicKey); System.out.println("===========乙方使用公钥对数据进行加密=============="); System.out.println("加密后的数据:" + Base64.encodeBase64String(code2)); System.out.println("=============乙方将数据传送给甲方======================"); System.out.println("===========甲方使用私钥对数据进行解密=============="); //甲方使用私钥对数据进行解密 byte[] decode2 = decryptByPrivateKey(code2, privateKey); System.out.println("甲方解密后的数据:" + new String(decode2)); } /** * 初始化密钥对 * @return Map 甲方密钥的Map */ public static Map<String, Object> initKey() throws Exception { //实例化密钥生成器 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); //初始化密钥生成器 keyPairGenerator.initialize(KEY_SIZE); //生成密钥对 KeyPair keyPair = keyPairGenerator.generateKeyPair(); //甲方公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); //甲方私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); //将密钥存储在map中 Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * 私钥加密 * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception { //取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); //数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * 公钥加密 * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //初始化公钥 //密钥材料转换 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); //产生公钥 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); //数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pubKey); return cipher.doFinal(data); } /** * 私钥解密 * * @param data 待解密数据 * @param key 私密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception { //取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); //数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * 公钥解密 * * @param data 待解密数据 * @param key 密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //初始化公钥 //密钥材料转换 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); //产生公钥 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); //数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pubKey); return cipher.doFinal(data); } /** * 取得私钥 * * @param keyMap 密钥map * @return byte[] 私钥 */ public static byte[] getPrivateKey(Map<String, Object> keyMap) { Key key = (Key) keyMap.get(PRIVATE_KEY); return key.getEncoded(); } /** * 取得公钥 * * @param keyMap 密钥map * @return byte[] 公钥 */ public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return key.getEncoded(); } }
8cc9391357e3ba391df696e8d8e07427fec76f45
540ed9a87297b21b506c2499493680f87f53c8af
/src/util/FileOutputStreamUtil.java
81177e643dbfe797f7f90d73261a87a2f5464a65
[]
no_license
sb0321/multipleThreadFolder
11da7f3aed4d94dcd01fba890bcc2bb0b78d1402
7ed54a1ec657cffa016e702190a6facccac4801e
refs/heads/master
2023-03-19T07:10:14.832194
2021-03-18T19:01:05
2021-03-18T19:01:05
349,180,825
0
0
null
null
null
null
UTF-8
Java
false
false
1,187
java
package util; import java.io.*; public class FileOutputStreamUtil { private final String THREAD_NAME; private static final String DIR_PROPERTY = "user.dir"; private static final String FOLDER = "/folder/"; private final String ROOT; public FileOutputStreamUtil(String name) { this.THREAD_NAME = name; ROOT = System.getProperty(DIR_PROPERTY) + FOLDER; System.out.println(ROOT); } public void makeDirIfDoesNotExist() { File root = new File(ROOT); File d = new File(ROOT + THREAD_NAME); if (!root.isDirectory() && root.mkdir()) { System.out.println("경로 생성: " + root.toPath()); } if(!d.isDirectory() && d.mkdir()) { System.out.println(THREAD_NAME + " 쓰레드의 폴더 생성: " + d.toPath()); } } public void makeFile(String name) { String fileName = name + ".txt"; try { FileWriter fileWriter = new FileWriter(ROOT + THREAD_NAME + "/" + fileName); fileWriter.write(name); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
1e498d578faa567ee029b75ba6a8c4dcdf2cef35
442a660162355ae5299a6be811ec09f44d3f8a61
/main/src/main/java/com/brufino/android/playground/components/main/pages/statistics/StatisticsFragment.java
9f55144c547533da2219dc8faece37cdff8076ed
[]
no_license
bernardorufino/android-transfer
a53158450b5a339bd1fdd83f9d29dbbdbfa88991
cf35125a55310191dd1a8b3d25dccc5dbd2b0a1d
refs/heads/master
2021-10-24T23:24:52.796255
2019-03-23T15:21:33
2019-03-23T15:21:33
178,473,904
0
0
null
null
null
null
UTF-8
Java
false
false
1,705
java
package com.brufino.android.playground.components.main.pages.statistics; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import com.brufino.android.playground.databinding.StatisticsFragmentBinding; import com.brufino.android.playground.provision.Provisioners; public class StatisticsFragment extends Fragment { private final StatisticsFragmentProvisioner mProvisioner; private ViewModelProvider.Factory mViewModelFactory; private StatisticsFragmentBinding mBinding; public StatisticsFragment() { mProvisioner = Provisioners.get().getStatisticsFragmentProvisioner(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewModelFactory = mProvisioner.getViewModelFactory(); } @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mBinding = StatisticsFragmentBinding.inflate(inflater, container, false); mBinding.setLifecycleOwner(this); return mBinding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); StatisticsViewModel data = ViewModelProviders.of(this, mViewModelFactory).get(StatisticsViewModel.class); mBinding.setViewModel(data); } }
86b28135c1cba4ac1e93aed43b09e841378f2e70
d7d7b0c25a923a699ffa579e1bab546435443302
/NGServer/Invoker/src/main/java/org/Invoker/rpc/protocol/SpringMVC.java
e9283ef02cccd7e8ca5ed8498e0bcb751aefe2e9
[]
no_license
github188/test-3
9cd2417319161a014df8b54aa68579843ade8885
92c8b20ba19185fca1e0293fe7208102b338a9ca
refs/heads/master
2020-03-15T09:36:37.329325
2017-12-18T02:40:21
2017-12-18T02:40:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,460
java
package org.Invoker.rpc.protocol; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc public class SpringMVC extends WebMvcConfigurerAdapter { // private nari.Logger.Logger logger = LoggerManager.getLogger(this.getClass()); /** * 非必须 */ @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable("mvcServlet"); } //配置html等的方法 @Override public void configureViewResolvers(ViewResolverRegistry registry){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/"); viewResolver.setSuffix(".html"); viewResolver.setViewClass(InternalResourceView.class); registry.viewResolver(viewResolver); } @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addWebRequestInterceptor(new WebRequestInterceptor() { // // @Override // public void preHandle(WebRequest arg0) throws Exception { // logger.info("1"); // } // // @Override // public void postHandle(WebRequest arg0, ModelMap arg1) throws Exception { // logger.info("2"); // } // // @Override // public void afterCompletion(WebRequest arg0, Exception arg1) throws Exception { // logger.info("3"); // } // }); } /** * 如果项目的一些资源文件放在/WEB-INF/resources/下面 * 在浏览器访问的地址就是类似:http://host:port/projectName/WEB-INF/resources/xxx.css * 但是加了如下定义之后就可以这样访问: * http://host:port/projectName/resources/xxx.css * 非必须 */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { // registry.addResourceHandler("/resources").addResourceLocations("classpath:/resources/"); } }
dacb27fe9b406ab57ade864242ce30532cef1149
885f5580c7de1a9807152e7a602e5c6417a15471
/SyscortRazorpayNewCards/src/test/java/com/syscort/pages/EcomTestPage.java
69e20c0f0acba87645c707609a298a5e21764414
[]
no_license
rajvpatil5/Eclipse-New-Version
7bf12468d6c0915e5574385de9b82d5286349517
4544e804c2f890054614b659ea40bb7fe91c9082
refs/heads/main
2023-05-15T03:26:36.451400
2021-06-10T09:23:33
2021-06-10T09:23:33
361,465,579
0
0
null
null
null
null
UTF-8
Java
false
false
1,214
java
package com.syscort.pages; import org.openqa.selenium.By; public class EcomTestPage { public static By textEmail = By.xpath("//input[@name='email']"); public static By textPhone = By.xpath("//input[@name='phone']"); public static By textAmount = By.xpath("//*[@id='form-section']/form/div[1]/div[3]/div/div[2]/div[1]/input"); public static By submitBtn = By.xpath("//button[@type='submit']"); // Card Modal public static By checkoutFrame = By.xpath("//iframe[@class='razorpay-checkout-frame']"); public static By cardBtn = By.xpath("//button[@method='card']"); public static By cardNumber = By.xpath("//input[@id='card_number']"); public static By cardExpiry = By.xpath("//input[@id='card_expiry']"); public static By cardName = By.xpath("//input[@id='card_name']"); public static By cardCvv = By.xpath("//input[@id='card_cvv']"); public static By payBtn = By.xpath("//span[@id='footer-cta']"); public static By ipin = By.xpath("//input[@id='txtipin']"); public static By SubmitPayBtn = By.xpath("//input[@id='btnverify']"); public static By errorMessage = By.xpath("//div[@id='fd-t']"); public static By paymentID = By.xpath(" //*[@id='status-section-container']/div[3]/div[5]/div/div[1]"); }
3efbc4c468e4406769a38b27cebb75110ee95ef7
3cc4d7e1eafd91c994e998773875ab220fc6144b
/app/src/main/java/com/zhangzd/video/MainActivity.java
30878ec10c95b53cd8c57a7346757424955feec7
[]
no_license
amibition521/VideoPlayer
60581730fa1094b3a9f8675410bb38265cbbd8e3
e402db752dc34721bfccfb6226b2d1b57a7c081e
refs/heads/master
2022-02-24T09:16:10.699812
2019-09-24T08:17:30
2019-09-24T08:17:30
208,955,475
0
0
null
2019-09-22T03:09:31
2019-09-17T03:56:53
C
UTF-8
Java
false
false
3,003
java
package com.zhangzd.video; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.TextView; import com.yanzhenjie.permission.Action; import com.yanzhenjie.permission.AndPermission; import com.yanzhenjie.permission.runtime.Permission; import java.util.List; public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{ static { System.loadLibrary("native-lib"); } SurfaceHolder mSurfaceHolder; // final String src = "/storage/emulated/0/DCIM/Camera/e7a9c442d1cda4462fc03459d71d8b7c.mp4"; final String src = "/storage/emulated/0/tencent/QQfile_recv/disco.mp3"; // final String src = "https://ips.ifeng.com/video19.ifeng.com/video09/2018/12/07/p5749945-102-009-184237.mp4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SurfaceView surfaceView = findViewById(R.id.surface_view); mSurfaceHolder = surfaceView.getHolder(); mSurfaceHolder.addCallback(this); final TextView textView = findViewById(R.id.tv2); textView.setMovementMethod(ScrollingMovementMethod.getInstance()); final TextView textView1 = findViewById(R.id.tv1); textView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AndPermission.with(MainActivity.this) .runtime() .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE,Permission.RECORD_AUDIO) .onGranted(new Action<List<String>>() { @Override public void onAction(List<String> data) { // avioreading(src); playAudio(src); } }) .onDenied(new Action<List<String>>() { @Override public void onAction(List<String> data) { } }).start(); } }); } public native int avcodecinfo(); public native int avioreading(String src); public native int sysloginit(); public native int play(Object surface, String src); public native int playAudio(String url); public native int stopAudio(); @Override public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
2ac25ae54e740bfe0885d2bc795bf7e634a6284c
091cf57a4726e99b8f6cf90f197ed96aae7fbead
/src/main/java/com/seezoon/service/modules/sys/entity/SysParam.java
7b13cd6bf4c84a656cedbe2b3ae9f73da6ced5b2
[]
no_license
734839030/seezoon-boot
5b3274b81ff4157778d1a83175ba4f7ccf4ad7ea
a965385c0b1b0f92114338cf0c0d2e2528e20455
refs/heads/master
2023-01-29T23:47:49.105120
2020-05-06T03:39:16
2020-05-06T03:39:16
155,083,708
14
8
null
2023-01-06T05:07:03
2018-10-28T15:07:14
JavaScript
UTF-8
Java
false
false
988
java
package com.seezoon.service.modules.sys.entity; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.seezoon.boot.common.entity.BaseEntity; /** * 系统参数 * * @author hdf 2018年4月1日 */ public class SysParam extends BaseEntity<String> { /** * */ private static final long serialVersionUID = 1L; /** * 名称 */ @NotNull @Length(min=1,max=50) private String name; /** * 键 */ @NotNull @Length(min=1,max=50) private String paramKey; /** * 值 */ @NotNull @Length(min=1,max=50) private String paramValue; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParamKey() { return paramKey; } public void setParamKey(String paramKey) { this.paramKey = paramKey; } public String getParamValue() { return paramValue; } public void setParamValue(String paramValue) { this.paramValue = paramValue; } }
d45940b6ee0c96b29c466b024779a008c97cbcb3
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/google--j2objc/97be5e92b907bf452731a01306c40193e2374173/after/Options.java
bfcdff2a03aa6d11de90ef8186d7a1883ceefa10
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
25,985
java
/* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.Resources; import com.google.devtools.j2objc.util.ErrorUtil; import com.google.devtools.j2objc.util.FileUtil; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** * The set of tool properties, initialized by the command-line arguments. * This class was extracted from the main class, to make it easier for * other classes to access options. * * @author Tom Ball */ public class Options { private static List<String> sourcePathEntries = Lists.newArrayList("."); private static List<String> classPathEntries = Lists.newArrayList("."); private static List<String> pluginPathEntries = Lists.newArrayList(); private static String pluginOptionString = ""; private static List<Plugin> plugins = new ArrayList<Plugin>(); private static File outputDirectory = new File("."); private static OutputStyleOption outputStyle = OutputStyleOption.PACKAGE; private static String implementationSuffix = ".m"; private static MemoryManagementOption memoryManagementOption = null; private static boolean emitLineDirectives = false; private static boolean warningsAsErrors = false; private static boolean deprecatedDeclarations = false; // Keys are class names, values are header paths (with a .h). private static Map<String, String> headerMappings = Maps.newLinkedHashMap(); private static File outputHeaderMappingFile = null; private static Map<String, String> classMappings = Maps.newLinkedHashMap(); private static Map<String, String> methodMappings = Maps.newLinkedHashMap(); private static boolean stripGwtIncompatible = false; private static boolean segmentedHeaders = false; private static String fileEncoding = System.getProperty("file.encoding", "UTF-8"); private static boolean jsniWarnings = true; private static boolean buildClosure = false; private static boolean stripReflection = false; private static boolean extractUnsequencedModifications = true; private static boolean docCommentsEnabled = false; private static boolean finalMethodsAsFunctions = true; private static boolean removeClassMethods = false; private static boolean hidePrivateMembers = true; private static int batchTranslateMaximum = 0; private static File proGuardUsageFile = null; static final String DEFAULT_HEADER_MAPPING_FILE = "mappings.j2objc"; // Null if not set (means we use the default). Can be empty also (means we use no mapping files). private static List<String> headerMappingFiles = null; private static final String JRE_MAPPINGS_FILE = "JRE.mappings"; private static String fileHeader; private static final String FILE_HEADER_KEY = "file-header"; private static String usageMessage; private static String helpMessage; private static final String USAGE_MSG_KEY = "usage-message"; private static final String HELP_MSG_KEY = "help-message"; private static String temporaryDirectory; private static final String XBOOTCLASSPATH = "-Xbootclasspath:"; private static String bootclasspath = System.getProperty("sun.boot.class.path"); private static Map<String, String> packagePrefixes = Maps.newHashMap(); private static final String BATCH_PROCESSING_MAX_FLAG = "--batch-translate-max="; static { // Load string resources. URL propertiesUrl = Resources.getResource(J2ObjC.class, "J2ObjC.properties"); Properties properties = new Properties(); try { properties.load(propertiesUrl.openStream()); } catch (IOException e) { System.err.println("unable to access tool properties: " + e); System.exit(1); } fileHeader = properties.getProperty(FILE_HEADER_KEY); Preconditions.checkNotNull(fileHeader); usageMessage = properties.getProperty(USAGE_MSG_KEY); Preconditions.checkNotNull(usageMessage); helpMessage = properties.getProperty(HELP_MSG_KEY); Preconditions.checkNotNull(helpMessage); } /** * Types of memory management to be used by translated code. */ public static enum MemoryManagementOption { REFERENCE_COUNTING, ARC } private static final MemoryManagementOption DEFAULT_MEMORY_MANAGEMENT_OPTION = MemoryManagementOption.REFERENCE_COUNTING; /** * Types of output file generation. Output files are generated in * the specified output directory in an optional sub-directory. */ public static enum OutputStyleOption { /** Use the class's package, like javac.*/ PACKAGE, /** Use the relative directory of the input file. */ SOURCE, /** Don't use a relative directory. */ NONE } public static final OutputStyleOption DEFAULT_OUTPUT_STYLE_OPTION = OutputStyleOption.PACKAGE; /** * Set all log handlers in this package with a common level. */ private static void setLogLevel(Level level) { Logger.getLogger("com.google.devtools.j2objc").setLevel(level); } public static boolean isVerbose() { return Logger.getLogger("com.google.devtools.j2objc").getLevel() == Level.FINEST; } /** * Load the options from a command-line, returning the arguments that were * not option-related (usually files). If help is requested or an error is * detected, the appropriate status method is invoked and the app terminates. * @throws IOException */ public static String[] load(String[] args) throws IOException { setLogLevel(Level.INFO); addJreMappings(); // Create a temporary directory as the sourcepath's first entry, so that // modified sources will take precedence over regular files. sourcePathEntries = Lists.newArrayList(); int nArg = 0; String[] noFiles = new String[0]; while (nArg < args.length) { String arg = args[nArg]; if (arg.isEmpty()) { ++nArg; continue; } if (arg.equals("-classpath")) { if (++nArg == args.length) { return noFiles; } classPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-sourcepath")) { if (++nArg == args.length) { usage("-sourcepath requires an argument"); } sourcePathEntries.addAll(getPathArgument(args[nArg])); } else if (arg.equals("-pluginpath")) { if (++nArg == args.length) { usage("-pluginpath requires an argument"); } pluginPathEntries = getPathArgument(args[nArg]); } else if (arg.equals("-pluginoptions")) { if (++nArg == args.length){ usage("-pluginoptions requires an argument"); } pluginOptionString = args[nArg]; } else if (arg.equals("-d")) { if (++nArg == args.length) { usage("-d requires an argument"); } outputDirectory = new File(args[nArg]); } else if (arg.equals("--mapping")) { if (++nArg == args.length) { usage("--mapping requires an argument"); } addMappingsFiles(args[nArg].split(",")); } else if (arg.equals("--header-mapping")) { if (++nArg == args.length) { usage("--header-mapping requires an argument"); } if (args[nArg].isEmpty()) { // For when user supplies an empty mapping files list. Otherwise the default will be used. headerMappingFiles = Collections.<String>emptyList(); } else { headerMappingFiles = Lists.newArrayList(args[nArg].split(",")); } } else if (arg.equals("--output-header-mapping")) { if (++nArg == args.length) { usage("--output-header-mapping requires an argument"); } outputHeaderMappingFile = new File(args[nArg]); } else if (arg.equals("--dead-code-report")) { if (++nArg == args.length) { usage("--dead-code-report requires an argument"); } proGuardUsageFile = new File(args[nArg]); } else if (arg.equals("--prefix")) { if (++nArg == args.length) { usage("--prefix requires an argument"); } addPrefixOption(args[nArg]); } else if (arg.equals("--prefixes")) { if (++nArg == args.length) { usage("--prefixes requires an argument"); } addPrefixesFile(args[nArg]); } else if (arg.equals("-x")) { if (++nArg == args.length) { usage("-x requires an argument"); } String s = args[nArg]; if (s.equals("objective-c")) { implementationSuffix = ".m"; } else if (s.equals("objective-c++")) { implementationSuffix = ".mm"; } else { usage("unsupported language: " + s); } } else if (arg.equals("--ignore-missing-imports")) { ErrorUtil.error("--ignore-missing-imports is no longer supported"); } else if (arg.equals("-use-reference-counting")) { checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING); } else if (arg.equals("--no-package-directories")) { outputStyle = OutputStyleOption.NONE; } else if (arg.equals("--preserve-full-paths")) { outputStyle = OutputStyleOption.SOURCE; } else if (arg.equals("-use-arc")) { checkMemoryManagementOption(MemoryManagementOption.ARC); } else if (arg.equals("-g")) { emitLineDirectives = true; } else if (arg.equals("-Werror")) { warningsAsErrors = true; } else if (arg.equals("--generate-deprecated")) { deprecatedDeclarations = true; } else if (arg.equals("-q") || arg.equals("--quiet")) { setLogLevel(Level.WARNING); } else if (arg.equals("-t") || arg.equals("--timing-info")) { setLogLevel(Level.FINE); } else if (arg.equals("-v") || arg.equals("--verbose")) { setLogLevel(Level.FINEST); } else if (arg.startsWith(XBOOTCLASSPATH)) { bootclasspath = arg.substring(XBOOTCLASSPATH.length()); } else if (arg.equals("-Xno-jsni-delimiters")) { // TODO(tball): remove flag when all client builds stop using it. } else if (arg.equals("-Xno-jsni-warnings")) { jsniWarnings = false; } else if (arg.equals("-encoding")) { if (++nArg == args.length) { usage("-encoding requires an argument"); } fileEncoding = args[nArg]; try { // Verify encoding has a supported charset. Charset.forName(fileEncoding); } catch (UnsupportedCharsetException e) { ErrorUtil.warning(e.getMessage()); } } else if (arg.equals("--strip-gwt-incompatible")) { stripGwtIncompatible = true; } else if (arg.equals("--strip-reflection")) { stripReflection = true; } else if (arg.equals("--segmented-headers")) { segmentedHeaders = true; } else if (arg.equals("--build-closure")) { buildClosure = true; } else if (arg.equals("--extract-unsequenced")) { extractUnsequencedModifications = true; } else if (arg.equals("--no-extract-unsequenced")) { extractUnsequencedModifications = false; } else if (arg.equals("--doc-comments")) { docCommentsEnabled = true; } else if (arg.startsWith(BATCH_PROCESSING_MAX_FLAG)) { batchTranslateMaximum = Integer.parseInt(arg.substring(BATCH_PROCESSING_MAX_FLAG.length())); // TODO(tball): remove obsolete flag once projects stop using it. } else if (arg.equals("--final-methods-as-functions")) { finalMethodsAsFunctions = true; } else if (arg.equals("--no-final-methods-functions")) { finalMethodsAsFunctions = false; } else if (arg.equals("--no-class-methods")) { removeClassMethods = true; // TODO(tball): remove obsolete flag once projects stop using it. } else if (arg.equals("--hide-private-members")) { hidePrivateMembers = true; } else if (arg.equals("--no-hide-private-members")) { hidePrivateMembers = false; } else if (arg.startsWith("-h") || arg.equals("--help")) { help(false); } else if (arg.startsWith("-")) { usage("invalid flag: " + arg); } else { break; } ++nArg; } if (memoryManagementOption == null) { memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING; } int nFiles = args.length - nArg; String[] files = new String[nFiles]; for (int i = 0; i < nFiles; i++) { String path = args[i + nArg]; if (path.endsWith(".jar")) { appendSourcePath(path); } files[i] = path; } return files; } /** * Add prefix option, which has a format of "<package>=<prefix>". */ private static void addPrefixOption(String arg) { int i = arg.indexOf('='); // Make sure key and value are at least 1 character. if (i < 1 || i >= arg.length() - 1) { usage("invalid prefix format"); } String pkg = arg.substring(0, i); String prefix = arg.substring(i + 1); addPackagePrefix(pkg, prefix); } /** * Add a file map of packages to their respective prefixes, using the * Properties file format. */ private static void addPrefixesFile(String filename) throws IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream(filename); props.load(fis); fis.close(); addPrefixProperties(props); } @VisibleForTesting static void addPrefixProperties(Properties props) { for (String pkg : props.stringPropertyNames()) { addPackagePrefix(pkg, props.getProperty(pkg).trim()); } } private static void addMappingsFiles(String[] filenames) throws IOException { for (String filename : filenames) { if (!filename.isEmpty()) { addMappingsProperties(FileUtil.loadProperties(filename)); } } } private static void addJreMappings() throws IOException { InputStream stream = J2ObjC.class.getResourceAsStream(JRE_MAPPINGS_FILE); addMappingsProperties(FileUtil.loadProperties(stream)); } private static void addMappingsProperties(Properties mappings) { Enumeration<?> keyIterator = mappings.propertyNames(); while (keyIterator.hasMoreElements()) { String key = (String) keyIterator.nextElement(); if (key.indexOf('(') > 0) { // All method mappings have parentheses characters, classes don't. String iosMethod = mappings.getProperty(key); methodMappings.put(key, iosMethod); } else { String iosClass = mappings.getProperty(key); classMappings.put(key, iosClass); } } } /** * Check that the memory management option wasn't previously set to a * different value. If okay, then set the option. */ private static void checkMemoryManagementOption(MemoryManagementOption option) { if (memoryManagementOption != null && memoryManagementOption != option) { usage("Multiple memory management options cannot be set."); } setMemoryManagementOption(option); } public static void usage(String invalidUseMsg) { System.err.println("j2objc: " + invalidUseMsg); System.err.println(usageMessage); System.exit(1); } public static void help(boolean errorExit) { System.err.println(helpMessage); // javac exits with 2, but any non-zero value works. System.exit(errorExit ? 2 : 0); } private static List<String> getPathArgument(String argument) { List<String> entries = Lists.newArrayList(); for (String entry : Splitter.on(File.pathSeparatorChar).split(argument)) { if (new File(entry).exists()) { // JDT fails with bad path entries. entries.add(entry); } else if (entry.startsWith("~/")) { // Expand bash/csh tildes, which don't get expanded by the shell // first if in the middle of a path string. String expanded = System.getProperty("user.home") + entry.substring(1); if (new File(expanded).exists()) { entries.add(expanded); } } } return entries; } public static boolean docCommentsEnabled() { return docCommentsEnabled; } @VisibleForTesting public static void setDocCommentsEnabled(boolean value) { docCommentsEnabled = value; } @VisibleForTesting public static void resetDocComments() { docCommentsEnabled = false; } public static List<String> getSourcePathEntries() { return sourcePathEntries; } public static void appendSourcePath(String entry) { sourcePathEntries.add(entry); } public static void insertSourcePath(int index, String entry) { sourcePathEntries.add(index, entry); } public static List<String> getClassPathEntries() { return classPathEntries; } public static String[] getPluginPathEntries() { return pluginPathEntries.toArray(new String[pluginPathEntries.size()]); } public static String getPluginOptionString() { return pluginOptionString; } public static List<Plugin> getPlugins() { return plugins; } public static File getOutputDirectory() { return outputDirectory; } /** * If true, put output files in sub-directories defined by * package declaration (like javac does). */ public static boolean usePackageDirectories() { return outputStyle == OutputStyleOption.PACKAGE; } /** * If true, put output files in the same directories from * which the input files were read. */ public static boolean useSourceDirectories() { return outputStyle == OutputStyleOption.SOURCE; } public static void setPackageDirectories(OutputStyleOption style) { outputStyle = style; } public static String getImplementationFileSuffix() { return implementationSuffix; } public static boolean useReferenceCounting() { return memoryManagementOption == MemoryManagementOption.REFERENCE_COUNTING; } public static boolean useARC() { return memoryManagementOption == MemoryManagementOption.ARC; } public static MemoryManagementOption getMemoryManagementOption() { return memoryManagementOption; } // Used by tests. public static void setMemoryManagementOption(MemoryManagementOption option) { memoryManagementOption = option; } public static void resetMemoryManagementOption() { memoryManagementOption = DEFAULT_MEMORY_MANAGEMENT_OPTION; } public static boolean emitLineDirectives() { return emitLineDirectives; } public static void setEmitLineDirectives(boolean b) { emitLineDirectives = b; } public static boolean treatWarningsAsErrors() { return warningsAsErrors; } @VisibleForTesting public static void enableDeprecatedDeclarations() { deprecatedDeclarations = true; } @VisibleForTesting public static void resetDeprecatedDeclarations() { deprecatedDeclarations = false; } public static boolean generateDeprecatedDeclarations() { return deprecatedDeclarations; } public static Map<String, String> getClassMappings() { return classMappings; } public static Map<String, String> getMethodMappings() { return methodMappings; } public static Map<String, String> getHeaderMappings() { return headerMappings; } @Nullable public static List<String> getHeaderMappingFiles() { return headerMappingFiles; } public static void setHeaderMappingFiles(List<String> headerMappingFiles) { Options.headerMappingFiles = headerMappingFiles; } public static String getUsageMessage() { return usageMessage; } public static String getHelpMessage() { return helpMessage; } public static String getFileHeader() { return fileHeader; } public static File getProGuardUsageFile() { return proGuardUsageFile; } public static File getOutputHeaderMappingFile() { return outputHeaderMappingFile; } @VisibleForTesting public static void setOutputHeaderMappingFile(File outputHeaderMappingFile) { Options.outputHeaderMappingFile = outputHeaderMappingFile; } public static List<String> getBootClasspath() { return getPathArgument(bootclasspath); } public static Map<String, String> getPackagePrefixes() { return packagePrefixes; } public static String addPackagePrefix(String pkg, String prefix) { return packagePrefixes.put(pkg, prefix); } @VisibleForTesting public static void clearPackagePrefixes() { packagePrefixes.clear(); } public static String getTemporaryDirectory() throws IOException { if (temporaryDirectory != null) { return temporaryDirectory; } File tmpfile = File.createTempFile("j2objc", Long.toString(System.nanoTime())); if (!tmpfile.delete()) { throw new IOException("Could not delete temp file: " + tmpfile.getAbsolutePath()); } if (!tmpfile.mkdir()) { throw new IOException("Could not create temp directory: " + tmpfile.getAbsolutePath()); } temporaryDirectory = tmpfile.getAbsolutePath(); return temporaryDirectory; } // Called on exit. This is done here rather than using File.deleteOnExit(), // so the package directories created by the dead-code-eliminator don't have // to be tracked. public static void deleteTemporaryDirectory() { if (temporaryDirectory != null) { deleteDir(new File(temporaryDirectory)); temporaryDirectory = null; } } static void deleteDir(File dir) { for (File f : dir.listFiles()) { if (f.isDirectory()) { deleteDir(f); } else if (f.getName().endsWith(".java")) { // Only delete Java files, as other temporary files (like hsperfdata) // may also be in tmpdir. // TODO(kstanger): It doesn't make sense that hsperfdata would show up in our tempdir. // Consider deleting this method and using FileUtil#deleteTempDir() instead. f.delete(); } } dir.delete(); // Will fail if other files in dir, which is fine. } public static String fileEncoding() { return fileEncoding; } public static Charset getCharset() { return Charset.forName(fileEncoding); } public static boolean stripGwtIncompatibleMethods() { return stripGwtIncompatible; } @VisibleForTesting public static void setStripGwtIncompatibleMethods(boolean b) { stripGwtIncompatible = b; } public static boolean generateSegmentedHeaders() { return segmentedHeaders; } @VisibleForTesting public static void enableSegmentedHeaders() { segmentedHeaders = true; } @VisibleForTesting public static void resetSegmentedHeaders() { segmentedHeaders = false; } public static boolean jsniWarnings() { return jsniWarnings; } public static void setJsniWarnings(boolean b) { jsniWarnings = b; } public static boolean buildClosure() { return buildClosure; } @VisibleForTesting public static void setBuildClosure(boolean b) { buildClosure = b; } @VisibleForTesting public static void resetBuildClosure() { buildClosure = false; } public static boolean stripReflection() { return stripReflection; } @VisibleForTesting public static void setStripReflection(boolean b) { stripReflection = b; } public static boolean extractUnsequencedModifications() { return extractUnsequencedModifications; } @VisibleForTesting public static void enableExtractUnsequencedModifications() { extractUnsequencedModifications = true; } @VisibleForTesting public static void resetExtractUnsequencedModifications() { extractUnsequencedModifications = false; } public static int batchTranslateMaximum() { return batchTranslateMaximum; } @VisibleForTesting public static void setBatchTranslateMaximum(int max) { batchTranslateMaximum = max; } @VisibleForTesting public static void resetBatchTranslateMaximum() { batchTranslateMaximum = 0; } public static boolean finalMethodsAsFunctions() { return finalMethodsAsFunctions; } @VisibleForTesting public static void enableFinalMethodsAsFunctions() { finalMethodsAsFunctions = true; } @VisibleForTesting public static void resetFinalMethodsAsFunctions() { finalMethodsAsFunctions = false; } public static boolean removeClassMethods() { return removeClassMethods; } @VisibleForTesting public static void setRemoveClassMethods(boolean b) { removeClassMethods = b; } @VisibleForTesting public static void resetRemoveClassMethods() { removeClassMethods = false; } public static boolean hidePrivateMembers() { return hidePrivateMembers; } @VisibleForTesting public static void enableHidePrivateMembers() { hidePrivateMembers = true; } @VisibleForTesting public static void resetHidePrivateMembers() { hidePrivateMembers = false; } public static boolean shouldPreProcess() { return Options.getHeaderMappingFiles() != null && Options.useSourceDirectories(); } }
a86a455f36e3d711154d437cc8b782b312283b93
8d366835936f55d0db8f65492cdcca5990d400ef
/app/src/main/java/com/dgsw/doorlock/tool/task/GetRFIDTask.java
027f671a10fc1cc23d60f3f5d0716e83e5ff294b
[]
no_license
DGSWDoorlock/AndroidApp
a3e3818eb7636194df465fc50216d6c6f5e709a0
d85d4e9418e79c49ac6b1779fd2d0a8805342d63
refs/heads/master
2021-09-01T15:20:19.546500
2017-12-27T17:16:51
2017-12-27T17:16:51
114,576,343
0
0
null
null
null
null
UTF-8
Java
false
false
2,421
java
package com.dgsw.doorlock.tool.task; import android.os.AsyncTask; import android.util.Log; import com.dgsw.doorlock.data.EntryInfo; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import static com.dgsw.doorlock.activity.Main.IP_ADDRESS; /** * Created by kimji on 2017-12-17. */ public class GetRFIDTask extends AsyncTask<EntryInfo, Integer, String> { private final String id; private String RFID; public GetRFIDTask(String id) { this.id = id; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(EntryInfo[] infos) { try { URL Url = new URL(" http://" + IP_ADDRESS + ":8080/ENT_SYSTEM/webresources/com.dgsw.entinfo/" + URLEncoder.encode(id, "UTF-8"));//받을 주소 + ID HttpURLConnection conn = (HttpURLConnection) Url.openConnection();//연결해줄 Connection conn.setRequestMethod("GET");//POST 형식 conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true);//입력 가능 int Res = conn.getResponseCode(); if (Res != HttpURLConnection.HTTP_OK) Log.e("RESPONSE_CODE", Res + ""); BufferedReader br; try { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception e) { e.printStackTrace(); br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } String line = br.readLine(); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(line); RFID = jsonObject.get("rfid").toString(); br.close(); } catch (IOException | ParseException e) { e.printStackTrace(); } return RFID; } @Override protected void onProgressUpdate(Integer... params) { } @Override protected void onPostExecute(String result) { super.onPostExecute(result); } }
8daa98917d2fb4122817614a082b771cc8995997
4e1787629588da82a11e6cb4845c57923f527e5d
/coherence-spring-core/src/main/java/com/oracle/coherence/spring/messaging/CoherencePublisherScanRegistrar.java
e9ca5f89c1ded6caa909a26db9556bdec1d0104c
[ "UPL-1.0", "BSD-3-Clause", "EPL-2.0", "CC-BY-3.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CDDL-1.0", "CC0-1.0", "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-dco-1.1", "LGPL-2.1-only" ]
permissive
coherence-community/coherence-spring
ab17ed8010b971e16766452cf936a7e2a865cc43
b1eb9e90e8c90188df985b42fe89206dad535a67
refs/heads/main
2023-09-02T07:56:48.464208
2023-09-01T15:56:09
2023-09-01T15:56:09
8,587,598
30
22
UPL-1.0
2023-09-14T20:28:57
2013-03-05T19:46:48
Java
UTF-8
Java
false
false
9,801
java
/* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. */ package com.oracle.coherence.spring.messaging; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import com.oracle.coherence.spring.annotation.CoherencePublisher; import com.oracle.coherence.spring.annotation.CoherencePublisherScan; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.Aware; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AspectJTypeFilter; import org.springframework.core.type.filter.AssignableTypeFilter; import org.springframework.core.type.filter.RegexPatternTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * {@link ImportBeanDefinitionRegistrar} implementation to scan and register Coherence publishers. * * @author Artem Bilan * @author Gary Russell * * @since 3.0 */ public class CoherencePublisherScanRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { private final Map<TypeFilter, ImportBeanDefinitionRegistrar> componentRegistrars = new HashMap<>(); private ResourceLoader resourceLoader; private Environment environment; public CoherencePublisherScanRegistrar() { this.componentRegistrars.put(new AnnotationTypeFilter(CoherencePublisher.class, true), new CoherencePublisherRegistrar()); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { final Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(CoherencePublisherScan.class.getName()); Assert.notNull(annotationAttributes, "No matching CoherencePublisherScan was found."); Collection<String> basePackages = getBasePackages(importingClassMetadata, registry); if (basePackages.isEmpty()) { basePackages = Collections.singleton(ClassUtils.getPackageName(importingClassMetadata.getClassName())); } final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false, this.environment) { @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isIndependent() && !beanDefinition.getMetadata().isAnnotation(); } @Override protected BeanDefinitionRegistry getRegistry() { return registry; } }; filter(registry, annotationAttributes, scanner); scanner.setResourceLoader(this.resourceLoader); for (String basePackage : basePackages) { Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage); for (BeanDefinition candidateComponent : candidateComponents) { if (candidateComponent instanceof AnnotatedBeanDefinition) { for (ImportBeanDefinitionRegistrar registrar : this.componentRegistrars.values()) { registrar.registerBeanDefinitions(((AnnotatedBeanDefinition) candidateComponent).getMetadata(), registry); } } } } } /** * Get the collection of base packages from the {@link CoherencePublisherScan} annotation if available. * @param importingClassMetadata the AnnotationMetadata * @param registry the BeanDefinitionRegistry * @return the basePackages, never null */ protected Collection<String> getBasePackages(AnnotationMetadata importingClassMetadata, @SuppressWarnings("unused") BeanDefinitionRegistry registry) { Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(CoherencePublisherScan.class.getName()); Set<String> basePackages = new HashSet<>(); if (annotationAttributes == null) { return basePackages; } for (String pkg : (String[]) annotationAttributes.get("value")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (Class<?> clazz : (Class<?>[]) annotationAttributes.get("basePackageClasses")) { basePackages.add(ClassUtils.getPackageName(clazz)); } return basePackages; } private void filter(BeanDefinitionRegistry registry, Map<String, Object> componentScan, ClassPathScanningCandidateComponentProvider scanner) { if ((boolean) componentScan.get("useDefaultFilters")) { for (TypeFilter typeFilter : this.componentRegistrars.keySet()) { scanner.addIncludeFilter(typeFilter); } } for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("includeFilters")) { for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) { scanner.addIncludeFilter(typeFilter); } } for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("excludeFilters")) { for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) { scanner.addExcludeFilter(typeFilter); } } } private List<TypeFilter> typeFiltersFor(AnnotationAttributes filter, BeanDefinitionRegistry registry) { List<TypeFilter> typeFilters = new ArrayList<>(); FilterType filterType = filter.getEnum("type"); for (Class<?> filterClass : filter.getClassArray("classes")) { switch (filterType) { case ANNOTATION: Assert.isAssignable(Annotation.class, filterClass, "An error occurred while processing a @CoherencePublisherScan ANNOTATION type filter: "); @SuppressWarnings("unchecked") Class<Annotation> annotationType = (Class<Annotation>) filterClass; typeFilters.add(new AnnotationTypeFilter(annotationType)); break; case ASSIGNABLE_TYPE: typeFilters.add(new AssignableTypeFilter(filterClass)); break; case CUSTOM: Assert.isAssignable(TypeFilter.class, filterClass, "An error occurred while processing a @CoherencePublisherScan CUSTOM type filter: "); TypeFilter typeFilter = BeanUtils.instantiateClass(filterClass, TypeFilter.class); invokeAwareMethods(filter, this.environment, this.resourceLoader, registry); typeFilters.add(typeFilter); break; default: throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); } } for (String expression : filter.getStringArray("pattern")) { switch (filterType) { case ASPECTJ: typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader())); break; case REGEX: typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression))); break; default: throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType); } } return typeFilters; } private static void invokeAwareMethods(Object parserStrategyBean, Environment environment, ResourceLoader resourceLoader, BeanDefinitionRegistry registry) { if (parserStrategyBean instanceof Aware) { if (parserStrategyBean instanceof BeanClassLoaderAware) { ClassLoader classLoader = (registry instanceof ConfigurableBeanFactory) ? ((ConfigurableBeanFactory) registry).getBeanClassLoader() : resourceLoader.getClassLoader(); if (classLoader != null) { ((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader); } } if (parserStrategyBean instanceof BeanFactoryAware && registry instanceof BeanFactory) { ((BeanFactoryAware) parserStrategyBean).setBeanFactory((BeanFactory) registry); } if (parserStrategyBean instanceof EnvironmentAware) { ((EnvironmentAware) parserStrategyBean).setEnvironment(environment); } if (parserStrategyBean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) parserStrategyBean).setResourceLoader(resourceLoader); } } } }
f8d2c37934b074e4a2fbc0187aef545f0dcdf5fe
0203c612b12f5247b05e8c575820de2a593212b7
/Week6/Task10/src/sample/Controller.java
d4b8237fe6d0e812461577605bd9fe930a811a07
[]
no_license
VeselinTodorov2000/Java-OOP-2021
72995291f00f22cc552c26abac093a2400bb669c
98e4705de5e91bf9107d710f042fdc4b12cd064d
refs/heads/main
2023-06-04T01:49:25.221947
2021-06-21T20:22:17
2021-06-21T20:22:17
342,679,554
0
0
null
null
null
null
UTF-8
Java
false
false
1,945
java
package sample; import java.net.URL; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; public class Controller { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private Button btnCalculate; @FXML private Button btnQuit; @FXML private TextField txtDecimalNumber; @FXML private TextField txtOnesComplement; @FXML private TextField txtTwosComplement; @FXML private TextField txtSum; @FXML void btnCalculateOnAction(ActionEvent event) { byte entered = Byte.parseByte(txtDecimalNumber.getText()); byte onesComplement = (byte)(entered ^ 1); byte twosComplement = (byte)(onesComplement + 1); txtOnesComplement.setText(String.format("%d", onesComplement)); txtTwosComplement.setText(String.format("%d", twosComplement)); txtSum.setText(String.format("%d", onesComplement + twosComplement)); } @FXML void btnQuitOnAction(ActionEvent event) { Platform.exit(); } @FXML void initialize() { assert btnCalculate != null : "fx:id=\"btnCalculate\" was not injected: check your FXML file 'sample.fxml'."; assert btnQuit != null : "fx:id=\"btnQuit\" was not injected: check your FXML file 'sample.fxml'."; assert txtDecimalNumber != null : "fx:id=\"txtDecimalNumber\" was not injected: check your FXML file 'sample.fxml'."; assert txtOnesComplement != null : "fx:id=\"txtOnesComplement\" was not injected: check your FXML file 'sample.fxml'."; assert txtTwosComplement != null : "fx:id=\"txtTwosComplement\" was not injected: check your FXML file 'sample.fxml'."; assert txtSum != null : "fx:id=\"txtSum\" was not injected: check your FXML file 'sample.fxml'."; } }
c78598ccddc3fc5a1409be2138a75d94829f279a
07c473a7754057e99e6c81b00172b9a1a43c0e96
/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/cpp/CcInfoApi.java
54238d0d8279967a25e3a65c1140bc2b4e1c30bd
[ "Apache-2.0" ]
permissive
chenshuo/bazel
ffd3f37331db1ce5979f43aa3d27b96a6efcd1a2
c2ba4a08a788097297da81b58e2fb9ffdb22a581
refs/heads/master
2020-04-29T20:13:31.491356
2019-03-18T21:51:45
2019-03-18T21:53:24
176,378,348
3
0
Apache-2.0
2019-03-18T22:18:32
2019-03-18T22:18:32
null
UTF-8
Java
false
false
3,950
java
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.cpp; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.skylarkbuildapi.ProviderApi; import com.google.devtools.build.lib.skylarkbuildapi.StructApi; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.ParamType; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkConstructor; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; import com.google.devtools.build.lib.syntax.Environment; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.Runtime.NoneType; /** Wrapper for every C++ compilation and linking provider. */ @SkylarkModule( name = "CcInfo", category = SkylarkModuleCategory.PROVIDER, doc = "A provider containing information for C++ compilation and linking.") public interface CcInfoApi extends StructApi { String NAME = "CcInfo"; @SkylarkCallable( name = "compilation_context", doc = "Returns the <code>CompilationContext</code>", structField = true) CcCompilationContextApi getCcCompilationContext(); @SkylarkCallable( name = "linking_context", doc = "Returns the <code>LinkingContext</code>", structField = true) CcLinkingContextApi getCcLinkingContext(); /** The provider implementing this can construct the CcInfo provider. */ @SkylarkModule( name = "CcProvider", doc = "A provider for compilation and linking of C++. This " + "is also a marking provider telling C++ rules that they can depend on the rule " + "with this provider. If it is not intended for the rule to be depended on by C++, " + "the rule should wrap the CcInfo in some other provider.") interface Provider extends ProviderApi { @SkylarkCallable( name = NAME, doc = "The <code>CcInfo</code> constructor.", useLocation = true, useEnvironment = true, parameters = { @Param( name = "compilation_context", doc = "The <code>CompilationContext</code>.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = CcCompilationContextApi.class), @ParamType(type = NoneType.class) }), @Param( name = "linking_context", doc = "The <code>LinkingContext</code>.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = CcLinkingContextApi.class), @ParamType(type = NoneType.class) }) }, selfCall = true) @SkylarkConstructor(objectType = CcInfoApi.class, receiverNameForDoc = NAME) CcInfoApi createInfo( Object ccCompilationContext, Object ccLinkingInfo, Location location, Environment environment) throws EvalException; } }
67328021694558e9a6704e1fad62b2b40a8fb061
353ae5b753263a68af145c3d624952040618f7b6
/src/main/java/com/dao/AddrMapper.java
81d1c7e29b0d62aa406a8e73160c747b20c9925f
[]
no_license
snowfengjia/jianhuoShop
2d982297cbf5f77fcb15ad82ea63a350511e7511
705cf25f4489b4d2440b8febdc0b7c35180ec2b2
refs/heads/master
2020-03-25T22:56:34.150478
2018-11-14T10:17:12
2018-11-14T10:17:12
144,251,863
2
0
null
null
null
null
UTF-8
Java
false
false
766
java
package com.dao; import java.util.List; import java.util.Map; import com.pojo.Addr; /** * @author Administrator * 订单状态mapper */ public interface AddrMapper { int deleteByPrimaryKey(Integer fid); int insert(Addr record); int insertSelective(Addr record); Addr selectByPrimaryKey(Integer fid); int updateByPrimaryKeySelective(Addr record); int updateByPrimaryKey(Addr record); public Addr checkUname(Map<String, Object> uname); // 查询所有信息 public List<Addr> getAll(Map<String, Object> map); // 获取条数 public int getCount(Map<String, Object> po); // 分页 public List<Addr> getByPage(Map<String, Object> map); // 模糊查询并分页 public List<Addr> select(Map<String, Object> map); }
72ab146ef737d5813f6cd8cb654b080803e7603d
122e91f41ecdb52826b2b9af1b0d57ab9d9d6117
/app/src/androidTest/java/net/skhu/androidmidtest/ExampleInstrumentedTest.java
99ccfbbd2459499391f502dddce49f619bf82ba8
[]
no_license
anpiso/androidMidTest
5dd671230f14a74441e066a0b8af275a8fbf3e9a
dd07bb55555f1b91f2ba9f8fbf1453de12e60099
refs/heads/master
2022-06-08T11:49:30.288648
2020-05-06T08:51:11
2020-05-06T08:51:11
261,082,708
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package net.skhu.androidmidtest; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("net.skhu.androidmidtest", appContext.getPackageName()); } }
c3db427afa86a9e7d6b4c49f3f2fd3c31446e3f2
4ebde5edac16dfb32adda59f6158c46b9db33d63
/src/CriarPersonagemMonstro.java
8ff3adb4f6853453e3d3c29ce605dce6c4e4a1bf
[]
no_license
giokittens/MonstroVCRobo
b914641cf00026ad84f07a0d356a133f89316907
d3c8f4e4258fd51d40c286ad2146f79249b83f8b
refs/heads/master
2020-09-06T00:11:40.180477
2019-11-07T15:23:03
2019-11-07T15:23:03
220,254,108
0
0
null
null
null
null
UTF-8
Java
false
false
10,797
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. */ /** * * @author Aluno */ public class CriarPersonagemMonstro extends javax.swing.JFrame { /** * Creates new form CriarPersonagemMonstro */ public CriarPersonagemMonstro() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { CampoAtaque = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); CampoNome = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); CampoHP = new javax.swing.JSlider(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); CampoDefesa = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); CampoAgilidade = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); CampoAtaque.setBackground(new java.awt.Color(51, 204, 255)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mostronnn.png"))); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N jLabel2.setText("Definição do Monstro"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Nome"); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("HP"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("Ataque"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("Defesa"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setText("Agilidade"); jButton1.setText("Salvar"); javax.swing.GroupLayout CampoAtaqueLayout = new javax.swing.GroupLayout(CampoAtaque); CampoAtaque.setLayout(CampoAtaqueLayout); CampoAtaqueLayout.setHorizontalGroup( CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addGap(168, 168, 168) .addComponent(jLabel2) .addContainerGap(137, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, CampoAtaqueLayout.createSequentialGroup() .addContainerGap() .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton1)) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAgilidade, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(CampoHP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CampoNome) .addComponent(jTextField2) .addComponent(CampoDefesa)) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7)))) .addGap(37, 37, 37)) ); CampoAtaqueLayout.setVerticalGroup( CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoHP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(3, 3, 3) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoDefesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoAgilidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE) .addComponent(jButton1)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAtaque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAtaque, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CriarPersonagemMonstro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField CampoAgilidade; private javax.swing.JPanel CampoAtaque; private javax.swing.JTextField CampoDefesa; private javax.swing.JSlider CampoHP; private javax.swing.JTextField CampoNome; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
[ "" ]
ccb6eaab68d640031985fc733177cdb5a0d9f9fe
b7478c7cacc237ae56f34986fa1bfcb7416dcb6e
/main/java/utils/JwtUtil.java
bbbdabdd873e5f1ee4006e47ee902271450bfa82
[]
no_license
Semperdecus/Kwetter
ee775526efb5877c857d64df2b8ed6b8528796e3
b0f3a6235f34aba56c292b58f5f664342fe85b5b
refs/heads/master
2023-01-10T05:01:05.851025
2019-06-08T20:44:26
2019-06-08T20:44:26
171,243,102
0
0
null
2023-01-01T07:57:25
2019-02-18T08:22:45
Java
UTF-8
Java
false
false
5,208
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 utils; import java.util.Date; import javax.xml.bind.DatatypeConverter; import models.Account; import io.jsonwebtoken.*; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.Key; import java.util.Properties; import javax.crypto.spec.SecretKeySpec; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import gherkin.deps.com.google.gson.JsonObject; import static io.jsonwebtoken.security.Keys.secretKeyFor; import java.io.IOException; import javax.crypto.spec.SecretKeySpec; import javax.json.JsonArray; /** * * @author teren */ public class JwtUtil { /** * Expiration time of JWT token in milliseconds 604 800 000 = 1 week */ private final long EXPIRATIONTIME = 604800000; public JwtUtil() { } public String makeAccountJwtToken(String id, String issuer, Account account) throws IOException { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setId(id) .setIssuedAt(now) .setSubject(createJSONAccount(account)) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); Date exp; //if it has been specified, let's add the expiration if (EXPIRATIONTIME >= 0) { long expMillis = nowMillis + EXPIRATIONTIME; exp = new Date(expMillis); builder.setExpiration(exp); } JsonObject token = new JsonObject(); token.addProperty("token", builder.compact()); token.addProperty("expiresIn", exp.toString()); //Builds the JWT and serializes it to a compact, URL-safe string return token.toString(); } public String apiKey() throws IOException { String apiKey = null; InputStream inputStream = null; try { Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { prop.load(inputStream); } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } Date time = new Date(System.currentTimeMillis()); // get the property value and print it out apiKey = prop.getProperty("apiKey"); } catch (Exception e) { System.out.println("Exception: " + e); } finally { inputStream.close(); } return apiKey; } public String createJSONAccount(Account account) { String jsonInString = ""; ObjectMapper mapper = new ObjectMapper(); try { // Convert object to JSON string jsonInString = mapper.writeValueAsString(account); // System.out.println(jsonInString); // Convert object to JSON string and pretty print //jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(account); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonInString; } public boolean validateJwt(String jwsString) throws IOException { String[] splited = jwsString.split(" "); int length = splited.length; //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); Jws<Claims> jws; try { jws = Jwts.parser() .setSigningKey(signingKey) .parseClaimsJws(splited[length -1]); return true; } catch (JwtException ex) { ex.printStackTrace(); // we *cannot* use the JWT as intended by its creator } return false; } }
23b4fb7124343906e567716598945109310ea1f5
87b691743c3024ad1798b45fc868e22c45a4cbce
/src/main/java/net/floodlightcontroller/packetstreamer/PacketStreamerHandler.java
402dffdb989fd0bb52e5f99a21a81306df82693b
[ "Apache-2.0" ]
permissive
jimmyoic/floodlight-qosmanager
97b7ac3934a1363c4c4f664bbddf375c35440387
4d20272ed68aec92433c834c31a6ebaea0063b51
refs/heads/master
2021-01-09T23:42:13.155477
2015-01-07T13:39:48
2015-01-07T13:39:48
21,138,890
12
4
null
null
null
null
UTF-8
Java
false
false
6,900
java
package net.floodlightcontroller.packetstreamer; import net.floodlightcontroller.core.annotations.LogMessageCategory; import net.floodlightcontroller.core.annotations.LogMessageDoc; import net.floodlightcontroller.core.annotations.LogMessageDocs; import net.floodlightcontroller.packetstreamer.thrift.*; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Map; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The PacketStreamer handler class that implements the service APIs. */ @LogMessageCategory("OpenFlow Message Tracing") public class PacketStreamerHandler implements PacketStreamer.Iface { /** * The queue wrapper class that contains the queue for the streamed packets. */ protected class SessionQueue { protected BlockingQueue<ByteBuffer> pQueue; /** * The queue wrapper constructor */ public SessionQueue() { this.pQueue = new LinkedBlockingQueue<ByteBuffer>(); } /** * The access method to get to the internal queue. */ public BlockingQueue<ByteBuffer> getQueue() { return this.pQueue; } } /** * The class logger object */ protected static Logger log = LoggerFactory.getLogger(PacketStreamerServer.class); /** * A sessionId-to-queue mapping */ protected Map<String, SessionQueue> msgQueues; /** * The handler's constructor */ public PacketStreamerHandler() { this.msgQueues = new ConcurrentHashMap<String, SessionQueue>(); } /** * The implementation for getPackets() function. * This is a blocking API. * * @param sessionid * @return A list of packets associated with the session */ @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Interrupted while waiting for session start", explanation="The thread was interrupted waiting " + "for the packet streamer session to start", recommendation=LogMessageDoc.CHECK_CONTROLLER), @LogMessageDoc(level="ERROR", message="Interrupted while waiting for packets", explanation="The thread was interrupted waiting " + "for packets", recommendation=LogMessageDoc.CHECK_CONTROLLER), }) public List<ByteBuffer> getPackets(String sessionid) throws org.apache.thrift.TException { List<ByteBuffer> packets = new ArrayList<ByteBuffer>(); int count = 0; while (!msgQueues.containsKey(sessionid) && count++ < 100) { log.debug("Queue for session {} doesn't exist yet.", sessionid); try { Thread.sleep(100); // Wait 100 ms to check again. } catch (InterruptedException e) { log.error("Interrupted while waiting for session start"); } } if (count < 100) { SessionQueue pQueue = msgQueues.get(sessionid); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); // Block if queue is empty try { packets.add(queue.take()); queue.drainTo(packets); } catch (InterruptedException e) { log.error("Interrupted while waiting for packets"); } } return packets; } /** * The implementation for pushMessageSync() function. * * @param msg * @return 1 for success, 0 for failure * @throws TException */ @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Could not push empty message", explanation="An empty message was sent to the packet streamer", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG), @LogMessageDoc(level="ERROR", message="queue for session {sessionId} is null", explanation="The queue for the packet streamer session " + "is missing", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG), }) public int pushMessageSync(Message msg) throws org.apache.thrift.TException { if (msg == null) { log.error("Could not push empty message"); return 0; } List<String> sessionids = msg.getSessionIDs(); for (String sid : sessionids) { SessionQueue pQueue = null; if (!msgQueues.containsKey(sid)) { pQueue = new SessionQueue(); msgQueues.put(sid, pQueue); } else { pQueue = msgQueues.get(sid); } log.debug("pushMessageSync: SessionId: " + sid + " Receive a message, " + msg.toString() + "\n"); ByteBuffer bb = ByteBuffer.wrap(msg.getPacket().getData()); //ByteBuffer dst = ByteBuffer.wrap(msg.getPacket().toString().getBytes()); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); if (queue != null) { if (!queue.offer(bb)) { log.error("Failed to queue message for session: " + sid); } else { log.debug("insert a message to session: " + sid); } } else { log.error("queue for session {} is null", sid); } } return 1; } /** * The implementation for pushMessageAsync() function. * * @param msg * @throws TException */ @Override public void pushMessageAsync(Message msg) throws org.apache.thrift.TException { pushMessageSync(msg); return; } /** * The implementation for terminateSession() function. * It removes the session to queue association. * @param sessionid * @throws TException */ @Override public void terminateSession(String sessionid) throws org.apache.thrift.TException { if (!msgQueues.containsKey(sessionid)) { return; } SessionQueue pQueue = msgQueues.get(sessionid); log.debug("terminateSession: SessionId: " + sessionid + "\n"); String data = "FilterTimeout"; ByteBuffer bb = ByteBuffer.wrap(data.getBytes()); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); if (queue != null) { if (!queue.offer(bb)) { log.error("Failed to queue message for session: " + sessionid); } msgQueues.remove(sessionid); } else { log.error("queue for session {} is null", sessionid); } } }
94d8ee5116c6055eadf506691bdc24e2aae660b8
cec628def1aad94ccbefa814d2a0dbd51588e9bd
/css.lib/src/org/netbeans/modules/css/lib/ErrorNode.java
8a25d727f8630db671bdd52b96ae54844f454a5e
[]
no_license
emilianbold/netbeans-releases
ad6e6e52a896212cb628d4522a4f8ae685d84d90
2fd6dc84c187e3c79a959b3ddb4da1a9703659c7
refs/heads/master
2021-01-12T04:58:24.877580
2017-10-17T14:38:27
2017-10-17T14:38:27
78,269,363
30
15
null
2020-10-13T08:36:08
2017-01-07T09:07:28
null
UTF-8
Java
false
false
2,797
java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2011 Sun Microsystems, Inc. */ package org.netbeans.modules.css.lib; import org.netbeans.modules.css.lib.api.NodeType; import org.netbeans.modules.css.lib.api.ProblemDescription; /** * * @author marekfukala */ public class ErrorNode extends RuleNode { private ProblemDescription problemDescription; public ErrorNode(int from, int to, ProblemDescription pd, CharSequence source) { super(NodeType.error, source); this.from = from; this.to = to; this.problemDescription = pd; } @Override public NodeType type() { return NodeType.error; } public ProblemDescription getProblemDescription() { return problemDescription; } }
a1c76c0e8dabed6d2e87142198f3b61b3bf66b08
00dd0e5eaa44900f3e147e332b80ea06bcf407aa
/src/com/aerospike/benchmarks/Workload.java
dcf16e6f6ec530463ccaf0b95be54fd0dc4ff2c1
[]
no_license
aminer/llist-benchmark-tool
e7fd024200fd68134bb62ee5280471ad4ef04f6f
eefe1542e0a4ee7cd73e6b27cb04e0d3f56ae8ac
refs/heads/master
2016-09-05T19:11:03.463053
2015-07-17T22:56:44
2015-07-17T22:56:44
37,932,398
0
0
null
null
null
null
UTF-8
Java
false
false
1,034
java
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements WHICH ARE COMPATIBLE WITH THE APACHE LICENSE, VERSION 2.0. * * 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.aerospike.benchmarks; /** * Benchmark workload type. */ public enum Workload { /** * Initialize data with sequential key writes. */ INITIALIZE, /** * Read/Update. Perform random key, random read all bins or write all bins workload. */ READ_UPDATE, }
7cafd904640b8e7db6a00c3ddb2b15f440750fcc
eb7ef0755288506490718792f6758e03d126e314
/KallSonysOms/KallSonysOms-bakend-clientService/src/main/java/org/datacontract/schemas/_2004/_07/productoentities/CategoriaEntity.java
b8f3dc2b55c4dd53ab63e60b20574273412e5572
[]
no_license
njmube/PICA
91815fd7a74abe13c5cb250efb3ea96aedeb1cd4
367df7186340748410019ae4194d325628462f9c
refs/heads/master
2020-12-20T23:46:48.443861
2017-05-31T13:06:02
2017-05-31T13:06:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,314
java
package org.datacontract.schemas._2004._07.productoentities; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para CategoriaEntity complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="CategoriaEntity"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Categoria" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="IdCategoria" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CategoriaEntity", propOrder = { "categoria", "idCategoria" }) public class CategoriaEntity { @XmlElement(name = "Categoria", nillable = true) protected String categoria; @XmlElement(name = "IdCategoria") protected Integer idCategoria; /** * Obtiene el valor de la propiedad categoria. * * @return * possible object is * {@link String } * */ public String getCategoria() { return categoria; } /** * Define el valor de la propiedad categoria. * * @param value * allowed object is * {@link String } * */ public void setCategoria(String value) { this.categoria = value; } /** * Obtiene el valor de la propiedad idCategoria. * * @return * possible object is * {@link Integer } * */ public Integer getIdCategoria() { return idCategoria; } /** * Define el valor de la propiedad idCategoria. * * @param value * allowed object is * {@link Integer } * */ public void setIdCategoria(Integer value) { this.idCategoria = value; } }
3fde825ecc4b4f465b4d8f4faf4fde76ccf5df3a
d394411d9dd74e03a597c2e7f8076c382913b418
/src/main/java/ra/net/NetServerApplication.java
407bb05df5301df30972c40f1e28027ddc839a92
[ "MIT" ]
permissive
EastLu/RA
2d75d734d24ca06b0cc533a964566d145cb09d6f
44c0b3967dd7077dbd005d076117c68b86e6bf11
refs/heads/main
2023-06-20T23:09:02.745214
2021-07-27T07:44:54
2021-07-27T07:44:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,696
java
package ra.net; import java.io.IOException; import java.net.ServerSocket; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.naming.NamingException; import ra.net.nio.DataNetService; import ra.net.nio.PackageHandleOutput; import ra.net.processor.CommandProcessorListener; import ra.net.processor.CommandProcessorProvider; import ra.net.processor.DataNetCommandProvider; import ra.net.processor.NetCommandProvider; import ra.net.request.Request; import ra.util.annotation.Configuration; import ra.util.annotation.ServerApplication; /** * {@link NetService}, {@link DataNetService} manager. * * @author Ray Li */ public class NetServerApplication implements NetServiceProvider { private static NetServerApplication instance; private static final String NET = "Net"; private ServerSocket serverSocket; private Map<String, Serviceable<?>> servicePool; private Map<String, User> userList; private MessageSender sender; private ExecutorService threadPool; private ServerConfiguration configuration; /** Initialize. */ public NetServerApplication() { servicePool = new HashMap<>(); userList = new ConcurrentHashMap<>(); sender = new MessageSender(); sender.setNetServiceProvider(this); } /** * User offline. * * @param index Socket index */ public void removeUser(int index) { User user = userList.get("" + index); if (user != null) { user.close(); userList.remove("" + index); } } /** * Put the user into user pool. * * @param index index * @param listener listener */ public void putUser(int index, User listener) { userList.put("" + index, listener); } /** * Put {@link NetService}. * * @param index service index * @param service service * @throws NamingException The key already exists */ public void putNetService(int index, NetService service) throws NamingException { this.putService(NET + index, service); } /** * Put DataNetService. * * @param index service index * @param service service * @throws NamingException NamingException */ public void putDataNetService(int index, DataNetService service) throws NamingException { this.putService(NET + index, service); } /** * Put Serviceable. * * @param index index * @param service service * @throws NamingException NamingException */ public void putService(int index, Serviceable<?> service) throws NamingException { this.putService(NET + index, service); } /** * Put Serviceable. * * @param key key * @param service service * @throws NamingException NamingException */ public void putService(String key, Serviceable<?> service) throws NamingException { if (servicePool.containsKey(key)) { throw new NamingException("Naming repeat, key = " + key); } servicePool.put(key, service); } @Override public Serviceable<?> getService(int index) { return servicePool.get(NET + index); } /** * Returns service. * * @param key key * @return service */ public Serviceable<?> getService(String key) { return servicePool.get(key); } /** * Returns service. * * @param index specify index * @return NetService */ public NetService getNetService(int index) { return (NetService) servicePool.get(NET + index); } /** * Returns service. * * @param index specify index * @return DataNetService */ public DataNetService getDataNetService(int index) { return (DataNetService) servicePool.get(NET + index); } /** * Returns user. * * @param index specify index * @return User */ public User getUser(int index) { return userList.get("" + index); } @Override public Map<String, User> getUsers() { return userList; } /** * Returns message sender. * * @return MessageSender */ public MessageSender getMessageSender() { return sender; } /** * Returns server configuration. * * @return ServerConfiguration */ public ServerConfiguration getConfiguration() { return configuration; } /** * Get current application. * * @return NetServerApplication */ public static NetServerApplication getApplication() { return instance; } /** * Run server. * * @param source source * @param args args */ @SuppressWarnings("resource") public static void run(Class<?> source, String... args) { if (!source.isAnnotationPresent(ServerApplication.class)) { throw new RuntimeException("Source '" + source + "' is not annotation @ServerApplication."); } NetServerApplication application = new NetServerApplication(); ServerConfiguration configuration = null; String path = null; if (source.isAnnotationPresent(Configuration.class)) { Configuration configurationAnnotation = source.getAnnotation(Configuration.class); path = configurationAnnotation.value(); } else { throw new RuntimeException("Source '" + source + "' is not annotation @Configuration."); } try { configuration = new ServerConfiguration(path); } catch (IOException e) { e.printStackTrace(); } application.configuration = configuration; int poolSize = application.configuration.getPropertyAsInt("server.netservice.max-threads", 200); int port = application.configuration.getPropertyAsInt("server.port", 20000); ServerApplication annotation = source.getAnnotation(ServerApplication.class); Class<? extends CommandProcessorProvider<? extends Request>> commandProviderClass = annotation.serviceMode(); ServerSocket serverSocket = null; System.out.printf( "port=%d, poolsize=%d, commandProvider=%s\n", port, poolSize, commandProviderClass.getName()); try { serverSocket = new ServerSocket(port, poolSize); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException( "ServerSocket not initialize, port = " + port + ",poolSize=" + poolSize + ".", e); } CommandProcessorProvider<? extends Request> providerObject = null; try { providerObject = commandProviderClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "The provider class '" + commandProviderClass + "' constructor is a mismatch."); } if (NetCommandProvider.class.isAssignableFrom(commandProviderClass)) { application.runNetService(serverSocket, port, poolSize, (NetCommandProvider) providerObject); } else if (DataNetCommandProvider.class.isAssignableFrom(commandProviderClass)) { application.runNetDataService( serverSocket, port, poolSize, (DataNetCommandProvider) providerObject); } else { throw new RuntimeException( "The provider class '" + commandProviderClass + "' invalid, please use or inherit NetServiceCommandProvider, " + "DataNetServiceCommandProvider."); } instance = application; } /** * NetServerApplication initialize. * * @param serverSocket serverSocket * @param port port * @param poolSize request pool size * @param providerClass command provider */ private void runNetService( ServerSocket serverSocket, int port, int poolSize, NetCommandProvider commandProvider) { this.serverSocket = serverSocket; threadPool = Executors.newFixedThreadPool(poolSize); NetService.Builder builder = new NetService.Builder(); NetService service = null; builder .setSendExecutor(threadPool) .setSocketSoTimeout(Duration.ofSeconds(20)) .setServerSocket(serverSocket); for (int i = 1; i <= poolSize; i++) { builder.setIndex(i); service = builder.build(); service.setCommandProcessorProvider( new NetCommandProvider() { @Override public CommandProcessorListener<NetService.NetRequest> createCommand() { return commandProvider.createCommand(); } @Override public void offline(int index) { commandProvider.offline(index); removeUser(index); } }); try { putNetService(i, service); } catch (NamingException e) { e.printStackTrace(); } service.start(); } } /** * NetServerApplication initialize. * * @param serverSocket serverSocket * @param port port * @param poolSize request pool size * @param providerClass command provider */ private void runNetDataService( ServerSocket serverSocket, int port, int poolSize, DataNetCommandProvider commandProvider) { this.serverSocket = serverSocket; threadPool = Executors.newFixedThreadPool(poolSize); DataNetService.Builder builder = new DataNetService.Builder() .setSendExecutor(threadPool) .setServerSocket(serverSocket) .setCommandProcessorProvider( new DataNetCommandProvider() { @Override public CommandProcessorListener<DataNetService.DataNetRequest> createCommand() { return commandProvider.createCommand(); } @Override public void offline(int index) { commandProvider.offline(index); removeUser(index); } }) .setSocketSoTimeout(Duration.ofSeconds(60)) .setTransferListener(new PackageHandleOutput()); DataNetService service = null; for (int i = 1; i <= poolSize; i++) { builder.setIndex(i); service = builder.build(); try { putDataNetService(i, service); } catch (NamingException e) { e.printStackTrace(); } service.start(); } } /** Finish application. */ public void close() { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } threadPool.shutdownNow(); servicePool .values() .stream() .filter(service -> AutoCloseable.class.isInstance(service)) .map(AutoCloseable.class::cast) .forEach( service -> { try { service.close(); } catch (Exception e) { e.printStackTrace(); } }); userList.values().forEach(user -> user.close()); } }
a15ea92b473f96722da365c549d29c5ad2573cf1
0e894d0257811bf883e0d46fcfbb5d08f100637e
/src/main/java/com/enginemobi/bssuite/domain/Promotion.java
464ad576294b64661a3e8a93a5f1ddc145271a4b
[ "Apache-2.0" ]
permissive
pkcool/bssuite
ded01f8c015bdc23209bb97ee97be7ebbebad5a7
6771fed3c2e2bb2b318f5cc8e6edafd1b787a063
refs/heads/develop-0.3.x
2021-01-10T06:20:51.001239
2015-12-08T03:05:22
2015-12-08T03:05:22
44,002,076
6
7
null
2015-11-06T11:13:35
2015-10-10T08:32:55
Java
UTF-8
Java
false
false
3,859
java
package com.enginemobi.bssuite.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import java.time.LocalDate; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Promotion. */ @Entity @Table(name = "promotion") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "promotion") public class Promotion implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Column(name = "code", nullable = false) private String code; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "start_date") private LocalDate startDate; @Column(name = "end_date") private LocalDate endDate; @Column(name = "cost") private Double cost; @Column(name = "income") private Double income; @Column(name = "expense") private Double expense; @Column(name = "date_created") private LocalDate dateCreated; @ManyToOne @JoinColumn(name = "store_id") private Store store; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public Double getCost() { return cost; } public void setCost(Double cost) { this.cost = cost; } public Double getIncome() { return income; } public void setIncome(Double income) { this.income = income; } public Double getExpense() { return expense; } public void setExpense(Double expense) { this.expense = expense; } public LocalDate getDateCreated() { return dateCreated; } public void setDateCreated(LocalDate dateCreated) { this.dateCreated = dateCreated; } public Store getStore() { return store; } public void setStore(Store store) { this.store = store; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Promotion promotion = (Promotion) o; return Objects.equals(id, promotion.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Promotion{" + "id=" + id + ", code='" + code + "'" + ", name='" + name + "'" + ", description='" + description + "'" + ", startDate='" + startDate + "'" + ", endDate='" + endDate + "'" + ", cost='" + cost + "'" + ", income='" + income + "'" + ", expense='" + expense + "'" + ", dateCreated='" + dateCreated + "'" + '}'; } }
eb665103d6cc1b3cf5c448483fe8e8e9a115d4ab
753c19c237b3a24a5e58938ba530b26284c2cbc2
/app/src/main/java/com/fred_w/demo/codercommunity/mvp/model/entity/AccessToken.java
42ca65f3e2044cb1fb1d9ac8a85441e5bba417dd
[]
no_license
wjl7123093/CoderCommunity
df1ecf810affe9b24b618e3c85e805a964132f63
766bbe98188d6319727cf83dfe6cba3bfdc7fd93
refs/heads/master
2021-09-04T08:57:09.162253
2018-01-17T13:57:31
2018-01-17T13:57:31
115,528,585
0
0
null
null
null
null
UTF-8
Java
false
false
1,651
java
package com.fred_w.demo.codercommunity.mvp.model.entity; /** * AccessToken Entity * * @author Fred_W * @version v1.0.0 * * @crdate 2017-12-31 * @update */ public class AccessToken { private int code; private String access_token; private String refresh_token; private String token_type; private int expires_in; private int uid; @Override public String toString() { return "AccessToken{" + "access_token='" + access_token + '\'' + ", refresh_token='" + refresh_token + '\'' + ", token_type='" + token_type + '\'' + ", expires_in=" + expires_in + ", uid=" + uid + '}'; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getRefresh_token() { return refresh_token; } public void setRefresh_token(String refresh_token) { this.refresh_token = refresh_token; } public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } }
0e59eefffeadb8a78f60aced557956e19d091d11
7111b3e8d178b5084e9335f6dd8ebc345c4ee052
/array method return type.java
b6bfc4f2b28568364f2c4683c5f7c7e5296bc87a
[]
no_license
CanonJavaDev/practice
b0e92da11c2064c4b69628a458d189dd4c232412
559d13ce58f76912aed0d392264376bd89dbf51d
refs/heads/master
2021-01-17T16:03:09.058189
2017-02-23T23:32:15
2017-02-23T23:32:15
82,977,904
0
0
null
2017-02-23T23:32:16
2017-02-23T22:31:47
Java
UTF-8
Java
false
false
678
java
//array method return type class Test { int[] m1( ) //Method return type is array { System.out.println("Method----1"); int [ ] a = {10,20,30}; return a; } void m2(double[] d) // Method argument is array { System.out.println("Method---2"); for (double dd : d) { System.out.println(dd); } } public static void main(String[] args) { Test t =new Test(); // instance, constructor int[] x = t.m1(); for (int xx : x) { System.out.println(xx); } double[] d = {10.5,20.6,30.7}; t.m2(d); } } /* C:\Users\Ritesh\Desktop\corejava\Sample>java Test Method----1 10 20 30 Method---2 10.5 20.6 30.7 */
141eda8136a251a4c14900d7319fa6c14a33121b
f2e83d1fcbfcca23313f5d12af309b71e686d106
/Desktop/KOSMO/workspace/java/KKosmo/src/object06/cooperation/Student.java
6a89b4b2121c66cb58fa0f98442135e0f4074358
[]
no_license
jason-moonKor/Kosmo0815class-Java
129a7c93fef5fd97d8a99fa8b99c96eb2c65a136
6875623bcd411a5f9a14c782bd805105bed03a83
refs/heads/main
2023-07-16T03:49:47.809679
2021-09-03T09:16:08
2021-09-03T09:16:08
402,705,729
0
0
null
null
null
null
UTF-8
Java
false
false
705
java
package object06.cooperation; public class Student { String studentName; public int grade; public int money; public int busFee = 1000; public int subFee = 1500; public Student(String studentName, int money) { this.studentName = studentName; this.money = money; } public void takeBus(Bus bus) { System.out.println(this.studentName + "이 버스를 탔습니다"); bus.take(busFee); this.money -= busFee; } public void takeSubway(Subway subway) { System.out.println(this.studentName+ "이 지하철을 탔습니다"); subway.take(subFee); this.money -= subFee; } public void showInfo() { System.out.println(studentName + "의 남은 돈은 " + money + "입니다."); } }
697c907fbb0426aeec428bc380132b244b902dae
2f4d648198afa52c17f626cc2d4bfb4d7f3e8d5a
/src/uex/durian/Box.java
da6c4529b93c890bca6f9007b424db21ba06a830
[]
no_license
jgarciapft/PracticaLaberintos
bd91bf074140d0d916aa4dfc22f77d7638ef06fa
c1c2a43ec1de609fe3e5269a8f04b2943324d9b1
refs/heads/master
2020-05-03T11:46:52.779898
2019-04-22T16:09:05
2019-04-22T16:09:05
178,608,994
0
0
null
null
null
null
UTF-8
Java
false
false
18,005
java
/* * Copyright 2016 DiffPlug * * 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 uex.durian; import java.util.Objects; import java.util.function.*; /** * Provides get/set access to a mutable non-null value. */ public interface Box<T> extends Supplier<T>, Consumer<T> { /** * Creates a `Box` holding the given value in a `volatile` field. * <p> * Every call to {@link #set(Object)} confirms that the argument * is actually non-null, and the value is stored in a volatile variable. */ public static <T> Box<T> ofVolatile(T value) { return new Volatile<>(value); } /** * Creates a `Box` holding the given value in a non-`volatile` field. * <p> * The value is stored in standard non-volatile * field, and non-null-ness is not checked on * every call to set. */ public static <T> Box<T> of(T value) { return new Default<>(value); } /** * Creates a `Box` from a `Supplier` and a `Consumer`. */ public static <T> Box<T> from(Supplier<T> getter, Consumer<T> setter) { Objects.requireNonNull(getter); Objects.requireNonNull(setter); return new Box<T>() { @Override public T get() { return Objects.requireNonNull(getter.get()); } @Override public void set(T value) { setter.accept(Objects.requireNonNull(value)); } @Override public String toString() { return "Box.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(T value); /** * Delegates to set(). * * @deprecated Provided to satisfy the {@link Consumer} interface; use {@link #set} instead. */ @Deprecated default void accept(T value) { set(value); } /** * Performs a set() on the result of a get(). * <p> * Some implementations may provide atomic semantics, * but it's not required. */ default T modify(Function<? super T, ? extends T> mutator) { T modified = mutator.apply(get()); set(modified); return modified; } /** * Maps one {@code Box} to another {@code Box}, preserving any * {@link #modify(Function)} guarantees of the underlying Box. */ default <R> Box<R> map(Converter<T, R> converter) { return new Mapped<>(this, converter); } /** * Provides get/set access to a mutable nullable value. */ public interface Nullable<T> extends Supplier<T>, Consumer<T> { /** * Creates a `Box.Nullable` holding the given possibly-null value in a `volatile` field. */ public static <T> Nullable<T> ofVolatile(T init) { return new Volatile<>(init); } /** * Creates a `Box.Nullable` holding a null value in a `volatile` field. */ public static <T> Nullable<T> ofVolatileNull() { return ofVolatile(null); } /** * Creates a `Box.Nullable` holding the given possibly-null value in a non-`volatile` field. */ public static <T> Nullable<T> of(T init) { return new Default<>(init); } /** * Creates a `Box.Nullable` holding null value in a non-`volatile` field. */ public static <T> Nullable<T> ofNull() { return of(null); } /** * Creates a `Box.Nullable` from a `Supplier` and a `Consumer`. */ public static <T> Nullable<T> from(Supplier<T> getter, Consumer<T> setter) { Objects.requireNonNull(getter); Objects.requireNonNull(setter); return new Nullable<T>() { @Override public T get() { return getter.get(); } @Override public void set(T value) { setter.accept(value); } @Override public String toString() { return "Box.Nullable.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(T value); /** * Delegates to set(). * * @deprecated Provided to satisfy the {@code Function} interface; use {@link #set} instead. */ @Deprecated default void accept(T value) { set(value); } /** * Shortcut for doing a set() on the result of a get(). */ default T modify(Function<? super T, ? extends T> mutator) { T modified = mutator.apply(get()); set(modified); return modified; } /** * Maps one {@code Box} to another {@code Box}, preserving any * {@link #modify(Function)} guarantees of the underlying Box. */ default <R> Nullable<R> map(ConverterNullable<T, R> converter) { return new Nullable.Mapped<>(this, converter); } static final class Mapped<T, R> implements Nullable<R> { private final Nullable<T> delegate; private final ConverterNullable<T, R> converter; public Mapped(Nullable<T> delegate, ConverterNullable<T, R> converter) { this.delegate = delegate; this.converter = converter; } @Override public R get() { return converter.convert(delegate.get()); } @Override public void set(R value) { delegate.set(converter.revert(value)); } /** * Shortcut for doing a set() on the result of a get(). */ @Override public R modify(Function<? super R, ? extends R> mutator) { Box.Nullable<R> result = Box.Nullable.of(null); delegate.modify(input -> { R unmappedResult = mutator.apply(converter.convert(input)); result.set(unmappedResult); return converter.revert(unmappedResult); }); return result.get(); } @Override public String toString() { return "[" + delegate + " mapped to " + get() + " by " + converter + "]"; } } static class Volatile<T> implements Box.Nullable<T> { private volatile T obj; private Volatile(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = obj; } @Override public String toString() { return "Box.Nullable.ofVolatile[" + get() + "]"; } } static class Default<T> implements Box.Nullable<T> { private T obj; private Default(T init) { this.obj = init; } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = obj; } @Override public String toString() { return "Box.Nullable.of[" + get() + "]"; } } } /** * A `Box` for primitive doubles. */ public interface Dbl extends DoubleSupplier, DoubleConsumer, Box<Double> { /** * Creates a `Box.Dbl` holding the given value in a non-`volatile` field. */ public static Dbl of(double value) { return new Default(value); } /** * Creates a `Box.Dbl` from a `DoubleSupplier` and a `DoubleConsumer`. */ public static Dbl from(DoubleSupplier getter, DoubleConsumer setter) { return new Dbl() { @Override public double getAsDouble() { return getter.getAsDouble(); } @Override public void set(double value) { setter.accept(value); } @Override public String toString() { return "Box.Dbl.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(double value); @Override double getAsDouble(); /** * Delegates to {@link #getAsDouble()}. * * @deprecated Provided to satisfy {@code Box<Double>}; use {@link #getAsDouble()} instead. */ @Override @Deprecated default Double get() { return getAsDouble(); } /** * Delegates to {@link #set(double)}. * * @deprecated Provided to satisfy {@code Box<Double>}; use {@link #set(double)} instead. */ @Override @Deprecated default void set(Double value) { set(value.doubleValue()); } /** * Delegates to {@link #set(double)}. * * @deprecated Provided to satisfy the {@link DoubleConsumer}; use {@link #set(double)} instead. */ @Deprecated @Override default void accept(double value) { set(value); } static class Default implements Box.Dbl { private double obj; private Default(double init) { set(init); } @Override public double getAsDouble() { return obj; } @Override public void set(double obj) { this.obj = obj; } @Override public String toString() { return "Box.Dbl.of[" + getAsDouble() + "]"; } } } /** * A `Box` for primitive ints. */ public interface Int extends IntSupplier, IntConsumer, Box<Integer> { /** * Creates a `Box.Int` holding the given value in a non-`volatile` field. */ public static Int of(int value) { return new Default(value); } /** * Creates a `Box.Int` from a `IntSupplier` and a `IntConsumer`. */ public static Int from(IntSupplier getter, IntConsumer setter) { return new Int() { @Override public int getAsInt() { return getter.getAsInt(); } @Override public void set(int value) { setter.accept(value); } @Override public String toString() { return "Box.Int.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by {@link #getAsInt()}. */ void set(int value); @Override int getAsInt(); /** * Delegates to {@link #getAsInt()}. * * @deprecated Provided to satisfy {@code Box<Integer>}; use {@link #getAsInt()} instead. */ @Override @Deprecated default Integer get() { return getAsInt(); } /** * Delegates to {@link #set(int)}. * * @deprecated Provided to satisfy {@code Box<Integer>}; use {@link #set(int)} instead. */ @Override @Deprecated default void set(Integer value) { set(value.intValue()); } /** * Delegates to {@link #set}. * * @deprecated Provided to satisfy the {@link IntConsumer} interface; use {@link #set(int)} instead. */ @Deprecated @Override default void accept(int value) { set(value); } static class Default implements Box.Int { private int obj; private Default(int init) { set(init); } @Override public int getAsInt() { return obj; } @Override public void set(int obj) { this.obj = obj; } @Override public String toString() { return "Box.Int.of[" + get() + "]"; } } } /** * A `Box` for primitive longs. */ public interface Lng extends LongSupplier, LongConsumer, Box<Long> { /** * Creates a `Box.Long` holding the given value in a non-`volatile` field. */ public static Lng of(long value) { return new Default(value); } /** * Creates a `Box.Long` from a `LongSupplier` and a `LongConsumer`. */ public static Lng from(LongSupplier getter, LongConsumer setter) { return new Lng() { @Override public long getAsLong() { return getter.getAsLong(); } @Override public void set(long value) { setter.accept(value); } @Override public String toString() { return "Box.Long.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by {@link #getAsLong()}. */ void set(long value); @Override long getAsLong(); /** * Auto-boxed getter. * * @deprecated Provided to satisfy {@code Box<Long>} interface; use {@link #getAsLong()} instead. */ @Override @Deprecated default Long get() { return getAsLong(); } /** * Delegates to {@link #set(long)}. * * @deprecated Provided to satisfy {@code Box<Long>} interface; use {@link #set(long)} instead. */ @Override @Deprecated default void set(Long value) { set(value.longValue()); } /** * Delegates to {@link #set(long)}. * * @deprecated Provided to satisfy {@link LongConsumer} interface; use {@link #set(long)} instead. */ @Deprecated @Override default void accept(long value) { set(value); } static class Default implements Box.Lng { private long obj; private Default(long init) { set(init); } @Override public long getAsLong() { return obj; } @Override public void set(long obj) { this.obj = obj; } @Override public String toString() { return "Box.Long.of[" + get() + "]"; } } } static final class Mapped<T, R> implements Box<R> { private final Box<T> delegate; private final Converter<T, R> converter; public Mapped(Box<T> delegate, Converter<T, R> converter) { this.delegate = delegate; this.converter = converter; } @Override public R get() { return converter.convertNonNull(delegate.get()); } @Override public void set(R value) { delegate.set(converter.revertNonNull(value)); } /** * Shortcut for doing a set() on the result of a get(). */ @Override public R modify(Function<? super R, ? extends R> mutator) { Box.Nullable<R> result = Box.Nullable.of(null); delegate.modify(input -> { R unmappedResult = mutator.apply(converter.convertNonNull(input)); result.set(unmappedResult); return converter.revertNonNull(unmappedResult); }); return result.get(); } @Override public String toString() { return "[" + delegate + " mapped to " + get() + " by " + converter + "]"; } } static final class Volatile<T> implements Box<T> { private volatile T obj; private Volatile(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = Objects.requireNonNull(obj); } @Override public String toString() { return "Box.ofVolatile[" + get() + "]"; } } static final class Default<T> implements Box<T> { private T obj; private Default(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = Objects.requireNonNull(obj); } @Override public String toString() { return "Box.of[" + get() + "]"; } } }
d317e905f0747313430bf337323d902fdff44899
618bff98f8b0b2e0258b4ef069ff373ee3b7cc76
/app/src/main/java/com/atozmak/devtfdemo/entities/ArticleDetail.java
4b6be5125dffc185a0e9ca6a4a019b35ec01581d
[]
no_license
lostinthefall/DevtfDemo
2388d48e0fdf4255ed778a1f8d3fdb79c55e26d1
8b6e24804916819473566538a1604eaa9b07ce1c
refs/heads/master
2020-07-05T05:04:53.603308
2016-03-20T08:31:01
2016-03-20T08:31:01
54,305,874
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
package com.atozmak.devtfdemo.entities; /** * Created by Mak on 2016/3/19. */ public class ArticleDetail { public String postId; public String content; public ArticleDetail() { } public ArticleDetail(String postId, String content) { this.postId = postId; this.content = content; } }
d9fc8d75d9b6722cd232c146736d6feb8e77741e
e6e16791661f6883e043721c243bc32f2a13c88d
/src/main/java/cn/diffpi/kit/video/BuilderUtil.java
c2e121f5c1515df39fe77d0174b6a6c0e49f18cd
[]
no_license
SuperHeYilin/hi-video-resty
5be7db63c964c8024d9b998ff776075dfada68ab
eddfa90b3045ab96a2aed4cd9944bbc6ea6df272
refs/heads/master
2022-09-03T10:49:25.995353
2020-04-21T09:11:25
2020-04-21T09:11:25
141,672,804
0
0
null
2022-09-01T22:48:01
2018-07-20T06:30:30
Java
UTF-8
Java
false
false
548
java
package cn.diffpi.kit.video; /** * 打开文件的工具类 */ public class BuilderUtil { private BuilderUtil() { } public static ProcessBuilder getInstance() { return BuilderSingleton.INSTANCE.getInstance(); } private static enum BuilderSingleton { INSTANCE; private ProcessBuilder processBuilder; private BuilderSingleton() { processBuilder = new ProcessBuilder(); } public ProcessBuilder getInstance() { return processBuilder; } } }
42699b2ed705503084df6cbb94b25d97977a8f25
f7393adbe4582f440ecbfe2b74562f25d3ae1b67
/Common/src/main/java/cn/qqtheme/framework/util/ScreenUtils.java
7d6eadfd12fff00776a706c3d59afdc217cc07e5
[ "Apache-2.0" ]
permissive
alicfeng/sise
b7a20329ca1c80cc575e8e9e2ad48364db4ec639
230dcdd417ca1b9b034d8c7d95ef193a446999e9
refs/heads/master
2021-06-16T16:42:29.309496
2017-05-15T12:05:29
2017-05-15T12:05:29
59,456,580
3
0
null
null
null
null
UTF-8
Java
false
false
2,923
java
package cn.qqtheme.framework.util; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import android.view.Window; import android.view.WindowManager; /** * 获取屏幕宽高等信息、全屏切换、保持屏幕常亮、截屏等 * * @author liyujiang[QQ:1032694760] * @since 2015/11/26 */ public final class ScreenUtils { private static boolean isFullScreen = false; /** * Display metrics display metrics. * * @param context the context * @return the display metrics */ public static DisplayMetrics displayMetrics(Context context) { DisplayMetrics dm = new DisplayMetrics(); WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); LogUtils.debug("screen width=" + dm.widthPixels + "px, screen height=" + dm.heightPixels + "px, densityDpi=" + dm.densityDpi + ", density=" + dm.density); return dm; } /** * Width pixels int. * * @param context the context * @return the int */ public static int widthPixels(Context context) { return displayMetrics(context).widthPixels; } /** * Height pixels int. * * @param context the context * @return the int */ public static int heightPixels(Context context) { return displayMetrics(context).heightPixels; } /** * Density float. * * @param context the context * @return the float */ public static float density(Context context) { return displayMetrics(context).density; } /** * Density dpi int. * * @param context the context * @return the int */ public static int densityDpi(Context context) { return displayMetrics(context).densityDpi; } /** * Is full screen boolean. * * @return the boolean */ public static boolean isFullScreen() { return isFullScreen; } /** * Toggle full displayMetrics. * * @param activity the activity */ public static void toggleFullScreen(Activity activity) { Window window = activity.getWindow(); int flagFullscreen = WindowManager.LayoutParams.FLAG_FULLSCREEN; if (isFullScreen) { window.clearFlags(flagFullscreen); isFullScreen = false; } else { window.setFlags(flagFullscreen, flagFullscreen); isFullScreen = true; } } /** * 保持屏幕常亮 * * @param activity the activity */ public static void keepBright(Activity activity) { //需在setContentView前调用 int keepScreenOn = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; activity.getWindow().setFlags(keepScreenOn, keepScreenOn); } }
cb9f564020641afa150e14f8426a3145b8ba3e3f
d212614b72eeca746e8f8c3bbb2fcae8593ea9ea
/app/src/main/java/com/hapus/android/store/Product_details_activity.java
b3b4cad1e7ee0c7fbe520e0c9cbaa2dd08139707
[]
no_license
ksasanka11/Hapus
da17c5af5190d4e111db2f6152e4bb43580780f8
94a9534788b65a05b4a3c0e3f7706324eeae5d38
refs/heads/master
2022-11-04T07:30:53.127164
2019-05-15T08:02:32
2019-05-15T08:02:32
171,491,481
0
0
null
null
null
null
UTF-8
Java
false
false
5,865
java
package com.hapus.android.store; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.telephony.SmsManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.List; public class Product_details_activity extends AppCompatActivity { private ViewPager productImagesViewPager; private TabLayout viewpagerIndicator; private TextView productTitle; private TextView averageRatingMiniView; private TextView productPrice; private FloatingActionButton addToWishListbtn;//todo:wishlist activity private FirebaseFirestore mFirebaseFirestore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_details_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); productImagesViewPager = findViewById(R.id.product_images_viewpager); viewpagerIndicator = findViewById(R.id.viewpager_indicator); productTitle = findViewById(R.id.product_title); averageRatingMiniView = findViewById(R.id.tv_product_rating_miniview); productPrice = findViewById(R.id.product_price); mFirebaseFirestore = FirebaseFirestore.getInstance(); final List<String> productImages = new ArrayList<>(); Intent i = getIntent(); String productID = i.getStringExtra("productId"); Log.e("Products", productID); mFirebaseFirestore.collection("PRODUCTS").document(productID).get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ DocumentSnapshot documentSnapshot = task.getResult(); for(long x = 1; x <= (long)documentSnapshot.get("no_of_product_images"); x++){ productImages.add(documentSnapshot.get("product_image_"+x).toString()); } ProductImagesAdapter productImagesAdapter=new ProductImagesAdapter(productImages); productImagesViewPager.setAdapter(productImagesAdapter); productTitle.setText(documentSnapshot.get("product_title").toString()); averageRatingMiniView.setText(documentSnapshot.get("average_rating").toString()); productPrice.setText("Rs."+documentSnapshot.get("product_price").toString()+"/kg"); }else{ String error = task.getException().getMessage(); Toast.makeText(Product_details_activity.this, error, Toast.LENGTH_SHORT).show(); } } }); viewpagerIndicator.setupWithViewPager(productImagesViewPager,true); final Button sendMsg=findViewById(R.id.buy_now_btn); sendMsg.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ FirebaseFirestore.getInstance().collection("ADMIN_PHONE").document("nZHDmKKeN2ByVIeitiQR").get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ SmsManager smsManager = SmsManager.getDefault(); DocumentSnapshot documentSnapshot = task.getResult(); String phone_number = documentSnapshot.get("phone_number").toString(); smsManager.sendTextMessage(phone_number, null, "Hello", null, null); } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.search_and_cart_icon, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { finish(); return true; } else if (id == R.id.main_search_icon) { //todo: search return true; } else if (id == R.id.main_cart_icon) { //todo: cart return true; } return super.onOptionsItemSelected(item); } }
f36da24543be4a4bc3dbeeb093f3f29b698e33d8
a418c919d65fa3b66becfe43d4f166d462f09bfe
/cachecloud-open-web/src/main/java/com/sohu/cache/entity/MachineInfo.java
50a24de61f446315871e2566a21f80d0d89a4a3f
[ "Apache-2.0" ]
permissive
luwenbin006/cachecloud
b977b3665893381ed87bc3956602040923b4c208
f69631196c6eeca350d08c27ceae0835bd4e8f21
refs/heads/master
2021-01-21T09:20:37.812445
2016-11-29T09:55:05
2016-11-29T09:55:05
56,665,982
1
0
null
2016-04-20T07:36:07
2016-04-20T07:36:07
null
UTF-8
Java
false
false
5,182
java
package com.sohu.cache.entity; import java.util.Date; import com.sohu.cache.util.ConstUtils; /** * 机器的属性信息 * * Created by lingguo on 14-6-27. */ public class MachineInfo { /** * 机器id */ private long id; /** * ssh用户名 */ private String sshUser= ConstUtils.USERNAME; /** * ssh密码 */ private String sshPasswd=ConstUtils.PASSWORD; /** * ip地址 */ private String ip; /** * 机房 */ private String room; /** * 内存,单位G */ private int mem; /** * cpu数量 */ private int cpu; /** * 是否虚机,0否,1是 */ private int virtual; /** * 宿主机ip */ private String realIp; /** * 上线时间 */ private Date serviceTime; /** * 故障次数 */ private int faultCount; /** * 修改时间 */ private Date modifyTime; /** * 是否启用报警,0否,1是 */ private int warn; /** * 是否可用,0否,1是 */ private int available; /** * 机器资源的类型,0表示我们提供的原生资源,其它整数对应外部应用提供的机器资源池 */ private int type; /** * groupId */ private int groupId; /** * 额外说明:(例如本机器有其他web或者其他服务) */ private String extraDesc; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSshUser() { return sshUser; } public void setSshUser(String sshUser) { this.sshUser = sshUser; } public String getSshPasswd() { return sshPasswd; } public void setSshPasswd(String sshPasswd) { this.sshPasswd = sshPasswd; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public int getMem() { return mem; } public void setMem(int mem) { this.mem = mem; } public int getCpu() { return cpu; } public void setCpu(int cpu) { this.cpu = cpu; } public int getVirtual() { return virtual; } public void setVirtual(int virtual) { this.virtual = virtual; } public String getRealIp() { return realIp; } public void setRealIp(String realIp) { this.realIp = realIp; } public Date getServiceTime() { return serviceTime; } public void setServiceTime(Date serviceTime) { this.serviceTime = serviceTime; } public int getFaultCount() { return faultCount; } public void setFaultCount(int faultCount) { this.faultCount = faultCount; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public int getWarn() { return warn; } public void setWarn(int warn) { this.warn = warn; } public int getAvailable() { return available; } public void setAvailable(int available) { this.available = available; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public String getExtraDesc() { return extraDesc; } public void setExtraDesc(String extraDesc) { this.extraDesc = extraDesc; } /** * 获取组描述 * @return */ public String getGroupDesc() { return MachineGroupEnum.getMachineGroupInfo(type); } @Override public String toString() { return "MachineInfo{" + "id=" + id + ", sshUser='" + sshUser + '\'' + ", sshPasswd='" + sshPasswd + '\'' + ", ip='" + ip + '\'' + ", room='" + room + '\'' + ", mem=" + mem + ", cpu=" + cpu + ", virtual=" + virtual + ", realIp='" + realIp + '\'' + ", serviceTime=" + serviceTime + ", faultCount=" + faultCount + ", modifyTime=" + modifyTime + ", warn=" + warn + ", available=" + available + ", type=" + type + ", groupId=" + groupId + ", extraDesc=" + extraDesc + '}'; } }
44a2514ea63c78a736f19c50d7ab26fd63fdd22e
e605abef2bfe8283c73a8013c0efcbb80ae8bac3
/src/main/java/com/ngo/cg/exception/NoSuchDonationException.java
fca68b7009488f903c2ddc44cf967f3b0be11243
[]
no_license
sriaashritha/NGO
e46710719529787a55ad490517101dbaa3cd05bf
3201ed768b57a0f5feae5c209fc53b794884ac5b
refs/heads/master
2023-03-31T00:34:23.625092
2021-03-30T19:36:06
2021-03-30T19:36:06
353,118,995
0
0
null
null
null
null
UTF-8
Java
false
false
224
java
package com.ngo.cg.exception; public class NoSuchDonationException extends Exception { private static final long serialVersionUID = 1L; public NoSuchDonationException(String errorMessage) { super(errorMessage); } }
c2df0aaba5cde0e465dd1606bd8fb56f5022d0a1
d73e0d5c800ef6fc2782cc16779602554fdd3d7a
/src/main/java/addressbook/Util.java
b4620747c9fa859f7b4c11da991a488805fa1f1d
[]
no_license
tosinoni/AddressBookSpring
c5e7dbc03832539d93ae521a5770db63cf38cbf2
0d84625a213740982fedb90ed87ad9f6b7c4c693
refs/heads/master
2021-05-02T11:25:47.365523
2018-02-08T17:48:07
2018-02-08T17:48:07
120,775,524
0
0
null
null
null
null
UTF-8
Java
false
false
492
java
package addressbook; import java.util.Collection; public class Util { public static <E> void addAllIfNotNull(Collection<E> list, Collection<? extends E> c) { if (c != null) { list.addAll(c); } } public static <E> void addIfNotNull(Collection<E> list, E c) { if (c != null) { list.add(c); } } public static<E> boolean isCollectionEmpty(Collection<E> list) { return list == null || list.isEmpty(); } }
3db4840c54e0e7eb64f983525dca6bf6aca72da9
15e4a6aff3a6af870e05ed4b9eb7a9d6abbaa215
/Tracker/src/Position.java
dd02424e9b7eeb540a8341e5a5c9c8c8f1859fba
[]
no_license
junechoi93/formicidae
b52c9762441e42e6f52f3a5110c6094471acb38e
2a7373d828a21a76f2d4c564a9605a74c2c5005a
refs/heads/master
2020-04-20T08:24:26.962847
2014-03-05T10:01:34
2014-03-05T10:01:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,619
java
import processing.core.PApplet; import processing.core.PVector; public class Position { PVector origin; PVector avgspeed; // Average speed in pixels/second float lastmovetime; // Last moved time in seconds static float averagingTime =1.0f; // Averaging time in seconds int channel; int id; int groupid; int groupsize; public Position(PVector origin, int channel, int id) { this.origin=origin; this.avgspeed=new PVector(0f,0f); this.lastmovetime= 0f; this.channel = channel; this.id = id; this.groupid = id; this.groupsize = 1; } public Position(int channel) { this.origin = new PVector(0f,0f); this.avgspeed=new PVector(0f,0f); this.lastmovetime = 0f; this.channel = channel; } int getcolor(PApplet parent) { final int colors[] = {0xffff0000, 0xff00ff00, 0xff0000ff, 0xffFFFF00, 0xffFF00FF, 0xff00ffff}; int col=colors[(id-1)%colors.length]; //PApplet.println("Color="+String.format("%x", col)); return col; } void move(PVector newpos, int groupid, int groupsize, float elapsed) { //PApplet.println("move("+newpos+","+elapsed+"), lastmovetime="+lastmovetime); if (lastmovetime!=0.0 && elapsed>lastmovetime) { PVector moved=newpos.get(); moved.sub(origin); moved.mult(1.0f/(elapsed-lastmovetime)); // Running average using exponential decay float k=(elapsed-lastmovetime)/averagingTime; if (k>1.0f) k=1.0f; avgspeed.mult(1-k); moved.mult(k); avgspeed.add(moved); //PApplet.println("\t\t\t\tk="+k+", Speed="+avgspeed); } origin=newpos; lastmovetime=elapsed; this.groupid=groupid; this.groupsize=groupsize; } }
d928cc2b907a9fee83f1752caf8a58375abea553
fdcb69f1d67ea822e7cdf51a00b4381785e05ea9
/src/main/java/edu/web/ContentType.java
d5638c25dac00df5a3a6e972120ccfdb872ff849
[]
no_license
lanaflonPerso/ProgramingServlets
1add2cd0cda7e2ad06db2c4db963f21162211a19
dab4357680c6c21531a6bcbe96c02e41d049becc
refs/heads/master
2020-12-02T03:03:06.362668
2018-01-03T20:34:44
2018-01-03T20:34:44
230,866,127
0
1
null
2019-12-30T07:06:03
2019-12-30T07:06:02
null
UTF-8
Java
false
false
1,068
java
package edu.web; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by R.Karimov on 11/29/17. */ @WebServlet(name = "ContentType", urlPatterns = "/ContentType") public class ContentType extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); out.println("Rno\tName\tMath\tPhys\tComputer Sc\tTotal"); out.println("101\tSekhar\t90\t90\t90\t=SUM(B2:D2)"); out.println("102\tSrinivasan\t95\t95\t95\t=SUM(B2:D2)"); } }
c49d6b3df749ea3e3a719030281342c04c44dbdf
d6090b00f33bbf5ef14d7cb2372bb3a0c04bd138
/src/com/weidi/bluetoothchat/widget/ChatImageView.java
e5cf74899ebcf9cfebd60bc9b5e38e9aa6873c9f
[]
no_license
weidi5858258/BluetoothChat
2de2fac837fdc1481853cc6238015140d6c925f8
f4183dcf7c2770fe27af4728a61cbfc5a840ac45
refs/heads/master
2021-05-10T18:40:27.015858
2018-01-20T04:15:46
2018-01-20T04:15:46
118,131,985
0
0
null
null
null
null
UTF-8
Java
false
false
5,924
java
package com.weidi.bluetoothchat.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.NinePatch; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.NinePatchDrawable; import android.util.AttributeSet; import android.widget.ImageView; import com.weidi.bluetoothchat.R; public class ChatImageView extends ImageView { private int mMaskResId; private Bitmap mBitmap; private Bitmap mMaskBmp; private NinePatchDrawable mMaskDrawable; private Bitmap mResult; private Paint mPaint; private Paint mMaskPaint; private Matrix mMatrix; public ChatImageView(Context context) { super(context); init(); } public ChatImageView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ChatImageView, 0, 0); if (a != null) { mMaskResId = a.getResourceId(R.styleable.ChatImageView_chat_image_mask, 0); a.recycle(); } init(); } private void init() { mMatrix = new Matrix(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); if (mMaskResId <= 0) { return; } mMaskBmp = BitmapFactory.decodeResource(getResources(),mMaskResId); if(mMaskBmp==null){ return; } byte[] ninePatchChunk = mMaskBmp.getNinePatchChunk(); if (ninePatchChunk != null && NinePatch.isNinePatchChunk(ninePatchChunk)) { mMaskDrawable = new NinePatchDrawable(getResources(), mMaskBmp, ninePatchChunk, new Rect(), null); } internalSetImage(); } private void internalSetImage() { if (mMaskResId <= 0) { return; } if (mBitmap == null) { return; } final int width = getWidth(); final int height = getHeight(); if (width <= 0 || height <= 0) { return; } boolean canReUseBitmap = mResult != null && mResult.getWidth() == width && mResult.getHeight() == height; if (!canReUseBitmap) { mResult = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(mResult); if (canReUseBitmap) { canvas.drawColor(Color.TRANSPARENT); } // CENTER_CROP Bitmap mMatrix.reset(); float scale; float dx = 0, dy = 0; int bmpWidth = mBitmap.getWidth(); int bmpHeight = mBitmap.getHeight(); if (bmpWidth * height > width * bmpHeight) { scale = (float) height / (float) bmpHeight; dx = (width - bmpWidth * scale) * 0.5f; } else { scale = (float) width / (float) bmpWidth; dy = (height - bmpHeight * scale) * 0.5f; } mMatrix.setScale(scale, scale); mMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f)); canvas.save(); canvas.concat(mMatrix); canvas.drawBitmap(mBitmap, 0, 0, mPaint); canvas.restore(); if (mMaskDrawable != null) { mMaskDrawable.getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); mMaskDrawable.setBounds(0, 0, width, height); mMaskDrawable.draw(canvas); } else if (mMaskBmp != null) { if (mMaskPaint == null) { mMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } canvas.drawBitmap(mMaskBmp, 0, 0, mMaskPaint); } super.setImageBitmap(mResult); } @Override public void setImageBitmap(Bitmap bm) { mBitmap = bm; if (mMaskResId > 0 && mBitmap != null) { internalSetImage(); } else { super.setImageBitmap(bm); } } @Override // public void setImageResource(@DrawableRes int resId) { public void setImageResource(int resId) { mBitmap = getBitmapFromDrawable(getResources().getDrawable(resId)); internalSetImage(); } @Override public void setImageDrawable(Drawable drawable) { Bitmap bmp = getBitmapFromDrawable(drawable); if (mBitmap == bmp) { super.setImageDrawable(drawable); } else { mBitmap = bmp; internalSetImage(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); internalSetImage(); } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { return null; } } }
b94cef6dba54eb88530f57e18c2e876b6819f0b7
9419f4ac1836eb7f08d0fc08c5c0d4e5b5860a67
/src/edu/npu/votingsystem/domain/Register.java
c632a5d4a889422ea3fc9d51da11fa2877af7f46
[]
no_license
Rohini341999/VotingSystem
80484137aec3fd6f7080838232936f84be854dff
413fe5b679fb1879482dfb70bdd8dcb2d41c0c73
refs/heads/main
2023-01-29T02:03:38.310446
2020-12-16T15:35:20
2020-12-16T15:35:20
322,014,748
0
1
null
null
null
null
UTF-8
Java
false
false
663
java
package edu.npu.votingsystem.domain; public class Register { private String fName,lName,username,password; public Register() { // TODO Auto-generated constructor stub } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } }
c6405673f58d1464703df8874909f412002bb8b4
a36653d99bc288d14cfd317b22495beb16385775
/Developers_Life_Easy/src/streamsdemos/ReductionExample_3.java
08b4205c797106359a1649324cea9ef73881e710
[]
no_license
crescentjava/Java8
c8c2e7c80735a33dc05d9e21d52e29074243d22f
7c394ece987a4666bce8dcfbae4178142a4733e3
refs/heads/main
2023-08-24T17:49:34.966499
2021-10-17T16:40:25
2021-10-17T16:40:25
387,865,336
0
0
null
null
null
null
UTF-8
Java
false
false
575
java
package streamsdemos; import java.util.Arrays; import java.util.List; import java.util.Optional; public class ReductionExample_3 { public static void main(String... args) { List<Integer> list = Arrays.asList(); // List<Integer> list = Arrays.asList(-10,-8); Optional<Integer> red = //Optional:needed because default values can't be always defined list.stream() .reduce(Integer::max); System.out.println("red = " + red); System.out.println("red = " + red.get()); } }
0cef3ef04624595136a2d76f352f9a9f9faa8d3f
a1b8a83d2c7360284072548e5d0e3e16d79a6b58
/wyait-manage/src/main/java/com/wyait/manage/service/db1/ComboService.java
a9ea755fed23937b4c7f20bc592029c16c567978
[]
no_license
adolphs/system
443822789243c4590456e24dd5294430336f49cf
9a391d5249ac44b498b2e628dec5945a3acebf3c
refs/heads/main
2023-02-27T02:07:43.527298
2021-02-08T09:55:44
2021-02-08T09:55:44
305,930,810
0
0
null
null
null
null
UTF-8
Java
false
false
2,945
java
package com.wyait.manage.service.db1; import com.baomidou.mybatisplus.service.IService; import com.wyait.manage.entity.ComboDetailsVo; import com.wyait.manage.pojo.*; import com.wyait.manage.pojo.result.ResponseResult; import com.wyait.manage.utils.PageDataResult; import java.util.List; import java.util.Map; /** * @author h_baojian * @version 1.0 * @date 2020/7/3 21:00 */ public interface ComboService extends IService<Combo> { String setSituationTOW(Integer pid, Integer type, String situationDescribe, Integer situationId, Integer situationIdTOW); PageDataResult getComboList(Combo combo, Integer page, Integer limit); String setCombo(Combo combo); String delCombo(Integer comboId); ComboDetailsVo getComboDetailsVo(Integer id,Integer departmentId); String addDooo(Combo combo); String delComboDooo(ComboDooo comboDooo); String updateComboDooo(Combo combo); PageDataResult getComboSituationList(ComboSituation comboSituation, Integer page, Integer limit); String addComboSituation(Integer comboId, String situationDescribe, String detailsDescribe,Integer id); ComboSituation selectComboSituationById(Integer id); List<ComboSituation> selectPidByComboSituationId(Integer id); String addComboSituationV2(ComboSituation comboSituation); String delComboSituation(Integer id); List<ComboSituationDetails> selectSituationDetailsByComboSituationId(Integer id); String setComboSituationDetails(ComboSituationDetails comboSituationDetails); String delComboSituationDetails(Integer id); String setDataAndComboSituation(Integer dataId, Integer comboSituationId, Integer comboSituationDetailsId); List<ComboSituationDetails> getCmoboSituationDetails(Integer id); List<ComboSituation> findSituationByPid(Integer situationDetailsId); String delSituationByPidAndSituationId(Integer situationId, Integer pid); String putApprovalType(Integer comboId, Integer approvalType, String approvalText); List<Combo> findAllCombo(); List<ComboSituation> findAllComboSituation(Integer comboId); Map<String,Object> fetchMattersNums(); Combo getComboById(Integer id); ResponseResult APIComboList(String type); ResponseResult queryComboSituation(Integer comoId); ResponseResult queryComboSituationDetailsByPid(Integer comboSituationDetailsId); ResponseResult queryComboDataList(String comboSituationDetailsIds,Integer comboId) throws InterruptedException; ResponseResult getAllSituation(Integer comboId); /** * 获取套餐的流程图url * @param comboId 套餐id * @return */ ResponseResult getComboUrl(Integer comboId); /** * 根据套餐ID查询所涉及到的部门 * @param comboId * @return */ ResponseResult getDepartmentByComboId(Integer comboId); /** * 获取热门套餐 * @return */ ResponseResult getHotCombo(); }
a2909e6a11dd4ee11d9560ca9bd9358b6d58f8ab
3acf3be737b76584a818a73acfead5a23472ad46
/src/main/java/com/gcaraciolo/payroll/domain/ChangeEmployeeMailTransaction.java
cb992bc0e4b560d4f716c7a7f6d3108f7a1e6225
[]
no_license
gcaraciolo/payroll
3a702d924b24b949819dcdb94ac76e97d967745e
3c6c459623ea59001f554abf8a2606691f54a937
refs/heads/master
2020-09-07T02:58:46.432279
2019-11-12T00:59:25
2019-11-12T00:59:25
220,636,835
2
1
null
null
null
null
UTF-8
Java
false
false
310
java
package com.gcaraciolo.payroll.domain; public class ChangeEmployeeMailTransaction extends ChangeEmployeeMethodTransaction { public ChangeEmployeeMailTransaction(Integer empId) { super(empId); } @Override protected PaymentMethod getMethod() { return new MailMethod(); } }
d1901ad85eecb430e9def69e62d7d8b1a4526173
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/JetBrains--intellij-community/9065a9cb83f6dc01ca89bfabfe44404e15438682/before/Dictionary.java
c46e7f90f312f5d732879967631036ec860b0f34
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
883
java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.spellchecker.dictionary; import org.jetbrains.annotations.NotNull; import java.util.Set; public interface Dictionary { Set<String> getWords(); void acceptWord(@NotNull String word); void replaceAllWords(Set<String> newWords); String getName(); }
3ed26b251c23efd868951c93539f38d942d130ae
cc8aeb50685b0b7fa46b70a54f25ecf3808adb69
/src/java/dao/PlanDAO.java
fd7fc3b39739b09254dfcc65aead59db39944952
[]
no_license
hanx2307/gyma
b1f1043fd99c62926eed7e0c712241a767795aee
cbd405f9fe8a88b2e2f0c11ea93c5feba94d6f18
refs/heads/master
2020-05-31T21:58:25.338895
2017-06-12T04:10:30
2017-06-12T04:10:30
94,049,885
0
0
null
null
null
null
UTF-8
Java
false
false
4,040
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 dao; import connect.DBConnect; import java.sql.Connection; import static java.sql.JDBCType.NULL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import models.Plan; import models.User; /** * * @author Jack */ public class PlanDAO { public ArrayList<Plan> getListPlan() throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT * FROM plan"; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); ArrayList<Plan> list = new ArrayList<>(); while (rs.next()) { Plan plan = new Plan(); plan.setPlanID(rs.getLong("id")); plan.setPlanDescription(rs.getString("plan_description")); plan.setPlanName(rs.getString("plan_name")); plan.setPlanDay(rs.getLong("plan_day")); plan.setPlanRate(rs.getLong("plan_rate")); list.add(plan); } return list; } public Plan getListPlanFromID(Long id) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT * FROM plan WHERE id = '"+id+"' "; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { Plan plan = new Plan(); plan.setPlanID(rs.getLong("id")); plan.setPlanDescription(rs.getString("plan_description")); plan.setPlanName(rs.getString("plan_name")); plan.setPlanDay(rs.getLong("plan_day")); plan.setPlanRate(rs.getLong("plan_rate")); return plan; } return null; } public Plan getdayPlanFromID(Long id) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT plan_day FROM plan WHERE id = '"+id+"' "; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { Plan plan = new Plan(); plan.setPlanDay(rs.getLong("plan_day")); return plan; } return null; } public boolean insertPlan(Plan p) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "INSERT INTO plan VALUES(?,?,?,?,?)"; try { PreparedStatement ps = conn.prepareCall(sql); ps.setNull(1, java.sql.Types.INTEGER); ps.setString(2, p.getPlanName()); ps.setString(3, p.getPlanDescription()); ps.setLong(4, p.getPlanDay()); ps.setLong(5, p.getPlanRate()); return ps.executeUpdate() == 1; } catch (SQLException ex) { Logger.getLogger(PlanDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean updatePlan(Plan p) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "UPDATE plan SET plan_name = ? ,plan_description = ?, plan_day = ?, plan_rate = ? WHERE id = ?"; try { PreparedStatement ps = conn.prepareCall(sql); ps.setString(1, p.getPlanName()); ps.setString(2, p.getPlanDescription()); ps.setLong(3, p.getPlanDay()); ps.setLong(4, p.getPlanRate()); ps.setLong(5, p.getPlanID()); return ps.executeUpdate() == 1; } catch (SQLException ex) { Logger.getLogger(PlanDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public static void main(String[] args) throws SQLException { // PlanDAO dao = new PlanDAO(); // dao.insertPlan(new Plan(1,"VIP","Day la Vip",30,150000)); } }
3fae543be18ad4f65b6b5391ad3821be15eabd3e
3ed4c2da885a01a4d845088307ff6c241590b294
/Object Oriented/assignment-4-madubata-master/assignment-4-madubata-master/src/main/java/edu/neu/ccs/cs5004/Problem3/JournalPaper.java
b736b311aa181b5e93f1999a0e8e5699fcffd79a
[]
no_license
Moltenbrown/Computer-Science-Projects
033b410fb3b53180b559d82511972994ae247ff8
4d09c752004bdd6d04aa0a7f15132dc60d3ac9eb
refs/heads/master
2021-06-27T00:28:26.504303
2020-11-01T03:01:45
2020-11-01T03:01:45
164,078,244
0
0
null
2020-10-13T21:40:06
2019-01-04T08:11:42
Python
UTF-8
Java
false
false
3,170
java
package edu.neu.ccs.cs5004.Problem3; import java.util.Objects; /** * Represents a paper in a journal with all its details--the journal name, the * journal issue number, and the month as a three letter abbreviation, as strings. * * @author Goch */ public class JournalPaper extends AbstractPublication { private String journalName; private Integer issueNumber; private String month; /** * Creates a new journal paper from a title, an author, a journal name, a issue number, a month, * and a year. * @param title the paper title. * @param author the author wrote the paper. * @param journalName the name of the journal. * @param issueNumber the journal issue number. * @param month the month when the journal was published. * @param year the year when the journal was published. * @throws Exception occurs when the year entered does not contain 4 digits, or the month * entered is not a three letter abbreviation. */ public JournalPaper(String title, Person author, String journalName, Integer issueNumber, String month, Integer year) throws Exception{ super(title, author, year); this.journalName = journalName; this.issueNumber = issueNumber; this.month = month; if(month.length() < 3 || month.length() > 3){ throw new InvalidMonthException("The month must be in three letter abbreviated form."); } } /** * Returns the name of the journal. * @return the journal name. */ public String getJournalName() { return journalName; } /** * Returns the journal's issue number. * @return the journal issue number. */ public Integer getIssueNumber() { return issueNumber; } /** * Returns the month the journal was published. * @return the month the journal was published. */ public String getMonth() { return month; } /** * Evaluates whether the object being compared is the same as the journal paper. * @param o the object being compared to the journal paper. * @return true if the object is the same as the journal paper, and false otherwise. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JournalPaper)) { return false; } if (!super.equals(o)) { return false; } JournalPaper that = (JournalPaper) o; return Objects.equals(journalName, that.journalName) && Objects.equals(issueNumber, that.issueNumber) && Objects.equals(month, that.month); } /** * Returns the integer hashcode representation of the journal paper. * @return the integer hashcode representation of the journal paper. */ @Override public int hashCode() { return Objects.hash(super.hashCode(), journalName, issueNumber, month); } /** * Return a string describing the journal paper, using the journal name, * the issue number, month, year, and title. * @return a string describing the conference paper. */ @Override public String toString() { return journalName + ", Issue No. " + issueNumber + ", " + month + " " + super.getYear() + ", " + super.getTitle(); } }
1167d356b723f29a52a4b5bf284ae65cd2ced149
a6c2d9177bbca8cb4bab58a4fc1536e82ed7d220
/src/main/java/com/shenke/repository/WuliaoRepository.java
e889b9c89b1dfe7aed518b9f562ae98280914cbb
[]
no_license
chao3373/MES
05eaf1728167e38a2236313818696ff775b49e76
152b2d71e1a7cc8f23883d5fc8d8f535794fbde5
refs/heads/master
2022-07-11T03:49:27.224172
2020-02-11T11:36:13
2020-02-11T11:36:13
193,823,642
0
0
null
2022-06-29T17:28:12
2019-06-26T03:33:37
JavaScript
UTF-8
Java
false
false
1,108
java
package com.shenke.repository; import com.shenke.entity.Wuliao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface WuliaoRepository extends JpaRepository<Wuliao,Integer> , JpaSpecificationExecutor<Wuliao> { /** * 根据大图ID查找 * @param id * @return */ @Query(value = "select * from t_wuliao where big_drawing_id =?1",nativeQuery = true) public List<Wuliao> findByBigDrawingId(Integer id); /** * 根据订单Id查询 * @param saleListId * @return */ @Query(value = "select * from t_wuliao where sale_list_id = ?1",nativeQuery = true) List<Wuliao> findBySaleListId(Integer saleListId); /** * 根据大图id删除 * @param id */ @Modifying @Query(value = "delete from t_wuliao where big_drawing_id = ?1",nativeQuery = true) void deleteByBigDrawingId(Integer id); }
15aed1133ab774bf2df501f8f1a24f891c2bb301
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/test/java/org/gradle/test/performancenull_28/Testnull_2771.java
ebe4449eea62503e167992945f7434d21d3decbf
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
304
java
package org.gradle.test.performancenull_28; import static org.junit.Assert.*; public class Testnull_2771 { private final Productionnull_2771 production = new Productionnull_2771("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
511188504b8614d2e6bd729ed52870eadf2a70c1
8a85d5987d859e96d382b754b72e39be8feaaf40
/src/main/java/com/strangeman/classmates/bean/MessageExample.java
907de01ad557768d2613ecd036cc2e7fd48280d6
[]
no_license
chapter7ofnight/classmates
34e07ffbe389c96651c9c4c1df1b775c2c9cb973
42ff6d44076c254557e1d4598de10285f08e6d6c
refs/heads/master
2020-03-07T17:11:17.737496
2018-05-10T03:05:58
2018-05-10T03:05:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,192
java
package com.strangeman.classmates.bean; import java.util.ArrayList; import java.util.List; public class MessageExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public MessageExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andFromIsNull() { addCriterion("from is null"); return (Criteria) this; } public Criteria andFromIsNotNull() { addCriterion("from is not null"); return (Criteria) this; } public Criteria andFromEqualTo(String value) { addCriterion("from =", value, "from"); return (Criteria) this; } public Criteria andFromNotEqualTo(String value) { addCriterion("from <>", value, "from"); return (Criteria) this; } public Criteria andFromGreaterThan(String value) { addCriterion("from >", value, "from"); return (Criteria) this; } public Criteria andFromGreaterThanOrEqualTo(String value) { addCriterion("from >=", value, "from"); return (Criteria) this; } public Criteria andFromLessThan(String value) { addCriterion("from <", value, "from"); return (Criteria) this; } public Criteria andFromLessThanOrEqualTo(String value) { addCriterion("from <=", value, "from"); return (Criteria) this; } public Criteria andFromLike(String value) { addCriterion("from like", value, "from"); return (Criteria) this; } public Criteria andFromNotLike(String value) { addCriterion("from not like", value, "from"); return (Criteria) this; } public Criteria andFromIn(List<String> values) { addCriterion("from in", values, "from"); return (Criteria) this; } public Criteria andFromNotIn(List<String> values) { addCriterion("from not in", values, "from"); return (Criteria) this; } public Criteria andFromBetween(String value1, String value2) { addCriterion("from between", value1, value2, "from"); return (Criteria) this; } public Criteria andFromNotBetween(String value1, String value2) { addCriterion("from not between", value1, value2, "from"); return (Criteria) this; } public Criteria andToIsNull() { addCriterion("to is null"); return (Criteria) this; } public Criteria andToIsNotNull() { addCriterion("to is not null"); return (Criteria) this; } public Criteria andToEqualTo(String value) { addCriterion("to =", value, "to"); return (Criteria) this; } public Criteria andToNotEqualTo(String value) { addCriterion("to <>", value, "to"); return (Criteria) this; } public Criteria andToGreaterThan(String value) { addCriterion("to >", value, "to"); return (Criteria) this; } public Criteria andToGreaterThanOrEqualTo(String value) { addCriterion("to >=", value, "to"); return (Criteria) this; } public Criteria andToLessThan(String value) { addCriterion("to <", value, "to"); return (Criteria) this; } public Criteria andToLessThanOrEqualTo(String value) { addCriterion("to <=", value, "to"); return (Criteria) this; } public Criteria andToLike(String value) { addCriterion("to like", value, "to"); return (Criteria) this; } public Criteria andToNotLike(String value) { addCriterion("to not like", value, "to"); return (Criteria) this; } public Criteria andToIn(List<String> values) { addCriterion("to in", values, "to"); return (Criteria) this; } public Criteria andToNotIn(List<String> values) { addCriterion("to not in", values, "to"); return (Criteria) this; } public Criteria andToBetween(String value1, String value2) { addCriterion("to between", value1, value2, "to"); return (Criteria) this; } public Criteria andToNotBetween(String value1, String value2) { addCriterion("to not between", value1, value2, "to"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(String value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(String value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(String value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(String value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(String value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(String value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLike(String value) { addCriterion("create_time like", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotLike(String value) { addCriterion("create_time not like", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<String> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<String> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(String value1, String value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(String value1, String value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andReadFlagIsNull() { addCriterion("read_flag is null"); return (Criteria) this; } public Criteria andReadFlagIsNotNull() { addCriterion("read_flag is not null"); return (Criteria) this; } public Criteria andReadFlagEqualTo(Integer value) { addCriterion("read_flag =", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagNotEqualTo(Integer value) { addCriterion("read_flag <>", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagGreaterThan(Integer value) { addCriterion("read_flag >", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagGreaterThanOrEqualTo(Integer value) { addCriterion("read_flag >=", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagLessThan(Integer value) { addCriterion("read_flag <", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagLessThanOrEqualTo(Integer value) { addCriterion("read_flag <=", value, "readFlag"); return (Criteria) this; } public Criteria andReadFlagIn(List<Integer> values) { addCriterion("read_flag in", values, "readFlag"); return (Criteria) this; } public Criteria andReadFlagNotIn(List<Integer> values) { addCriterion("read_flag not in", values, "readFlag"); return (Criteria) this; } public Criteria andReadFlagBetween(Integer value1, Integer value2) { addCriterion("read_flag between", value1, value2, "readFlag"); return (Criteria) this; } public Criteria andReadFlagNotBetween(Integer value1, Integer value2) { addCriterion("read_flag not between", value1, value2, "readFlag"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
afcf8f1c9e7a30b034112d135be49307d6ed656e
5cabdb14f69058b144b2fc194e613c8123481fc3
/src/main/java/by/teplouhova/chef/builder/impl/VegetablesSTAXBuilder.java
f24ca5260093ab6b5a43368dca522c9b3ff6843e
[]
no_license
Katinuta/xmlparsing
a84b8a994dc7bd5a3efd0e843ca0bf37a5a9e6c8
6c709a77f15dbead04751adebb8f1b6da889f7eb
refs/heads/master
2021-08-14T16:54:42.054512
2017-11-16T08:50:14
2017-11-16T08:50:14
110,946,849
0
0
null
null
null
null
UTF-8
Java
false
false
8,462
java
package by.teplouhova.chef.builder.impl; import by.teplouhova.chef.builder.AbstractVegetablesBuilder; import by.teplouhova.chef.builder.SaladEnum; import by.teplouhova.chef.entity.CuttingStyle; import by.teplouhova.chef.entity.Vegetable; import by.teplouhova.chef.entity.WayCooking; import by.teplouhova.chef.entity.FruitVegetable; import by.teplouhova.chef.entity.LeafyVegetable; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class VegetablesSTAXBuilder extends AbstractVegetablesBuilder { private static final Logger LOGGER = LogManager.getLogger(); private Vegetable vegetable; private XMLInputFactory xmlInputFactory; public VegetablesSTAXBuilder() { xmlInputFactory = XMLInputFactory.newInstance(); } public void buildSalad(String fileName) { XMLStreamReader reader; String name; try (FileInputStream inputStream = new FileInputStream(new File(fileName))) { reader = xmlInputFactory.createXMLStreamReader(inputStream); while (reader.hasNext()) { int type = reader.next(); if (type == XMLStreamConstants.START_ELEMENT) { name = reader.getLocalName(); if (SaladEnum.valueOf(name.toUpperCase().replace("-", "_")) == SaladEnum.LEAFY_VEGETABLE) { vegetable = new LeafyVegetable(); vegetable = buildVegetable(reader); salad.add(vegetable); } if (SaladEnum.valueOf(name.toUpperCase().replace("-", "_")) == SaladEnum.FRUIT_VEGETABLE) { vegetable = new FruitVegetable(); vegetable = buildVegetable(reader); salad.add(vegetable); } } } } catch (FileNotFoundException e) { LOGGER.log(Level.FATAL, "File is not found : " + fileName + " " + e); throw new RuntimeException("File is not found : " + fileName + " " + e); } catch (XMLStreamException e) { LOGGER.log(Level.ERROR, "Error STAX-parser " + e); } catch (IOException e) { LOGGER.log(Level.FATAL, "Error file" + fileName + e); throw new RuntimeException("Error file" + fileName + e); } } private Vegetable buildVegetable(XMLStreamReader reader) { String name; if (reader.getAttributeCount() != 0) { int countAttribute = reader.getAttributeCount(); for (int index = 0; index < countAttribute; index++) { name = reader.getAttributeLocalName(index); switch (SaladEnum.valueOf(name.toUpperCase().replace("-", "_"))) { case VEGETABLE_ID: vegetable.setVegetableId(reader.getAttributeValue(null, SaladEnum.VEGETABLE_ID.getValue())); break; case VEGETABLE_NAME: vegetable.setVegetableName(reader.getAttributeValue(null, SaladEnum.VEGETABLE_NAME.getValue())); break; case WAY_COOKING: vegetable.setWayCooking( WayCooking.valueOf(reader.getAttributeValue(null, SaladEnum.WAY_COOKING.getValue()).toUpperCase())); break; } } } try { while (reader.hasNext()) { int type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: { name = reader.getLocalName(); switch (SaladEnum.valueOf(name.toUpperCase().replace("-", "_"))) { case WEIGHT: vegetable.setWeight(Integer.parseInt(getXMLTxt(reader))); break; case CALORICITY: vegetable.setCaloricity(Integer.parseInt(getXMLTxt(reader))); break; case CUTTING_STYLE: vegetable.setCuttingStyle(CuttingStyle.valueOf(getXMLTxt(reader).toUpperCase())); break; case COMPOSITION: vegetable.setComposition(buildComposition(reader)); break; case USING_SEEKS: { if (vegetable instanceof FruitVegetable) { ((FruitVegetable) vegetable).setUsingSeeks(Boolean.valueOf(getXMLTxt(reader))); } break; } case USING_LEAF: { if (vegetable instanceof LeafyVegetable) { ((LeafyVegetable) vegetable).setUsingLeaf(Boolean.valueOf(getXMLTxt(reader))); } break; } case USING_STALK: { if (vegetable instanceof LeafyVegetable) { ((LeafyVegetable) vegetable).setUsingStalk(Boolean.valueOf(getXMLTxt(reader))); } break; } } break; } case XMLStreamConstants.END_ELEMENT: { name = reader.getLocalName().replace("-", "_").toUpperCase(); if (SaladEnum.valueOf(name) == SaladEnum.LEAFY_VEGETABLE || SaladEnum.valueOf(name) == SaladEnum.FRUIT_VEGETABLE) { if (vegetable.getWayCooking() == null) { vegetable.setWayCooking(WayCooking.RAW); } return vegetable; } break; } } } } catch (XMLStreamException e) { LOGGER.log(Level.ERROR, "Error STAX-parser " + e); } return vegetable; } private String getXMLTxt(XMLStreamReader reader) throws XMLStreamException { String text = null; if (reader.hasNext()) { reader.next(); if (!reader.isEndElement()) { text = reader.getText(); } } return text; } private Vegetable.Composition buildComposition(XMLStreamReader reader) throws XMLStreamException { Vegetable.Composition composition = new Vegetable.Composition(); int type; String name; while (reader.hasNext()) { type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: { name = reader.getLocalName(); switch (SaladEnum.valueOf(name.replace("-", "_").toUpperCase())) { case FAT: composition.setFat(Double.parseDouble(getXMLTxt(reader))); break; case CARBOHYDRATE: composition.setCarbohydrate(Double.parseDouble(getXMLTxt(reader))); break; case PROTEIN: composition.setProtein(Double.parseDouble(getXMLTxt(reader))); break; } break; } case XMLStreamConstants.END_ELEMENT: { name = reader.getLocalName(); if (SaladEnum.valueOf(name.replace("-", "_").toUpperCase()) == SaladEnum.COMPOSITION) { return composition; } break; } } } throw new XMLStreamException(); } }
36f1b2614ce638a90ab1386f40346b50ed9a7e1a
46f2a4d17fb83ddf8f28facc7a02e0af7feb8357
/app/src/main/java/com/example/phompang/thermalfeedback/adapter/ContactAdapter.java
0a856d6c7355d24af020d984a8c00ab3a556223d
[]
no_license
PhompAng/ThermalFeedback
f204e6ee8f120f0025e6db0b1bbd71365d635787
9804a34748746be11b5c6255a7f5c56eb7a158f1
refs/heads/master
2021-03-27T16:11:01.551705
2018-01-11T07:03:27
2018-01-11T07:03:27
78,106,099
0
0
null
null
null
null
UTF-8
Java
false
false
2,601
java
package com.example.phompang.thermalfeedback.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.phompang.thermalfeedback.R; import com.example.phompang.thermalfeedback.model.Contact; import com.mikhaellopez.circularimageview.CircularImageView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by phompang on 12/29/2016 AD. */ public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> { private Context context; private List<Contact> contacts; private ViewHolder.OnContactDeleteListener listener; public ContactAdapter(Context context, List<Contact> contacts, ViewHolder.OnContactDeleteListener listener) { this.context = context; this.contacts = contacts; this.listener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.layout_contact, parent, false); return new ViewHolder(v, listener); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Contact contact = contacts.get(position); holder.name.setText(contact.getName()); holder.phone.setText(contact.getPhone()); } @Override public void onViewRecycled(ViewHolder holder) { super.onViewRecycled(holder); } @Override public int getItemCount() { return contacts.size(); } public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.img) CircularImageView img; @BindView(R.id.name) TextView name; @BindView(R.id.phone) TextView phone; @BindView(R.id.delete) ImageView delete; OnContactDeleteListener listener; ViewHolder(View itemView, OnContactDeleteListener listener) { super(itemView); ButterKnife.bind(this, itemView); this.listener = listener; delete.setOnClickListener(this); } @Override public void onClick(View v) { if (listener != null) { listener.onContactDelete(getAdapterPosition()); } } public interface OnContactDeleteListener { void onContactDelete(int position); } } }
7f1883e35f6cf2956cb0b30102362692029bc8cb
ee631691814915676e70ef5097910b3304bd23f1
/src/main/java/com/tian/cola/dao/comment/CommentDAO.java
3d5573c83a120d65d1b45183ca055bd4520a45e3
[]
no_license
tiancz/ssm
8342aab056f2326b505c1d0547626ad9a51575d1
bcf2ab017c250baa7a8eea61009d4a3ef6d18728
refs/heads/master
2021-01-19T03:50:52.910335
2017-10-08T07:10:23
2017-10-08T07:10:23
65,386,193
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.tian.cola.dao.comment; import java.util.List; import com.tian.cola.dto.comment.CommentDTO; /** * <p>Title:Comment</p> * <p>Description:</p> * @author tianchaozhe665 * @Email [email protected] * @date 2016年11月24日 下午11:03:57 **/ public interface CommentDAO { public List<CommentDTO> queryComments(String articleId); public int countComment(String articleId); }
3c613ed85c0ef3788e72d9119d0aab8be3d34834
b0261e231fc02a2a1714327807a38a9579e9652d
/fromLocal/VendingMachine/src/main/java/com/bl/vendingmachine/controller/VendingMachineController.java
247dff393880c7db3215038e002552811223aea4
[]
no_license
thebenlarson/classProjects
48982430dacf62ea9493ffc6a36f24d7efa9d44f
bb815e2a4bd66412973df4848a09e5792154613c
refs/heads/master
2023-02-18T17:05:44.891118
2021-01-21T03:04:15
2021-01-21T03:04:15
331,496,660
0
0
null
null
null
null
UTF-8
Java
false
false
3,585
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 com.bl.vendingmachine.controller; import com.bl.vendingmachine.dao.VendingMachineInvalidCodeException; import com.bl.vendingmachine.dao.VendingMachinePersistenceException; import com.bl.vendingmachine.dto.VendingItem; import com.bl.vendingmachine.service.*; import com.bl.vendingmachine.ui.*; import java.util.List; import java.util.Scanner; /** * * @author benth */ public class VendingMachineController { VendingMachineService service; VendingMachineView view; Scanner scanner = new Scanner(System.in); public VendingMachineController(VendingMachineService service, VendingMachineView view){ this.service = service; this.view = view; } public void run(){ boolean exit = false; int choice; loadData(); while (!exit){ displayInventory(); boolean invalidChoice; do { invalidChoice = false; choice = getMenuChoice(); switch(choice){ case 1: addMoney(); break; case 2: makePurchase(); break; case 3: exit = true; break; default: invalidChoice(); invalidChoice = true; break; } } while (invalidChoice); } giveChange(); saveData(); } private void displayInventory(){ List<VendingItem> inventory = service.getInStockVendingItems(); view.displayInventory(inventory, service.getBalance()); } private void loadData(){ try { service.loadInventory(); } catch (VendingMachinePersistenceException ex) { displayException(ex); } } private void saveData(){ try { service.writeInventory(); } catch (VendingMachinePersistenceException ex) { displayException(ex); } } private int getMenuChoice(){ return view.displayMenu(); } private void addMoney(){ boolean error; do { error = false; try{ service.addMoney(view.getAddMoney()); } catch (NumberFormatException e){ error = true; displayInputError(); } } while (error); } private void makePurchase(){ try{ service.checkBalance(); VendingItem vendingItem = service.purchaseVendingItem(view.getCode()); view.getItem(vendingItem); } catch (VendingMachineInsufficientFundsException | VendingMachineNoItemInventoryException | VendingMachineInvalidCodeException | VendingMachinePersistenceException e){ displayException(e); } } private void invalidChoice(){ view.displayInvalidChoice(); } private void displayException(Exception e){ view.displayException(e); } private void displayInputError(){ view.displayInputError(); } private void giveChange(){ view.displayChange(service.getChange()); } }
21cd33d1923b75c991a41641cc6b734dc5459baa
2deeed0d4f5d78aafe0b1174529326b8d3fb1ab2
/android/app/src/main/java/thevolt/flutter_screen/MainActivity.java
6531384496c2a3a6725773d9c1bf87da33bdf109
[]
no_license
Ranshikha/flutter_delivery_screen
7077a423a7a9d6e1fc92505ef48c6abbd0f38084
9bd157f9dec4a3a3845c7d7be67c78d53dde30d4
refs/heads/master
2020-12-14T00:51:22.357795
2020-01-21T16:30:24
2020-01-21T16:30:24
234,582,682
0
0
null
null
null
null
UTF-8
Java
false
false
432
java
package thevolt.flutter_screen; import androidx.annotation.NonNull; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine); } }
d3f30ecc8d9d5e8ca257a2b43add0110421eba6c
8eaf88146f7d3eb3f82d43ccac8177d58b229ff0
/Topicos_Plugin.java
34041ba180c2bd6465bddf8362f5d5e3f3953880
[]
no_license
LucasFreitasRocha/pluginsImageJ
2371510eb78959fc8e9952e27b1b113388ca0044
d9c0f8fd8ae2027de23606dc03bb0949b540f819
refs/heads/master
2021-10-28T09:41:09.718441
2021-10-25T01:43:04
2021-10-25T01:43:04
214,248,965
1
0
null
null
null
null
UTF-8
Java
false
false
284
java
import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import ij.plugin.PlugIn; import ij.process.ImageProcessor; public class Topicos_Plugin implements PlugIn { public void run(String arg) { ImagePlus read = WindowManager.getImage("READ"); read.show(); } }
0ef243c5c066b19a60dabdf0cc9fd40aa06da4f6
ad7497c62b6bf9e40e241de1044a4bef63a34aa7
/skysail.server/src/de/twenty11/skysail/server/um/domain/PasswordsMatchValidator.java
cd9c638b4ac3c0fcf097ccb1d725241516671c24
[ "Apache-2.0" ]
permissive
evandor/skysail-framework
f99dbaceb6383ce899077cdf0acd40787acbca03
480df6f043ab85328ecc6cc38958c501edbc2374
refs/heads/master
2021-01-17T08:40:00.758281
2016-11-21T07:50:38
2016-11-21T07:50:38
28,823,015
1
0
null
null
null
null
UTF-8
Java
false
false
651
java
package de.twenty11.skysail.server.um.domain; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, Registration> { @Override public void initialize(PasswordsMatch passwordParameters) { } @Override public boolean isValid(Registration registration, ConstraintValidatorContext arg1) { if (registration.getPassword() == null && registration.getPwdRepeated() == null) { return true; } return registration.getPassword().equals(registration.getPwdRepeated()); } }
1ddcb618deb8b9f27bc64a1f1e2054d01b9cc9fe
0b673f0187ab1d169972c35265d98579ac0115e7
/CDRD/src/br/com/contos/jdbc/JDBCNotificacaoDAO.java
123bd7b5a1aa6bcdc1485cea6a3c42ec31332bd1
[]
no_license
confoosed/Contos-De-Reinos-Distantes
860fad4ea1f39674988dc6f3b51353f184a2a8be
d7760b20d10cbe37b977a5e7d089301fcda01684
refs/heads/master
2020-03-27T22:30:53.109500
2018-09-03T17:46:27
2018-09-03T17:46:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,558
java
package br.com.contos.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import br.com.contos.classes.Notificacao; import br.com.contos.jdbcinterfaces.NotificacaoDAO; public class JDBCNotificacaoDAO implements NotificacaoDAO{ private Connection conexao; public JDBCNotificacaoDAO(Connection conexao) { this.conexao = conexao; } public boolean inserir(Notificacao notificacao){ String comando = "INSERT INTO notificacacoes (notificacao, data_criacao, usuario_id) VALUES (?,?,?)"; PreparedStatement p; try{ p = this.conexao.prepareStatement(comando); p.setString(1, notificacao.getNotificacao()); p.setString(2, notificacao.getDataCriacao()); p.setString(3, notificacao.getUsuarioId()); p.execute(); } catch (SQLException e) { e.printStackTrace(); return false; } return true; } public boolean atualizar(Notificacao notificacao){ String comando = "UPDATE notificacoes SET notificacao=?"; comando += " WHERE id=?"; PreparedStatement p; try { p = this.conexao.prepareStatement(comando); p.setString(1, notificacao.getNotificacao()); p.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return false; } return true; } public boolean deletar(Notificacao notificacao) { String comando = "DELETE FROM notificacoes WHERE notificacao = '" + notificacao +"'"; Statement p; try { p = this.conexao.createStatement(); p.execute(comando); } catch (SQLException e) { e.printStackTrace(); return false; } return true; } public List<Notificacao> buscar(String busca) { String comando = "SELECT * FROM notificacoes"; System.out.println(comando); List<Notificacao> listNotificacao = new ArrayList<Notificacao>(); Notificacao notificacao = null; try { Statement stmt = conexao.createStatement(); ResultSet rs = stmt.executeQuery(comando); while (rs.next()) { notificacao = new Notificacao(); String notif = rs.getString("notificacao"); String datacriacao = notificacao.converteNascimentoParaFrontend(rs.getString("dataCriacao")); String usuarioid = rs.getString("usuarioId"); notificacao.setNotificacao(notif); notificacao.setDataCriacao(datacriacao); notificacao.setUsuarioId(usuarioid); listNotificacao.add(notificacao); } } catch (Exception e) { e.printStackTrace(); } return listNotificacao; } }
1bb839034ca7fb64724514d9f14ce10a00875949
8ae4facdbd06a3116c22b009820e1f9daea6799a
/discovery/src/test/java/com/example/basics/DiscoveryApplicationTests.java
3683808ee69fb66cd9995c9d07be58ef73eea3b2
[]
no_license
sivanandapanda/spring-cloud-gateway
96e29305397daacf565367fee5fa996d8ea958d6
783fcba564e0e092fa42f02ead66180d9c90b48e
refs/heads/main
2023-03-12T15:46:49.597568
2021-02-27T13:27:16
2021-02-27T13:27:16
341,947,894
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package com.example.basics; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DiscoveryApplicationTests { @Test void contextLoads() { } }
a3a7900f392ea38ecc0ba3f21aee4119d586446c
f18fcc1981d16bc49a9c171b4b13a5a83aa055d1
/src/au/com/billingbuddy/business/objects/ProcessSubscriptionsMDTR.java
1e5966833922c6f33665139e1e66cf930d539408
[]
no_license
edicsonm/BillingBuddyServer
ec7477770c026dcb37b5049f0bc29eed0fa832f1
f6a0afa8e4dc865e46ce14ae6c06644ec38bdb24
refs/heads/master
2021-01-02T09:43:46.834643
2015-05-29T11:46:53
2015-05-29T11:46:53
28,280,646
0
0
null
null
null
null
UTF-8
Java
false
false
39,489
java
package au.com.billingbuddy.business.objects; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import au.com.billigbuddy.utils.ErrorManager; import au.com.billingbuddy.common.objects.ConfigurationSystem; import au.com.billingbuddy.common.objects.Utilities; import au.com.billingbuddy.connection.objects.MySQLTransaction; import au.com.billingbuddy.dao.objects.SubscriptionsToProcessDAO; import au.com.billingbuddy.dao.objects.ErrorLogDAO; import au.com.billingbuddy.dao.objects.SubmittedProcessLogDAO; import au.com.billingbuddy.exceptions.objects.SubscriptionsToProcessDAOException; import au.com.billingbuddy.exceptions.objects.ErrorLogDAOException; import au.com.billingbuddy.exceptions.objects.MySQLConnectionException; import au.com.billingbuddy.exceptions.objects.MySQLTransactionException; import au.com.billingbuddy.exceptions.objects.SubmittedProcessLogDAOException; import au.com.billingbuddy.exceptions.objects.SubscriptionsMDTRException; import au.com.billingbuddy.loggers.LoggerDeclined; import au.com.billingbuddy.loggers.LoggerProcessed; import au.com.billingbuddy.vo.objects.SubscriptionsToProcessVO; import au.com.billingbuddy.vo.objects.ErrorLogVO; import au.com.billingbuddy.vo.objects.SubmittedProcessLogVO; import com.stripe.Stripe; import com.stripe.exception.APIConnectionException; import com.stripe.exception.APIException; import com.stripe.exception.AuthenticationException; import com.stripe.exception.CardException; import com.stripe.exception.InvalidRequestException; import com.stripe.model.Charge; public class ProcessSubscriptionsMDTR { private static ProcessSubscriptionsMDTR instance = null; private HashMap<String, ProcessSubscription> hashThreadsProcessSubscription = new HashMap<String, ProcessSubscription>(); private SubmittedProcessLogVO submittedProcessLogVO = new SubmittedProcessLogVO(); private MySQLTransaction mySQLTransaction = null; private String processName = "ProcessSubscriptions"; private long initialTime; private long finalTime; private long initialTimeThreadsCreation; private long finalTimeThreadsCreation; private boolean writeInErrorLog = false; private String logFileName; private boolean answer = true; private boolean unpaids = false; private boolean noUpdated = false; private int numberUnpaids = 0; private int numberNoUpdated = 0; private int numberUpdated = 0; private int numberCharged = 0; private int numberSent = 0; private int numberTransactionsToProcess = 0; private boolean swErrorOnlevel1 = false; private boolean errorFileExist = false; private ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess = null; /*"trace", "debug", "info", "warn", "error" and "fatal"*/ private static final Logger logger = LogManager.getLogger(ProcessSubscriptionsMDTR.class); private static final Logger loggerProcessed = LoggerProcessed.logger; private static final Logger loggerDeclined = LoggerDeclined.logger; public static synchronized ProcessSubscriptionsMDTR getInstance() { if (instance == null) { instance = new ProcessSubscriptionsMDTR(); } return instance; } private ProcessSubscriptionsMDTR() { Stripe.apiKey = ConfigurationSystem.getKey("apiKey"); } public HashMap<String,String> executeSubscriptionsToProcess() throws SubscriptionsMDTRException { HashMap<String,String> resp = null; initVariables(); try { SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(); logger.info("/*****************************************************************************************************/"); logger.info("/**********************INICIANDO EL PROCESO DE PROC_EXECUTE_SUBSCRIPTIONS_PROCESS *********************/"); logger.info("/******************************************************************************************************/"); resp = subscriptionsToProcessDAO.execute(); if(resp != null){ Set<String> set = resp.keySet(); for (String key : set) { logger.info(key+" --> "+resp.get(key)); } logger.info("/*****************************************************************************************************/"); logger.info("/************************TERMINA EL PROCESO DE PROC_EXECUTE_SUBSCRIPTIONS_PROCESS*********************/"); logger.info("/*****************************************************************************************************/"); if(resp.get("P_ERROR_CODE").equalsIgnoreCase("000")){ try { boolean respuesta = instance.proccesSubscriptions(); if (!respuesta){//Se presento algun error if(instance.isWriteInErrorLog()){ logger.info("Se presentaron errores, la informacion se encuentra almacenada en el archivo " + instance.getLogFileName()); logger.info("Verifique las causas de los errores y ejecute el proceso de recuperacion de errores."); } } } catch (SubscriptionsMDTRException e) { logger.info(e.getMessage()); logger.error(e); } }else{ try { JSONObject informationDetails = new JSONObject(); informationDetails.putAll(resp); submittedProcessLogVO.setProcessName(processName); submittedProcessLogVO.setStartTime(Calendar.getInstance().getTime().toString()); submittedProcessLogVO.setStatusProcess("Error"); submittedProcessLogVO.setInformation(informationDetails.toJSONString()); SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO(); submittedProcessLogDAO.insert(submittedProcessLogVO); } catch (SubmittedProcessLogDAOException e) { throw new SubscriptionsMDTRException(e); } logger.info("Se presentaron errores"); logger.info(resp.get("P_ERROR_TEXT")); } }else{ logger.info("/*****************************************************************************************************/"); logger.info("/**************************TERMINA EL PROCESO DE EXECUTESUBSCRIPTIONSTOPROCESS************************/"); logger.info("/*****************************************************************************************************/"); } } catch (SubscriptionsToProcessDAOException e) { logger.info(e.getMessage()); logger.error(e); } catch (MySQLConnectionException e) { logger.info(e.getMessage()); logger.error(e); } return resp; } private void initVariables() { numberUnpaids = 0; numberNoUpdated = 0; numberUpdated = 0; numberCharged = 0; numberSent = 0; numberTransactionsToProcess = 0; swErrorOnlevel1 = false; errorFileExist = false; } public synchronized boolean proccesSubscriptions() throws SubscriptionsMDTRException { logger.info("/*****************************************************************************************************/"); logger.info("/*********************************INICIANDO EL PROCESO DE SUBSCRIPCIONES******************************/"); logger.info("/*****************************************************************************************************/"); setLogFileName(ConfigurationSystem.getKey("urlSaveErrorFilesSaveInformationSubscriptions") + processName + " - "+ Calendar.getInstance().getTime()); loggerProcessed.info("Iniciando trazas sobre el procesamiento " + getLogFileName()); loggerDeclined.info("Iniciando trazas sobre el procesamiento " + getLogFileName()); try { initialTime = Calendar.getInstance().getTimeInMillis(); mySQLTransaction = new MySQLTransaction(); submittedProcessLogVO.setProcessName(processName); submittedProcessLogVO.setStartTime(Calendar.getInstance().getTime().toString()); submittedProcessLogVO.setStatusProcess("OnExecution"); SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO(); submittedProcessLogDAO.insert(submittedProcessLogVO); SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(mySQLTransaction); listSubscriptionsToProcess = subscriptionsToProcessDAO.search(); if(listSubscriptionsToProcess != null && listSubscriptionsToProcess.size() > 0) { numberTransactionsToProcess = listSubscriptionsToProcess.size(); initialTimeThreadsCreation = Calendar.getInstance().getTimeInMillis(); for (int position = 0; position<listSubscriptionsToProcess.size(); position++) { SubscriptionsToProcessVO subscriptionsToProcessVO = listSubscriptionsToProcess.get(position); int first = listSubscriptionsToProcess.indexOf(subscriptionsToProcessVO); int last = listSubscriptionsToProcess.lastIndexOf(subscriptionsToProcessVO); logger.trace(position+" "+subscriptionsToProcessVO.getSubscriptionId() + " first: " + first+" "+subscriptionsToProcessVO.getSubscriptionId() + " last: " + last); ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcessAUX = new ArrayList<SubscriptionsToProcessVO>(listSubscriptionsToProcess.subList(first, last + 1)); position = last; ProcessSubscription processSubscription = new ProcessSubscription(listSubscriptionsToProcessAUX, subscriptionsToProcessDAO, mySQLTransaction); processSubscription.setName(subscriptionsToProcessVO.getSubscriptionId()); processSubscription.start(); hashThreadsProcessSubscription.put(processSubscription.getName(), processSubscription); // // finalTimeIndividual = Calendar.getInstance().getTimeInMillis(); // System.out.println("Tiempo total para procesar una subscripcion: " + (finalTimeIndividual-initialTimeIndividual) + " ms."); } finalTimeThreadsCreation = Calendar.getInstance().getTimeInMillis(); logger.info("Todos los hilos fueron creados en "+(finalTimeThreadsCreation-initialTimeThreadsCreation) + " ms. Se llama al proceso de monitoreo de los hilos creados"); MonitorProcessSubscription monitorProcessSubscription = new MonitorProcessSubscription(hashThreadsProcessSubscription); monitorProcessSubscription.start(); } else { finalTime = Calendar.getInstance().getTimeInMillis(); logger.info("No se encontraron subscripciones para procesar, el tiempo de ejecucion fue de " + (finalTime-initialTime) + " ms."); try { submittedProcessLogDAO = new SubmittedProcessLogDAO(); submittedProcessLogVO.setEndTime(Calendar.getInstance().getTime().toString()); if(answer) submittedProcessLogVO.setStatusProcess("Success"); else submittedProcessLogVO.setStatusProcess("Error"); JSONObject informationDetails = new JSONObject(); JSONObject information = new JSONObject(); information.put("unpaids", unpaids); if(unpaids){ information.put("Recomendation","Run the \"Reprocess Process\" to resend the transactions to our processor."); information.put("Information", "There are subscripcions that our procesor could not charge to some card holders. The uncharged transactions information are available in the tables Reprocess_X "); informationDetails.put("InformationUnpaids", information); informationDetails.put("ReprocessUnpaids", unpaids); } information = new JSONObject(); information.put("noUpdated", noUpdated); if(noUpdated){ information.put("InformationNoUpdated", "There are subscripcions that were charged by our processor but the information was not updated in our systems."); information.put("Recomendation","Check system logs to determine the causes of the error."); informationDetails.put("InformationNoUpdated", information); } information = new JSONObject(); information.put("errorFileExist", errorFileExist); if(errorFileExist){ information.put("Information", "Was created a file that content information about the subscripcions that could not Update."); information.put("Recomendation","Execute the recovery process to update the correct field in our data base."); information.put("FileLocation",getLogFileName()); informationDetails.put("ReprocessErrorFile", errorFileExist); informationDetails.put("InformationErrorFileExist", information); } information = new JSONObject(); information.put("Total Time", ((finalTime-initialTime) + " ms.")); information.put("Total Transactions to process", numberTransactionsToProcess); information.put("Total Transactions no updates on Data Base", numberNoUpdated); information.put("Total Transactions updates on Data Base", numberUpdated); information.put("Total Transactions unpaids", numberUnpaids); information.put("Total Transactions chargeds", numberCharged); information.put("Total Transactions sent to our procesor", numberSent); information.put("Total Transactions keeped on file ", numberSent); informationDetails.put("Resume ProcessExecution", information); logger.info("Imprimiendo resumen de las transacciones procesadas cuando no se encuentra ninguna"); logger.info( "Total de numberNoUpdated: " + numberNoUpdated); logger.info( "Total de numberUpdated: " + numberUpdated); logger.info( "Total de numberUnpaids: " + numberUnpaids); logger.info( "Total de numberCharged: " + numberCharged); submittedProcessLogVO.setInformation(informationDetails.toJSONString()); submittedProcessLogDAO.update(submittedProcessLogVO); mySQLTransaction.commit(); } catch (MySQLConnectionException e) { e.printStackTrace(); } catch (MySQLTransactionException e) { e.printStackTrace(); } catch (SubmittedProcessLogDAOException e) { e.printStackTrace(); } finally{ try { if(mySQLTransaction != null){ mySQLTransaction.close(); } } catch (MySQLTransactionException e) { e.printStackTrace(); } } } } catch (MySQLConnectionException e) { logger.error(e); logger.info("/*****************************************************************************************************/"); logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/"); logger.info("/*****************************************************************************************************/"); throw new SubscriptionsMDTRException(e); } catch (SubscriptionsToProcessDAOException e) { logger.error(e); logger.info("/*****************************************************************************************************/"); logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/"); logger.info("/*****************************************************************************************************/"); SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e); subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.proccesDailySubscriptions.DailySubscriptionDAOException"); throw subscriptionsMDTRException; } catch (MySQLTransactionException e) { logger.error(e); logger.info("/*****************************************************************************************************/"); logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/"); logger.info("/*****************************************************************************************************/"); SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e); subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.proccesDailySubscriptions.MySQLTransactionException"); throw subscriptionsMDTRException; } catch (SubmittedProcessLogDAOException e) { logger.error(e); logger.info("/*****************************************************************************************************/"); logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/"); logger.info("/*****************************************************************************************************/"); throw new SubscriptionsMDTRException(e); } return answer; } public ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess() throws SubscriptionsMDTRException{ ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess = null; try { SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(); listSubscriptionsToProcess = subscriptionsToProcessDAO.search(); } catch (MySQLConnectionException e) { e.printStackTrace(); SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e); subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.listSubscriptionsToProcess.MySQLConnectionException"); throw subscriptionsMDTRException; } catch (SubscriptionsToProcessDAOException e) { e.printStackTrace(); SubscriptionsMDTRException subscriptionsMDTRException = new SubscriptionsMDTRException(e); subscriptionsMDTRException.setErrorCode("SubscriptionsMDTR.listSubscriptionsToProcess.SubscriptionsToProcessDAOException e"); throw subscriptionsMDTRException; } return listSubscriptionsToProcess; } public synchronized void writeError(JSONObject errorDetails){ try{ writeInErrorLog = true; File file = new File(getLogFileName()); if(!file.exists()){ file.createNewFile(); } FileWriter fstream = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fstream); out.write(errorDetails.toJSONString()); out.newLine(); out.close(); }catch(IOException e){ e.printStackTrace(); } } public JSONObject reprocessFile(JSONObject jSONObjectParameters) throws SubscriptionsMDTRException { logger.info("/*****************************************************************************************************/"); logger.info("/**********************INICIANDO PROCESO DE REPROCESAMIENTO DE ARCHIVO********************************/"); logger.info("/*****************************************************************************************************/"); MySQLTransaction mySQLTransaction = null; File archivo = null; FileReader fileReader = null; BufferedReader bufferedReader = null; SubscriptionsToProcessVO subscriptionsToProcessVO = null; int unProcessed = 0; int processed = 0; int totalRegistries = 0; try { mySQLTransaction = new MySQLTransaction(); mySQLTransaction.start(); SubscriptionsToProcessDAO subscriptionsToProcessDAO = new SubscriptionsToProcessDAO(mySQLTransaction); archivo = new File(jSONObjectParameters.get("fileName").toString()); fileReader = new FileReader(archivo); bufferedReader = new BufferedReader(fileReader); String linea; while ((linea = bufferedReader.readLine()) != null) { totalRegistries ++ ; System.out.println(linea); Object obj = JSONValue.parse(linea); JSONObject jSONObject = (JSONObject) obj; subscriptionsToProcessVO = new SubscriptionsToProcessVO(); subscriptionsToProcessVO.setStatus(jSONObject.get("Supr_Status").toString()); subscriptionsToProcessVO.setAuthorizerCode(jSONObject.get("Supr_AuthorizerCode")!= null? jSONObject.get("Supr_AuthorizerCode").toString():null); subscriptionsToProcessVO.setAuthorizerReason(jSONObject.get("Supr_AuthorizerReason") != null ? jSONObject.get("Supr_AuthorizerReason").toString():null); subscriptionsToProcessVO.setProcessAttempt(Integer.parseInt(jSONObject.get("Supr_ProcessAttempt").toString())); subscriptionsToProcessVO.setId(jSONObject.get("Supr_ID").toString()); if(jSONObject.get("ReprocessTRX") != null && jSONObject.get("ReprocessTRX").toString().equalsIgnoreCase("true")){ try { processed ++; int resp = subscriptionsToProcessDAO.update(subscriptionsToProcessVO); logger.debug("Reprocesando la subscripcion " + subscriptionsToProcessVO.getId()+",la respuesta obtenida es " + resp); } catch (SubscriptionsToProcessDAOException e) { mySQLTransaction.rollback(); throw new SubscriptionsMDTRException(e); } }else{ unProcessed ++; } } if(totalRegistries == processed) { SubmittedProcessLogDAO submittedProcessLogDAO = new SubmittedProcessLogDAO(mySQLTransaction); submittedProcessLogVO.setId(jSONObjectParameters.get("idSubmittedProcessLog").toString()); submittedProcessLogVO = submittedProcessLogDAO.searchByID(submittedProcessLogVO); Object obj = JSONValue.parse(submittedProcessLogVO.getInformation()); JSONObject jSONObjectInitial = (JSONObject) obj; jSONObjectInitial.remove("ReprocessErrorFile"); JSONObject jSONObjectFinal = new JSONObject(); jSONObjectFinal.put("Total number of registries", totalRegistries); jSONObjectFinal.put("Number of processed", processed); jSONObjectFinal.put("Number of unProcessed", unProcessed); jSONObjectFinal.put("Reprocessing date", Calendar.getInstance().getTime().toString()); JSONObject information = new JSONObject(); information.put("Initial Information", jSONObjectInitial); information.put("Final Information", jSONObjectFinal); submittedProcessLogVO.setInformation(information.toJSONString()); submittedProcessLogVO.setStatusProcess("Success"); submittedProcessLogDAO.update(submittedProcessLogVO); jSONObjectParameters.put("answer", true); }else { if(processed == 0) jSONObjectParameters.put("errorType", "noRegistriesUpdated"); jSONObjectParameters.put("answer", false); } mySQLTransaction.commit(); // System.out.println("Termina el proceso satisfactoriamente"); jSONObjectParameters.put("unProcessed", unProcessed); jSONObjectParameters.put("processed", processed); jSONObjectParameters.put("totalRegistries", totalRegistries); /*System.out.println("unProcessed: " + unProcessed); System.out.println("processed: " + processed); System.out.println("totalRegistries: " + totalRegistries);*/ logger.info("/*****************************************************************************************************/"); logger.info("/**********************TERMINANDO PROCESO DE REPROCESAMIENTO DE ARCHIVO*******************************/"); logger.info("/*****************************************************************************************************/"); return jSONObjectParameters; } catch (MySQLTransactionException e) { /*e.printStackTrace();*/ throw new SubscriptionsMDTRException(e); } catch (MySQLConnectionException e) { /*e.printStackTrace();*/ throw new SubscriptionsMDTRException(e); } catch (FileNotFoundException e) { /*e.printStackTrace();*/ throw new SubscriptionsMDTRException(e); } catch (IOException e) { /*e.printStackTrace();*/ throw new SubscriptionsMDTRException(e); } catch (SubmittedProcessLogDAOException e) { throw new SubscriptionsMDTRException(e); } finally { try { if (null != fileReader) { fileReader.close(); } } catch (Exception e2) { throw new SubscriptionsMDTRException(e2); } try { if(mySQLTransaction != null){ mySQLTransaction.close(); } } catch (MySQLTransactionException e) { e.printStackTrace(); } } } public void manageError(JSONObject jSONObject,String processName, String fileName) { try { ErrorLogDAO errorLogDAO = new ErrorLogDAO(); ErrorLogVO errorLogVO = new ErrorLogVO(); errorLogVO.setProcessName(processName); errorLogVO.setInformation(jSONObject.toJSONString()); if(errorLogDAO.insert(errorLogVO) == 0){ ErrorManager.logDailySubscriptionErrorFile(fileName, jSONObject); } } catch (MySQLConnectionException e) { e.printStackTrace(); } catch (ErrorLogDAOException e) { e.printStackTrace(); } } public boolean isWriteInErrorLog() { return writeInErrorLog; } public void setWriteInErrorLog(boolean writeInErrorLog) { this.writeInErrorLog = writeInErrorLog; } public String getLogFileName() { return logFileName; } public void setLogFileName(String logFileName) { this.logFileName = logFileName; } class MonitorProcessSubscription extends Thread { HashMap<String, ProcessSubscription> hashProcessSubscription = new HashMap<String, ProcessSubscription>(); public MonitorProcessSubscription(HashMap<String, ProcessSubscription> hashProcessSubscription){ this.hashProcessSubscription = hashProcessSubscription; } @Override public void run() { while (!hashProcessSubscription.isEmpty()) { logger.info("Esperando la finalizacion de " + hashProcessSubscription.size() + " hilos ... " + "(numberSent: " + numberSent + ") (numberCharged: " +numberCharged+") (numberUnpaids: " + numberUnpaids+")"); try { this.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } finalTime = Calendar.getInstance().getTimeInMillis(); logger.info("Termina el monitoreo de los hilos creados para procesar todas las subscripciones en " + (finalTime-initialTime) + " ms."); } } class ProcessSubscription extends Thread { private Map<String, Object> hashMapCharge = new HashMap<String, Object>(); private ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess; private SubscriptionsToProcessDAO subscriptionsToProcessDAO; private SubmittedProcessLogDAO submittedProcessLogDAO; private MySQLTransaction mySQLTransaction; private int level = 0; private boolean unpaidSubGroup = false; private boolean executeThread = true; public ProcessSubscription(ArrayList<SubscriptionsToProcessVO> listSubscriptionsToProcess, SubscriptionsToProcessDAO subscriptionsToProcessDAO, MySQLTransaction mySQLTransaction){ this.listSubscriptionsToProcess = listSubscriptionsToProcess; this.subscriptionsToProcessDAO = subscriptionsToProcessDAO; this.mySQLTransaction = mySQLTransaction; } @Override public void run() { logger.trace("El hilo " + this.getName() + " tiene " + listSubscriptionsToProcess.size() + " elementos para procesar"); while(executeThread){ try { for (SubscriptionsToProcessVO subscriptionsToProcessVO : listSubscriptionsToProcess) { logger.trace("Ejecutando " + subscriptionsToProcessVO.getId() + " de la subscripcion " + this.getName()); hashMapCharge.put("amount", Utilities.currencyToStripe(subscriptionsToProcessVO.getAmount(), subscriptionsToProcessVO.getCurrency())); hashMapCharge.put("currency", subscriptionsToProcessVO.getCurrency()); hashMapCharge.put("description", "Charge for [email protected]"); Map<String, Object> hashMapCard = new HashMap<String, Object>(); hashMapCard.put("number", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getNumber()); hashMapCard.put("exp_month", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getExpMonth()); hashMapCard.put("exp_year", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getExpYear()); hashMapCard.put("cvc", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getCvv()); hashMapCard.put("name", subscriptionsToProcessVO.getMerchantCustomerCardVO().getCardVO().getName()); hashMapCharge.put("card", hashMapCard); try { subscriptionsToProcessVO.setStatus("Sending"); subscriptionsToProcessVO.setAuthorizerCode(null); subscriptionsToProcessVO.setAuthorizerReason(null); if (subscriptionsToProcessDAO.update(subscriptionsToProcessVO) != 0) { logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXX Envia la subscripcion numero "+subscriptionsToProcessVO.getId()); level = 1; try { sent(); Charge charge = Charge.create(hashMapCharge); subscriptionsToProcessVO.setStatus("Charged"); subscriptionsToProcessVO.setAuthorizerCode(charge.getId()); subscriptionsToProcessVO.setAuthorizerReason(null); charged(); logger.debug("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged."); // LoggerProcessed.logger.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged."); loggerProcessed.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue Charged."); } catch (CardException e) { unpaid(); unpaids = true; unpaidSubGroup = true; subscriptionsToProcessVO.setProcessAttempt(subscriptionsToProcessVO.getProcessAttempt() + 1); subscriptionsToProcessVO.setStatus("Unpaid"); subscriptionsToProcessVO.setAuthorizerCode(null); subscriptionsToProcessVO.setAuthorizerReason(e.getMessage()); logger.debug("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue decline."); loggerDeclined.info("La subscripcion "+subscriptionsToProcessVO.getId()+ " fue decline."); } subscriptionsToProcessVO.setErrorCode("1");//User esta variable para simular errores, Con este valor no actualiza // subscriptionsToProcessVO.setErrorCode("2");//User esta variable para simular errores, con este valor lanza una exception if(subscriptionsToProcessDAO.update(subscriptionsToProcessVO) == 0) { // System.out.println("No fue posible actualizar la informacion del pago. Suspender todo el proceso. " + "Generar informe con la informacion del error"); JSONObject errorDetails = new JSONObject(); errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus()); errorDetails.put("Supr_AuthorizerCode", subscriptionsToProcessVO.getAuthorizerCode()); errorDetails.put("Supr_AuthorizerReason", subscriptionsToProcessVO.getAuthorizerReason()); errorDetails.put("Supr_ProcessAttempt", subscriptionsToProcessVO.getProcessAttempt()); errorDetails.put("Supr_ID", subscriptionsToProcessVO.getId()); errorDetails.put("Subs_ID", subscriptionsToProcessVO.getSubscriptionId()); errorDetails.put("AutorizationID", subscriptionsToProcessVO.getAuthorizerCode()); errorDetails.put("CALL_DailySubscriptionDAO", subscriptionsToProcessDAO.getCallString()); errorDetails.put("ReprocessTRX",true); writeError(errorDetails); answer = false; noUpdated = true; noUpdated(); setSwErrorOnlevel1(true); errorFileExist = true; }else{ updated(); } if(unpaidSubGroup) break; //Rompe el ciclo despues de que consigue una subscripcion que no fue aprobada y es actualizada en las tablas de las subscripciones }else{ logger.debug("No actualiza el registro para la subscripcion "+subscriptionsToProcessVO.getId()+ "."); } } catch (SubscriptionsToProcessDAOException e) { logger.debug("No fue posible actualizar la informacion del pago. Suspender todo el proceso. " + "Generar informe con la informacion del error " + subscriptionsToProcessDAO.getCallString()); JSONObject errorDetails = new JSONObject(); errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus()); errorDetails.put("Supr_Status", subscriptionsToProcessVO.getStatus()); errorDetails.put("Supr_AuthorizerCode", subscriptionsToProcessVO.getAuthorizerCode()); errorDetails.put("Supr_AuthorizerReason", subscriptionsToProcessVO.getAuthorizerReason()); errorDetails.put("Supr_ProcessAttempt", subscriptionsToProcessVO.getProcessAttempt()); errorDetails.put("Supr_ID", subscriptionsToProcessVO.getId()); errorDetails.put("Subs_ID", subscriptionsToProcessVO.getSubscriptionId()); errorDetails.put("AutorizationID", subscriptionsToProcessVO.getAuthorizerCode()); errorDetails.put("CALL_DailySubscriptionDAO", subscriptionsToProcessDAO.getCallString()); if(level == 1) { /*Esto es para verificar que el archivo de errores contiene transacciones que deben ser cargadas en la BD. *Esto es porque el error ocurre antes de enviar la transaccion, por lo que el registro no se debe modificar para que *pueda ser reenviado como si fuese la primera vez*/ setSwErrorOnlevel1(true); errorDetails.put("ReprocessTRX",true); }else{ errorDetails.put("ReprocessTRX",false); } noUpdated(); writeError(errorDetails); answer = false; errorFileExist = true; new SubscriptionsMDTRException(e, subscriptionsToProcessDAO.getCallString()); break; } } } catch (AuthenticationException e) { e.printStackTrace(); } catch (APIConnectionException e) { e.printStackTrace(); } catch (APIException e) { e.printStackTrace(); } catch (InvalidRequestException e) { e.printStackTrace(); } executeThread = false; } hashThreadsProcessSubscription.remove(this.getName()); if (hashThreadsProcessSubscription.isEmpty()) { finalTime = Calendar.getInstance().getTimeInMillis(); logger.info("A Tiempo total para procesar todas las subscripciones: " + (finalTime-initialTime) + " ms."); System.out.println("Tiempo total para procesar todas las subscripciones: " + (finalTime-initialTime) + " ms."); try { submittedProcessLogDAO = new SubmittedProcessLogDAO(); submittedProcessLogVO.setEndTime(Calendar.getInstance().getTime().toString()); if(answer) submittedProcessLogVO.setStatusProcess("Success"); else submittedProcessLogVO.setStatusProcess("Error"); JSONObject informationDetails = new JSONObject(); JSONObject information = new JSONObject(); // information.put("unpaids", unpaids); // if(unpaids){ // information.put("Recomendation","Run the \"Reprocess Process\" to resend the transactions to our processor."); // information.put("Information", "There are subscripcions that our procesor could not charge to some card holders. The uncharges transactions information are available in the tables Reprocess_X "); // informationDetails.put("InformationUnpaids", information); // informationDetails.put("ReprocessUnpaids", unpaids); // } information = new JSONObject(); information.put("noUpdated", noUpdated); if(noUpdated && swErrorOnlevel1){ information.put("InformationNoUpdated", "There are subscripcions that were charged by our processor but the information was not updated in our systems."); information.put("Recomendation","Check system logs to determine the causes of the error."); informationDetails.put("InformationNoUpdated", information); } information = new JSONObject(); information.put("errorFileExist", errorFileExist); if(errorFileExist && swErrorOnlevel1){ information.put("Information", "Was created a file that content information about the subscripcions that could not Update."); information.put("Recomendation","Execute the recovery process to update the correct field in our data base."); information.put("FileLocation",getLogFileName()); informationDetails.put("ReprocessErrorFile", errorFileExist); informationDetails.put("InformationErrorFileExist", information); }else if(errorFileExist && !swErrorOnlevel1){ information.put("Information", "Was created a file that content information about the subscripcions that could not be sent to out processor."); information.put("FileLocation",getLogFileName()); informationDetails.put("ReprocessErrorFile", false); informationDetails.put("InformationErrorFileExist", information); } information = new JSONObject(); information.put("Total Time", ((finalTime-initialTime) + " ms.")); information.put("Total Transactions to process", numberTransactionsToProcess); information.put("Total Transactions no updates on Data Base", numberNoUpdated); information.put("Total Transactions updates on Data Base", numberUpdated); information.put("Total Transactions keeped on file ", numberNoUpdated); information.put("Total Transactions unpaids", numberUnpaids); information.put("Total Transactions chargeds", numberCharged); information.put("Total Transactions sent to our procesor", numberSent); informationDetails.put("Resume ProcessExecution", information); logger.info("Imprimiendo resumen FINAL ... "); logger.info("Total Time " + ((finalTime-initialTime) + " ms.")); logger.info("Total Transactions to process " + numberTransactionsToProcess); logger.info("Total Transactions no updates on Data Base "+ numberNoUpdated); logger.info("Total Transactions updates on Data Base "+ numberUpdated); logger.info("Total Transactions keeped on file "+ numberNoUpdated); logger.info("Total Transactions unpaids "+ numberUnpaids); logger.info("Total Transactions chargeds "+ numberCharged); logger.info("Total Transactions sent to our procesor "+ numberSent); submittedProcessLogVO.setInformation(informationDetails.toJSONString()); submittedProcessLogDAO.update(submittedProcessLogVO); mySQLTransaction.commit(); } catch (MySQLConnectionException e) { e.printStackTrace(); } catch (MySQLTransactionException e) { e.printStackTrace(); } catch (SubmittedProcessLogDAOException e) { e.printStackTrace(); } finally{ try { if(mySQLTransaction != null){ mySQLTransaction.close(); } } catch (MySQLTransactionException e) { e.printStackTrace(); } } logger.info("/*****************************************************************************************************/"); logger.info("/*********************************TERMINA EL PROCESO DE SUBSCRIPCIONES********************************/"); logger.info("/*****************************************************************************************************/"); } } public void cancel() { executeThread = false; } } private synchronized void sent(){ numberSent ++; } private synchronized void charged(){ numberCharged ++; } private synchronized void unpaid(){ numberUnpaids ++; } private synchronized void noUpdated(){ numberNoUpdated ++; } private synchronized void updated(){ numberUpdated ++; } public synchronized void setSwErrorOnlevel1(boolean swErrorOnlevel1) { this.swErrorOnlevel1 = swErrorOnlevel1; } public HashMap<String, ProcessSubscription> getHashThreadsProcessSubscription() { return hashThreadsProcessSubscription; } public void printThreads() { System.out.println("Imprimiendo hilos .... "); Set<String> set = hashThreadsProcessSubscription.keySet(); for (String key : set) { ProcessSubscription processSubscription = hashThreadsProcessSubscription.get(key); System.out.println("Nombre hilo " + processSubscription.getName()); } } public void destroyThread(String name) { System.out.println("Intentando cancelar hijo .... " + name); ProcessSubscription processSubscription = hashThreadsProcessSubscription.get(name); if(processSubscription != null ) processSubscription.cancel(); else System.out.println("Hilo no encontrado ..."); } }
19778fa81690f994961fe9edb5dec81a02d7f0b4
09683aaffcd781992f89746f5be5bebcf8cf864b
/src/main/java/com/github/dwladdimiroc/stormMonitor/util/Metrics.java
b2026a6a38d8f916a551e5282862e561adea1a1e
[]
no_license
dwladdimiroc/storm-monitor
3740465ef6608e85b01f09e6a75d3cbf39b36236
a6a155b3fdacb07e752b53943ec9ef813cfc0fce
refs/heads/master
2021-03-08T05:20:27.705797
2020-09-28T08:10:32
2020-09-28T08:10:32
246,320,204
0
0
null
null
null
null
UTF-8
Java
false
false
4,709
java
package com.github.dwladdimiroc.stormMonitor.util; import com.github.dwladdimiroc.stormMonitor.StormAdaptative; import com.github.dwladdimiroc.stormMonitor.eda.Stats; import com.github.dwladdimiroc.stormMonitor.eda.TopologyApp; import com.codahale.metrics.CsvReporter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; public class Metrics { private final static Logger logger = LoggerFactory.getLogger(Metrics.class); private final boolean showLogger = false; static final MetricRegistry metricsRegistry = new MetricRegistry(); private Map<String, Long> input; private Map<String, Long> throughput; private Map<String, Long> queue; private Map<String, Double> latency; private Map<String, Double> utilization; private Map<String, Integer> replication; private CsvReporter reporter; private Config confMape; public Metrics(String pathFolder, Config confMape) { new File(pathFolder).mkdir(); this.input = new HashMap<String, Long>(); this.throughput = new HashMap<String, Long>(); this.queue = new HashMap<String, Long>(); this.latency = new HashMap<String, Double>(); this.utilization = new HashMap<String, Double>(); this.replication = new HashMap<String, Integer>(); this.confMape = confMape; this.reporter = CsvReporter.forRegistry(metricsRegistry).formatFor(Locale.US).convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.SECONDS).build(new File(pathFolder)); } public void start() { // try { // Thread.sleep(1000); this.reporter.start(this.confMape.getWindowMonitor(), TimeUnit.SECONDS); // } catch (InterruptedException e) { // e.printStackTrace(); // } } public void createStatsBolt(final String nameBolt) { this.throughput.put(nameBolt, Long.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@throughput"), new Gauge<Long>() { @Override public Long getValue() { return throughput.get(nameBolt); } }); this.queue.put(nameBolt, Long.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@queue"), new Gauge<Long>() { @Override public Long getValue() { return queue.get(nameBolt); } }); this.latency.put(nameBolt, Double.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@latency"), new Gauge<Double>() { @Override public Double getValue() { return latency.get(nameBolt); } }); this.utilization.put(nameBolt, Double.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@utilization"), new Gauge<Double>() { @Override public Double getValue() { return utilization.get(nameBolt); } }); this.replication.put(nameBolt, Integer.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameBolt + "@replication"), new Gauge<Integer>() { @Override public Integer getValue() { return replication.get(nameBolt); } }); } public void createStatsSpout(final String nameSpout) { this.input.put(nameSpout, Long.valueOf(0)); Metrics.metricsRegistry.register(MetricRegistry.name(StormAdaptative.class, nameSpout + "@input"), new Gauge<Long>() { @Override public Long getValue() { return input.get(nameSpout); } }); } public void sendStats(TopologyApp topologyApp) { for (String bolt : topologyApp.keySet()) { sendStatsBolt(bolt, topologyApp.getStats(bolt)); } for (String spout : topologyApp.getInputStats().keyInput()) { sendStatsSpout(spout, topologyApp.getInputStats().getStreamInput(spout)); } topologyApp.getInputStats().clear(); } private void sendStatsSpout(String spout, long input) { if (showLogger) logger.info("[Spout={}],[Input={}]", spout, input); this.input.put(spout, input); } private void sendStatsBolt(String bolt, Stats statsBolt) { if (showLogger) logger.info("[Bolt={}],[Executed={}],[LastSimple={}],[Queue={}],[Raw={},{}]", bolt, statsBolt.getThroughput(), statsBolt.getLastSample(), statsBolt.getQueue(), statsBolt.getTimeAvg(), statsBolt.getExecutedTotal()); this.throughput.put(bolt, statsBolt.getThroughput()); this.queue.put(bolt, statsBolt.getQueue()); this.latency.put(bolt, statsBolt.getTimeAvg()); this.utilization.put(bolt, statsBolt.getLastSample()); this.replication.put(bolt, statsBolt.getReplicas()); } }
959ea27df12ea412b297f6b1c9123d440f0d09a2
275bdfd603e2890ffeedd71a1778ff89f1385228
/gcp/src/main/java/com/example/oauth2/Setup.java
9ea09559e002453f0dc1ef4f253ed4f9d74ee9e6
[]
no_license
kariyappah/myprojects
fab87dec16d93f40fc66aeb09679cbdf0f6cfedd
d69fb769fefeb00a0e7fe1f831cc26607e0f5e74
refs/heads/master
2021-01-19T12:25:14.541044
2017-08-21T06:18:46
2017-08-21T06:18:46
100,784,801
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.example.oauth2; public class Setup { public static final String CLIENT_ID = "95344702868-m3qt0589t2m0oahscg21mgudkofjpsum.apps.googleusercontent.com"; public static final String CLIENT_SECRET = "5QX5SjLrYHRPNhzA1ZsKnn2v"; public static final String REDIRECT_URL = "https://mygcpproject-10081982.appspot.com/oauth2callback"; }
[ "manasu@manasu" ]
manasu@manasu
06c37fcf2effb9cb1bd05aec0fb80c769b0ad40e
04fc52b043955887b2526b30bfedaf8dcf9d80d2
/src/brickBreaker/MapGenerator.java
9aea54111fa8a155174566e74449dc86f96d17d2
[]
no_license
nethraui/brickbreaker
073187759ed46c993d7bfd95272663c951df74f9
64245d7ebfb191ab993d6c00377070273af2e9e1
refs/heads/master
2022-09-05T19:04:35.813853
2020-05-27T02:35:31
2020-05-27T02:35:31
267,202,428
0
0
null
null
null
null
UTF-8
Java
false
false
1,115
java
package brickBreaker; import java.awt.*; public class MapGenerator { public int map[][]; public int brickWidth; public int brickHeight; public MapGenerator(int row, int col){ map = new int[row][col]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { map[i][j] = 1; } } brickWidth = 540/col; brickHeight = 150/row; } public void draw(Graphics2D g){ for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if(map[i][j] > 0){ g.setColor(Color.white); g.fillRect(j * brickWidth + 80,i * brickHeight + 50, brickWidth, brickHeight); g.setStroke(new BasicStroke(3)); g.setColor(Color.black); g.drawRect(j * brickWidth + 80,i * brickHeight + 50, brickWidth, brickHeight); } } } } public void setBrickValue(int value, int row, int col){ map[row][col] = value; } }
dc33b569a19994003c3bd125019504fcbf22ac10
b080e60bf6e61a75d40d9f7644ae34418861de70
/src/mc/alk/arena/controllers/messaging/MatchMessager.java
0cd89bb70498b1b91d3d80e013a7dd8790f87f43
[]
no_license
Kirill20/BattleArena
4e3de390d8c4fa36507a77c371435dd5f23d652c
79d6c5d166ad8fa6bcb513e2008961ef46b4a0cc
refs/heads/master
2021-01-18T10:42:44.622387
2013-08-08T05:38:25
2013-08-08T05:38:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,139
java
package mc.alk.arena.controllers.messaging; import java.util.Collection; import java.util.List; import mc.alk.arena.competition.match.Match; import mc.alk.arena.objects.ArenaPlayer; import mc.alk.arena.objects.MatchState; import mc.alk.arena.objects.messaging.AnnouncementOptions; import mc.alk.arena.objects.messaging.Channel; import mc.alk.arena.objects.teams.ArenaTeam; public class MatchMessager { MatchMessageHandler impl; final AnnouncementOptions bos; boolean silent = false; public MatchMessager(Match match){ this.impl = new MatchMessageImpl(match); this.bos = match.getParams().getAnnouncementOptions(); } private Channel getChannel(MatchState state) { if (silent) return Channel.NullChannel; return bos != null && bos.hasOption(true,state) ? bos.getChannel(true,state) : AnnouncementOptions.getDefaultChannel(true,state); } public void sendOnBeginMsg(List<ArenaTeam> teams) { try{impl.sendOnBeginMsg(getChannel(MatchState.ONBEGIN), teams);}catch(Exception e){e.printStackTrace();} } public void sendOnPreStartMsg(List<ArenaTeam> teams) { sendOnPreStartMsg(teams, getChannel(MatchState.ONPRESTART)); } public void sendOnPreStartMsg(List<ArenaTeam> teams, Channel serverChannel) { try{impl.sendOnPreStartMsg(serverChannel, teams);}catch(Exception e){e.printStackTrace();} } public void sendOnStartMsg(List<ArenaTeam> teams) { try{impl.sendOnStartMsg(getChannel(MatchState.ONSTART), teams);}catch(Exception e){e.printStackTrace();} } public void sendOnVictoryMsg(Collection<ArenaTeam> winners, Collection<ArenaTeam> losers) { try{impl.sendOnVictoryMsg(getChannel(MatchState.ONVICTORY), winners,losers);}catch(Exception e){e.printStackTrace();} } public void sendOnDrawMessage(Collection<ArenaTeam> drawers, Collection<ArenaTeam> losers) { try{impl.sendOnDrawMsg(getChannel(MatchState.ONVICTORY), drawers, losers);}catch(Exception e){e.printStackTrace();} } public void sendYourTeamNotReadyMsg(ArenaTeam t1) { try{impl.sendYourTeamNotReadyMsg(t1);}catch(Exception e){e.printStackTrace();} } public void sendOtherTeamNotReadyMsg(ArenaTeam t1) { try{impl.sendOtherTeamNotReadyMsg(t1);}catch(Exception e){e.printStackTrace();} } public void sendOnIntervalMsg(int remaining, Collection<ArenaTeam> currentLeaders) { try{impl.sendOnIntervalMsg(getChannel(MatchState.ONMATCHINTERVAL), currentLeaders, remaining);}catch(Exception e){e.printStackTrace();} } public void sendTimeExpired() { try{impl.sendTimeExpired(getChannel(MatchState.ONMATCHTIMEEXPIRED));}catch(Exception e){e.printStackTrace();} } public void setMessageHandler(MatchMessageHandler mc) { this.impl = mc; } public MatchMessageHandler getMessageHandler() { return impl; } public void setSilent(boolean silent){ this.silent = silent; } public void sendAddedToTeam(ArenaTeam team, ArenaPlayer player) { try{impl.sendAddedToTeam(team,player);}catch(Exception e){e.printStackTrace();} } public void sendCountdownTillPrestart(int remaining) { try{impl.sendCountdownTillPrestart(getChannel(MatchState.ONCOUNTDOWNTOEVENT), remaining);} catch(Exception e){e.printStackTrace();} } }
d82b7198b03d0083f5cf47ed0b0c3e59570967b7
a36e8b0697fbc7356f74ed6e5dfefc8ec31a0f92
/src/net/shopxx/controller/member/PasswordController.java
38efdc36a5f7551947191205c208bbb1304d2bf8
[]
no_license
cwy329233832/shop
eb11fe65e96705f0c291e5f7ab2b7adb2fa01e94
d88331f74741af1d558c079b072769b787408230
refs/heads/master
2021-03-01T07:00:29.606834
2019-01-26T09:43:25
2019-01-26T09:43:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,034
java
/* * Copyright 2005-2017 shopxx.net. All rights reserved. * Support: http://www.shopxx.net * License: http://www.shopxx.net/license */ package net.shopxx.controller.member; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import net.shopxx.entity.Member; import net.shopxx.security.CurrentUser; import net.shopxx.service.MemberService; /** * Controller密码 * * @author SHOP++ Team * @version 5.0 */ @Controller("memberPasswordController") @RequestMapping("/member/password") public class PasswordController extends BaseController { @Inject private MemberService memberService; /** * 验证当前密码 */ @GetMapping("/check_current_password") public @ResponseBody boolean checkCurrentPassword(String currentPassword, @CurrentUser Member currentUser) { return StringUtils.isNotEmpty(currentPassword) && currentUser.isValidCredentials(currentPassword); } /** * 编辑 */ @GetMapping("/edit") public String edit() { return "member/password/edit"; } /** * 更新 */ @PostMapping("/update") public String update(String currentPassword, String password, @CurrentUser Member currentUser, RedirectAttributes redirectAttributes) { if (StringUtils.isEmpty(password) || StringUtils.isEmpty(currentPassword)) { return UNPROCESSABLE_ENTITY_VIEW; } if (!isValid(Member.class, "password", password)) { return UNPROCESSABLE_ENTITY_VIEW; } if (!currentUser.isValidCredentials(currentPassword)) { return UNPROCESSABLE_ENTITY_VIEW; } currentUser.setPassword(password); memberService.update(currentUser); addFlashMessage(redirectAttributes, SUCCESS_MESSAGE); return "redirect:edit"; } }
d4549e303ce6b5ec20efa6abbe088f61ffeb40ea
343773ae835dbbaefde9f653f9211570bd8455d6
/src/main/java/teamroots/embers/api/power/IEmberPacketProducer.java
808c2e9465bafa7959a83ae732eacd1ad8e1a5f0
[ "MIT" ]
permissive
DaedalusGame/EmbersRekindled
a06895d5bc3d0cf6739965828eab96edcdd35a78
a2437713ea29ee9ca76b3e14f6e67f8e8862ccaa
refs/heads/rekindled
2022-05-01T12:03:20.268625
2021-03-03T19:13:27
2021-03-03T19:13:27
135,477,242
41
37
MIT
2022-03-26T17:47:02
2018-05-30T17:38:40
Java
UTF-8
Java
false
false
215
java
package teamroots.embers.api.power; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; public interface IEmberPacketProducer { void setTargetPosition(BlockPos pos, EnumFacing side); }
76e697c4e20c667bc7916ffc62cf33b21db414e8
d9017ff594120c4d8bc38f8ef4b31843b7be1c28
/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/CustomUserDataRepository.java
28347d023f0bae8b9bcc3057b8e77e87fe9af5c6
[ "Apache-2.0" ]
permissive
reachtokish/appsmith
979ccee42ffda132284d0f161bcc369f1212172b
46e368afa9776b13d8cb177f1a9f8a89c119afb4
refs/heads/release
2023-01-02T08:42:14.096088
2022-08-22T12:15:03
2022-08-22T12:15:03
301,500,835
1
0
Apache-2.0
2020-10-06T06:23:17
2020-10-05T18:19:19
null
UTF-8
Java
false
false
197
java
package com.appsmith.server.repositories; import com.appsmith.server.repositories.ce.CustomUserDataRepositoryCE; public interface CustomUserDataRepository extends CustomUserDataRepositoryCE { }
64231840e7e0bd50e1f3bedb1ff51261893b2b67
6a59e5bd764735c86eeaac4225e6705a07e5e8d0
/app/src/main/java/com/app/cellular/mobile/Navigation_main/Address_Ontrack.java
40da554adc4499cd8b8b1d4da832d97d1bc5c9ea
[]
no_license
priyankagiri14/cellular_mobile
4290720b42fcd710e271fb049b442b27c5f02d4b
64088000aefe836383517713dae4bb719c8e2c3b
refs/heads/master
2020-09-25T14:02:56.788142
2020-02-18T12:00:34
2020-02-18T12:00:34
226,018,859
0
0
null
null
null
null
UTF-8
Java
false
false
2,589
java
package com.app.cellular.mobile.Navigation_main; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import com.google.android.material.navigation.NavigationView; import com.app.cellular.mobile.AboutActivity; import com.app.cellular.mobile.R; public class Address_Ontrack extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { Toolbar toolbar; /** * This method is initializing all the design components which will be used further for some functionalty. * @param savedInstanceState */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.address_ontrack); DrawerLayout drawer = findViewById(R.id.address_drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); toolbar=findViewById(R.id.toolbar); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); } /** * This function will return the boolean value for the menu item to performm some functionality according to the code written in the conditions. * @param item * @return this function returns the boolean value (true or false) */ public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_login) { // Handle the camera action Intent i=new Intent(this, Navigation_Main.class); startActivity(i); } else if (id == R.id.nav_contacts) { Intent i1=new Intent(this, Contact_Ontrack.class); startActivity(i1); } else if (id == R.id.nav_address) { }else if (id == R.id.aboutdrawer) { Intent i1=new Intent(this, AboutActivity.class); startActivity(i1); } DrawerLayout drawer = findViewById(R.id.address_drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
8a227ce6881664602e6cc9cf2396e221e8ad979d
5707536bdaffe1c0de2abfa838111cabb287c452
/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/dto/OAuthIDTokenAlgorithmDTO.java
bfc0e1347e3f018689af84acf749647b0022986e
[ "Apache-2.0" ]
permissive
wso2-extensions/identity-inbound-auth-oauth
1ea5481d0595e56fdf972c1bc6e6bd1c61bd7d82
d153b3dd2ae065df135566cb6e8951ac8c1a8645
refs/heads/master
2023-09-01T08:58:09.127138
2023-09-01T05:37:33
2023-09-01T05:37:33
52,758,721
28
410
Apache-2.0
2023-09-14T12:13:20
2016-02-29T02:41:06
Java
UTF-8
Java
false
false
2,325
java
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.identity.oauth.dto; import java.util.List; /** * Class to transfer ID token encryption related algorithms. */ public class OAuthIDTokenAlgorithmDTO { private String defaultIdTokenEncryptionAlgorithm; private List<String> supportedIdTokenEncryptionAlgorithms; private String defaultIdTokenEncryptionMethod; private List<String> supportedIdTokenEncryptionMethods; public String getDefaultIdTokenEncryptionAlgorithm() { return defaultIdTokenEncryptionAlgorithm; } public String getDefaultIdTokenEncryptionMethod() { return defaultIdTokenEncryptionMethod; } public List<String> getSupportedIdTokenEncryptionAlgorithms() { return supportedIdTokenEncryptionAlgorithms; } public List<String> getSupportedIdTokenEncryptionMethods() { return supportedIdTokenEncryptionMethods; } public void setDefaultIdTokenEncryptionAlgorithm(String defaultIdTokenEncryptionAlgorithm) { this.defaultIdTokenEncryptionAlgorithm = defaultIdTokenEncryptionAlgorithm; } public void setDefaultIdTokenEncryptionMethod(String defaultIdTokenEncryptionMethod) { this.defaultIdTokenEncryptionMethod = defaultIdTokenEncryptionMethod; } public void setSupportedIdTokenEncryptionAlgorithms(List<String> supportedIdTokenEncryptionAlgorithms) { this.supportedIdTokenEncryptionAlgorithms = supportedIdTokenEncryptionAlgorithms; } public void setSupportedIdTokenEncryptionMethods(List<String> supportedIdTokenEncryptionMethods) { this.supportedIdTokenEncryptionMethods = supportedIdTokenEncryptionMethods; } }
dabfd04001a03ba3a52331add5fb9a5d0935bdea
41bebb1d64f52ff5acd4d48ce91a56fa97ec0c41
/src/test/java/seedu/address/logic/suggestions/TrieTest.java
92fdde32ea5ca5f150400e114a3188a913a7f2b0
[ "MIT" ]
permissive
linnnruoo/JitHub
a3eea0e6d42e3b69d38e006b182de9aff1cb6252
c9fbd34a85929e3e494a0c89d3e59737bd4d831a
refs/heads/master
2020-03-30T09:22:01.861211
2018-11-12T15:55:12
2018-11-12T15:55:12
151,073,023
0
0
null
null
null
null
UTF-8
Java
false
false
5,599
java
package seedu.address.logic.suggestions; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.ClearScheduleCommand; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.ExportAllCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.HistoryCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.ScheduleCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.logic.commands.TodoCommand; import seedu.address.logic.commands.UndoCommand; public class TrieTest { private Trie dictionary; @Before public void setUp() { dictionary = new Trie(); } @Test public void insert() { dictionary.insert(AddCommand.COMMAND_WORD); } @Test public void searchChar() { dictionary.insert(AddCommand.COMMAND_WORD); // check if 'add' exists assertTrue(dictionary.search('a')); assertTrue(dictionary.search('d')); assertTrue(dictionary.search('d')); // check if 's' exists after 'add' assertFalse(dictionary.search('s')); } @Test public void searchString() { dictionary.insert(AddCommand.COMMAND_WORD); // check if 'add' exists assertTrue(dictionary.search("add")); } @Test public void moveUpCrawler() { dictionary.insert(AddCommand.COMMAND_WORD); //check if first character 'a' is valid assertTrue(dictionary.search('a')); dictionary.moveSearchCrawlerToParent(); //check if first character 'a' is still valid after using moveSearchCrawlerToParent assertTrue(dictionary.search('a')); dictionary.moveSearchCrawlerToParent(); dictionary.moveSearchCrawlerToParent(); //check if moving back to parent once after it is already at the root causes issues assertTrue(dictionary.search('a')); } @Test public void searchStringMultipleValuesInTrie() { dictionary.insert(AddCommand.COMMAND_WORD); dictionary.insert(HistoryCommand.COMMAND_WORD); dictionary.insert(HelpCommand.COMMAND_WORD); assertTrue(dictionary.search("add")); assertTrue(dictionary.search("history")); assertTrue(dictionary.search("help")); } @Test public void searchCharMultipleValuesInTrie() { dictionary.insert(AddCommand.COMMAND_WORD); dictionary.insert(HistoryCommand.COMMAND_WORD); dictionary.insert(HelpCommand.COMMAND_WORD); assertTrue(dictionary.search('a')); assertTrue(dictionary.search('d')); assertFalse(dictionary.search('h')); dictionary.moveSearchCrawlerToParent(); dictionary.moveSearchCrawlerToParent(); assertTrue(dictionary.search('h')); assertTrue(dictionary.search('i')); assertFalse(dictionary.search('e')); //'hie' does not exist assertTrue(dictionary.search('s')); //'his' exists dictionary.moveSearchCrawlerToParent(); //'hi' dictionary.moveSearchCrawlerToParent(); //'h' assertTrue(dictionary.search('e')); //'he' exists } @Test public void getListOfWords() { dictionary.insert(AddCommand.COMMAND_WORD); dictionary.insert(ClearCommand.COMMAND_WORD); dictionary.insert(DeleteCommand.COMMAND_WORD); dictionary.insert(EditCommand.COMMAND_WORD); dictionary.insert(ExitCommand.COMMAND_WORD); dictionary.insert(ExportAllCommand.COMMAND_WORD); dictionary.insert(FindCommand.COMMAND_WORD); dictionary.insert(HelpCommand.COMMAND_WORD); dictionary.insert(HistoryCommand.COMMAND_WORD); dictionary.insert(ListCommand.COMMAND_WORD); dictionary.insert(RedoCommand.COMMAND_WORD); dictionary.insert(ScheduleCommand.COMMAND_WORD); dictionary.insert(SelectCommand.COMMAND_WORD); dictionary.insert(TodoCommand.COMMAND_WORD); dictionary.insert(UndoCommand.COMMAND_WORD); List<String> eWordList = new ArrayList<>(); eWordList.add(EditCommand.COMMAND_WORD); eWordList.add(ExitCommand.COMMAND_WORD); eWordList.add(ExportAllCommand.COMMAND_WORD); assertTrue(eWordList.containsAll(dictionary.getListOfWords("e"))); assertFalse(eWordList.containsAll(dictionary.getListOfWords("a"))); List<String> exWordList = new ArrayList<>(); exWordList.add(ExitCommand.COMMAND_WORD); exWordList.add(ExportAllCommand.COMMAND_WORD); assertTrue(exWordList.containsAll(dictionary.getListOfWords("ex"))); assertFalse(exWordList.containsAll(dictionary.getListOfWords("e"))); } @Test public void withSameStartingNames_getListOfWords() { dictionary.insert(ClearCommand.COMMAND_WORD); dictionary.insert(ClearScheduleCommand.COMMAND_WORD); List<String> cWordList = new ArrayList<>(); cWordList.add(ClearCommand.COMMAND_WORD); cWordList.add(ClearScheduleCommand.COMMAND_WORD); assertTrue(cWordList.containsAll(dictionary.getListOfWords("c"))); } }
b83d806306faa1bfbb0428e76cc08084e2f68e77
7e3dee96374e6c5316b937196a7e2036307a9059
/android-sdk/src/main/java/com/sensorberg/sdk/model/realm/RealmScan.java
975b468c4f0caee8c63525e2a75b0bfa3e5e15a2
[ "MIT" ]
permissive
passavent7/android-sdk
d43ba27ac678166697b534de94b7fe81a27af119
e5b322ace12544434901d3a1fa9f292c160d577a
refs/heads/master
2020-12-26T04:37:35.772802
2015-06-04T09:39:15
2015-06-04T09:39:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,291
java
package com.sensorberg.sdk.model.realm; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.sensorberg.sdk.model.ISO8601TypeAdapter; import com.sensorberg.sdk.scanner.ScanEvent; import com.sensorberg.sdk.scanner.ScanEventType; import java.io.IOException; import java.lang.reflect.Type; import java.util.Date; import java.util.List; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmQuery; import io.realm.RealmResults; public class RealmScan extends RealmObject { private long eventTime; private boolean isEntry; private String proximityUUID; private int proximityMajor; private int proximityMinor; private long sentToServerTimestamp; private long createdAt; public static RealmScan from(ScanEvent scanEvent, Realm realm, long now) { RealmScan value = realm.createObject(RealmScan.class); value.setEventTime(scanEvent.getEventTime()); value.setEntry(scanEvent.getEventMask() == ScanEventType.ENTRY.getMask()); value.setProximityUUID(scanEvent.getBeaconId().getUuid().toString()); value.setProximityMajor(scanEvent.getBeaconId().getMajorId()); value.setProximityMinor(scanEvent.getBeaconId().getMinorId()); value.setSentToServerTimestamp(RealmFields.Scan.NO_DATE); value.setCreatedAt(now); return value; } public boolean isEntry() { return isEntry; } public void setEntry(boolean isEntry) { this.isEntry = isEntry; } public String getProximityUUID() { return proximityUUID; } public void setProximityUUID(String proximityUUID) { this.proximityUUID = proximityUUID; } public int getProximityMajor() { return proximityMajor; } public void setProximityMajor(int proximityMajor) { this.proximityMajor = proximityMajor; } public int getProximityMinor() { return proximityMinor; } public void setProximityMinor(int proximityMinor) { this.proximityMinor = proximityMinor; } public long getEventTime() { return eventTime; } public void setEventTime(long eventTime) { this.eventTime = eventTime; } public long getSentToServerTimestamp() { return sentToServerTimestamp; } public void setSentToServerTimestamp(long sentToServerTimestamp) { this.sentToServerTimestamp = sentToServerTimestamp; } public String getPid(){ return this.getProximityUUID().replace("-", "") + String.format("%1$05d%2$05d", this.getProximityMajor() , this.getProximityMinor()); } public int getTrigger(){ return isEntry() ? ScanEventType.ENTRY.getMask() : ScanEventType.EXIT.getMask(); } public static Type ADAPTER_TYPE() { try { return Class.forName("io.realm.RealmScanRealmProxy"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException("io.realm.RealmScanRealmProxy was not found"); } } public static RealmResults<RealmScan> notSentScans(Realm realm){ RealmQuery<RealmScan> scans = realm.where(RealmScan.class) .equalTo(RealmFields.Scan.sentToServerTimestamp, RealmFields.Scan.NO_DATE); return scans.findAll(); } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } public static void maskAsSent(List<RealmScan> scans, Realm realm, long now, long cacheTtl) { if (scans.size() > 0) { realm.beginTransaction(); for (int i = scans.size() - 1; i >= 0; i--) { scans.get(i).setSentToServerTimestamp(now); } realm.commitTransaction(); } removeAllOlderThan(realm, now, cacheTtl); } public static void removeAllOlderThan(Realm realm, long now, long cacheTtl) { RealmResults<?> actionsToDelete = realm.where(RealmScan.class) .lessThan(RealmFields.Scan.createdAt, now - cacheTtl) .not().equalTo(RealmFields.Scan.sentToServerTimestamp, RealmFields.Action.NO_DATE) .findAll(); if (actionsToDelete.size() > 0){ realm.beginTransaction(); for (int i = actionsToDelete.size() - 1; i >= 0; i--) { actionsToDelete.get(i).removeFromRealm(); } realm.commitTransaction(); } } public static class RealmScanObjectTypeAdapter extends TypeAdapter<RealmScan> { @Override public void write(JsonWriter out, RealmScan value) throws IOException { out.beginObject(); out.name("pid").value(value.getPid()); out.name("trigger").value(value.getTrigger()); out.name("dt"); ISO8601TypeAdapter.DATE_ADAPTER.write(out, new Date(value.getEventTime())); out.endObject(); } @Override public RealmScan read(JsonReader in) throws IOException { throw new IllegalArgumentException("you must not use this to read a RealmScanObject"); } } }
3ad5a5139d807e16e1d2653dd702981387538171
06f700275881d252d5994cfb2d6f51316e1a2ab1
/build/generated-sources/jax-ws/com/ilient/api/ApiServiceRequestAttachment.java
48d7566514ee58f14b092b4b2c450c7021cdd18f
[]
no_license
danielshsp/sqlConn
6418aed765c3d94f8b53fc6b981db0ed699cdeac
9ec1eaed8618af400e1e5cc55e1a63d3bcd00818
refs/heads/master
2020-04-27T22:05:53.686993
2019-03-09T17:13:22
2019-03-09T17:13:22
174,723,196
0
0
null
null
null
null
UTF-8
Java
false
false
3,805
java
package com.ilient.api; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for apiServiceRequestAttachment complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="apiServiceRequestAttachment"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fileContent" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/> * &lt;element name="fileDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="fileId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="fileName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="srId" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "apiServiceRequestAttachment", propOrder = { "fileContent", "fileDate", "fileId", "fileName", "srId" }) public class ApiServiceRequestAttachment { protected byte[] fileContent; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar fileDate; protected String fileId; protected String fileName; protected int srId; /** * Gets the value of the fileContent property. * * @return * possible object is * byte[] */ public byte[] getFileContent() { return fileContent; } /** * Sets the value of the fileContent property. * * @param value * allowed object is * byte[] */ public void setFileContent(byte[] value) { this.fileContent = value; } /** * Gets the value of the fileDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getFileDate() { return fileDate; } /** * Sets the value of the fileDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setFileDate(XMLGregorianCalendar value) { this.fileDate = value; } /** * Gets the value of the fileId property. * * @return * possible object is * {@link String } * */ public String getFileId() { return fileId; } /** * Sets the value of the fileId property. * * @param value * allowed object is * {@link String } * */ public void setFileId(String value) { this.fileId = value; } /** * Gets the value of the fileName property. * * @return * possible object is * {@link String } * */ public String getFileName() { return fileName; } /** * Sets the value of the fileName property. * * @param value * allowed object is * {@link String } * */ public void setFileName(String value) { this.fileName = value; } /** * Gets the value of the srId property. * */ public int getSrId() { return srId; } /** * Sets the value of the srId property. * */ public void setSrId(int value) { this.srId = value; } }
[ "gkx638" ]
gkx638
a9b1a07c6fd3456015391a0a794103a7c9683b85
c28d079399340f12b9655868113d641bc8b89209
/src/main/java/model/WeatherReportResponse.java
bc7c504f2e6c2446deda8db38498b5dd5693bfbb
[]
no_license
chiragNarkhede/Weather-Reporting-Comparator
9c6655a14f87cd6a60ac463aa1acb9d96abad6c5
a581a42e3958d76f43d2a3989100fc4a90b7cd05
refs/heads/master
2022-12-11T20:26:10.098497
2020-08-13T14:19:29
2020-08-13T14:19:29
286,822,677
1
0
null
null
null
null
UTF-8
Java
false
false
843
java
package model; import java.util.List; import model.WeatherDetails; import model.WindDetails; import model.MainDetails; /* Create Object for JSON response * which received from API */ public class WeatherReportResponse { public List<WeatherDetails> weather ; public MainDetails main; public WindDetails wind; public String name; public MainDetails getMain() { return main; } public void setMain(MainDetails main) { this.main = main; } public WindDetails getWind() { return wind; } public void setWind(WindDetails wind) { this.wind = wind; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<WeatherDetails> getWeather() { return weather; } public void setWeather(List<WeatherDetails> weather) { this.weather = weather; } }
80ccb13570d83e45e0a7d71677e7eaf5b9801aaf
0663afe07eec169dbe8a932acea6ecae52a11299
/src/main/java/com/atguigu/crud/service/UserService.java
e59c6423d2054dcea54d0d52371c80ee0c2d69ba
[]
no_license
qiushanling-admin/ssm-crud
139e58d7e19580afcbbbac8ca60de178134f88c6
36bac38bb6b006546ea9da983d0623039affd5c7
refs/heads/master
2020-12-04T13:26:09.406661
2019-03-15T03:10:00
2019-03-15T03:10:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,199
java
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.User; import com.atguigu.crud.bean.UserExample; import com.atguigu.crud.bean.UserExample.Criteria; import com.atguigu.crud.dao.UserMapper; @Service public class UserService { @Autowired UserMapper userMapper; /** * 校验用户名 * @param username * @return */ public boolean checkUserName(String username) { UserExample userExample = new UserExample(); Criteria criteria = userExample.createCriteria(); criteria.andUsernameEqualTo(username); long count = userMapper.countByExample(userExample); return count==0; } /** * 添加用户 * @param user */ public void add(User user) { userMapper.insert(user); } /** * 激活用户 * @param code */ public boolean active(String code) { UserExample userExample = new UserExample(); Criteria criteria = userExample.createCriteria(); criteria.andCodeEqualTo(code); List<User> userList = userMapper.selectByExample(userExample); User user = userList.get(0); user.setState(true); int count = userMapper.updateByPrimaryKey(user); return count!=0; } /** * 登录 * @param user * @return */ public User login(User user) { UserExample userExample = new UserExample(); Criteria criteria = userExample.createCriteria(); criteria.andUsernameEqualTo(user.getUsername()); criteria.andPasswordEqualTo(user.getPassword()); criteria.andStateEqualTo(true); List<User> userList = userMapper.selectByExample(userExample); if(userList.size()>0){ User currentUser = userList.get(0); return currentUser; }else{ return null; } } public User getUserByUserName(String username){ UserExample userExample = new UserExample(); Criteria criteria = userExample.createCriteria(); criteria.andUsernameEqualTo(username); criteria.andStateEqualTo(true); List<User> userList = userMapper.selectByExample(userExample); if(userList.size()>0){ User currentUser = userList.get(0); return currentUser; }else{ return null; } } }
f3ff394252e5a0f254633b5b0bfcb2277245aea8
2bd7643730a0048e0ba1e7bb663a97166c54dc54
/EBPSv2/src/main/java/com/controller/rest/application/FrequentlyAskedQuestionRestController.java
613c057b76a3b1f084e001d02ce66223f6f1863b
[]
no_license
bkings/BuildingPermitDynamic
3f8b4d7fa8aaff45b43f05fc16fcb1ea54da3ad7
bb7322f6e04b2017854a5ceebcf4b37d755d000b
refs/heads/master
2023-02-16T20:46:37.209422
2021-01-17T06:40:25
2021-01-17T06:40:25
299,945,567
1
0
null
2020-10-21T13:30:47
2020-09-30T14:25:30
Java
UTF-8
Java
false
false
1,419
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 com.controller.rest.application; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; 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.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.service.application.FrequentlyAskedQuestionService; @RestController @CrossOrigin @RequestMapping("api/application/FrequentlyAskedQuestion") public class FrequentlyAskedQuestionRestController { @Autowired FrequentlyAskedQuestionService service; @GetMapping() public Object show() { return service.getAll(); } @GetMapping("/{id}") public Object showById(@PathVariable Integer id) { return service.getById(id); } @PostMapping() public Object doSave(@RequestBody String jsonData, @RequestHeader(value = "Authorization") String Authorization) { return service.save(jsonData,Authorization); } }
f99ee953719ad246ac3be3c7fec4c8a0e5c428ec
b239ac53ff301239a8838ad2c0424f23bec9a6f0
/jgrzesiak_mod4/deitelfig16_15/StaticCharMethods.java
0a0c784b73ca0c51d8e887ac98f5016de8f6ccb9
[]
no_license
jhgrz/itp120
8e4a00589621f0f80b4af8f5f494b19341d7e8d4
3aff341b5bdfc70158d9083d1046da188273496b
refs/heads/master
2021-01-16T23:17:23.404018
2017-02-22T16:50:13
2017-02-22T16:50:13
82,817,285
1
0
null
null
null
null
UTF-8
Java
false
false
2,564
java
package deitelfig16_15; // Fig. 16.15: StaticCharMethods.java // Character static methods for testing characters and converting case. import java.util.Scanner; public class StaticCharMethods { public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); // create scanner System.out.println( "Enter a character and press Enter" ); String input = scanner.next(); char c = input.charAt( 0 ); // get input character // display character info System.out.printf( "is defined: %b\n", Character.isDefined( c ) ); System.out.printf( "is digit: %b\n", Character.isDigit( c ) ); System.out.printf( "is first character in a Java identifier: %b\n", Character.isJavaIdentifierStart( c ) ); System.out.printf( "is part of a Java identifier: %b\n", Character.isJavaIdentifierPart( c ) ); System.out.printf( "is letter: %b\n", Character.isLetter( c ) ); System.out.printf( "is letter or digit: %b\n", Character.isLetterOrDigit( c ) ); System.out.printf( "is lower case: %b\n", Character.isLowerCase( c ) ); System.out.printf( "is upper case: %b\n", Character.isUpperCase( c ) ); System.out.printf( "to upper case: %s\n", Character.toUpperCase( c ) ); System.out.printf( "to lower case: %s\n", Character.toLowerCase( c ) ); } // end main } // end class StaticCharMethods /************************************************************************** * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
6828d9138ee6483c9ca473747a1638e7d8bf8a53
4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849
/aliyun-java-sdk-viapi-regen/src/main/java/com/aliyuncs/viapi_regen/model/v20211119/CheckDatasetOssBucketCORSRequest.java
d1160f68aafd6cb2b8e672e143c6c3187c25a545
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-java-sdk
a263fa08e261f12d45586d1b3ad8a6609bba0e91
e19239808ad2298d32dda77db29a6d809e4f7add
refs/heads/master
2023-09-03T12:28:09.765286
2023-09-01T09:03:00
2023-09-01T09:03:00
39,555,898
1,542
1,317
NOASSERTION
2023-09-14T07:27:05
2015-07-23T08:41:13
Java
UTF-8
Java
false
false
1,708
java
/* * 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.aliyuncs.viapi_regen.model.v20211119; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.viapi_regen.Endpoint; /** * @author auto create * @version */ public class CheckDatasetOssBucketCORSRequest extends RpcAcsRequest<CheckDatasetOssBucketCORSResponse> { private Long labelsetId; public CheckDatasetOssBucketCORSRequest() { super("viapi-regen", "2021-11-19", "CheckDatasetOssBucketCORS", "selflearning"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public Long getLabelsetId() { return this.labelsetId; } public void setLabelsetId(Long labelsetId) { this.labelsetId = labelsetId; if(labelsetId != null){ putBodyParameter("LabelsetId", labelsetId.toString()); } } @Override public Class<CheckDatasetOssBucketCORSResponse> getResponseClass() { return CheckDatasetOssBucketCORSResponse.class; } }
5506dbd686fe0af2c55f7d287237448cda28a4bf
429499b7d25bab3d74daec5064afeb2dc26dc607
/src/main/java/com/Project/ESB/IService/FillAttenteIService.java
6eb3ac12f32b148e20b4d2d43d5dfc60b96a1704
[]
no_license
HajlaouiAmine/esb_pfe
1f0c1a3ef3422ceb68765cf527b91eecbaec562a
7c6661841ad6e2f21ac003ace5bf78e16fbb07d1
refs/heads/main
2023-04-29T07:49:54.041038
2021-05-18T12:19:30
2021-05-18T12:19:30
368,510,163
0
1
null
null
null
null
UTF-8
Java
false
false
166
java
package com.Project.ESB.IService; import com.Project.ESB.Model.FillAttente; public interface FillAttenteIService { FillAttente créer(FillAttente fillAttente); }
2274e76905261637ea0bab91d36be95442b4ecdc
714bf80a42af65d5fe8cd3d33784f739eb87292c
/src/StartWindow.java
33be2337bdb400fb5346c1a168cc24bbbb7f2c78
[]
no_license
jweiler2020/Block_Game
d9cff070700e7f66741b554896103c8305270965
30cdb0ae445c756220e7a1d5e6f81f186f855352
refs/heads/master
2020-04-26T05:13:15.990625
2019-04-29T01:57:47
2019-04-29T01:57:47
173,327,025
0
0
null
null
null
null
UTF-8
Java
false
false
3,394
java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class StartWindow extends JFrame implements ActionListener { private JButton playGameButton, settingsButton, quitButton; private JButton backToMainButton; private JPanel mainPanel, settingsPanel; private CardLayout cl = new CardLayout(); public StartWindow(String title) { super(title); // Useful objects Font labelFont = new Font("Arial", Font.BOLD, 20); Font buttonFont = new Font("Arial", Font.PLAIN, 15); GridBagConstraints c = new GridBagConstraints(); //----------------------------Start Main Panel------------------------------// JLabel mainPanelLabel = new JLabel("Block Game 2019 Edition™", JLabel.CENTER); mainPanelLabel.setFont(labelFont); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); playGameButton = new JButton("Play"); playGameButton.addActionListener(this); playGameButton.setFont(buttonFont); settingsButton = new JButton("Settings"); settingsButton.addActionListener(this); settingsButton.setFont(buttonFont); quitButton = new JButton("Quit"); quitButton.addActionListener(this); quitButton.setFont(buttonFont); c.weightx = 1; c.weighty = 1 / 3d; c.insets = new Insets(5, 0, 5, 0); c.gridx = 0; c.gridy = 0; buttonPanel.add(playGameButton, c); c.gridy++; buttonPanel.add(settingsButton, c); c.gridy++; buttonPanel.add(quitButton, c); mainPanel = new JPanel(); mainPanel.setName("mainPanel"); mainPanel.setLayout(new GridBagLayout()); c.weightx = 1; c.weighty = 0.5; c.gridx = 0; c.insets = new Insets(0, 0, 0, 0); c.gridy = 0; mainPanel.add(mainPanelLabel, c); c.gridy++; mainPanel.add(buttonPanel, c); //----------------------------End Main Panel--------------------------------// //----------------------------Start Settings Panel--------------------------// JLabel settingsPanelLabel = new JLabel("Settings"); settingsPanelLabel.setFont(labelFont); backToMainButton = new JButton("Back to Main Menu"); backToMainButton.addActionListener(this); backToMainButton.setFont(buttonFont); settingsPanel = new JPanel(); settingsPanel.setName("settingsPanel"); settingsPanel.setLayout(new GridBagLayout()); c.weightx = 1; c.weighty = 0.5; c.gridx = 0; c.gridy = 0; settingsPanel.add(settingsPanelLabel, c); c.gridy++; settingsPanel.add(backToMainButton, c); //---------------------------End Settings Panel-----------------------------// Container con = getContentPane(); con.setLayout(cl); con.add(mainPanel, mainPanel.getName()); con.add(settingsPanel, settingsPanel.getName()); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == playGameButton) { new GameController(); dispose(); } else if (e.getSource() == settingsButton) { cl.show(getContentPane(), settingsPanel.getName()); } else if (e.getSource() == quitButton) { System.exit(0); } else if (e.getSource() == backToMainButton) { cl.show(getContentPane(), mainPanel.getName()); } } public static void main(String[] args) { StartWindow win = new StartWindow("Block Game 2019 Edition™"); win.setBounds(200, 200, 400, 300); win.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); win.setResizable(false); win.setVisible(true); } }
56b7d912d1dc37c38eaad76337a80d60f34dafee
089469c624662b3598ca264ef5564cd96656105d
/app/src/main/java/com/android/github/souravbera/e_commerce/ConfirmFinalOrderActivity.java
1f97cf6566203c3e05c991df502e0b4d9ff55842
[]
no_license
nano-research-labs/E-Commerce-Clothes-App
065b10664e03d23af50ec7408cc14b27d958a3c2
7221b08e0193c43f09ab4abfe1f987226de2fca8
refs/heads/master
2023-02-05T06:57:36.748563
2020-12-23T13:24:13
2020-12-23T13:24:13
296,399,881
0
1
null
2020-12-23T13:24:15
2020-09-17T17:44:04
Java
UTF-8
Java
false
false
5,130
java
package com.android.github.souravbera.e_commerce; import android.content.Intent; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.android.github.souravbera.e_commerce.Prevalent.Prevalent; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.rey.material.widget.TextView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; public class ConfirmFinalOrderActivity extends AppCompatActivity { private EditText nameEditText, phoneEditText, addressEditText, cityEditText; private Button confirmOrderbtn; private String totalAmount= ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confirm_final_order); totalAmount= getIntent().getStringExtra("Total Price"); Toast.makeText(this,"Total Price= Rs."+totalAmount,Toast.LENGTH_SHORT).show(); confirmOrderbtn= findViewById(R.id.confirm_final_btn); nameEditText= findViewById(R.id.shippment_name); addressEditText= findViewById(R.id.shippment_address); cityEditText= findViewById(R.id.shippment_city); phoneEditText= findViewById(R.id.shippment_phone); confirmOrderbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Check(); } }); } private void Check() { if(TextUtils.isEmpty(nameEditText.getText().toString())) { Toast.makeText(this, "Please Provide your full Name", Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(addressEditText.getText().toString())) { Toast.makeText(this, "Please Provide your Address", Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(cityEditText.getText().toString())) { Toast.makeText(this, "Please Provide your City Name", Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(phoneEditText.getText().toString())) { Toast.makeText(this, "Please Confirm your Phone Number", Toast.LENGTH_SHORT).show(); } else{ ConfirmOrder(); } } private void ConfirmOrder() { final String saveCurrentDate, saveCurrentTime; Calendar calForData= Calendar.getInstance(); SimpleDateFormat currentDate= new SimpleDateFormat("MMM dd, yyyy"); saveCurrentDate= currentDate.format(calForData.getTime()); SimpleDateFormat currentTime= new SimpleDateFormat("HH:mm:ss a"); saveCurrentTime= currentTime.format(calForData.getTime()); final DatabaseReference ordersRef= FirebaseDatabase.getInstance().getReference() .child("Orders") .child(Prevalent.currentOnlineUser.getPhone()); HashMap<String, Object> orderMap= new HashMap<>(); orderMap.put("totalAmount", totalAmount); orderMap.put("name",nameEditText.getText().toString()); orderMap.put("phone",phoneEditText.getText().toString()); orderMap.put("address",addressEditText.getText().toString()); orderMap.put("city",cityEditText.getText().toString()); orderMap.put("date",saveCurrentDate); orderMap.put("time",saveCurrentTime); orderMap.put("state","not shipped"); ordersRef.updateChildren(orderMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { FirebaseDatabase.getInstance().getReference() .child("Cart List") .child("User View") .child(Prevalent.currentOnlineUser.getPhone()) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Toast.makeText(ConfirmFinalOrderActivity.this, "your final Order has been placed successfully",Toast.LENGTH_SHORT).show(); Intent intent= new Intent(ConfirmFinalOrderActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } }); } } }); } }
c4b0b055bbb31a11bdf7f0cb37a55e730559ed79
3b50b3b55a9fd4f6bc90315d2bda9c07ec599116
/app/src/main/java/com/d/httprequest/model/WpTerm.java
fea8fd5e0c073f305260783effd6bcb96c80a6ce
[]
no_license
huuhuybn/HttpRequest3
c0a0359c7dd759a8fc9df97706025de43c890f02
79beb0d59a3dad1a93bfcf29edcf1dbe22239d6b
refs/heads/master
2020-06-21T01:39:11.865132
2019-07-17T04:03:26
2019-07-17T04:03:26
197,312,450
2
1
null
null
null
null
UTF-8
Java
false
false
824
java
package com.d.httprequest.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class WpTerm { @SerializedName("taxonomy") @Expose private String taxonomy; @SerializedName("embeddable") @Expose private Boolean embeddable; @SerializedName("href") @Expose private String href; public String getTaxonomy() { return taxonomy; } public void setTaxonomy(String taxonomy) { this.taxonomy = taxonomy; } public Boolean getEmbeddable() { return embeddable; } public void setEmbeddable(Boolean embeddable) { this.embeddable = embeddable; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
ca05cc53c4319fde39ad3b866d1d2decb47e1bfb
202b67a83f0558b4db7e570d8daf73517d319f4f
/app/src/main/java/com/lorem/simpledictionary/LoaderActivity.java
9cc8425badae2eaf90418045104f0cc3931b91dc
[]
no_license
ravimahfunda/SimpleDictionary
53b2d9fa4fd29855c387a28750639d5bf3efffa5
8f75eb63ad0aa2f8973291de679bd2ddc0aa961f
refs/heads/master
2020-03-26T11:26:52.737391
2018-08-15T11:12:50
2018-08-15T11:12:50
144,843,108
1
0
null
null
null
null
UTF-8
Java
false
false
5,247
java
package com.lorem.simpledictionary; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Debug; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ProgressBar; import com.lorem.simpledictionary.db.DatabaseContract; import com.lorem.simpledictionary.db.OperationHelper; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.ArrayList; public class LoaderActivity extends AppCompatActivity { ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loader); progressBar = (ProgressBar) findViewById(R.id.pb_load); new LoadData().execute(); } private class LoadData extends AsyncTask<Void, Integer, Void> { final String TAG = LoadData.class.getSimpleName(); OperationHelper operationHelper; OperationHelper operationID; double progress; double maxprogress = 100; @Override protected void onPreExecute() { operationHelper = new OperationHelper(LoaderActivity.this); } @Override protected Void doInBackground(Void... params) { SharedPreferences preferences = getSharedPreferences("LOADER", Context.MODE_PRIVATE); Boolean firstRun = preferences.getBoolean("LOADED", true); if (firstRun) { ArrayList<Word> enWords = preLoadRaw(R.raw.english_indonesia); ArrayList<Word> idWords = preLoadRaw(R.raw.indonesia_english); progress = 10; publishProgress((int) progress); Double progressMaxInsert = 100.0; Double progressDiff = (progressMaxInsert - progress) / (enWords.size() + idWords.size()); try { operationHelper.open(); } catch (SQLException e) { e.printStackTrace(); } operationHelper.beginTransaction(); try { for (Word model : enWords) { Log.d("INSRETION EN", "Inserting word " + model.getWord()); operationHelper.insertTransaction(DatabaseContract.TABLE_EN,model); progress += progressDiff; publishProgress((int) progress); } for (Word model : idWords) { Log.d("INSRETION ID", "Inserting word " + model.getWord()); operationHelper.insertTransaction(DatabaseContract.TABLE_ID,model); progress += progressDiff; publishProgress((int) progress); } // Jika semua proses telah di set success maka akan di commit ke database operationHelper.setTransactionSuccess(); } catch (Exception e) { // Jika gagal maka do nothing Log.e(TAG, "doInBackground: Exception"); } operationHelper.endTransaction(); operationHelper.close(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("LOADED", false); editor.apply(); publishProgress((int) maxprogress); } else { try { synchronized (this) { this.wait(1000); publishProgress(50); this.wait(1000); publishProgress((int) maxprogress); } } catch (Exception e) { } } return null; } @Override protected void onProgressUpdate(Integer... values) { progressBar.setProgress(values[0]); } @Override protected void onPostExecute(Void result) { Intent i = new Intent(LoaderActivity.this, MainActivity.class); startActivity(i); finish(); } } public ArrayList<Word> preLoadRaw(int fileId) { ArrayList<Word> mahasiswaModels = new ArrayList<>(); String line = null; BufferedReader reader; try { Resources res = getResources(); InputStream raw_dict = res.openRawResource(fileId); reader = new BufferedReader(new InputStreamReader(raw_dict)); int count = 0; do { line = reader.readLine(); String[] splitstr = line.split("\t"); Word mahasiswaModel; mahasiswaModel = new Word(splitstr[0], splitstr[1]); mahasiswaModels.add(mahasiswaModel); count++; } while (line != null); } catch (Exception e) { e.printStackTrace(); } return mahasiswaModels; } }
d0ae45a9dbce69419fe70e78a8d88e8c1ba0f5da
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_e67d2acfe8112a311fdb5af31767119d184d6362/Pointer/11_e67d2acfe8112a311fdb5af31767119d184d6362_Pointer_s.java
dbbb1e084bcc6e694e59a8d1a2d37f4656603592
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
152,476
java
/* * BridJ - Dynamic and blazing-fast native interop for Java. * http://bridj.googlecode.com/ * * Copyright (c) 2010-2013, Olivier Chafik (http://ochafik.com/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted 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 Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK 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 REGENTS AND 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.bridj; import org.bridj.util.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.nio.*; import java.lang.annotation.Annotation; import java.util.*; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import static org.bridj.SizeT.safeIntCast; /** * Pointer to a native memory location.<br> * Pointer is the entry point of any pointer-related operation in BridJ. * <p> * <u><b>Manipulating memory</b></u> * <p> * <ul> * <li>Wrapping a memory address as a pointer : {@link Pointer#pointerToAddress(long)} * </li> * <li>Reading / writing a primitive from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}()} / {@link Pointer#set${prim.CapName}(${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}()} / {@link Pointer#set${sizePrim}(long)} <br> #end *</li> * <li>Reading / writing the nth contiguous primitive value from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}AtIndex(long)} / {@link Pointer#set${prim.CapName}AtIndex(long, ${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}AtIndex(long)} / {@link Pointer#set${sizePrim}AtIndex(long, long)} <br> #end *</li> * <li>Reading / writing a primitive from / to the pointed memory location with a byte offset:<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}AtOffset(long)} / {@link Pointer#set${prim.CapName}AtOffset(long, ${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}AtOffset(long)} / {@link Pointer#set${sizePrim}AtOffset(long, long)} <br> #end *</li> * <li>Reading / writing an array of primitives from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}s(int)} / {@link Pointer#set${prim.CapName}s(${prim.Name}[])} ; With an offset : {@link Pointer#get${prim.CapName}sAtOffset(long, int)} / {@link Pointer#set${prim.CapName}sAtOffset(long, ${prim.Name}[])}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}s(int)} / {@link Pointer#set${sizePrim}s(long[])} ; With an offset : {@link Pointer#get${sizePrim}sAtOffset(long, int)} / {@link Pointer#set${sizePrim}sAtOffset(long, long[])}<br> #end * </li> * <li>Reading / writing an NIO buffer of primitives from / to the pointed memory location :<br> #foreach ($prim in $primitivesNoBool) #if ($prim.Name != "char")* {@link Pointer#get${prim.BufferName}(long)} (can be used for writing as well) / {@link Pointer#set${prim.CapName}s(${prim.BufferName})}<br> #end #end * </li> * <li>Reading / writing a String from / to the pointed memory location using the default charset :<br> #foreach ($string in ["C", "WideC"]) * {@link Pointer#get${string}String()} / {@link Pointer#set${string}String(String)} ; With an offset : {@link Pointer#get${string}StringAtOffset(long)} / {@link Pointer#set${string}StringAtOffset(long, String)}<br> #end * </li> * <li>Reading / writing a String with control on the charset :<br> * {@link Pointer#getStringAtOffset(long, StringType, Charset)} / {@link Pointer#setStringAtOffset(long, String, StringType, Charset)}<br> * </ul> * <p> * <u><b>Allocating memory</b></u> * <p> * <ul> * <li>Getting the pointer to a struct / a C++ class / a COM object : * {@link Pointer#pointerTo(NativeObject)} * </li> * <li>Allocating a dynamic callback (without a static {@link Callback} definition, which would be the preferred way) :<br> * {@link Pointer#allocateDynamicCallback(DynamicCallback, org.bridj.ann.Convention.Style, Type, Type[])} * </li> * <li>Allocating a primitive with / without an initial value (zero-initialized) :<br> #foreach ($prim in $primitives) * {@link Pointer#pointerTo${prim.CapName}(${prim.Name})} / {@link Pointer#allocate${prim.CapName}()}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}(long)} / {@link Pointer#allocate${sizePrim}()}<br> #end * </li> * <li>Allocating an array of primitives with / without initial values (zero-initialized) :<br> #foreach ($prim in $primitivesNoBool) * {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])} or {@link Pointer#pointerTo${prim.CapName}s(${prim.BufferName})} / {@link Pointer#allocate${prim.CapName}s(long)}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}s(long[])} / {@link Pointer#allocate${sizePrim}s(long)}<br> #end * {@link Pointer#pointerToBuffer(Buffer)} / n/a<br> * </li> * <li>Allocating a native String :<br> #foreach ($string in ["C", "WideC"]) * {@link Pointer#pointerTo${string}String(String) } (default charset)<br> #end * {@link Pointer#pointerToString(String, StringType, Charset) }<br> * </li> * <li>Allocating a {@link ListType#Dynamic} Java {@link java.util.List} that uses native memory storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list):<br> * {@link Pointer#allocateList(Class, long) } * </li> * <li>Transforming a pointer to a Java {@link java.util.List} that uses the pointer as storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list, if it's {@link ListType#Dynamic}) :<br> * {@link Pointer#asList(ListType) }<br> * {@link Pointer#asList() }<br> * </li> * </ul> * <p> * <u><b>Casting pointers</b></u> * <p> * <ul> * <li>Cast a pointer to a {@link DynamicFunction} :<br> * {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } * </li> * <li>Cast a pointer to a {@link StructObject} or a {@link Callback} (as the ones generated by <a href="http://code.google.com/p/jnaerator/">JNAerator</a>) <br>: * {@link Pointer#as(Class) } * </li> * <li>Cast a pointer to a complex type pointer (use {@link org.bridj.cpp.CPPType#getCPPType(Object[])} to create a C++ template type, for instance) :<br> * {@link Pointer#as(Type) } * </li> * <li>Get an untyped pointer :<br> * {@link Pointer#asUntyped() } * </li> * </ul> * <p> * <u><b>Dealing with pointer bounds</b></u> * <p> * <ul> * <li>Pointers to memory allocated through Pointer.pointerTo*, Pointer.allocate* have validity bounds that help prevent buffer overflows, at least when the Pointer API is used * </li> * <li>{@link Pointer#offset(long)}, {@link Pointer#next(long)} and other similar methods retain pointer bounds * </li> * <li>{@link Pointer#getValidBytes()} and {@link Pointer#getValidElements()} return the amount of valid memory readable from the pointer * </li> * <li>Bounds can be declared manually with {@link Pointer#validBytes(long)} (useful for memory allocated by native code) * </li> * </ul> */ public abstract class Pointer<T> implements Comparable<Pointer<?>>, Iterable<T> { #macro (declareCheckedPeerAtOffset $byteOffset $validityCheckLength) long checkedPeer = peer + $byteOffset; if (validStart != UNKNOWN_VALIDITY && ( checkedPeer < validStart || (checkedPeer + $validityCheckLength) > validEnd )) { invalidPeer(checkedPeer, $validityCheckLength); } #end #macro (declareCheckedPeer $validityCheckLength) #declareCheckedPeerAtOffset("0", $validityCheckLength) #end #macro (docAllocateCopy $cPrimName $primWrapper) /** * Allocate enough memory for a single $cPrimName value, copy the value provided in argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param value initial value for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName value given in argument */ #end #macro (docAllocateArrayCopy $cPrimName $primWrapper) /** * Allocate enough memory for values.length $cPrimName values, copy the values provided as argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon : <pre>{@code for (float f : pointerTo(1f, 2f, 3.3f)) System.out.println(f); }</pre> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName consecutive values provided in argument */ #end #macro (docAllocateArray2DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 2D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 2D C array would be */ #end #macro (docAllocateArray3DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 3D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 3D C array would be */ #end #macro (docAllocate $cPrimName $primWrapper) /** * Allocate enough memory for a $cPrimName value and return a pointer to it.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * @return pointer to a single zero-initialized $cPrimName value */ #end #macro (docAllocateArray $cPrimName $primWrapper) /** * Allocate enough memory for arrayLength $cPrimName values and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon. * @return pointer to arrayLength zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray2D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @return pointer to dim1 * dim2 zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray3D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 * dim3 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @return pointer to dim1 * dim2 * dim3 zero-initialized $cPrimName consecutive values */ #end #macro (docGet $cPrimName $primWrapper) /** * Read a $cPrimName value from the pointed memory location */ #end #macro (docGetOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Read a $cPrimName value from the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docGetIndex $typeName $equivalentOffsetCall) /** * Read the nth contiguous $typeName value from the pointed memory location.<br> * Equivalent to <code>${equivalentOffsetCall}</code>. * @param valueIndex index of the value to read */ #end #macro (docGetArray $cPrimName $primWrapper) /** * Read an array of $cPrimName values of the specified length from the pointed memory location */ #end #macro (docGetRemainingArray $cPrimName $primWrapper) /** * Read the array of remaining $cPrimName values from the pointed memory location */ #end #macro (docGetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Read an array of $cPrimName values of the specified length from the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docSet $cPrimName $primWrapper) /** * Write a $cPrimName value to the pointed memory location */ #end #macro (docSetOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Write a $cPrimName value to the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docSetIndex $typeName $equivalentOffsetCall) /** * Write the nth contiguous $typeName value to the pointed memory location.<br> * Equivalent to <code>${equivalentOffsetCall}</code>. * @param valueIndex index of the value to write * @param value $typeName value to write */ #end #macro (docSetArray $cPrimName $primWrapper) /** * Write an array of $cPrimName values to the pointed memory location */ #end #macro (docSetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Write an array of $cPrimName values to the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end /** The NULL pointer is <b>always</b> Java's null value */ public static final Pointer NULL = null; /** * Size of a pointer in bytes. <br> * This is 4 bytes in a 32 bits environment and 8 bytes in a 64 bits environment.<br> * Note that some 64 bits environments allow for 32 bits JVM execution (using the -d32 command line argument for Sun's JVM, for instance). In that case, Java programs will believe they're executed in a 32 bits environment. */ public static final int SIZE = Platform.POINTER_SIZE; static { Platform.initLibrary(); } protected static long UNKNOWN_VALIDITY = -1; protected static long NO_PARENT = 0/*-1*/; /** * Default alignment used to allocate memory from the static factory methods in Pointer class (any value lower or equal to 1 means no alignment) */ public static final int defaultAlignment = Integer.parseInt(Platform.getenvOrProperty("BRIDJ_DEFAULT_ALIGNMENT", "bridj.defaultAlignment", "-1")); protected final PointerIO<T> io; protected final long peer, offsetInParent; protected final Pointer<?> parent; protected volatile Object sibling; protected final long validStart, validEnd; /** * Object responsible for reclamation of some pointed memory when it's not used anymore. */ public interface Releaser { void release(Pointer<?> p); } Pointer(PointerIO<T> io, long peer, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, Object sibling) { this.io = io; this.peer = peer; this.validStart = validStart; this.validEnd = validEnd; this.parent = parent; this.offsetInParent = offsetInParent; this.sibling = sibling; if (peer == 0) throw new IllegalArgumentException("Pointer instance cannot have NULL peer ! (use null Pointer instead)"); if (BridJ.debugPointers) creationTrace = new RuntimeException().fillInStackTrace(); } Throwable creationTrace; #foreach ($data in [ ["Ordered", true, ""], ["Disordered", false, "_disordered"] ]) #set ($orderingPrefix = $data.get(0)) #set ($ordered = $data.get(1)) #set ($nativeSuffix = $data.get(2)) static class ${orderingPrefix}Pointer<T> extends Pointer<T> { ${orderingPrefix}Pointer(PointerIO<T> io, long peer, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, Object sibling) { super(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } @Override public boolean isOrdered() { return $ordered; } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end @Override public Pointer<T> set${prim.CapName}(${prim.Name} value) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setInt((int)value); #end #declareCheckedPeer(${primSize}) #if ($prim.Name != "byte" && $prim.Name != "boolean") JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); #else JNI.set_${prim.Name}(checkedPeer, value); #end return this; } @Override public Pointer<T> set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setIntAtOffset(byteOffset, (int)value); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize}") #if ($prim.Name != "byte" && $prim.Name != "boolean") JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); #else JNI.set_${prim.Name}(checkedPeer, value); #end return this; } @Override public ${prim.Name} get${prim.CapName}() { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return (char)getInt(); #end #declareCheckedPeer(${primSize}) #if ($prim.Name != "byte" && $prim.Name != "boolean") return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); #else return JNI.get_${prim.Name}(checkedPeer); #end } @Override public ${prim.Name} get${prim.CapName}AtOffset(long byteOffset) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return (char)getIntAtOffset(byteOffset); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize}") #if ($prim.Name != "byte" && $prim.Name != "boolean") return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); #else return JNI.get_${prim.Name}(checkedPeer); #end } #end #foreach ($sizePrim in ["SizeT", "CLong"]) #macro (setPrimitiveValue $primName $peer $value) #if ($primName != "byte" && $primName != "boolean") JNI.set_${primName}${nativeSuffix}($peer, $value); #else JNI.set_${primName}($peer, value); #end #end @Override public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length) { if (values == null) throw new IllegalArgumentException("Null values"); if (${sizePrim}.SIZE == 8) { setLongsAtOffset(byteOffset, values, valuesOffset, length); } else { int n = length; #declareCheckedPeerAtOffset("byteOffset" "n * 4") long peer = checkedPeer; int valuesIndex = valuesOffset; for (int i = 0; i < n; i++) { int value = (int)values[valuesIndex]; #setPrimitiveValue("int" "peer" "value") peer += 4; valuesIndex++; } } return this; } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, int[] values) { if (${sizePrim}.SIZE == 4) { setIntsAtOffset(byteOffset, values); } else { int n = values.length; #declareCheckedPeerAtOffset("byteOffset" "n * 8") long peer = checkedPeer; for (int i = 0; i < n; i++) { int value = values[i]; #setPrimitiveValue("long" "peer" "value") peer += 8; } } return this; } #end } #end /** * Create a {@code Pointer<T>} type. <br> * For Instance, {@code Pointer.pointerType(Integer.class) } returns a type that represents {@code Pointer<Integer> } */ public static Type pointerType(Type targetType) { return org.bridj.util.DefaultParameterizedType.paramType(Pointer.class, targetType); } /** * Create a {@code IntValuedEnum<T>} type. <br> * For Instance, {@code Pointer.intEnumType(SomeEnum.class) } returns a type that represents {@code IntValuedEnum<SomeEnum> } */ public static <E extends Enum<E>> Type intEnumType(Class<? extends IntValuedEnum<E>> targetType) { return org.bridj.util.DefaultParameterizedType.paramType(IntValuedEnum.class, targetType); } /** * Manually release the memory pointed by this pointer if it was allocated on the Java side.<br> * If the pointer is an offset version of another pointer (using {@link Pointer#offset(long)} or {@link Pointer#next(long)}, for instance), this method tries to release the original pointer.<br> * If the memory was not allocated from the Java side, this method does nothing either.<br> * If the memory was already successfully released, this throws a RuntimeException. * @throws RuntimeException if the pointer was already released */ public synchronized void release() { Object sibling = this.sibling; this.sibling = null; if (sibling instanceof Pointer) ((Pointer)sibling).release(); } /** * Compare to another pointer based on pointed addresses. * @param p other pointer * @return 1 if this pointer's address is greater than p's (or if p is null), -1 if the opposite is true, 0 if this and p point to the same memory location. */ //@Override public int compareTo(Pointer<?> p) { if (p == null) return 1; long p1 = getPeer(), p2 = p.getPeer(); return p1 == p2 ? 0 : p1 < p2 ? -1 : 1; } /** * Compare the byteCount bytes at the memory location pointed by this pointer to the byteCount bytes at the memory location pointer by other using the C @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcmp/">memcmp</a> function.<br> * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytes(Pointer<?> other, long byteCount) { return compareBytesAtOffset(0, other, 0, byteCount); } /** * Compare the byteCount bytes at the memory location pointed by this pointer shifted by byteOffset to the byteCount bytes at the memory location pointer by other shifted by otherByteOffset using the C @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcmp/">memcmp</a> function.<br> * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues) * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytesAtOffset(long byteOffset, Pointer<?> other, long otherByteOffset, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") return JNI.memcmp(checkedPeer, other.getCheckedPeer(otherByteOffset, byteCount), byteCount); } /** * Compute a hash code based on pointed address. */ @Override public int hashCode() { int hc = new Long(getPeer()).hashCode(); return hc; } @Override public String toString() { return "Pointer(peer = 0x" + Long.toHexString(getPeer()) + ", targetType = " + Utils.toString(getTargetType()) + ", order = " + order() + ")"; } protected final void invalidPeer(long peer, long validityCheckLength) { throw new IndexOutOfBoundsException("Cannot access to memory data of length " + validityCheckLength + " at offset " + (peer - getPeer()) + " : valid memory start is " + validStart + ", valid memory size is " + (validEnd - validStart)); } private final long getCheckedPeer(long byteOffset, long validityCheckLength) { #declareCheckedPeerAtOffset("byteOffset" "validityCheckLength") return checkedPeer; } /** * Returns a pointer which address value was obtained by this pointer's by adding a byte offset.<br> * The returned pointer will prevent the memory associated to this pointer from being automatically reclaimed as long as it lives, unless Pointer.release() is called on the originally-allocated pointer. * @param byteOffset offset in bytes of the new pointer vs. this pointer. The expression {@code p.offset(byteOffset).getPeer() - p.getPeer() == byteOffset} is always true. */ public Pointer<T> offset(long byteOffset) { return offset(byteOffset, getIO()); } <U> Pointer<U> offset(long byteOffset, PointerIO<U> pio) { if (byteOffset == 0) return pio == this.io ? (Pointer<U>)this : as(pio); long newPeer = getPeer() + byteOffset; Object newSibling = getSibling() != null ? getSibling() : this; if (validStart == UNKNOWN_VALIDITY) return newPointer(pio, newPeer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, newSibling); if (newPeer > validEnd || newPeer < validStart) throw new IndexOutOfBoundsException("Invalid pointer offset : " + byteOffset + " (validBytes = " + getValidBytes() + ") !"); return newPointer(pio, newPeer, isOrdered(), validStart, validEnd, null, NO_PARENT, null, newSibling); } /** * Creates a pointer that has the given number of valid bytes ahead.<br> * If the pointer was already bound, the valid bytes must be lower or equal to the current getValidBytes() value. */ public Pointer<T> validBytes(long byteCount) { long peer = getPeer(); long newValidEnd = peer + byteCount; if (validStart == peer && validEnd == newValidEnd) return this; if (validEnd != UNKNOWN_VALIDITY && newValidEnd > validEnd) throw new IndexOutOfBoundsException("Cannot extend validity of pointed memory from " + validEnd + " to " + newValidEnd); Object newSibling = getSibling() != null ? getSibling() : this; return newPointer(getIO(), peer, isOrdered(), validStart, newValidEnd, parent, offsetInParent, null, newSibling); } /** * Creates a pointer that forgot any memory validity information.<br> * Such pointers are typically faster than validity-aware pointers, since they perform less checks at each operation, but they're more prone to crashes if misused. * @deprecated Pointers obtained via this method are faster but unsafe and are likely to cause crashes hard to debug if your logic is wrong. */ @Deprecated public Pointer<T> withoutValidityInformation() { long peer = getPeer(); if (validStart == UNKNOWN_VALIDITY) return this; Object newSibling = getSibling() != null ? getSibling() : this; return newPointer(getIO(), peer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, parent, offsetInParent, null, newSibling); } /** * Creates a copy of the pointed memory location (allocates a new area of memory) and returns a pointer to it.<br> * The pointer's bounds must be known (see {@link Pointer#getValidBytes()}, {@link Pointer#validBytes(long)} or {@link Pointer#validElements(long)}). */ public Pointer<T> clone() { long length = getValidElements(); if (length < 0) throw new UnsupportedOperationException("Number of bytes unknown, unable to clone memory (use validBytes(long))"); Pointer<T> c = allocateArray(getIO(), length); copyTo(c); return c; } /** * Creates a pointer that has the given number of valid elements ahead.<br> * If the pointer was already bound, elementCount must be lower or equal to the current getValidElements() value. */ public Pointer<T> validElements(long elementCount) { return validBytes(elementCount * getIO("Cannot define elements validity").getTargetSize()); } /** * Returns a pointer to this pointer.<br> * It will only succeed if this pointer was dereferenced from another pointer.<br> * Let's take the following C++ code : * <pre>{@code int** pp = ...; int* p = pp[10]; int** ref = &p; ASSERT(pp == ref); }</pre> * Here is its equivalent Java code : * <pre>{@code Pointer<Pointer<Integer>> pp = ...; Pointer<Integer> p = pp.get(10); Pointer<Pointer<Integer>> ref = p.getReference(); assert pp.equals(ref); }</pre> */ public Pointer<Pointer<T>> getReference() { if (parent == null) throw new UnsupportedOperationException("Cannot get reference to this pointer, it wasn't created from Pointer.getPointer(offset) or from a similar method."); PointerIO io = getIO(); return parent.offset(offsetInParent).as(io == null ? null : io.getReferenceIO()); } /** * Get the address of the memory pointed to by this pointer ("cast this pointer to long", in C jargon).<br> * This is equivalent to the C code {@code (size_t)&pointer} * @return Address of the memory pointed to by this pointer */ public final long getPeer() { return peer; } /** * Create a native callback which signature corresponds to the provided calling convention, return type and parameter types, and which redirects calls to the provided Java {@link org.bridj.DynamicCallback} handler.<br/> * For instance, a callback of C signature <code>double (*)(float, int)</code> that adds its two arguments can be created with :<br> * <code>{@code * Pointer callback = Pointer.allocateDynamicCallback( * new DynamicCallback<Integer>() { * public Double apply(Object... args) { * float a = (Float)args[0]; * int b = (Integer)args[1]; * return (double)(a + b); * } * }, * null, // Use the platform's default calling convention * int.class, // return type * float.class, double.class // parameter types * ); * }</code><br> * For the <code>void</code> return type, you can use {@link java.lang.Void} :<br> * <code>{@code * Pointer callback = Pointer.allocateDynamicCallback( * new DynamicCallback<Void>() { * public Void apply(Object... args) { * ... * return null; // Void cannot be instantiated anyway ;-) * } * }, * null, // Use the platform's default calling convention * int.class, // return type * float.class, double.class // parameter types * ); * }</code><br> * @return Pointer to a native callback that redirects calls to the provided Java callback instance, and that will be destroyed whenever the pointer is released (make sure you keep a reference to it !) */ public static <R> Pointer<DynamicFunction<R>> allocateDynamicCallback(DynamicCallback<R> callback, org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { if (callback == null) throw new IllegalArgumentException("Java callback handler cannot be null !"); if (returnType == null) throw new IllegalArgumentException("Callback return type cannot be null !"); if (parameterTypes == null) throw new IllegalArgumentException("Invalid (null) list of parameter types !"); try { MethodCallInfo mci = new MethodCallInfo(returnType, parameterTypes, false); Method method = DynamicCallback.class.getMethod("apply", Object[].class); mci.setMethod(method); mci.setJavaSignature("([Ljava/lang/Object;)Ljava/lang/Object;"); mci.setCallingConvention(callingConvention); mci.setGenericCallback(true); mci.setJavaCallback(callback); //System.out.println("Java sig return CRuntime.createCToJavaCallback(mci, DynamicCallback.class); } catch (Exception ex) { throw new RuntimeException("Failed to allocate dynamic callback for convention " + callingConvention + ", return type " + Utils.toString(returnType) + " and parameter types " + Arrays.asList(parameterTypes) + " : " + ex, ex); } } /** * Cast this pointer to another pointer type * @param newIO */ public <U> Pointer<U> as(PointerIO<U> newIO) { return viewAs(isOrdered(), newIO); } /** * Create a view of this pointer that has the byte order provided in argument, or return this if this pointer already uses the requested byte order. * @param order byte order (endianness) of the returned pointer */ public Pointer<T> order(ByteOrder order) { if (order.equals(ByteOrder.nativeOrder()) == isOrdered()) return this; return viewAs(!isOrdered(), getIO()); } /** * Get the byte order (endianness) of this pointer. */ public ByteOrder order() { ByteOrder order = isOrdered() ? ByteOrder.nativeOrder() : ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; return order; } <U> Pointer<U> viewAs(boolean ordered, PointerIO<U> newIO) { if (newIO == io && ordered == isOrdered()) return (Pointer<U>)this; else return newPointer(newIO, getPeer(), ordered, getValidStart(), getValidEnd(), getParent(), getOffsetInParent(), null, getSibling() != null ? getSibling() : this); } /** * Get the PointerIO instance used by this pointer to get and set pointed values. */ public final PointerIO<T> getIO() { return io; } /** * Whether this pointer reads data in the system's native byte order or not. * See {@link Pointer#order()}, {@link Pointer#order(ByteOrder)} */ public abstract boolean isOrdered(); final long getOffsetInParent() { return offsetInParent; } final Pointer<?> getParent() { return parent; } final Object getSibling() { return sibling; } final long getValidEnd() { return validEnd; } final long getValidStart() { return validStart; } /** * Cast this pointer to another pointer type<br> * Synonym of {@link Pointer#as(Class)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); * }</code><br> * @param <U> type of the elements pointed by the returned pointer * @param type type of the elements pointed by the returned pointer * @return pointer to type U elements at the same address as this pointer */ public <U> Pointer<U> as(Type type) { PointerIO<U> pio = PointerIO.getInstance(type); return as(pio); } /** * Cast this pointer to another pointer type.<br> * Synonym of {@link Pointer#as(Type)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); // or pointerT.as(U.class); * }</code><br> * @param <U> type of the elements pointed by the returned pointer * @param type type of the elements pointed by the returned pointer * @return pointer to type U elements at the same address as this pointer */ public <U> Pointer<U> as(Class<U> type) { return as((Type)type); } /** * Cast this pointer as a function pointer to a function that returns the specified return type and takes the specified parameter types.<br> * See for instance the following C code that uses a function pointer : * <pre>{@code * double (*ptr)(int, const char*) = someAddress; * double result = ptr(10, "hello"); * }</pre> * Its Java equivalent with BridJ is the following : * <pre>{@code * DynamicFunction ptr = someAddress.asDynamicFunction(null, double.class, int.class, Pointer.class); * double result = (Double)ptr.apply(10, pointerToCString("hello")); * }</pre> * Also see {@link CRuntime#getDynamicFunctionFactory(org.bridj.NativeLibrary, org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } for more options. * @param callingConvention calling convention used by the function (if null, default is typically {@link org.bridj.ann.Convention.Style#CDecl}) * @param returnType return type of the function * @param parameterTypes parameter types of the function */ public <R> DynamicFunction<R> asDynamicFunction(org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { return CRuntime.getInstance().getDynamicFunctionFactory(null, callingConvention, returnType, parameterTypes).newInstance(this); } /** * Cast this pointer to an untyped pointer.<br> * Synonym of {@code ptr.as((Class<?>)null)}.<br> * See {@link Pointer#as(Class)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * void* pointer = (void*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<?> pointer = pointerT.asUntyped(); // or pointerT.as((Class<?>)null); * }</code><br> * @return untyped pointer pointing to the same address as this pointer */ public Pointer<?> asUntyped() { return as((Class<?>)null); } /** * Get the amount of memory known to be valid from this pointer, or -1 if it is unknown.<br> * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) * @return amount of bytes that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getValidBytes() { long ve = getValidEnd(); return ve == UNKNOWN_VALIDITY ? -1 : ve - getPeer(); } /** * Get the amount of memory known to be valid from this pointer (expressed in elements of the target type, see {@link Pointer#getTargetType()}) or -1 if it is unknown.<br> * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) * @return amount of elements that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getValidElements() { long bytes = getValidBytes(); long elementSize = getTargetSize(); if (bytes < 0 || elementSize <= 0) return -1; return bytes / elementSize; } /** * Returns an iterator over the elements pointed by this pointer.<br> * If this pointer was allocated from Java with the allocateXXX, pointerToXXX methods (or is a view or a clone of such a pointer), the iteration is safely bounded.<br> * If this iterator is just a wrapper for a native-allocated pointer (or a view / clone of such a pointer), iteration will go forever (until illegal areas of memory are reached and cause a JVM crash). */ public ListIterator<T> iterator() { return new ListIterator<T>() { Pointer<T> next = Pointer.this.getValidElements() != 0 ? Pointer.this : null; Pointer<T> previous; //@Override public T next() { if (next == null) throw new NoSuchElementException(); T value = next.get(); previous = next; long valid = next.getValidElements(); next = valid < 0 || valid > 1 ? next.next(1) : null; return value; } //@Override public void remove() { throw new UnsupportedOperationException(); } //@Override public boolean hasNext() { long rem; return next != null && ((rem = next.getValidBytes()) < 0 || rem > 0); } //@Override public void add(T o) { throw new UnsupportedOperationException(); } //@Override public boolean hasPrevious() { return previous != null; } //@Override public int nextIndex() { throw new UnsupportedOperationException(); } //@Override public T previous() { //TODO return previous; throw new UnsupportedOperationException(); } //@Override public int previousIndex() { throw new UnsupportedOperationException(); } //@Override public void set(T o) { if (previous == null) throw new NoSuchElementException("You haven't called next() prior to calling ListIterator.set(E)"); previous.set(o); } }; } /** * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) */ public static <N extends NativeObject> Pointer<N> pointerTo(N instance) { return pointerTo(instance, null); } /** * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) */ public static <N extends NativeObjectInterface> Pointer<N> pointerTo(N instance) { return (Pointer)pointerTo((NativeObject)instance); } /** * Get a pointer to a native object, specifying the type of the pointer's target.<br> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static <R extends NativeObject> Pointer<R> pointerTo(NativeObject instance, Type targetType) { return instance == null ? null : (Pointer<R>)instance.peer; } /** * Get the address of a native object, specifying the type of the pointer's target (same as {@code pointerTo(instance, targetType).getPeer()}, see {@link Pointer#pointerTo(NativeObject, Type)}).<br> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static long getAddress(NativeObject instance, Class targetType) { return getPeer(pointerTo(instance, targetType)); } #docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Type)") public <O extends NativeObject> O getNativeObjectAtOffset(long byteOffset, Type type) { return (O)BridJ.createNativeObjectFromPointer((Pointer<O>)(byteOffset == 0 ? this : offset(byteOffset)), type); } #docSet("native object", "O extends NativeObject") public <O extends NativeObject> Pointer<T> setNativeObject(O value, Type type) { BridJ.copyNativeObjectToAddress(value, type, (Pointer)this); return this; } #docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Class)") public <O extends NativeObject> O getNativeObjectAtOffset(long byteOffset, Class<O> type) { return (O)getNativeObjectAtOffset(byteOffset, (Type)type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Class<O> type) { return (O)getNativeObject((Type)type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Type type) { O o = (O)getNativeObjectAtOffset(0, type); return o; } /** * Check that the pointer's peer is aligned to the target type alignment. * @throws RuntimeException If the target type of this pointer is unknown * @return getPeer() % alignment == 0 */ public boolean isAligned() { return isAligned(getIO("Cannot check alignment").getTargetAlignment()); } /** * Check that the pointer's peer is aligned to the given alignment. * If the pointer has no peer, this method returns true. * @return getPeer() % alignment == 0 */ public boolean isAligned(long alignment) { return isAligned(getPeer(), alignment); } /** * Check that the provided address is aligned to the given alignment. * @return address % alignment == 0 */ protected static boolean isAligned(long address, long alignment) { return computeRemainder(address, alignment) == 0; } protected static int computeRemainder(long address, long alignment) { switch ((int)alignment) { case -1: case 0: case 1: return 0; case 2: return (int)(address & 1); case 4: return (int)(address & 3); case 8: return (int)(address & 7); case 16: return (int)(address & 15); case 32: return (int)(address & 31); case 64: return (int)(address & 63); default: if (alignment < 0) return 0; return (int)(address % alignment); } } /** * Dereference this pointer (*ptr).<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) printf("%i\n", *array); }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { System.out.println("%i\n".format(array.get())); array = array.next(); } }</pre> Here is a simpler equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int value : array) // array knows its size, so we can iterate on it System.out.println("%i\n".format(value)); }</pre> @throws RuntimeException if called on an untyped {@code Pointer<?>} instance (see {@link Pointer#getTargetType()}) */ public T get() { return get(0); } /** * Returns null if pointer is null, otherwise dereferences the pointer (calls pointer.get()). */ public static <T> T get(Pointer<T> pointer) { return pointer == null ? null : pointer.get(); } /** Gets the n-th element from this pointer.<br> This is equivalent to the C/C++ square bracket syntax.<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; int index = 5; int value = array[index]; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); int index = 5; int value = array.get(index); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @throws RuntimeException if called on an untyped {@code Pointer<?>} instance ({@link Pointer#getTargetType()}) */ public T get(long index) { return getIO("Cannot get pointed value").get(this, index); } /** Assign a value to the pointed memory location, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) { int value = index; *array = value; } }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { int value = index; array.set(value); array = array.next(); } }</pre> @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) */ public T set(T value) { return set(0, value); } private static long getTargetSizeToAllocateArrayOrThrow(PointerIO<?> io) { long targetSize = -1; if (io == null || (targetSize = io.getTargetSize()) < 0) throwBecauseUntyped("Cannot allocate array "); return targetSize; } private static void throwBecauseUntyped(String message) { throw new RuntimeException("Pointer is not typed (call Pointer.as(Type) to create a typed pointer) : " + message); } static void throwUnexpected(Throwable ex) { throw new RuntimeException("Unexpected error", ex); } /** Sets the n-th element from this pointer, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).<br> This is equivalent to the C/C++ square bracket assignment syntax.<br> Take the following C++ code fragment : <pre>{@code float* array = new float[10]; int index = 5; float value = 12; array[index] = value; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Float> array = allocateFloats(10); int index = 5; float value = 12; array.set(index, value); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @param value value to set at pointed memory location @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) */ public T set(long index, T value) { getIO("Cannot set pointed value").set(this, index, value); return value; } /** * Get a pointer's peer (see {@link Pointer#getPeer}), or zero if the pointer is null. */ public static long getPeer(Pointer<?> pointer) { return pointer == null ? 0 : pointer.getPeer(); } /** * Get the unitary size of the pointed elements in bytes. * @throws RuntimeException if the target type is unknown (see {@link Pointer#getTargetType()}) */ public long getTargetSize() { return getIO("Cannot compute target size").getTargetSize(); } /** * Returns a pointer to the next target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return next(1) */ public Pointer<T> next() { return next(1); } /** * Returns a pointer to the n-th next (or previous) target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return offset(getTargetSize() * delta) */ public Pointer<T> next(long delta) { return offset(getIO("Cannot get pointers to next or previous targets").getTargetSize() * delta); } /** * Release pointers, if they're not null (see {@link Pointer#release}). */ public static void release(Pointer... pointers) { for (Pointer pointer : pointers) if (pointer != null) pointer.release(); } /** * Test equality of the pointer using the address.<br> * @return true if and only if obj is a Pointer instance and {@code obj.getPeer() == this.getPeer() } */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Pointer)) return false; Pointer p = (Pointer)obj; return getPeer() == p.getPeer(); } /** * Create a pointer out of a native memory address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == address } */ @Deprecated public static Pointer<?> pointerToAddress(long peer) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, long size) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, Class<P> targetClass, final Releaser releaser) { return pointerToAddress(peer, (Type)targetClass, releaser); } /** * Create a pointer out of a native memory address * @param targetType type of the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, Type targetType, final Releaser releaser) { PointerIO<P> pio = PointerIO.getInstance(targetType); return newPointer(pio, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, releaser, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io, Releaser releaser) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, Releaser releaser) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static Pointer<?> pointerToAddress(long peer, long size, Releaser releaser) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, long size, PointerIO<P> io, Releaser releaser) { return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static <P> Pointer<P> pointerToAddress(long peer, Class<P> targetClass) { return pointerToAddress(peer, (Type)targetClass); } /** * Create a pointer out of a native memory address * @param targetType type of the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static <P> Pointer<P> pointerToAddress(long peer, Type targetType) { return newPointer((PointerIO<P>)PointerIO.getInstance(targetType), peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> pointerToAddress(long peer, long size, PointerIO<U> io) { return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> newPointer( PointerIO<U> io, long peer, boolean ordered, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, final Releaser releaser, Object sibling) { if (peer == 0) return null; if (validEnd != UNKNOWN_VALIDITY) { long size = validEnd - validStart; if (size <= 0) return null; } if (releaser == null) { if (ordered) { return new OrderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } else { return new DisorderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } } else { assert sibling == null; #macro (bodyOfPointerWithReleaser) private volatile Releaser rel = releaser; //@Override public synchronized void release() { if (rel != null) { Releaser rel = this.rel; this.rel = null; rel.release(this); } } protected void finalize() { release(); } @Deprecated public synchronized Pointer<U> withReleaser(final Releaser beforeDeallocation) { final Releaser thisReleaser = rel; rel = null; return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation == null ? thisReleaser : new Releaser() { //@Override public void release(Pointer<?> p) { beforeDeallocation.release(p); if (thisReleaser != null) thisReleaser.release(p); } }, null); } #end if (ordered) { return new OrderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { #bodyOfPointerWithReleaser() }; } else { return new DisorderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { #bodyOfPointerWithReleaser() }; } } } #docAllocate("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointer(Class<P> type) { return (Pointer<P>)(Pointer)allocate(PointerIO.getInstance(type)); } #docAllocateArray("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointers(Class<P> type, long arrayLength) { return (Pointer<P>)(Pointer)allocateArray(PointerIO.getInstance(type), arrayLength); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Class<P> targetType) { return allocatePointer((Type)targetType); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Type targetType) { return (Pointer<Pointer<P>>)(Pointer)allocate(PointerIO.getPointerInstance(targetType)); } /** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Type targetType) { return allocatePointer(pointerType(targetType)); }/** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Class<P> targetType) { return allocatePointerPointer((Type)targetType); } #docAllocate("untyped pointer", "Pointer<?>") /** * Create a memory area large enough to hold an untyped pointer. * @return a pointer to a new memory area large enough to hold a single untyped pointer */ public static <V> Pointer<Pointer<?>> allocatePointer() { return (Pointer)allocate(PointerIO.getPointerInstance()); } #docAllocateArray("untyped pointer", "Pointer<?>") public static Pointer<Pointer<?>> allocatePointers(int arrayLength) { return (Pointer<Pointer<?>>)(Pointer)allocateArray(PointerIO.getPointerInstance(), arrayLength); } /** * Create a memory area large enough to hold an array of arrayLength typed pointers. * @param targetType target type of element pointers in the resulting pointer array. * @param arrayLength size of the allocated array, in elements * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers */ public static <P> Pointer<Pointer<P>> allocatePointers(Class<P> targetType, int arrayLength) { return allocatePointers((Type)targetType, arrayLength); } /** * Create a memory area large enough to hold an array of arrayLength typed pointers. * @param targetType target type of element pointers in the resulting pointer array. * @param arrayLength size of the allocated array, in elements * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers */ public static <P> Pointer<Pointer<P>> allocatePointers(Type targetType, int arrayLength) { return (Pointer<Pointer<P>>)(Pointer)allocateArray(PointerIO.getPointerInstance(targetType), arrayLength); // TODO } /** * Create a memory area large enough to a single items of type elementClass. * @param elementClass type of the array elements * @return a pointer to a new memory area large enough to hold a single item of type elementClass. */ public static <V> Pointer<V> allocate(Class<V> elementClass) { return allocate((Type)elementClass); } /** * Create a memory area large enough to a single items of type elementClass. * @param elementClass type of the array elements * @return a pointer to a new memory area large enough to hold a single item of type elementClass. */ public static <V> Pointer<V> allocate(Type elementClass) { return allocateArray(elementClass, 1); } /** * Create a memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve the element * @return a pointer to a new memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocate(PointerIO<V> io) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io), null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param arrayLength length of the array in elements * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength, final Releaser beforeDeallocation) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, beforeDeallocation); } /** * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param byteSize length of the array in bytes * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes */ public static <V> Pointer<V> allocateBytes(PointerIO<V> io, long byteSize, final Releaser beforeDeallocation) { return allocateAlignedBytes(io, byteSize, defaultAlignment, beforeDeallocation); } /** * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}), ensuring the pointer to the memory is aligned to the provided boundary. * @param io PointerIO instance able to store and retrieve elements of the array * @param byteSize length of the array in bytes * @param alignment boundary to which the returned pointer should be aligned * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes */ public static <V> Pointer<V> allocateAlignedBytes(PointerIO<V> io, long byteSize, int alignment, final Releaser beforeDeallocation) { if (byteSize == 0) return null; if (byteSize < 0) throw new IllegalArgumentException("Cannot allocate a negative amount of memory !"); long address, offset = 0; if (alignment <= 1) address = JNI.mallocNulled(byteSize); else { //address = JNI.mallocNulledAligned(byteSize, alignment); //if (address == 0) { // invalid alignment (< sizeof(void*) or not a power of 2 address = JNI.mallocNulled(byteSize + alignment - 1); long remainder = address % alignment; if (remainder > 0) offset = alignment - remainder; } } if (address == 0) throw new RuntimeException("Failed to allocate " + byteSize); Pointer<V> ptr = newPointer(io, address, true, address, address + byteSize + offset, null, NO_PARENT, beforeDeallocation == null ? freeReleaser : new Releaser() { //@Override public void release(Pointer<?> p) { beforeDeallocation.release(p); freeReleaser.release(p); } }, null); if (offset > 0) ptr = ptr.offset(offset); return ptr; } /** * Create a pointer that depends on this pointer and will call a releaser prior to release this pointer, when it is GC'd.<br> * This pointer MUST NOT be used anymore. * @deprecated This method can easily be misused and is reserved to advanced users. * @param beforeDeallocation releaser that should be run before this pointer's releaser (if any). * @return a new pointer to the same memory location as this pointer */ @Deprecated public synchronized Pointer<T> withReleaser(final Releaser beforeDeallocation) { return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation, null); } static Releaser freeReleaser = new FreeReleaser(); static class FreeReleaser implements Releaser { //@Override public void release(Pointer<?> p) { assert p.getSibling() == null; assert p.validStart == p.getPeer(); if (BridJ.debugPointers) BridJ.info("Freeing pointer " + p + " (peer = " + p.peer + ", validStart = " + p.validStart + ", validEnd = " + p.validEnd + ", validBytes = " + p.getValidBytes() + ")\n(Creation trace = \n\t" + Utils.toString(p.creationTrace).replaceAll("\n", "\n\t") + "\n)", new RuntimeException().fillInStackTrace()); if (!BridJ.debugNeverFree) JNI.free(p.getPeer()); } } /** * Create a memory area large enough to hold arrayLength items of type elementClass. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateArray(Class<V> elementClass, long arrayLength) { return allocateArray((Type)elementClass, arrayLength); } /** * Create a memory area large enough to hold arrayLength items of type elementClass. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateArray(Type elementClass, long arrayLength) { if (arrayLength == 0) return null; PointerIO pio = PointerIO.getInstance(elementClass); if (pio == null) throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); return (Pointer<V>)allocateArray(pio, arrayLength); } /** * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param alignment boundary to which the returned pointer should be aligned * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateAlignedArray(Class<V> elementClass, long arrayLength, int alignment) { return allocateAlignedArray((Type)elementClass, arrayLength, alignment); } /** * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param alignment boundary to which the returned pointer should be aligned * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateAlignedArray(Type elementClass, long arrayLength, int alignment) { PointerIO io = PointerIO.getInstance(elementClass); if (io == null) throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); return allocateAlignedBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, alignment, null); } /** * Create a pointer to the memory location used by a direct NIO buffer.<br> * If the NIO buffer is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerToArray(Object)}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.<br> * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer. */ public static Pointer<?> pointerToBuffer(Buffer buffer) { if (buffer == null) return null; #foreach ($prim in $primitivesNoBool) if (buffer instanceof ${prim.BufferName}) return (Pointer)pointerTo${prim.CapName}s((${prim.BufferName})buffer); #end throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); } /** * When a pointer was created with {@link Pointer#pointerToBuffer(Buffer)} on a non-direct buffer, a native copy of the buffer data was made. * This method updates the original buffer with the native memory, and does nothing if the buffer is direct <b>and</b> points to the same memory location as this pointer.<br> * @throws IllegalArgumentException if buffer is direct and does not point to the exact same location as this Pointer instance */ public void updateBuffer(Buffer buffer) { if (buffer == null) throw new IllegalArgumentException("Cannot update a null Buffer !"); if (Utils.isDirect(buffer)) { long address = JNI.getDirectBufferAddress(buffer); if (address != getPeer()) { throw new IllegalArgumentException("Direct buffer does not point to the same location as this Pointer instance, updating it makes no sense !"); } } else { #foreach ($prim in $primitivesNoBool) #if ($prim.Name != "char") if (buffer instanceof ${prim.BufferName}) { ((${prim.BufferName})buffer).duplicate().put(get${prim.BufferName}()); return; } #end #end throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); } } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive: $prim.Name -- #docAllocateCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}(${prim.Name} value) { Pointer<${prim.WrapperName}> mem = allocate(PointerIO.get${prim.CapName}Instance()); mem.set${prim.CapName}(value); return mem; } #docAllocateArrayCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.Name}... values) { if (values == null) return null; Pointer<${prim.WrapperName}> mem = allocateArray(PointerIO.get${prim.CapName}Instance(), values.length); mem.set${prim.CapName}sAtOffset(0, values, 0, values.length); return mem; } #docAllocateArray2DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> pointerTo${prim.CapName}s(${prim.Name}[][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length; Pointer<Pointer<${prim.WrapperName}>> mem = allocate${prim.CapName}s(dim1, dim2); for (int i1 = 0; i1 < dim1; i1++) mem.set${prim.CapName}sAtOffset(i1 * dim2 * ${primSize}, values[i1], 0, dim2); return mem; } #docAllocateArray3DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> pointerTo${prim.CapName}s(${prim.Name}[][][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length, dim3 = values[0][0].length; Pointer<Pointer<Pointer<${prim.WrapperName}>>> mem = allocate${prim.CapName}s(dim1, dim2, dim3); for (int i1 = 0; i1 < dim1; i1++) { int offset1 = i1 * dim2; for (int i2 = 0; i2 < dim2; i2++) { int offset2 = (offset1 + i2) * dim3; mem.set${prim.CapName}sAtOffset(offset2 * ${primSize}, values[i1][i2], 0, dim3); } } return mem; } #docAllocate($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}() { return allocate(PointerIO.get${prim.CapName}Instance()); } #docAllocateArray($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}s(long arrayLength) { return allocateArray(PointerIO.get${prim.CapName}Instance(), arrayLength); } #docAllocateArray2D($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> allocate${prim.CapName}s(long dim1, long dim2) { return allocateArray(PointerIO.getArrayInstance(PointerIO.get${prim.CapName}Instance(), new long[] { dim1, dim2 }, 0), dim1); } #docAllocateArray3D($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> allocate${prim.CapName}s(long dim1, long dim2, long dim3) { long[] dims = new long[] { dim1, dim2, dim3 }; return allocateArray( PointerIO.getArrayInstance( //PointerIO.get${prim.CapName}Instance(), PointerIO.getArrayInstance( PointerIO.get${prim.CapName}Instance(), dims, 1 ), dims, 0 ), dim1 ) ; } #end #foreach ($prim in $primitivesNoBool) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive (no bool): $prim.Name -- /** * Create a pointer to the memory location used by a direct NIO ${prim.BufferName}.<br> * If the NIO ${prim.BufferName} is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.<br> * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer.</br> */ public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.BufferName} buffer) { if (buffer == null) return null; if (!buffer.isDirect()) { return pointerTo${prim.CapName}s(buffer.array()); //throw new UnsupportedOperationException("Cannot create pointers to indirect ${prim.BufferName} buffers"); } long address = JNI.getDirectBufferAddress(buffer); long size = JNI.getDirectBufferCapacity(buffer); // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! size *= ${primSize}; //System.out.println("Buffer capacity = " + size); if (address == 0 || size == 0) return null; PointerIO<${prim.WrapperName}> io = CommonPointerIOs.${prim.Name}IO; boolean ordered = buffer.order().equals(ByteOrder.nativeOrder()); return newPointer(io, address, ordered, address, address + size, null, NO_PARENT, null, buffer); } #end /** * Get the type of pointed elements. */ public Type getTargetType() { PointerIO<T> io = getIO(); return io == null ? null : io.getTargetType(); } /** * Read an untyped pointer value from the pointed memory location * @deprecated Avoid using untyped pointers, if possible. */ @Deprecated public Pointer<?> getPointer() { return getPointerAtOffset(0, (PointerIO)null); } /** * Read a pointer value from the pointed memory location shifted by a byte offset */ public Pointer<?> getPointerAtOffset(long byteOffset) { return getPointerAtOffset(byteOffset, (PointerIO)null); } #docGetIndex("pointer" "getPointerAtOffset(valueIndex * Pointer.SIZE)") public Pointer<?> getPointerAtIndex(long valueIndex) { return getPointerAtOffset(valueIndex * Pointer.SIZE); } /** * Read a pointer value from the pointed memory location.<br> * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(Class<U> c) { return getPointerAtOffset(0, (PointerIO<U>)PointerIO.getInstance(c)); } /** * Read a pointer value from the pointed memory location * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(PointerIO<U> pio) { return getPointerAtOffset(0, pio); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, Class<U> c) { return getPointerAtOffset(byteOffset, (Type)c); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param t type of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, Type t) { return getPointerAtOffset(byteOffset, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, PointerIO<U> pio) { long value = getSizeTAtOffset(byteOffset); if (value == 0) return null; return newPointer(pio, value, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, this, byteOffset, null, null); } /** * Write a pointer value to the pointed memory location */ public Pointer<T> setPointer(Pointer<?> value) { return setPointerAtOffset(0, value); } /** * Write a pointer value to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointerAtOffset(long byteOffset, Pointer<?> value) { setSizeTAtOffset(byteOffset, value == null ? 0 : value.getPeer()); return this; } #docSetIndex("pointer" "setPointerAtOffset(valueIndex * Pointer.SIZE, value)") public Pointer<T> setPointerAtIndex(long valueIndex, Pointer<?> value) { setPointerAtOffset(valueIndex * Pointer.SIZE, value); return this; } /** * Read an array of untyped pointer values from the pointed memory location shifted by a byte offset * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ public Pointer<?>[] getPointersAtOffset(long byteOffset, int arrayLength) { return getPointersAtOffset(byteOffset, arrayLength, (PointerIO)null); } /** * Read the array of remaining untyped pointer values from the pointed memory location * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ @Deprecated public Pointer<?>[] getPointers() { long rem = getValidElements("Cannot create array if remaining length is not known. Please use getPointers(int length) instead."); return getPointersAtOffset(0L, (int)rem); } /** * Read an array of untyped pointer values from the pointed memory location * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ @Deprecated public Pointer<?>[] getPointers(int arrayLength) { return getPointersAtOffset(0, arrayLength); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t type of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, Type t) { return getPointersAtOffset(byteOffset, arrayLength, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t class of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, Class<U> t) { return getPointersAtOffset(byteOffset, arrayLength, (Type)t); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, PointerIO pio) { Pointer<U>[] values = (Pointer<U>[])new Pointer[arrayLength]; int s = Platform.POINTER_SIZE; for (int i = 0; i < arrayLength; i++) values[i] = getPointerAtOffset(byteOffset + i * s, pio); return values; } /** * Write an array of pointer values to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointersAtOffset(long byteOffset, Pointer<?>[] values) { return setPointersAtOffset(byteOffset, values, 0, values.length); } /** * Write length pointer values from the given array (starting at the given value offset) to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointersAtOffset(long byteOffset, Pointer<?>[] values, int valuesOffset, int length) { if (values == null) throw new IllegalArgumentException("Null values"); int n = length, s = Platform.POINTER_SIZE; for (int i = 0; i < n; i++) setPointerAtOffset(byteOffset + i * s, values[valuesOffset + i]); return this; } /** * Write an array of pointer values to the pointed memory location */ public Pointer<T> setPointers(Pointer<?>[] values) { return setPointersAtOffset(0, values); } /** * Read an array of elements from the pointed memory location shifted by a byte offset.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArrayAtOffset(long byteOffset, int length) { return getIO("Cannot create sublist").getArray(this, byteOffset, length); } /** * Read an array of elements from the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArray(int length) { return getArrayAtOffset(0L, length); } /** * Read the array of remaining elements from the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArray() { return getArray((int)getValidElements()); } /** * Read an NIO {@link Buffer} of elements from the pointed memory location shifted by a byte offset.<br> * @return an NIO {@link Buffer} of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBufferAtOffset(long byteOffset, int length) { return (B)getIO("Cannot create Buffer").getBuffer(this, byteOffset, length); } /** * Read an NIO {@link Buffer} of elements from the pointed memory location.<br> * @return an NIO {@link Buffer} of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBuffer(int length) { return (B)getBufferAtOffset(0L, length); } /** * Read the NIO {@link Buffer} of remaining elements from the pointed memory location.<br> * @return an array of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBuffer() { return (B)getBuffer((int)getValidElements()); } /** * Write an array of elements to the pointed memory location shifted by a byte offset.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) */ public Pointer<T> setArrayAtOffset(long byteOffset, Object array) { getIO("Cannot create sublist").setArray(this, byteOffset, array); return this; } /** * Allocate enough memory for array.length values, copy the values of the array provided as argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) * @param array primitive array containing the initial values for the created memory area * @return pointer to a new memory location that initially contains the consecutive values provided in argument */ public static <T> Pointer<T> pointerToArray(Object array) { if (array == null) return null; PointerIO<T> io = PointerIO.getArrayIO(array); if (io == null) throwBecauseUntyped("Cannot create pointer to array"); Pointer<T> ptr = allocateArray(io, java.lang.reflect.Array.getLength(array)); io.setArray(ptr, 0, array); return ptr; } /** * Write an array of elements to the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) */ public Pointer<T> setArray(Object array) { return setArrayAtOffset(0L, array); } #foreach ($sizePrim in ["SizeT", "CLong"]) //-- size primitive: $sizePrim -- #docAllocateCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}(long value) { Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); p.set${sizePrim}(value); return p; } #docAllocateCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}(${sizePrim} value) { Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); p.set${sizePrim}(value); return p; } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(long... values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(${sizePrim}... values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(int[] values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArray($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}s(long arrayLength) { return allocateArray(PointerIO.get${sizePrim}Instance(), arrayLength); } #docAllocate($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}() { return allocate(PointerIO.get${sizePrim}Instance()); } #docGet($sizePrim $sizePrim) public long get${sizePrim}() { return ${sizePrim}.SIZE == 8 ? getLong() : getInt(); } #docGetOffset($sizePrim $sizePrim "Pointer#get${sizePrim}()") public long get${sizePrim}AtOffset(long byteOffset) { return ${sizePrim}.SIZE == 8 ? getLongAtOffset(byteOffset) : getIntAtOffset(byteOffset); } #docGetIndex($sizePrim "get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE") public long get${sizePrim}AtIndex(long valueIndex) { return get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE); } #docGetRemainingArray($sizePrim $sizePrim) public long[] get${sizePrim}s() { long rem = getValidElements("Cannot create array if remaining length is not known. Please use get${sizePrim}s(int length) instead."); if (${sizePrim}.SIZE == 8) return getLongs((int)rem); return get${sizePrim}s((int)rem); } #docGetArray($sizePrim $sizePrim) public long[] get${sizePrim}s(int arrayLength) { if (${sizePrim}.SIZE == 8) return getLongs(arrayLength); return get${sizePrim}sAtOffset(0, arrayLength); } #docGetArrayOffset($sizePrim $sizePrim "Pointer#get${sizePrim}s(int)") public long[] get${sizePrim}sAtOffset(long byteOffset, int arrayLength) { if (${sizePrim}.SIZE == 8) return getLongsAtOffset(byteOffset, arrayLength); int[] values = getIntsAtOffset(byteOffset, arrayLength); long[] ret = new long[arrayLength]; for (int i = 0; i < arrayLength; i++) { ret[i] = //0xffffffffL & values[i]; } return ret; } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(long value) { if (${sizePrim}.SIZE == 8) setLong(value); else { setInt(SizeT.safeIntCast(value)); } return this; } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(${sizePrim} value) { return set${sizePrim}(value.longValue()); } #docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(long)") public Pointer<T> set${sizePrim}AtOffset(long byteOffset, long value) { if (${sizePrim}.SIZE == 8) setLongAtOffset(byteOffset, value); else { setIntAtOffset(byteOffset, SizeT.safeIntCast(value)); } return this; } #docSetIndex($sizePrim "set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value)") public Pointer<T> set${sizePrim}AtIndex(long valueIndex, long value) { return set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value); } #docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(${sizePrim})") public Pointer<T> set${sizePrim}AtOffset(long byteOffset, ${sizePrim} value) { return set${sizePrim}AtOffset(byteOffset, value.longValue()); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long[] values) { if (${sizePrim}.SIZE == 8) return setLongs(values); return set${sizePrim}sAtOffset(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(int[] values) { if (${sizePrim}.SIZE == 4) return setInts(values); return set${sizePrim}sAtOffset(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(${sizePrim}[] values) { return set${sizePrim}sAtOffset(0, values); } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values) { return set${sizePrim}sAtOffset(byteOffset, values, 0, values.length); } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") public abstract Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length); #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(${sizePrim}...)") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, ${sizePrim}... values) { if (values == null) throw new IllegalArgumentException("Null values"); int n = values.length, s = ${sizePrim}.SIZE; for (int i = 0; i < n; i++) set${sizePrim}AtOffset(byteOffset + i * s, values[i].longValue()); return this; } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") public abstract Pointer<T> set${sizePrim}sAtOffset(long byteOffset, int[] values); #end void setSignedIntegralAtOffset(long byteOffset, long value, long sizeOfIntegral) { switch ((int)sizeOfIntegral) { case 1: if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) throw new RuntimeException("Value out of byte bounds : " + value); setByteAtOffset(byteOffset, (byte)value); break; case 2: if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) throw new RuntimeException("Value out of short bounds : " + value); setShortAtOffset(byteOffset, (short)value); break; case 4: if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) throw new RuntimeException("Value out of int bounds : " + value); setIntAtOffset(byteOffset, (int)value); break; case 8: setLongAtOffset(byteOffset, value); break; default: throw new IllegalArgumentException("Cannot write integral type of size " + sizeOfIntegral + " (value = " + value + ")"); } } long getSignedIntegralAtOffset(long byteOffset, long sizeOfIntegral) { switch ((int)sizeOfIntegral) { case 1: return getByteAtOffset(byteOffset); case 2: return getShortAtOffset(byteOffset); case 4: return getIntAtOffset(byteOffset); case 8: return getLongAtOffset(byteOffset); default: throw new IllegalArgumentException("Cannot read integral type of size " + sizeOfIntegral); } } #docAllocateCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointer(Pointer<T> value) { Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocate(PointerIO.getPointerInstance()); p.setPointerAtOffset(0, value); return p; } #docAllocateArrayCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointers(Pointer<T>... values) { if (values == null) return null; int n = values.length, s = Pointer.SIZE; PointerIO<Pointer> pio = PointerIO.getPointerInstance(); // TODO get actual pointer instances PointerIO !!! Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocateArray(pio, n); for (int i = 0; i < n; i++) { p.setPointerAtOffset(i * s, values[i]); } return p; } /** * Copy all values from an NIO buffer to the pointed memory location shifted by a byte offset */ public Pointer<T> setValuesAtOffset(long byteOffset, Buffer values) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy length values from an NIO buffer (beginning at element at valuesOffset index) to the pointed memory location shifted by a byte offset */ public Pointer<T> setValuesAtOffset(long byteOffset, Buffer values, int valuesOffset, int length) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values, valuesOffset, length); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy values from an NIO buffer to the pointed memory location */ public Pointer<T> setValues(Buffer values) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}s((${prim.BufferName})values); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function.<br> * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead. */ @Deprecated public Pointer<T> copyBytesAtOffsetTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") JNI.memcpy(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); return this; } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function.<br> * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead.<br> * See {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)} for more options. */ @Deprecated public Pointer<T> copyBytesTo(Pointer<?> destination, long byteCount) { return copyBytesAtOffsetTo(0, destination, 0, byteCount); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ @Deprecated public Pointer<T> moveBytesAtOffsetTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") JNI.memmove(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); return this; } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer, using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ public Pointer<T> moveBytesTo(Pointer<?> destination, long byteCount) { return moveBytesAtOffsetTo(0, destination, 0, byteCount); } /** * Copy all valid bytes from the memory location indicated by this pointer to that of another pointer, using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ public Pointer<T> moveBytesTo(Pointer<?> destination) { return moveBytesTo(destination, getValidBytes("Cannot move an unbounded memory location. Please use validBytes(long).")); } final long getValidBytes(String error) { long rem = getValidBytes(); if (rem < 0) throw new IndexOutOfBoundsException(error); return rem; } final long getValidElements(String error) { long rem = getValidElements(); if (rem < 0) throw new IndexOutOfBoundsException(error); return rem; } final PointerIO<T> getIO(String error) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped(error); return io; } /** * Copy remaining bytes from this pointer to a destination using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function (see {@link Pointer#copyBytesTo(Pointer, long)}, {@link Pointer#getValidBytes()}) */ public Pointer<T> copyTo(Pointer<?> destination) { return copyTo(destination, getValidElements()); } /** * Copy remaining elements from this pointer to a destination using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function (see {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)}, {@link Pointer#getValidBytes}) */ public Pointer<T> copyTo(Pointer<?> destination, long elementCount) { PointerIO<T> io = getIO("Cannot copy untyped pointer without byte count information. Please use copyBytesAtOffsetTo(offset, destination, destinationOffset, byteCount) instead"); return copyBytesAtOffsetTo(0, destination, 0, elementCount * io.getTargetSize()); } /** * Find the first appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (behaviour equivalent to <a href="http://linux.die.net/man/3/memmem">memmem</a>, which is used underneath on platforms where it is available) */ public Pointer<T> find(Pointer<?> needle) { if (needle == null) return null; long firstOccurrence = JNI.memmem( getPeer(), getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), needle.getPeer(), needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") ); return pointerToAddress(firstOccurrence, io); } /** * Find the last appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (also see {@link Pointer#find(Pointer)}). */ public Pointer<T> findLast(Pointer<?> needle) { if (needle == null) return null; long lastOccurrence = JNI.memmem_last( getPeer(), getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), needle.getPeer(), needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") ); return pointerToAddress(lastOccurrence, io); } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive: $prim.Name -- #docSet(${prim.Name} ${prim.WrapperName}) public abstract Pointer<T> set${prim.CapName}(${prim.Name} value); #docSetOffset(${prim.Name} ${prim.WrapperName} "Pointer#set${prim.CapName}(${prim.Name})") public abstract Pointer<T> set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value); #docSetIndex(${prim.Name} "set${prim.CapName}AtOffset(valueIndex * $primSize, value)") public Pointer<T> set${prim.CapName}AtIndex(long valueIndex, ${prim.Name} value) { return set${prim.CapName}AtOffset(valueIndex * $primSize, value); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.Name}[] values) { return set${prim.CapName}sAtOffset(0, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values) { return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given array offset and for the given length from the provided array. */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values, int valuesOffset, int length) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setIntsAtOffset(byteOffset, wcharsToInts(values, valuesOffset, length)); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) { JNI.set_${prim.Name}_array_disordered(checkedPeer, values, valuesOffset, length); return this; } #end JNI.set_${prim.Name}_array(checkedPeer, values, valuesOffset, length); return this; } #docGet(${prim.Name} ${prim.WrapperName}) public abstract ${prim.Name} get${prim.CapName}(); #docGetOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}()") public abstract ${prim.Name} get${prim.CapName}AtOffset(long byteOffset); #docGetIndex(${prim.Name} "get${prim.CapName}AtOffset(valueIndex * $primSize)") public ${prim.Name} get${prim.CapName}AtIndex(long valueIndex) { return get${prim.CapName}AtOffset(valueIndex * $primSize); } #docGetArray(${prim.Name} ${prim.WrapperName}) public ${prim.Name}[] get${prim.CapName}s(int length) { return get${prim.CapName}sAtOffset(0, length); } #docGetRemainingArray(${prim.Name} ${prim.WrapperName}) public ${prim.Name}[] get${prim.CapName}s() { long validBytes = getValidBytes("Cannot create array if remaining length is not known. Please use get${prim.CapName}s(int length) instead."); return get${prim.CapName}s((int)(validBytes / ${primSize})); } #docGetArrayOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}s(int)") public ${prim.Name}[] get${prim.CapName}sAtOffset(long byteOffset, int length) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return intsToWChars(getIntsAtOffset(byteOffset, length)); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) return JNI.get_${prim.Name}_array_disordered(checkedPeer, length); #end return JNI.get_${prim.Name}_array(checkedPeer, length); } #end #foreach ($prim in $primitivesNoBool) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive (no bool): $prim.Name -- #if ($prim.Name != "char") /** * Read ${prim.Name} values into the specified destination array from the pointed memory location */ public void get${prim.CapName}s(${prim.Name}[] dest) { get${prim.BufferName}().get(dest); } /** * Read ${prim.Name} values into the specified destination buffer from the pointed memory location */ public void get${prim.CapName}s(${prim.BufferName} dest) { dest.duplicate().put(get${prim.BufferName}()); } /** * Read length ${prim.Name} values into the specified destination array from the pointed memory location shifted by a byte offset, storing values after the provided destination offset. */ public void get${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] dest, int destOffset, int length) { get${prim.BufferName}AtOffset(byteOffset, length).get(dest, destOffset, length); } #end /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.BufferName} values) { return set${prim.CapName}sAtOffset(0, values, 0, values.capacity()); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values) { return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.capacity()); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given buffer offset and for the given length from the provided buffer. */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values, long valuesOffset, long length) { if (values == null) throw new IllegalArgumentException("Null values"); #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) { for (int i = 0; i < length; i++) setCharAtOffset(byteOffset + i, values.get((int)(valuesOffset + i))); return this; } #end if (values.isDirect()) { long len = length * ${primSize}, off = valuesOffset * ${primSize}; long cap = JNI.getDirectBufferCapacity(values); // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! cap *= ${primSize}; if (cap < off + len) throw new IndexOutOfBoundsException("The provided buffer has a capacity (" + cap + " bytes) smaller than the requested write operation (" + len + " bytes starting at byte offset " + off + ")"); #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") JNI.memcpy(checkedPeer, JNI.getDirectBufferAddress(values) + off, len); } #if ($prim.Name != "char") else if (values.isReadOnly()) { get${prim.BufferName}AtOffset(byteOffset, length).put(values.duplicate()); } #end else { set${prim.CapName}sAtOffset(byteOffset, values.array(), (int)(values.arrayOffset() + valuesOffset), (int)length); } return this; } #if ($prim.Name != "char") /** * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location */ public ${prim.BufferName} get${prim.BufferName}(long length) { return get${prim.BufferName}AtOffset(0, length); } /** * Get a direct buffer of ${prim.Name} values that points to this pointer's target memory locations */ public ${prim.BufferName} get${prim.BufferName}() { long validBytes = getValidBytes("Cannot create buffer if remaining length is not known. Please use get${prim.BufferName}(long length) instead."); return get${prim.BufferName}AtOffset(0, validBytes / ${primSize}); } /** * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location shifted by a byte offset */ public ${prim.BufferName} get${prim.BufferName}AtOffset(long byteOffset, long length) { long blen = ${primSize} * length; #declareCheckedPeerAtOffset("byteOffset" "blen") ByteBuffer buffer = JNI.newDirectByteBuffer(checkedPeer, blen); buffer.order(order()); // mutates buffer order #if ($prim.Name == "byte") return buffer; #else return buffer.as${prim.BufferName}(); #end } #end #end /** * Type of a native character string.<br> * In the native world, there are several ways to represent a string.<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} */ public enum StringType { /** * C strings (a.k.a "NULL-terminated strings") have no size limit and are the most used strings in the C world. * They are stored with the bytes of the string (using either a single-byte encoding such as ASCII, ISO-8859 or windows-1252 or a C-string compatible multi-byte encoding, such as UTF-8), followed with a zero byte that indicates the end of the string.<br> * Corresponding C types : {@code char* }, {@code const char* }, {@code LPCSTR }<br> * Corresponding Pascal type : {@code PChar }<br> * See {@link Pointer#pointerToCString(String)}, {@link Pointer#getCString()} and {@link Pointer#setCString(String)} */ C(false, true), /** * Wide C strings are stored as C strings (see {@link StringType#C}) except they are composed of shorts instead of bytes (and are ended by one zero short value = two zero byte values). * This allows the use of two-bytes encodings, which is why this kind of strings is often found in modern Unicode-aware system APIs.<br> * Corresponding C types : {@code wchar_t* }, {@code const wchar_t* }, {@code LPCWSTR }<br> * See {@link Pointer#pointerToWideCString(String)}, {@link Pointer#getWideCString()} and {@link Pointer#setWideCString(String)} */ WideC(true, true), /** * Pascal strings can be up to 255 characters long.<br> * They are stored with a first byte that indicates the length of the string, followed by the ascii or extended ascii chars of the string (no support for multibyte encoding).<br> * They are often used in very old Mac OS programs and / or Pascal programs.<br> * Usual corresponding C types : {@code unsigned char* } and {@code const unsigned char* }<br> * Corresponding Pascal type : {@code ShortString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalShort(false, true), /** * Wide Pascal strings are ref-counted unicode strings that look like WideC strings but are prepended with a ref count and length (both 32 bits ints).<br> * They are the current default in Delphi (2010).<br> * Corresponding Pascal type : {@code WideString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalWide(true, true), /** * Pascal ANSI strings are ref-counted single-byte strings that look like C strings but are prepended with a ref count and length (both 32 bits ints).<br> * Corresponding Pascal type : {@code AnsiString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalAnsi(false, true), /** * Microsoft's BSTR strings, used in COM, OLE, MS.NET Interop and MS.NET Automation functions.<br> * See @see <a href="http://msdn.microsoft.com/en-us/library/ms221069.aspx">http://msdn.microsoft.com/en-us/library/ms221069.aspx</a> for more details.<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ BSTR(true, true), /** * STL strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ support reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ STL(false, false), /** * STL wide strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ supports reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ WideSTL(true, false); //MFCCString, //CComBSTR, //_bstr_t final boolean isWide, canCreate; StringType(boolean isWide, boolean canCreate) { this.isWide = isWide; this.canCreate = canCreate; } } private static void notAString(StringType type, String reason) { throw new RuntimeException("There is no " + type + " String here ! (" + reason + ")"); } protected void checkIntRefCount(StringType type, long byteOffset) { int refCount = getIntAtOffset(byteOffset); if (refCount <= 0) notAString(type, "invalid refcount: " + refCount); } /** * Read a native string from the pointed memory location using the default charset.<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getString(StringType type) { return getStringAtOffset(0, type, null); } /** * Read a native string from the pointed memory location, using the provided charset or the system's default if not provided. * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used * @return string read from native memory */ public String getString(StringType type, Charset charset) { return getStringAtOffset(0, type, charset); } String getSTLStringAtOffset(long byteOffset, StringType type, Charset charset) { // Assume the following layout : // - fixed buff of 16 chars // - ptr to dynamic array if the string is bigger // - size of the string (size_t) // - max allowed size of the string without the need for reallocation boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; long length = getSizeTAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = this; } else { pOff = 0; p = getPointerAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); } int endChar = wide ? p.getCharAtOffset(pOff + length * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + length); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + length); return p.getStringAtOffset(pOff, wide ? StringType.WideC : StringType.C, charset); } static <U> Pointer<U> setSTLString(Pointer<U> pointer, long byteOffset, String s, StringType type, Charset charset) { boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; long lengthOffset = byteOffset + fixedBuffSize + Pointer.SIZE; long capacityOffset = lengthOffset + Pointer.SIZE; long length = s.length(); if (pointer == null)// { && length > fixedBuffLength - 1) throw new UnsupportedOperationException("Cannot create STL strings (yet)"); long currentLength = pointer.getSizeTAtOffset(lengthOffset); long currentCapacity = pointer.getSizeTAtOffset(capacityOffset); if (currentLength < 0 || currentCapacity < 0 || currentLength > currentCapacity) notAString(type, "STL string format not recognized : currentLength = " + currentLength + ", currentCapacity = " + currentCapacity); if (length > currentCapacity) throw new RuntimeException("The target STL string is not large enough to write a string of length " + length + " (current capacity = " + currentCapacity + ")"); pointer.setSizeTAtOffset(lengthOffset, length); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = pointer; } else { pOff = 0; p = pointer.getPointerAtOffset(byteOffset + fixedBuffSize + SizeT.SIZE); } int endChar = wide ? p.getCharAtOffset(pOff + currentLength * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + currentLength); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + currentLength); p.setStringAtOffset(pOff, s, wide ? StringType.WideC : StringType.C, charset); return pointer; } /** * Read a native string from the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getStringAtOffset(long byteOffset, StringType type, Charset charset) { try { long len; switch (type) { case PascalShort: len = getByteAtOffset(byteOffset) & 0xff; return new String(getBytesAtOffset(byteOffset + 1, safeIntCast(len)), charset(charset)); case PascalWide: checkIntRefCount(type, byteOffset - 8); case BSTR: len = getIntAtOffset(byteOffset - 4); if (len < 0 || ((len & 1) == 1)) notAString(type, "invalid byte length: " + len); //len = wcslen(byteOffset); if (getCharAtOffset(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getCharsAtOffset(byteOffset, safeIntCast(len / Platform.WCHAR_T_SIZE))); case PascalAnsi: checkIntRefCount(type, byteOffset - 8); len = getIntAtOffset(byteOffset - 4); if (len < 0) notAString(type, "invalid byte length: " + len); if (getByteAtOffset(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); case C: len = strlen(byteOffset); return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); case WideC: len = wcslen(byteOffset); return new String(getCharsAtOffset(byteOffset, safeIntCast(len))); case STL: case WideSTL: return getSTLStringAtOffset(byteOffset, type, charset); default: throw new RuntimeException("Unhandled string type : " + type); } } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Write a native string to the pointed memory location using the default charset.<br> * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options. * @param s string to write * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setString(String s, StringType type) { return setString(this, 0, s, type, null); } /** * Write a native string to the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param s string to write * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setStringAtOffset(long byteOffset, String s, StringType type, Charset charset) { return setString(this, byteOffset, s, type, charset); } private static String charset(Charset charset) { return (charset == null ? Charset.defaultCharset() : charset).name(); } static <U> Pointer<U> setString(Pointer<U> pointer, long byteOffset, String s, StringType type, Charset charset) { try { if (s == null) return null; byte[] bytes; char[] chars; int bytesCount, headerBytes; int headerShift; switch (type) { case PascalShort: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); if (bytesCount > 255) throw new IllegalArgumentException("Pascal strings cannot be more than 255 chars long (tried to write string of byte length " + bytesCount + ")"); pointer.setByteAtOffset(byteOffset, (byte)bytesCount); pointer.setBytesAtOffset(byteOffset + 1, bytes, 0, bytesCount); break; case C: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); pointer.setBytesAtOffset(byteOffset, bytes, 0, bytesCount); pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); break; case WideC: chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) pointer = (Pointer<U>)allocateChars(bytesCount + 2); pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); break; case PascalWide: headerBytes = 8; chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 8, 1); // refcount pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case PascalAnsi: headerBytes = 8; bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) { pointer = (Pointer<U>)allocateBytes(headerBytes + bytesCount + 1); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 8, 1); // refcount pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header pointer.setBytesAtOffset(byteOffset, bytes); pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case BSTR: headerBytes = 4; chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header IN BYTES pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case STL: case WideSTL: return setSTLString(pointer, byteOffset, s, type, charset); default: throw new RuntimeException("Unhandled string type : " + type); } return (Pointer<U>)pointer; } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Allocate memory and write a string to it, using the system's default charset to convert the string (See {@link StringType} for details on the supported types).<br> * See {@link Pointer#setString(String, StringType)}, {@link Pointer#getString(StringType)}. * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to create. */ public static Pointer<?> pointerToString(String string, StringType type, Charset charset) { return setString(null, 0, string, type, charset); } #macro (defPointerToString $string $eltWrapper) /** * Allocate memory and write a ${string} string to it, using the system's default charset to convert the string. (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}String(String)}, {@link Pointer#get${string}String()}.<br> * See {@link Pointer#pointerToString(String, StringType, Charset)} for choice of the String type or Charset. */ public static Pointer<$eltWrapper> pointerTo${string}String(String string) { return setString(null, 0, string, StringType.${string}, null); } /** * Allocate an array of pointers to strings. */ public static Pointer<Pointer<$eltWrapper>> pointerTo${string}Strings(final String... strings) { if (strings == null) return null; final int len = strings.length; final Pointer<$eltWrapper>[] pointers = (Pointer<$eltWrapper>[])new Pointer[len]; Pointer<Pointer<$eltWrapper>> mem = allocateArray((PointerIO<Pointer<$eltWrapper>>)(PointerIO)PointerIO.getPointerInstance(${eltWrapper}.class), len, new Releaser() { //@Override public void release(Pointer<?> p) { Pointer<Pointer<$eltWrapper>> mem = (Pointer<Pointer<$eltWrapper>>)p; for (int i = 0; i < len; i++) { Pointer<$eltWrapper> pp = pointers[i]; if (pp != null) pp.release(); } }}); for (int i = 0; i < len; i++) mem.set(i, pointers[i] = pointerTo${string}String(strings[i])); return mem; } #end #defPointerToString("C" "Byte") #defPointerToString("WideC" "Character") #foreach ($string in ["C", "WideC"]) //-- StringType: $string -- /** * Read a ${string} string using the default charset from the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#get${string}StringAtOffset(long)}, {@link Pointer#getString(StringType)} and {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options */ public String get${string}String() { return get${string}StringAtOffset(0); } /** * Read a ${string} string using the default charset from the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options */ public String get${string}StringAtOffset(long byteOffset) { return getStringAtOffset(byteOffset, StringType.${string}, null); } /** * Write a ${string} string using the default charset to the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}StringAtOffset(long, String)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options */ public Pointer<T> set${string}String(String s) { return set${string}StringAtOffset(0, s); } /** * Write a ${string} string using the default charset to the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options */ public Pointer<T> set${string}StringAtOffset(long byteOffset, String s) { return setStringAtOffset(byteOffset, s, StringType.${string}, null); } #end /** * Get the length of the C string at the pointed memory location shifted by a byte offset (see {@link StringType#C}). */ protected long strlen(long byteOffset) { #declareCheckedPeerAtOffset("byteOffset" "1") return JNI.strlen(checkedPeer); } /** * Get the length of the wide C string at the pointed memory location shifted by a byte offset (see {@link StringType#WideC}). */ protected long wcslen(long byteOffset) { #declareCheckedPeerAtOffset("byteOffset" "Platform.WCHAR_T_SIZE") return JNI.wcslen(checkedPeer); } /** * Write zero bytes to all of the valid bytes pointed by this pointer */ public void clearValidBytes() { long bytes = getValidBytes(); if (bytes < 0) throw new UnsupportedOperationException("Number of valid bytes is unknown. Please use clearBytes(long) or validBytes(long)."); clearBytes(bytes); } /** * Write zero bytes to the first length bytes pointed by this pointer */ public void clearBytes(long length) { clearBytesAtOffset(0, length, (byte)0); } /** * Write a byte {@code value} to each of the {@code length} bytes at the address pointed to by this pointer shifted by a {@code byteOffset} */ public void clearBytesAtOffset(long byteOffset, long length, byte value) { #declareCheckedPeerAtOffset("byteOffset" "length") JNI.memset(checkedPeer, value, length); } /** * Find the first occurrence of a value in the memory block of length searchLength bytes pointed by this pointer shifted by a byteOffset */ public Pointer<T> findByte(long byteOffset, byte value, long searchLength) { #declareCheckedPeerAtOffset("byteOffset" "searchLength") long found = JNI.memchr(checkedPeer, value, searchLength); return found == 0 ? null : offset(found - checkedPeer); } /** * Alias for {@link Pointer#get(long)} defined for more natural use from the Scala language. */ public final T apply(long index) { return get(index); } /** * Alias for {@link Pointer\#set(long, Object)} defined for more natural use from the Scala language. */ public final void update(long index, T element) { set(index, element); } /** * Create an array with all the values in the bounded memory area.<br> * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. * @throws IndexOutOfBoundsException if this pointer's bounds are unknown */ public T[] toArray() { getIO("Cannot create array"); return toArray((int)getValidElements("Length of pointed memory is unknown, cannot create array out of this pointer")); } T[] toArray(int length) { Class<?> c = Utils.getClass(getIO("Cannot create array").getTargetType()); if (c == null) throw new RuntimeException("Unable to get the target type's class (target type = " + io.getTargetType() + ")"); return (T[])toArray((Object[])Array.newInstance(c, length)); } /** * Create an array with all the values in the bounded memory area, reusing the provided array if its type is compatible and its size is big enough.<br> * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. * @throws IndexOutOfBoundsException if this pointer's bounds are unknown */ public <U> U[] toArray(U[] array) { int n = (int)getValidElements(); if (n < 0) throwBecauseUntyped("Cannot create array"); if (array.length != n) return (U[])toArray(); for (int i = 0; i < n; i++) array[i] = (U)get(i); return array; } /** * Types of pointer-based list implementations that can be created through {@link Pointer#asList()} or {@link Pointer#asList(ListType)}. */ public enum ListType { /** * Read-only list */ Unmodifiable, /** * List is modifiable and can shrink, but capacity cannot be increased (some operations will hence throw UnsupportedOperationException when the capacity is unsufficient for the requested operation) */ FixedCapacity, /** * List is modifiable and its underlying memory will be reallocated if it needs to grow beyond its current capacity. */ Dynamic } /** * Create a {@link ListType#FixedCapacity} native list that uses this pointer as storage (and has this pointer's pointed valid elements as initial content).<br> * Same as {@link Pointer#asList(ListType)}({@link ListType#FixedCapacity}). */ public NativeList<T> asList() { return asList(ListType.FixedCapacity); } /** * Create a native list that uses this pointer as <b>initial</b> storage (and has this pointer's pointed valid elements as initial content).<br> * If the list is {@link ListType#Dynamic} and if its capacity is grown at some point, this pointer will probably no longer point to the native memory storage of the list, so you need to get back the pointer with {@link NativeList#getPointer()} when you're done mutating the list. */ public NativeList<T> asList(ListType type) { return new DefaultNativeList(this, type); } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param io Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(PointerIO<E> io, long capacity) { NativeList<E> list = new DefaultNativeList(allocateArray(io, capacity), ListType.Dynamic); list.clear(); return list; } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param type Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(Class<E> type, long capacity) { return allocateList((Type)type, capacity); } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param type Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(Type type, long capacity) { return (NativeList)allocateList(PointerIO.getInstance(type), capacity); } private static char[] intsToWChars(int[] in) { int n = in.length; char[] out = new char[n]; for (int i = 0; i < n; i++) out[i] = (char)in[i]; return out; } private static int[] wcharsToInts(char[] in, int valuesOffset, int length) { int[] out = new int[length]; for (int i = 0; i < length; i++) out[i] = in[valuesOffset + i]; return out; } }
9308501d1bfaf2ec9c57abd63792596b54b98b38
19106d337d6d26387b514ed0e1cdcf3816f7e979
/src/main/java/vsdl/wrepo/cql/query/ColumnInfo.java
f96be6aac9edaa70db6a8158af4e3da5451527c4
[]
no_license
VectorShadow/WickedRepository
e74a7242b0dad2cfb5878f9f9518315b409d53d9
c776b70bad647cd4bf8871444e845cbff460d526
refs/heads/master
2023-07-05T18:25:55.304420
2021-08-14T20:51:31
2021-08-14T20:51:31
392,843,643
0
0
null
null
null
null
UTF-8
Java
false
false
362
java
package vsdl.wrepo.cql.query; public class ColumnInfo { private final String NAME; private final String DATA_TYPE; public ColumnInfo(String name, String dataType) { NAME = name; DATA_TYPE = dataType; } public String getName() { return NAME; } public String getDataType() { return DATA_TYPE; } }
a40e29960195fa66f2984e33c4ddfd00b3050e17
d72ae697577033286befbebf9469723552523f93
/src/main/java/com/circuit/obj/Admin.java
c162ebc8158066b4e1c0582b4f0f6c770baf4ff2
[]
no_license
mjay1995/Capitan-System-New
74110112f899ff9e88cc9eb1fce12405dd5c263c
0fe70465c742c33b9a6a586cb520a430a91e3d81
refs/heads/master
2021-03-24T09:41:18.445005
2018-03-01T15:47:34
2018-03-01T15:47:34
115,422,553
0
0
null
null
null
null
UTF-8
Java
false
false
3,042
java
<<<<<<< HEAD /* * 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 com.circuit.obj; /** * * @author Marvin */ public class Admin { int id; int idNo; String firstName; String lastName; String username; String password; String fullname; String position; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getIdNo() { return idNo; } public void setIdNo(int idNo) { this.idNo = idNo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } } ======= /* * 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 com.circuit.obj; /** * * @author Marvin */ public class Admin { int id; int idNo; String firstName; String lastName; String username; String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getIdNo() { return idNo; } public void setIdNo(int idNo) { this.idNo = idNo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } >>>>>>> 2ab93fcef3975e1f2819e3d73b99eb62239bf359
1d54ea3478a09dcd025f751c39cc3a3080449e27
3bf15a294b2b76e4d00c54fbed9981cde0d99d36
/LAB 7/com/cg/eis/bean/Employee.java
80f7d8e43ea732c2c535e61e86e29120aa1d5472
[]
no_license
Thamimulla/Module1
0b155d420e5fda1b112fd661e95ce5ee8f458d45
ad7a63861bef0333c49680349d51400f3a766a62
refs/heads/main
2023-04-30T22:48:34.061848
2021-05-16T08:04:34
2021-05-16T08:04:34
353,276,152
0
0
null
null
null
null
UTF-8
Java
false
false
2,002
java
package com.cg.eis.bean; public class Employee { private int id; private String name; private double salary; private String designation; private String insuranceScheme; public Employee() { super(); } public Employee(int id, String name, double salary, String designation, String insuranceScheme) { super(); this.id = id; this.name = name; this.salary = salary; this.designation = designation; this.insuranceScheme = insuranceScheme; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getInsuranceScheme() { return insuranceScheme; } public void setInsuranceScheme(String insuranceScheme) { this.insuranceScheme = insuranceScheme; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { boolean isSame = false; // code to compare e1 and e2 if(obj instanceof Employee) { Employee e = (Employee)obj; boolean a = (this.id == e.id); boolean b = (this.name.equals(e.name)); boolean c = this.salary == e.salary; boolean d = this.designation.equals(e.designation); boolean n = this.insuranceScheme.equals(e.insuranceScheme); return a&&b&&c&&d&&n; } return isSame; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + ", designation=" + designation + ", insuranceScheme=" + insuranceScheme + "]"; } }
13941806b10815ffa1d28cc90a457ce99a5b22fa
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/27/27_91412c601b16af910a0d6d7e90499f12ad8aabfa/TextField/27_91412c601b16af910a0d6d7e90499f12ad8aabfa_TextField_t.java
03c9dd5ca87303b690144bfe232140cf0b30cce2
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
189,228
java
//#condition polish.usePolishGui /* * Copyright (c) 2004-2009 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * J2ME Polish is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with J2ME Polish; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ package de.enough.polish.ui; import java.io.IOException; import java.io.InputStream; import java.util.Timer; import java.util.TimerTask; import javax.microedition.lcdui.Canvas; //#if polish.TextField.useVirtualKeyboard import de.enough.polish.ui.keyboard.view.KeyboardView; //#endif import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; //#if polish.android import android.view.View; import android.view.View.MeasureSpec; //#endif //#if polish.TextField.useDirectInput && polish.TextField.usePredictiveInput && !(polish.blackberry || polish.android) import de.enough.polish.predictive.TextBuilder; import de.enough.polish.predictive.trie.TrieProvider; //#endif import de.enough.polish.util.ArrayList; import de.enough.polish.util.DeviceControl; import de.enough.polish.util.DeviceInfo; import de.enough.polish.util.DrawUtil; import de.enough.polish.util.IntHashMap; import de.enough.polish.util.Locale; import de.enough.polish.util.Properties; import de.enough.polish.util.TextUtil; import de.enough.polish.util.WrappedText; //#if polish.blackberry import de.enough.polish.blackberry.ui.FixedPointDecimalTextFilter; import de.enough.polish.blackberry.ui.PolishTextField; import de.enough.polish.blackberry.ui.PolishEditField; import de.enough.polish.blackberry.ui.PolishOneLineField; import de.enough.polish.blackberry.ui.PolishPasswordEditField; import de.enough.polish.blackberry.ui.PolishEmailAddressEditField; import net.rim.device.api.system.Application; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.BasicEditField; import net.rim.device.api.ui.text.TextFilter; //#endif //#if polish.series40sdk20 || polish.series40sdk11 import com.nokia.mid.ui.TextEditor; import com.nokia.mid.ui.TextEditorListener; //#endif //#if polish.api.windows import de.enough.polish.windows.Keyboard; //#endif //#if polish.android import de.enough.polish.android.lcdui.AndroidDisplay; import de.enough.polish.android.lcdui.AndroidTextField; import de.enough.polish.android.lcdui.AndroidTextFieldImpl; import de.enough.polish.android.midlet.MidletBridge; //#endif /** * A <code>TextField</code> is an editable text component that may be * placed into * a <A HREF="../../../javax/microedition/lcdui/Form.html"><CODE>Form</CODE></A>. It can be * given a piece of text that is used as the initial value. * * <P>A <code>TextField</code> has a maximum size, which is the * maximum number of characters * that can be stored in the object at any time (its capacity). This limit is * enforced when the <code>TextField</code> instance is constructed, * when the user is editing text within the <code>TextField</code>, as well as * when the application program calls methods on the * <code>TextField</code> that modify its * contents. The maximum size is the maximum stored capacity and is unrelated * to the number of characters that may be displayed at any given time. * The number of characters displayed and their arrangement into rows and * columns are determined by the device. </p> * * <p>The implementation may place a boundary on the maximum size, and the * maximum size actually assigned may be smaller than the application had * requested. The value actually assigned will be reflected in the value * returned by <A HREF="../../../javax/microedition/lcdui/TextField.html#getMaxSize()"><CODE>getMaxSize()</CODE></A>. A defensively-written * application should compare this value to the maximum size requested and be * prepared to handle cases where they differ.</p> * * <a name="constraints"></a> * <h3>Input Constraints</h3> * * <P>The <code>TextField</code> shares the concept of <em>input * constraints</em> with the <A HREF="../../../javax/microedition/lcdui/TextBox.html"><CODE>TextBox</CODE></A> class. The different * constraints allow the application to request that the user's input be * restricted in a variety of ways. The implementation is required to * restrict the user's input as requested by the application. For example, if * the application requests the <code>NUMERIC</code> constraint on a * <code>TextField</code>, the * implementation must allow only numeric characters to be entered. </p> * * <p>The <em>actual contents</em> of the text object are set and modified by * and are * reported to the application through the <code>TextBox</code> and * <code>TextField</code> APIs. The <em>displayed contents</em> may differ * from the actual contents if the implementation has chosen to provide * special formatting suitable for the text object's constraint setting. * For example, a <code>PHONENUMBER</code> field might be displayed with * digit separators and punctuation as * appropriate for the phone number conventions in use, grouping the digits * into country code, area code, prefix, etc. Any spaces or punctuation * provided are not considered part of the text object's actual contents. For * example, a text object with the <code>PHONENUMBER</code> * constraint might display as * follows:</p> * * <pre><code> * (408) 555-1212 * </code></pre> * * <p>but the actual contents of the object visible to the application * through the APIs would be the string * &quot;<code>4085551212</code>&quot;. * The <code>size</code> method reflects the number of characters in the * actual contents, not the number of characters that are displayed, so for * this example the <code>size</code> method would return <code>10</code>.</p> * * <p>Some constraints, such as <code>DECIMAL</code>, require the * implementation to perform syntactic validation of the contents of the text * object. The syntax checking is performed on the actual contents of the * text object, which may differ from the displayed contents as described * above. Syntax checking is performed on the initial contents passed to the * constructors, and it is also enforced for all method calls that affect the * contents of the text object. The methods and constructors throw * <code>IllegalArgumentException</code> if they would result in the contents * of the text object not conforming to the required syntax.</p> * * <p>The value passed to the <A HREF="../../../javax/microedition/lcdui/TextField.html#setConstraints(int)"><CODE>setConstraints()</CODE></A> method * consists of a restrictive constraint setting described above, as well as a * variety of flag bits that modify the behavior of text entry and display. * The value of the restrictive constraint setting is in the low order * <code>16</code> bits * of the value, and it may be extracted by combining the constraint value * with the <code>CONSTRAINT_MASK</code> constant using the bit-wise * <code>AND</code> (<code>&amp;</code>) operator. * The restrictive constraint settings are as follows: * * <blockquote><code> * ANY<br> * EMAILADDR<br> * NUMERIC<br> * PHONENUMBER<br> * URL<br> * DECIMAL<br> * </code></blockquote> * * <p>The modifier flags reside in the high order <code>16</code> bits * of the constraint * value, that is, those in the complement of the * <code>CONSTRAINT_MASK</code> constant. * The modifier flags may be tested individually by combining the constraint * value with a modifier flag using the bit-wise <code>AND</code> * (<code>&amp;</code>) operator. The * modifier flags are as follows: * * <blockquote><code> * PASSWORD<br> * UNEDITABLE<br> * SENSITIVE<br> * NON_PREDICTIVE<br> * INITIAL_CAPS_WORD<br> * INITIAL_CAPS_SENTENCE<br> * </code></blockquote> * * <a name="modes"></a> * <h3>Input Modes</h3> * * <p>The <code>TextField</code> shares the concept of <em>input * modes</em> with the <A HREF="../../../javax/microedition/lcdui/TextBox.html"><CODE>TextBox</CODE></A> class. The application can request that the * implementation use a particular input mode when the user initiates editing * of a <code>TextField</code> or <code>TextBox</code>. The input * mode is a concept that exists within * the user interface for text entry on a particular device. The application * does not request an input mode directly, since the user interface for text * entry is not standardized across devices. Instead, the application can * request that the entry of certain characters be made convenient. It can do * this by passing the name of a Unicode character subset to the <A HREF="../../../javax/microedition/lcdui/TextField.html#setInitialInputMode(java.lang.String)"><CODE>setInitialInputMode()</CODE></A> method. Calling this method * requests that the implementation set the mode of the text entry user * interface so that it is convenient for the user to enter characters in this * subset. The application can also request that the input mode have certain * behavioral characteristics by setting modifier flags in the constraints * value. * * <p>The requested input mode should be used whenever the user initiates the * editing of a <code>TextBox</code> or <code>TextField</code> object. * If the user had changed input * modes in a previous editing session, the application's requested input mode * should take precedence over the previous input mode set by the user. * However, the input mode is not restrictive, and the user is allowed to * change the input mode at any time during editing. If editing is already in * progress, calls to the <code>setInitialInputMode</code> method do not * affect the current input mode, but instead take effect at the next time the * user initiates editing of this text object. * * <p>The initial input mode is a hint to the implementation. If the * implementation cannot provide an input mode that satisfies the * application's request, it should use a default input mode. * * <P>The input mode that results from the application's request is not a * restriction on the set of characters the user is allowed to enter. The * user MUST be allowed to switch input modes to enter any character that is * allowed within the current constraint setting. The constraint * setting takes precedence over an input mode request, and the implementation * may refuse to supply a particular input mode if it is inconsistent with the * current constraint setting. * * <P>For example, if the current constraint is <code>ANY</code>, the call</P> * * <TABLE BORDER="2"> * <TR> * <TD ROWSPAN="1" COLSPAN="1"> * <pre><code> * setInitialInputMode("MIDP_UPPERCASE_LATIN"); </code></pre> * </TD> * </TR> * </TABLE> * * <p>should set the initial input mode to allow entry of uppercase Latin * characters. This does not restrict input to these characters, and the user * will be able to enter other characters by switching the input mode to allow * entry of numerals or lowercase Latin letters. However, if the current * constraint is <code>NUMERIC</code>, the implementation may ignore * the request to set an * initial input mode allowing <code>MIDP_UPPERCASE_LATIN</code> * characters because these * characters are not allowed in a <code>TextField</code> whose * constraint is <code>NUMERIC</code>. In * this case, the implementation may instead use an input mode that allows * entry of numerals, since such an input mode is most appropriate for entry * of data under the <code>NUMERIC</code> constraint. * * <P>A string is used to name the Unicode character subset passed as a * parameter to the * <A HREF="../../../javax/microedition/lcdui/TextField.html#setInitialInputMode(java.lang.String)"><CODE>setInitialInputMode()</CODE></A> method. * String comparison is case sensitive. * * <P>Unicode character blocks can be named by adding the prefix * &quot;<code>UCB</code>_&quot; to the * the string names of fields representing Unicode character blocks as defined * in the J2SE class <code>java.lang.Character.UnicodeBlock</code>. Any * Unicode character block may be named in this fashion. For convenience, the * most common Unicode character blocks are listed below. * * <blockquote><code> * UCB_BASIC_LATIN<br> * UCB_GREEK<br> * UCB_CYRILLIC<br> * UCB_ARMENIAN<br> * UCB_HEBREW<br> * UCB_ARABIC<br> * UCB_DEVANAGARI<br> * UCB_BENGALI<br> * UCB_THAI<br> * UCB_HIRAGANA<br> * UCB_KATAKANA<br> * UCB_HANGUL_SYLLABLES<br> * </code></blockquote> * * <P>&quot;Input subsets&quot; as defined by the J2SE class * <code>java.awt.im.InputSubset</code> may be named by adding the prefix * &quot;<code>IS_</code>&quot; to the string names of fields * representing input subsets as defined * in that class. Any defined input subset may be used. For convenience, the * names of the currently defined input subsets are listed below. * * <blockquote><code> * IS_FULLWIDTH_DIGITS<br> * IS_FULLWIDTH_LATIN<br> * IS_HALFWIDTH_KATAKANA<br> * IS_HANJA<br> * IS_KANJI<br> * IS_LATIN<br> * IS_LATIN_DIGITS<br> * IS_SIMPLIFIED_HANZI<br> * IS_TRADITIONAL_HANZI<br> * </code></blockquote> * * <P>MIDP has also defined the following character subsets: * * <blockquote> * <code>MIDP_UPPERCASE_LATIN</code> - the subset of * <code>IS_LATIN</code> that corresponds to * uppercase Latin letters * </blockquote> * <blockquote> * <code>MIDP_LOWERCASE_LATIN</code> - the subset of * <code>IS_LATIN</code> that corresponds to * lowercase Latin letters * </blockquote> * * <p> * Finally, implementation-specific character subsets may be named with * strings that have a prefix of &quot;<code>X_</code>&quot;. In * order to avoid namespace conflicts, * it is recommended that implementation-specific names include the name of * the defining company or organization after the initial * &quot;<code>X_</code>&quot; prefix. * * <p> For example, a Japanese language application might have a particular * <code>TextField</code> that the application intends to be used * primarily for input of * words that are &quot;loaned&quot; from languages other than Japanese. The * application might request an input mode facilitating Hiragana input by * issuing the following method call:</p> * * <TABLE BORDER="2"> * <TR> * <TD ROWSPAN="1" COLSPAN="1"> * <pre><code> * textfield.setInitialInputMode("UCB_HIRAGANA"); </code></pre> * </TD> * </TR> * </TABLE> * <h3>Implementation Note</h3> * * <p>Implementations need not compile in all the strings listed above. * Instead, they need only to compile in the strings that name Unicode * character subsets that they support. If the subset name passed by the * application does not match a known subset name, the request should simply * be ignored without error, and a default input mode should be used. This * lets implementations support this feature reasonably inexpensively. * However, it has the consequence that the application cannot tell whether * its request has been accepted, nor whether the Unicode character subset it * has requested is actually a valid subset. * <HR> * * @author Robert Virkus, [email protected] * @author Andrew Barnes, [email protected] basic implementation of direct input * @since MIDP 1.0 */ public class TextField extends StringItem //#if polish.TextField.useDirectInput && !(polish.blackberry || polish.android) //#define tmp.forceDirectInput //#define tmp.directInput //#elif polish.css.textfield-direct-input && !(polish.blackberry || polish.android) //#define tmp.directInput //#define tmp.allowDirectInput //#elif polish.api.windows //#define tmp.forceDirectInput //#define tmp.directInput //#endif //#if polish.TextField.useDirectInput && polish.TextField.usePredictiveInput && !(polish.blackberry || polish.android) //#define tmp.usePredictiveInput //#endif //#if tmp.directInput && polish.TextField.useDynamicCharset //#define tmp.useDynamicCharset //#endif //#if polish.TextField.supportSymbolsEntry && tmp.directInput //#define tmp.supportsSymbolEntry //#if !polish.css.style.textFieldSymbolTable && !polish.css.style.textFieldSymbolList //#abort You need to define the ".textFieldSymbolList" CSS style when enabling the polish.TextField.supportSymbolsEntry option. //#endif //#endif //#if !(polish.blackberry || polish.doja) || tmp.supportsSymbolEntry //#defineorappend tmp.implements=CommandListener //#define tmp.implementsCommandListener //#endif //#if polish.TextField.suppressCommands //#define tmp.suppressCommands //#if polish.key.maybeSupportsAsciiKeyMap //#defineorappend tmp.implements=ItemCommandListener //#define tmp.implementsItemCommandListener //#endif //#else //#defineorappend tmp.implements=ItemCommandListener //#define tmp.implementsItemCommandListener //#endif //#if polish.blackberry //#defineorappend tmp.implements=FieldChangeListener //#endif //#if polish.series40sdk20 || polish.series40sdk11 //#defineorappend tmp.implements=TextEditorListener //#endif //#if polish.LibraryBuild //#define tmp.implementsCommandListener //#define tmp.implementsItemCommandListener implements CommandListener, ItemCommandListener //#if polish.blackberry // , FieldChangeListener //#endif //#elif tmp.implements:defined //#= implements ${tmp.implements} //#endif { /** * The user is allowed to enter any text. * <A HREF="Form.html#linebreak">Line breaks</A> may be entered. * * <P>Constant <code>0</code> is assigned to <code>ANY</code>.</P> */ public static final int ANY = 0; /** * The user is allowed to enter an e-mail address. * * <P>Constant <code>1</code> is assigned to <code>EMAILADDR</code>.</P> * */ public static final int EMAILADDR = 1; /** * The user is allowed to enter only an integer value. The implementation * must restrict the contents either to be empty or to consist of an * optional minus sign followed by a string of one or more decimal * numerals. Unless the value is empty, it will be successfully parsable * using <A HREF="../../../java/lang/Integer.html#parseInt(java.lang.String)"><CODE>Integer.parseInt(String)</CODE></A>. * * <P>The minus sign consumes space in the text object. It is thus * impossible to enter negative numbers into a text object whose maximum * size is <code>1</code>.</P> * * <P>Constant <code>2</code> is assigned to <code>NUMERIC</code>.</P> * */ public static final int NUMERIC = 2; /** * The user is allowed to enter a phone number. The phone number is a * special * case, since a phone-based implementation may be linked to the * native phone * dialing application. The implementation may automatically start a phone * dialer application that is initialized so that pressing a single key * would be enough to make a call. The call must not made automatically * without requiring user's confirmation. Implementations may also * provide a feature to look up the phone number in the device's phone or * address database. * * <P>The exact set of characters allowed is specific to the device and to * the device's network and may include non-numeric characters, such as a * &quot;+&quot; prefix character.</P> * * <P>Some platforms may provide the capability to initiate voice calls * using the <A HREF="../../../javax/microedition/midlet/MIDlet.html#platformRequest(java.lang.String)"><CODE>MIDlet.platformRequest</CODE></A> method.</P> * * <P>Constant <code>3</code> is assigned to <code>PHONENUMBER</code>.</P> * */ public static final int PHONENUMBER = 3; /** * The user is allowed to enter a URL. * * <P>Constant <code>4</code> is assigned to <code>URL</code>.</P> * */ public static final int URL = 4; /** * The user is allowed to enter numeric values with optional decimal * fractions, for example &quot;-123&quot;, &quot;0.123&quot;, or * &quot;.5&quot;. * * <p>The implementation may display a period &quot;.&quot; or a * comma &quot;,&quot; for the decimal fraction separator, depending on * the conventions in use on the device. Similarly, the implementation * may display other device-specific characters as part of a decimal * string, such as spaces or commas for digit separators. However, the * only characters allowed in the actual contents of the text object are * period &quot;.&quot;, minus sign &quot;-&quot;, and the decimal * digits.</p> * * <p>The actual contents of a <code>DECIMAL</code> text object may be * empty. If the actual contents are not empty, they must conform to a * subset of the syntax for a <code>FloatingPointLiteral</code> as defined * by the <em>Java Language Specification</em>, section 3.10.2. This * subset syntax is defined as follows: the actual contents * must consist of an optional minus sign * &quot;-&quot;, followed by one or more whole-number decimal digits, * followed by an optional fraction separator, followed by zero or more * decimal fraction digits. The whole-number decimal digits may be * omitted if the fraction separator and one or more decimal fraction * digits are present.</p> * * <p>The syntax defined above is also enforced whenever the application * attempts to set or modify the contents of the text object by calling * a constructor or a method.</p> * * <p>Parsing this string value into a numeric value suitable for * computation is the responsibility of the application. If the contents * are not empty, the result can be parsed successfully by * <code>Double.valueOf</code> and related methods if they are present * in the runtime environment. </p> * * <p>The sign and the fraction separator consume space in the text * object. Applications should account for this when assigning a maximum * size for the text object.</p> * * <P>Constant <code>5</code> is assigned to <code>DECIMAL</code>.</p> * * * @since MIDP 2.0 */ public static final int DECIMAL = 5; /** * The user is allowed to enter numeric values with two decimal * fractions, for example &quot;-123.00&quot;, &quot;0.13&quot;, or * &quot;0.50&quot;. * * <p>Numbers are appended in the last decimal fraction by default, so when &quot;1&quot; is pressed this results * in &quot;0.01&quot;. Similarly pressing &quot;1&quot;, &quot;2&quot; and &quot;3&quot; results in &quot;1.23&quot;. * </p> * <p>Sample usage:</p> * <pre> * TextField cashRegister = new TextField("Price: ", null, 5, UiAccess.CONSTRAINT_FIXED_POINT_DECIMAL ); * </pre> * * <p>Constant <code>20</code> is assigned to <code>FIXED_POINT_DECIMAL</code>.</p> * * @since J2ME Polish 2.1.3 * @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL * @see #setNumberOfDecimalFractions(int) * @see #getNumberOfDecimalFractions() * @see #convertToFixedPointDecimal(String) * @see #convertToFixedPointDecimal(String, boolean) */ public static final int FIXED_POINT_DECIMAL = 20; /** * Indicates that the text entered is confidential data that should be * obscured whenever possible. The contents may be visible while the * user is entering data. However, the contents must never be divulged * to the user. In particular, the existing contents must not be shown * when the user edits the contents. The means by which the contents * are obscured is implementation-dependent. For example, each * character of the data might be masked with a * &quot;<code>*</code>&quot; character. The * <code>PASSWORD</code> modifier is useful for entering * confidential information * such as passwords or personal identification numbers (PINs). * * <p>Data entered into a <code>PASSWORD</code> field is treated * similarly to <code>SENSITIVE</code> * in that the implementation must never store the contents into a * dictionary or table for use in predictive, auto-completing, or other * accelerated input schemes. If the <code>PASSWORD</code> bit is * set in a constraint * value, the <code>SENSITIVE</code> and * <code>NON_PREDICTIVE</code> bits are also considered to be * set, regardless of their actual values. In addition, the * <code>INITIAL_CAPS_WORD</code> and * <code>INITIAL_CAPS_SENTENCE</code> flag bits should be ignored * even if they are set.</p> * * <p>The <code>PASSWORD</code> modifier can be combined with * other input constraints * by using the bit-wise <code>OR</code> operator (<code>|</code>). * The <code>PASSWORD</code> modifier is not * useful with some constraint values such as * <code>EMAILADDR</code>, <code>PHONENUMBER</code>, * and <code>URL</code>. These combinations are legal, however, * and no exception is * thrown if such a constraint is specified.</p> * * <p>Constant <code>0x10000</code> is assigned to * <code>PASSWORD</code>.</p> * */ public static final int PASSWORD = 0x10000; /** * Indicates that editing is currently disallowed. When this flag is set, * the implementation must prevent the user from changing the text * contents of this object. The implementation should also provide a * visual indication that the object's text cannot be edited. The intent * of this flag is that this text object has the potential to be edited, * and that there are circumstances where the application will clear this * flag and allow the user to edit the contents. * * <p>The <code>UNEDITABLE</code> modifier can be combined with * other input constraints * by using the bit-wise <code>OR</code> operator (<code>|</code>). * * <p>Constant <code>0x20000</code> is assigned to <code>UNEDITABLE</code>.</p> * * * @since MIDP 2.0 */ public static final int UNEDITABLE = 0x20000; /** * Indicates that the text entered is sensitive data that the * implementation must never store into a dictionary or table for use in * predictive, auto-completing, or other accelerated input schemes. A * credit card number is an example of sensitive data. * * <p>The <code>SENSITIVE</code> modifier can be combined with other input * constraints by using the bit-wise <code>OR</code> operator * (<code>|</code>).</p> * * <p>Constant <code>0x40000</code> is assigned to * <code>SENSITIVE</code>.</p> * * * @since MIDP 2.0 */ public static final int SENSITIVE = 0x40000; /** * Indicates that the text entered does not consist of words that are * likely to be found in dictionaries typically used by predictive input * schemes. If this bit is clear, the implementation is allowed to (but * is not required to) use predictive input facilities. If this bit is * set, the implementation should not use any predictive input facilities, * but it instead should allow character-by-character text entry. * * <p>The <code>NON_PREDICTIVE</code> modifier can be combined * with other input * constraints by using the bit-wise <code>OR</code> operator * (<code>|</code>). * * <P>Constant <code>0x80000</code> is assigned to * <code>NON_PREDICTIVE</code>.</P> * * * @since MIDP 2.0 */ public static final int NON_PREDICTIVE = 0x80000; /** * This flag is a hint to the implementation that during text editing, the * initial letter of each word should be capitalized. This hint should be * honored only on devices for which automatic capitalization is * appropriate and when the character set of the text being edited has the * notion of upper case and lower case letters. The definition of * word boundaries is implementation-specific. * * <p>If the application specifies both the * <code>INITIAL_CAPS_WORD</code> and the * <code>INITIAL_CAPS_SENTENCE</code> flags, * <code>INITIAL_CAPS_WORD</code> behavior should be used. * * <p>The <code>INITIAL_CAPS_WORD</code> modifier can be combined * with other input * constraints by using the bit-wise <code>OR</code> operator * (<code>|</code>). * * <p>Constant <code>0x100000</code> is assigned to * <code>INITIAL_CAPS_WORD</code>. * * * @since MIDP 2.0 */ public static final int INITIAL_CAPS_WORD = 0x100000; /** * This flag is a hint to the implementation that during text editing, the * initial letter of each sentence should be capitalized. This hint * should be honored only on devices for which automatic capitalization is * appropriate and when the character set of the text being edited has the * notion of upper case and lower case letters. The definition of * sentence boundaries is implementation-specific. * * <p>If the application specifies both the * <code>INITIAL_CAPS_WORD</code> and the * <code>INITIAL_CAPS_SENTENCE</code> flags, * <code>INITIAL_CAPS_WORD</code> behavior should be used. * * <p>The <code>INITIAL_CAPS_SENTENCE</code> modifier can be * combined with other input * constraints by using the bit-wise <code>OR</code> operator * (<code>|</code>). * * <p>Constant <code>0x200000</code> is assigned to * <code>INITIAL_CAPS_SENTENCE</code>. * * * @since MIDP 2.0 */ public static final int INITIAL_CAPS_SENTENCE = 0x200000; /** * A flag to hint to the implementation that during text editing,the * initial letter of each sentence should NOT be capitalized. */ public static final int INITIAL_CAPS_NEVER = 0x400000; /** * The mask value for determining the constraint mode. * The application should * use the bit-wise <code>AND</code> operation with a value returned by * <code>getConstraints()</code> and * <code>CONSTRAINT_MASK</code> in order to retrieve the current * constraint mode, * in order to remove any modifier flags such as the * <code>PASSWORD</code> flag. * * <P>Constant <code>0xFFFF</code> is assigned to * <code>CONSTRAINT_MASK</code>.</P> */ public static final int CONSTRAINT_MASK = 0xFFFF; // clear command is used in DateField, too: //#ifdef polish.command.clear.priority:defined //#= private final static int CLEAR_PRIORITY = ${polish.command.clear.priority}; //#else private final static int CLEAR_PRIORITY = 8; //#endif //#ifdef polish.command.clear.type:defined //#= private final static int CLEAR_TYPE = ${polish.command.clear.type}; //#else private final static int CLEAR_TYPE = Command.ITEM; //#endif //#ifdef polish.i18n.useDynamicTranslations /** * Command for clearing the complete text of this field */ public static Command CLEAR_CMD = new Command( Locale.get("polish.command.clear"), CLEAR_TYPE, CLEAR_PRIORITY ); //#elifdef polish.command.clear:defined //#= public static final Command CLEAR_CMD = new Command( "${polish.command.clear}", CLEAR_TYPE, CLEAR_PRIORITY ); //#else //# public static final Command CLEAR_CMD = new Command( "Clear", CLEAR_TYPE, CLEAR_PRIORITY ); //#endif //#ifndef tmp.suppressCommands //#if (polish.TextField.suppressDeleteCommand != true) && !polish.blackberry && !polish.TextField.keepDeleteCommand //#define tmp.updateDeleteCommand //#endif //#ifdef polish.command.delete.priority:defined //#= private final static int DELETE_PRIORITY = ${polish.command.delete.priority}; //#else private final static int DELETE_PRIORITY = 1; //#endif // the delete command is a Command.ITEM type when the extended menubar is used in conjunction with a defined return-key, // because CANCEL will be mapped on special keys like the return key on Sony Ericsson devices. private final static int DELETE_TYPE = //#ifdef polish.command.delete.type:defined //#= ${polish.command.delete.type}; //#elif polish.MenuBar.useExtendedMenuBar && (polish.key.ReturnKey:defined || polish.css.repaint-previous-screen && polish.hasPointerEvents) //# Command.ITEM; //#else Command.CANCEL; //#endif //#ifdef polish.i18n.useDynamicTranslations public static Command DELETE_CMD = new Command( Locale.get("polish.command.delete"), DELETE_TYPE, DELETE_PRIORITY ); //#elifdef polish.command.delete:defined //#= public static final Command DELETE_CMD = new Command( "${polish.command.delete}", DELETE_TYPE, DELETE_PRIORITY ); //#else //# public static final Command DELETE_CMD = new Command( "Delete", DELETE_TYPE, DELETE_PRIORITY ); //#endif //#endif //#if polish.key.maybeSupportsAsciiKeyMap //#ifdef polish.command.switch_keyboard.priority:defined //#= private final static int SWITCH_KEYBOARD_PRIORITY = ${polish.command.switch_keyboard.priority}; //#else private final static int SWITCH_KEYBOARD_PRIORITY = 1; //#endif private static Command SWITCH_KEYBOARD_CMD = new Command (Locale.get("polish.command.switch_keyboard"), Command.ITEM, SWITCH_KEYBOARD_PRIORITY); //#endif /** valid input characters for local parts of email addresses, apart from 0..9 and a..z. */ private static final String VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS = ".-_@!#$%&'*+/=?^`{|}~"; /** valid input characters for domain names, apart from 0..9 and a..z. */ private static final String VALID_DOMAIN_CHARACTERS = "._-"; private int maxSize; private int constraints = -1; //#ifdef polish.css.textfield-caret-color private int caretColor = -1; //#endif private char editingCaretChar = '|'; protected char caretChar = '|'; protected boolean showCaret; private long lastCaretSwitch; protected String title; private String passwordText; private boolean isPassword; private boolean enableDirectInput; private boolean noNewLine = false; private boolean noComplexInput = false; //#if (!tmp.suppressCommands && !tmp.supportsSymbolEntry) || tmp.supportsSymbolEntry private ItemCommandListener additionalItemCommandListener; //#endif // this is outside of the tmp.directInput block, so that it can be referenced from the UiAccess class protected int inputMode; // the current input mode //#if tmp.directInput || polish.android private int caretPosition; // the position of the caret in the text //#endif //#if tmp.directInput //#if tmp.supportsSymbolEntry protected static List symbolsList; //#if polish.TextField.Symbols:defined //#= private static String[] definedSymbols = ${ stringarray(polish.TextField.Symbols)}; //#else protected static String[] definedSymbols = {"&","@","/","\\","<",">","(",")","{","}","[","]",".","+","-","*",":","_","\"","#","$","%",":)",":(",";)",":x",":D",":P"}; //private static String definedSymbols = "@/\\<>(){}.,+-*:_\"#$%"; //#endif //#ifdef polish.command.entersymbol.priority:defined //#= private static int ENTER_SYMBOL_PRIORITY = ${polish.command.entersymbol.priority}; //#else private static int ENTER_SYMBOL_PRIORITY = 9; //#endif //#ifdef polish.i18n.useDynamicTranslations public static Command ENTER_SYMBOL_CMD = new Command( Locale.get("polish.command.entersymbol"), Command.SCREEN, ENTER_SYMBOL_PRIORITY ); //#elifdef polish.command.entersymbol:defined //#= public static final Command ENTER_SYMBOL_CMD = new Command( "${polish.command.entersymbol}", Command.SCREEN, ENTER_SYMBOL_PRIORITY ); //#else //# public static final Command ENTER_SYMBOL_CMD = new Command( "Add Symbol", Command.SCREEN, ENTER_SYMBOL_PRIORITY ); //#endif //#endif private boolean isKeyDown; //#ifdef polish.TextField.InputTimeout:defined //#= private static final int INPUT_TIMEOUT = ${polish.TextField.InputTimeout}; //#else private static final int INPUT_TIMEOUT = 1000; //#endif /** input mode for lowercase characters */ public static final int MODE_LOWERCASE = 0; /** input mode for entering one uppercase followed by lowercase characters */ public static final int MODE_FIRST_UPPERCASE = 1; // only the first character should be written in uppercase /** input mode for uppercase characters */ public static final int MODE_UPPERCASE = 2; /** input mode for numeric characters */ public static final int MODE_NUMBERS = 3; /** input mode for input using a separete native TextBox */ public static final int MODE_NATIVE = 4; //#ifdef polish.key.ChangeInputModeKey:defined //#= protected static final int KEY_CHANGE_MODE = ${polish.key.ChangeInputModeKey}; //#elif ${polish.vendor} == Generic public static final int KEY_CHANGE_MODE = DeviceInfo.getKeyInputModeSwitch(); //#else //# public static final int KEY_CHANGE_MODE = Canvas.KEY_POUND; //#endif //#ifdef polish.key.ClearKey:defined //#= public static final int KEY_DELETE = ${polish.key.ClearKey}; //#else public static final int KEY_DELETE = -8 ; //Canvas.KEY_STAR; //#endif //#if polish.key.shift:defined //#= private static final int KEY_SHIFT = ${polish.key.shift}; //#else private static final int KEY_SHIFT = -50; //#endif private boolean nextCharUppercase; // is needed for the FIRST_UPPERCASE-mode private boolean prepareNextCharUppercase; private String[] realTextLines; // the textLines with spaces and line breaks at the end private String originalRowText; // current line including spaces and line breaks at the end private int caretColumn; // the current column of the caret, 0 is the first column private int caretRow; // the current row of the caret, 0 is the first row private int caretX; private int caretY; private int caretWidth; //#ifdef polish.css.textfield-show-length private boolean showLength; //#endif private int lastKey; // the last key which has been pressed long lastInputTime; // the last time a key has been pressed private int characterIndex; // the index within the available characters of the current key // the characters for each key: //#ifdef polish.TextField.charactersKey1:defined //#= private static String charactersKey1 = "${polish.TextField.charactersKey1}"; //#else private static String charactersKey1 = ".,!?\u00bf:/()@_-+1'\";"; //#endif //#ifdef polish.TextField.charactersKey2:defined //#= private static String charactersKey2 = "${polish.TextField.charactersKey2}"; //#else private static String charactersKey2 = "abc2\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7"; //#endif //#ifdef polish.TextField.charactersKey3:defined //#= private static String charactersKey3 = "${polish.TextField.charactersKey3}"; //#else private static String charactersKey3 = "def3\u00e8\u00e9\u00ea\u00eb"; //#endif //#ifdef polish.TextField.charactersKey4:defined //#= private static String charactersKey4 = "${polish.TextField.charactersKey4}"; //#else private static String charactersKey4 = "ghi4\u00ec\u00ed\u00ee\u00ef"; //#endif //#ifdef polish.TextField.charactersKey5:defined //#= private static String charactersKey5 = "${polish.TextField.charactersKey5}"; //#else private static String charactersKey5 = "jkl5"; //#endif //#ifdef polish.TextField.charactersKey6:defined //#= private static String charactersKey6 = "${polish.TextField.charactersKey6}"; //#else private static String charactersKey6 = "mno6\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6"; //#endif //#ifdef polish.TextField.charactersKey7:defined //#= private static String charactersKey7 = "${polish.TextField.charactersKey7}"; //#else private static String charactersKey7 = "pqrs7\u00df"; //#endif //#ifdef polish.TextField.charactersKey8:defined //#= private static String charactersKey8 = "${polish.TextField.charactersKey8}"; //#else private static String charactersKey8 = "tuv8\u00f9\u00fa\u00fb\u00fc"; //#endif //#ifdef polish.TextField.charactersKey9:defined //#= private static String charactersKey9 = "${polish.TextField.charactersKey9}"; //#else private static String charactersKey9 = "wxyz9\u00fd"; //#endif //#ifdef polish.TextField.charactersKey0:defined //#= private static String charactersKey0 = "${polish.TextField.charactersKey0}"; //#else protected static String charactersKey0 = " 0"; //#endif //#ifdef polish.TextField.charactersKeyStar:defined //#= protected static String charactersKeyStar = "${polish.TextField.charactersKeyStar}"; //#else protected static String charactersKeyStar = ".,!?\u00bf:/@_-+1'\";"; //#endif //#ifdef polish.TextField.charactersKeyPound:defined //#= protected static String charactersKeyPound = "${polish.TextField.charactersKeyPound}"; //#else protected static String charactersKeyPound = null; //#endif /** map of characters that can be triggered witht the 0..9 and #, * keys */ public static String[] CHARACTERS = new String[]{ charactersKey0, charactersKey1, charactersKey2, charactersKey3, charactersKey4, charactersKey5, charactersKey6, charactersKey7, charactersKey8, charactersKey9 }; //#if tmp.useDynamicCharset public static String[] CHARACTERS_UPPER = new String[]{ charactersKey0, charactersKey1, charactersKey2, charactersKey3, charactersKey4, charactersKey5, charactersKey6, charactersKey7, charactersKey8, charactersKey9 }; public static boolean usesDynamicCharset; //#endif private static final String[] EMAIL_CHARACTERS = new String[]{ VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS + "0", VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS + "1", "abc2", "def3", "ghi4", "jkl5", "mno6", "pqrs7", "tuv8", "wxyz9" }; private String[] characters; private boolean isNumeric; private boolean isDecimal; private boolean isEmail; private boolean isUrl; private int rowHeight; //#if polish.TextField.includeInputInfo //#define tmp.includeInputInfo //#define tmp.useInputInfo protected StringItem infoItem; //#elif polish.TextField.showInputInfo != false //#define tmp.useInputInfo //#endif protected final Object lock = new Object(); private long deleteKeyRepeatCount; //#endif protected char emailSeparatorChar = ';'; //#if polish.android private AndroidTextField _androidTextField; //#endif //#if polish.blackberry private PolishTextField editField; //#if polish.Bugs.ItemStateListenerCalledTooEarly private long lastFieldChangedEvent; //#endif private int bbLastCursorPosition; //#endif //#if polish.series40sdk20 || polish.series40sdk11 private TextEditor series40sdk20Field; //#endif //#if polish.midp && !(polish.blackberry || polish.android || polish.api.windows) && !polish.TextField.useVirtualKeyboard //#define tmp.useNativeTextBox private de.enough.polish.midp.ui.TextBox midpTextBox; //#if polish.TextField.passCharacterToNativeEditor //Variable passedChar used as container for char which is passed to native TextBox. //So when key is pressed (e.g. '2') view goes to native mode and 'a' character is appended to the current text private char passedChar; //Timer responsible for checking delay between two, subsequent presses private final Timer keyDelayTimer = new Timer(); private TimerTask keyDelayTimerTask = null; //last time when button was pressed private long lastTimeKeyPressed; //number of presses of one phone button private int keyPressCounter = 0; //latest key pressed keyCode private int latestKey; //maximum delay between subseqent key presses. If exceeded, will timer will call native editor. private int delayBetweenKeys = //#if polish.nativeEditor.delayBetweenKeys:defined //#= ${polish.nativeEditor.delayBetweenKeys}; //#else 200; //#endif //#endif private boolean skipKeyReleasedEvent = false; //#endif private boolean cskOpensNativeEditor = true; //#if tmp.usePredictiveInput long lastTimePressed = -1; boolean predictiveInput = false; private PredictiveAccess predictiveAccess; boolean nextMode = this.predictiveInput; static final int SWITCH_DELAY = 1000; //#endif protected boolean flashCaret = true; protected boolean isUneditable; private boolean isShowInputInfo = true; private boolean suppressCommands = false; //#if polish.TextField.showHelpText private StringItem helpItem; //#endif //#if polish.key.maybeSupportsAsciiKeyMap private static boolean useAsciiKeyMap = false; //#endif //#if polish.key.supportsAsciiKeyMap || polish.key.maybeSupportsAsciiKeyMap //#define tmp.supportsAsciiKeyMap //#endif private boolean isKeyPressedHandled; private int numberOfDecimalFractions = 2; //#if polish.TextField.useVirtualKeyboard static IntHashMap keyboardViews = new IntHashMap(); //#endif //#if tmp.useDynamicCharset /** * Reads the .properties files for lowercase * and uppercase letters and maps the values of the predefined keys * to the character maps. Uses UTF-8 as encoding. * @param lowercaseUrl the properties file for lower case * @param uppercaseUrl the properties file for upper case */ public static void loadCharacterSets(String lowercaseUrl,String uppercaseUrl) { loadCharacterSets(lowercaseUrl, uppercaseUrl,"UTF8"); } /** * Reads the .properties files for lowercase * and uppercase letters and maps the values of the predefined keys * to the character maps. Uses UTF-8 as encoding. * @param lowercaseStream the input stream of properties for lower case * @param uppercaseStream the input stream of properties for upper case */ public static void loadCharacterSets(InputStream lowercaseStream, InputStream uppercaseStream) { loadCharacterSets(lowercaseStream, uppercaseStream,"UTF8"); } /** * Reads the .properties files for lowercase * and uppercase letters and maps the values of the predefined keys * to the character maps. * @param lowercaseUrl the properties file for lower case * @param uppercaseUrl the properties file for upper case * @param encoding the encoding to use */ public static void loadCharacterSets(String lowercaseUrl,String uppercaseUrl, String encoding) { loadCharacterSets(CHARACTERS,lowercaseUrl, encoding); loadCharacterSets(CHARACTERS_UPPER,uppercaseUrl, encoding); try { validateSets(); usesDynamicCharset = true; }catch(IllegalArgumentException e) { //#debug error System.out.println("unable to load dynamic character sets : " + e.getMessage()); } } /** * Reads the .properties files for lowercase * and uppercase letters and maps the values of the predefined keys * to the character maps. * @param lowercaseStream the properties file for lower case * @param uppercaseStream the properties file for upper case * @param encoding the encoding to use */ public static void loadCharacterSets(InputStream lowercaseStream,InputStream uppercaseStream, String encoding) { loadCharacterSets(CHARACTERS,lowercaseStream, encoding); loadCharacterSets(CHARACTERS_UPPER,uppercaseStream, encoding); try { validateSets(); usesDynamicCharset = true; }catch(IllegalArgumentException e) { //#debug error System.out.println("unable to load dynamic character sets : " + e.getMessage()); } } /** * Validates the character sets for lowercase and uppercase by * comparing the number of entries for a key * @throws IllegalArgumentException */ static void validateSets() throws IllegalArgumentException { for (int i = 0; i < CHARACTERS.length; i++) { if(CHARACTERS[i].length() != CHARACTERS_UPPER[i].length()) { throw new IllegalArgumentException("the dynamic charsets have a different number of entries at index " + i); } } } /** * Reads a .properties file and maps * the values of the predefined keys * to the specified character maps * @param target the character map * @param url the properties file * @param encoding the encoding */ static void loadCharacterSets(String[] target, String url, String encoding) { Properties properties; try { properties = new Properties(url,encoding); loadCharacterSets(target,properties); } catch (IOException e) { //#debug error System.out.println("unable to load character set : " + url); } } /** * Reads a .properties file and maps * the values of the predefined keys * to the specified character maps * @param target the character map * @param stream the properties file * @param encoding the encoding */ static void loadCharacterSets(String[] target, InputStream stream, String encoding) { Properties properties; try { properties = new Properties(); properties.load(stream, encoding, false); loadCharacterSets(target,properties); } catch (IOException e) { //#debug error System.out.println("unable to load character set : " + stream.toString()); } } /** * Reads a .properties file and maps * the values of the predefined keys * to the character maps * @param target the character map * @param properties the properties file */ static void loadCharacterSets(String[] target, Properties properties) { //#if tmp.directInput Object[] keys = properties.keys(); for (int i = 0; i < keys.length; i++) { String key = (String)keys[i]; try { int index = Integer.parseInt(key); target[index] = properties.getProperty(key); }catch(NumberFormatException e) { //#debug error System.out.println("key " + key + " has wrong format, must be 0 - 9" ); } } //#endif } //#endif /** * Creates a new <code>TextField</code> object with the given label, initial * contents, maximum size in characters, and constraints. * If the text parameter is <code>null</code>, the * <code>TextField</code> is created empty. * The <code>maxSize</code> parameter must be greater than zero. * An <code>IllegalArgumentException</code> is thrown if the * length of the initial contents string exceeds <code>maxSize</code>. * However, * the implementation may assign a maximum size smaller than the * application had requested. If this occurs, and if the length of the * contents exceeds the newly assigned maximum size, the contents are * truncated from the end in order to fit, and no exception is thrown. * * @param label item label * @param text the initial contents, or null if the TextField is to be empty * @param maxSize the maximum capacity in characters * @param constraints see input constraints * @throws IllegalArgumentException if maxSize is zero or less * or if the value of the constraints parameter is invalid * or if text is illegal for the specified constraints * or if the length of the string exceeds the requested maximum capacity */ public TextField( String label, String text, int maxSize, int constraints) { this( label, text, maxSize, constraints, null ); } /** * Creates a new <code>TextField</code> object with the given label, initial * contents, maximum size in characters, and constraints. * If the text parameter is <code>null</code>, the * <code>TextField</code> is created empty. * The <code>maxSize</code> parameter must be greater than zero. * An <code>IllegalArgumentException</code> is thrown if the * length of the initial contents string exceeds <code>maxSize</code>. * However, * the implementation may assign a maximum size smaller than the * application had requested. If this occurs, and if the length of the * contents exceeds the newly assigned maximum size, the contents are * truncated from the end in order to fit, and no exception is thrown. * * @param label item label * @param text the initial contents, or null if the TextField is to be empty * @param maxSize the maximum capacity in characters * @param constraints see input constraints * @param style the CSS style for this field * @throws IllegalArgumentException if maxSize is zero or less * or if the value of the constraints parameter is invalid * or if text is illegal for the specified constraints * or if the length of the string exceeds the requested maximum capacity */ public TextField( String label, String text, int maxSize, int constraints, Style style) { super( label, null, INTERACTIVE, style ); //#if polish.vendor == Generic && tmp.directInput int spaceKey = DeviceInfo.getKeySpace(); if (spaceKey == Canvas.KEY_POUND) { charactersKey0 = "0"; charactersKeyPound = " "; } //#endif this.maxSize = maxSize; if (label != null) { this.title = label; } else { //#ifdef polish.title.input:defined //#= this.title = "${polish.title.input}"; //#else this.title = "Input"; //#endif } if ((constraints & PASSWORD) == PASSWORD) { this.isPassword = true; } //#ifndef polish.hasPointerEvents int fieldType = constraints & 0xffff; if (fieldType == NUMERIC) { this.enableDirectInput = true; } //#endif //#if tmp.forceDirectInput this.enableDirectInput = true; //#endif setConstraints(constraints); //#if tmp.usePredictiveInput this.predictiveAccess = new PredictiveAccess(); this.predictiveAccess.init(this); //#endif //#if polish.TextField.showHelpText //#style help? this.helpItem = new StringItem(null,null); /* if (style != null && this.helpItem.style != null && this.helpItem.style.font == null) { this.helpItem.style.font = style.font; }*/ /*Font font = this.helpItem.getFont(); Font newFont = Font.getFont(font.getFace(), font.getStyle(), this.getFont().getSize()); this.helpItem.setFont(newFont);*/ //#ifdef polish.TextField.help:defined //#= this.helpItem.setText("${polish.TextField.help}"); //#else this.helpItem.setText("type text here"); //#endif //#endif //#if polish.key.maybeSupportsAsciiKeyMap //#if polish.api.windows if (Keyboard.needsQwertzAndNumericSupport()) { addCommand(SWITCH_KEYBOARD_CMD); } useAsciiKeyMap = true; //#endif //#endif //#if polish.TextField.noNewLine this.noNewLine = true; //#endif setString(text); } //#if tmp.useNativeTextBox /** * Creates the TextBox used for the actual input mode. */ private void createTextBox() { String currentText = this.isPassword ? this.passwordText : this.text; this.midpTextBox = new de.enough.polish.midp.ui.TextBox( this.title, currentText, this.maxSize, getMidpConstraints() ); this.midpTextBox.addCommand(StyleSheet.OK_CMD); if (!this.isUneditable) { this.midpTextBox.addCommand(StyleSheet.CANCEL_CMD); } this.midpTextBox.setCommandListener( this ); //#if polish.midp2 if ((this.constraints & TextField.INITIAL_CAPS_NEVER) == TextField.INITIAL_CAPS_NEVER){ this.midpTextBox.setInitialInputMode("MIDP_LOWERCASE_LATIN"); } //#endif } //#endif /** * Converts the current constraints into MIDP compatible ones * @return MIDP compatible constraints */ public int getMidpConstraints() { int cont = this.constraints; if ((cont & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL) { cont = cont & ~FIXED_POINT_DECIMAL | DECIMAL; } return cont; } /** * Gets the contents of the <code>TextField</code> as a string value. * * @return the current contents, an empty string when the current value is null. * @see #setString(java.lang.String) */ public String getString() { //#if polish.blackberry if ( this.editField != null ) { return this.editField.getText(); } //#endif //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null ) { return this.series40sdk20Field.getContent(); } //#endif if ( this.isPassword ) { if (this.passwordText == null) { return ""; } return this.passwordText; } else { if (this.text == null) { return ""; } return this.text; } } /** * Retrieves the decimal value entered with a dot as the decimal mark. * <ul> * <li>When the value has no decimal places it will be returned as it is: 12</li> * <li>When the value is null, null will be returned: null</li> * <li>When the value has decimal places, a dot will be used: 12.3</li> * </ul> * @return either the formatted value or null, when there was no input. * @throws IllegalStateException when the TextField is not DECIMAL constrained */ public String getDotSeparatedDecimalString() { //#if tmp.directInput //#if tmp.allowDirectInput if (this.enableDirectInput) { //#endif if (!this.isDecimal) { throw new IllegalStateException(); } String value = getString(); if ((this.constraints & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL) { // remove grouping separator: StringBuffer buffer = new StringBuffer(value.length()); for (int i=0; i<value.length(); i++) { char c = value.charAt(i); if (c == Locale.DECIMAL_SEPARATOR) { buffer.append('.'); } else if (c != Locale.GROUPING_SEPARATOR) { buffer.append(c); } } return buffer.toString(); } if ( Locale.DECIMAL_SEPARATOR == '.' || value == null) { return value; } else { return value.replace( Locale.DECIMAL_SEPARATOR, '.'); } //#if tmp.allowDirectInput } //#endif //#endif //#if !tmp.forceDirectInput if (( getConstraints() & DECIMAL)!= DECIMAL) { throw new IllegalStateException(); } String value = getString(); if (value == null) { return null; } return value.replace(',', '.'); //#endif } /** * Sets the contents of the <code>TextField</code> as a string * value, replacing the previous contents. * * @param text the new value of the TextField, or null if the TextField is to be made empty * @throws IllegalArgumentException if text is illegal for the current input constraints * or if the text would exceed the current maximum capacity * @see #getString() */ public void setString( String text) { //#debug System.out.println("setString [" + text + "] for " + this); //#if polish.android int cursorAdjustment = 0; //#endif if (text != null && text.length() > 0) { int fieldType = this.constraints & 0xffff; if (fieldType == FIXED_POINT_DECIMAL) { int lengthBefore = text.length(); text = convertToFixedPointDecimal(text, true); int lengthAfter = text.length(); //#if polish.android if (lengthAfter > lengthBefore) { cursorAdjustment = lengthAfter - lengthBefore; } else if (this.text != null && this.text.length() > 0 && this.text.charAt(0) == '0') { cursorAdjustment = 1; } //#elif !polish.blackberry if (lengthAfter > lengthBefore) { setCaretPosition( getCaretPosition() + lengthAfter - lengthBefore); } //#endif } } //#if tmp.useNativeTextBox if (this.midpTextBox != null) { this.midpTextBox.setString( text ); } //#endif //#if polish.android if (this._androidTextField != null) { if (text == null) { text = ""; } String currentText = this._androidTextField.getText().toString(); if (!currentText.equals(text)) { this._androidTextField.setTextKeepState(text); if (cursorAdjustment != 0) { this._androidTextField.moveCursor( cursorAdjustment ); } } } //#endif //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null && !this.series40sdk20Field.getContent().equals(text)) { this.series40sdk20Field.setContent(text); } //#endif //#if polish.blackberry if (this.editField != null && !this.editField.getText().equals(text) ) { Object bbLock = UiApplication.getEventLock(); if (this.screen == null) { this.screen = getScreen(); } synchronized (bbLock) { if (this.isFocused && this.isShown) { // don't want to have endless loops of change events: this.screen.notifyFocusSet(null); } if (text != null) { this.editField.setText(text); } else { this.editField.setText(""); // setting null triggers an IllegalArgumentException } if (this.isFocused && this.isShown) { this.screen.notifyFocusSet(this); } } } //#endif if (this.isPassword) { this.passwordText = text; if (text != null) { int length = text.length(); StringBuffer buffer = new StringBuffer( length ); for (int i = 0; i < length; i++) { buffer.append('*'); } text = buffer.toString(); } } //#ifdef tmp.directInput if (text == null) { this.caretPosition = 0; this.caretRow = 0; this.caretColumn = 0; this.caretX = 0; this.caretY = 0; } else if ( (this.caretPosition == 0 && (this.text == null || this.text.length() == 0) ) || ( this.caretPosition > text.length()) || (this.text != null && text != null && text.length() > (this.text.length()+1)) ) { this.caretPosition = text.length(); } //#endif //#if tmp.updateDeleteCommand if (this.isFocused) { updateDeleteCommand( text ); } //#endif setText(text); //#ifdef tmp.directInput if ((text == null || text.length() == 0) && this.inputMode == MODE_FIRST_UPPERCASE) { this.nextCharUppercase = true; } //#if polish.css.textfield-show-length && tmp.useInputInfo if (this.isFocused && this.showLength) { updateInfo(); } //#endif //#endif //#if tmp.usePredictiveInput if(this.predictiveInput) { this.predictiveAccess.synchronize(); } //#endif } /** * Sets the number of decimal fractions that are allowed for FIXED_POINT_DECIMAL constrained TextFields * @param number the number (defaults to 2) * @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL * @see #FIXED_POINT_DECIMAL */ public void setNumberOfDecimalFractions(int number) { this.numberOfDecimalFractions = number; } /** * Retrieves the number of decimal fractions that are allowed for FIXED_POINT_DECIMAL constrained TextFields * @return the number (defaults to 2) * @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL * @see #FIXED_POINT_DECIMAL */ public int getNumberOfDecimalFractions() { return this.numberOfDecimalFractions; } /** * Converts the given entry into cash format without grouping separator. * Subclasses may override this to implement their own behavior. * @param original the original text, e.g. "1" * @return the processed text, e.g. "0.01" * @see #FIXED_POINT_DECIMAL * @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL * @see #getNumberOfDecimalFractions() * @see #setNumberOfDecimalFractions(int) * @see #convertToFixedPointDecimal(String, boolean) */ protected String convertToFixedPointDecimal(String original) { return convertToFixedPointDecimal(original, false); } /** * Converts the given entry into cash format. * Subclasses may override this to implement their own behavior. * @param original the original text, e.g. "1" * @param addGroupingSeparator true when a grouping separator should be added like "1,000.00" * @return the processed text, e.g. "0.01" * @see #FIXED_POINT_DECIMAL * @see UiAccess#CONSTRAINT_FIXED_POINT_DECIMAL * @see #getNumberOfDecimalFractions() * @see #setNumberOfDecimalFractions(int) */ protected String convertToFixedPointDecimal(String original, boolean addGroupingSeparator) { int fractions = this.numberOfDecimalFractions; StringBuffer buffer = new StringBuffer( original.length() + 3 ); int added = 0; for (int i=original.length(); --i >= 0; ) { char c = original.charAt(i); if (c >= '0' && c <= '9') { buffer.insert(0, c); added++; if (added == fractions) { buffer.insert(0, Locale.DECIMAL_SEPARATOR); } } } fractions++; while (added > fractions) { char c = buffer.charAt(0); if (c == '0') { buffer.deleteCharAt(0); added--; } else { break; } } while (added < fractions) { buffer.insert(0, '0'); added++; if (added == fractions-1) { buffer.insert(0, Locale.DECIMAL_SEPARATOR); } } if (addGroupingSeparator) { int numberBeforeDecimalSeparator = buffer.length() - fractions - 1; if (numberBeforeDecimalSeparator >= 3) { for (int i = 3; i<=numberBeforeDecimalSeparator; i+=3) { int pos = numberBeforeDecimalSeparator - i + 1; buffer.insert(pos, Locale.GROUPING_SEPARATOR); } } } original = buffer.toString(); return original; } protected void updateDeleteCommand(String newText) { //#if tmp.updateDeleteCommand // remove delete command when the caret is before the first character, // add it when it is after the first character: // #debug //System.out.println("updateDeleteCommand: newText=[" + newText + "]"); if ( !this.isUneditable ) { if ( newText == null //#ifdef tmp.directInput || (this.caretPosition == 0 && this.caretChar == this.editingCaretChar) //#else || newText.length() == 0 //#endif ) { removeCommand( DELETE_CMD ); } else if ((this.text == null || this.text.length() == 0) //#if tmp.directInput // needed for native input as the string is passed as a whole // and thus skips caretPosition == 1 || this.caretPosition > 0 //#endif ) { addCommand( DELETE_CMD ); } } //#endif } /** * Copies the contents of the <code>TextField</code> into a character array starting at index zero. * Array elements beyond the characters copied are left * unchanged. * * @param data the character array to receive the value * @return the number of characters copied * @throws ArrayIndexOutOfBoundsException if the array is too short for the contents * @throws NullPointerException if data is null * @see #setChars(char[], int, int) */ public int getChars(char[] data) { if (this.text == null) { return 0; } String txt = this.text; if (this.isPassword) { txt = this.passwordText; } char[] textArray = txt.toCharArray(); System.arraycopy(textArray, 0, data, 0, textArray.length ); return textArray.length; } /** * Sets the contents of the <code>TextField</code> from a character array, * replacing the previous contents. * Characters are copied from the region of the * <code>data</code> array * starting at array index <code>offset</code> and running for * <code>length</code> characters. * If the data array is <code>null</code>, the <code>TextField</code> * is set to be empty and the other parameters are ignored. * * <p>The <code>offset</code> and <code>length</code> parameters must * specify a valid range of characters within * the character array <code>data</code>. * The <code>offset</code> parameter must be within the * range <code>[0..(data.length)]</code>, inclusive. * The <code>length</code> parameter * must be a non-negative integer such that * <code>(offset + length) &lt;= data.length</code>.</p> * * @param data the source of the character data * @param offset the beginning of the region of characters to copy * @param length the number of characters to copy * @throws ArrayIndexOutOfBoundsException - if offset and length do not specify a valid range within the data array * @throws IllegalArgumentException - if data is illegal for the current input constraints * or if the text would exceed the current maximum capacity * @see #getChars(char[]) */ public void setChars(char[] data, int offset, int length) { char[] copy = new char[ length ]; System.arraycopy(data, offset, copy, 0, length ); setString( new String( copy )); } /** * Inserts a string into the contents of the * <code>TextField</code>. The string is * inserted just prior to the character indicated by the * <code>position</code> parameter, where zero specifies the first * character of the contents of the <code>TextField</code>. If * <code>position</code> is * less than or equal to zero, the insertion occurs at the beginning of * the contents, thus effecting a prepend operation. If * <code>position</code> is greater than or equal to the current size of * the contents, the insertion occurs immediately after the end of the * contents, thus effecting an append operation. For example, * <code>text.insert(s, text.size())</code> always appends the string * <code>s</code> to the current contents. * * <p>The current size of the contents is increased by the number of * inserted characters. The resulting string must fit within the current * maximum capacity. </p> * * <p>If the application needs to simulate typing of characters it can * determining the location of the current insertion point * (&quot;caret&quot;) * using the with <CODE>getCaretPosition()</CODE> method. * For example, * <code>text.insert(s, text.getCaretPosition())</code> inserts the string * <code>s</code> at the current caret position.</p> * * @param src the String to be inserted * @param position the position at which insertion is to occur * @throws IllegalArgumentException if the resulting contents would be illegal for the current input constraints * or if the insertion would exceed the current maximum capacity * @throws NullPointerException if src is null */ public void insert( String src, int position) { String txt = getString(); // cannot be null String start = txt.substring( 0, position ); String end = txt.substring( position ); setString( start + src + end ); //#if tmp.directInput if (position == this.caretPosition) { this.caretPosition += src.length(); } //#else setCaretPosition( getCaretPosition() + src.length() ); //#endif //#if tmp.usePredictiveInput if(this.predictiveInput) this.predictiveAccess.synchronize(); //#endif } /** * Inserts a subrange of an array of characters into the contents of * the <code>TextField</code>. The <code>offset</code> and * <code>length</code> parameters indicate the subrange * of the data array to be used for insertion. Behavior is otherwise * identical to <A HREF="../../../javax/microedition/lcdui/TextField.html#insert(java.lang.String, int)"><CODE>insert(String, int)</CODE></A>. * * <p>The <code>offset</code> and <code>length</code> parameters must * specify a valid range of characters within * the character array <code>data</code>. * The <code>offset</code> parameter must be within the * range <code>[0..(data.length)]</code>, inclusive. * The <code>length</code> parameter * must be a non-negative integer such that * <code>(offset + length) &lt;= data.length</code>.</p> * * @param data - the source of the character data * @param offset - the beginning of the region of characters to copy * @param length - the number of characters to copy * @param position - the position at which insertion is to occur * @throws ArrayIndexOutOfBoundsException - if offset and length do not specify a valid range within the data array * @throws IllegalArgumentException - if the resulting contents would be illegal for the current input constraints * or if the insertion would exceed the current maximum capacity * @throws NullPointerException - if data is null */ public void insert(char[] data, int offset, int length, int position) { char[] copy = new char[ length ]; System.arraycopy( data, offset, copy, 0, length); insert( new String( copy ), position ); } /** * Deletes characters from the <code>TextField</code>. * * <p>The <code>offset</code> and <code>length</code> parameters must * specify a valid range of characters within * the contents of the <code>TextField</code>. * The <code>offset</code> parameter must be within the * range <code>[0..(size())]</code>, inclusive. * The <code>length</code> parameter * must be a non-negative integer such that * <code>(offset + length) &lt;= size()</code>.</p> * * @param offset the beginning of the region to be deleted * @param length the number of characters to be deleted * @throws IllegalArgumentException if the resulting contents would be illegal for the current input constraints * @throws StringIndexOutOfBoundsException if offset and length do not specify a valid range within the contents of the TextField */ public void delete(int offset, int length) { String txt = getString(); String start = txt.substring(0, offset ); String end = txt.substring( offset + length ); setString( start + end ); } /** * Returns the maximum size (number of characters) that can be * stored in this <code>TextField</code>. * * @return the maximum size in characters * @see #setMaxSize(int) */ public int getMaxSize() { return this.maxSize; } /** * Sets the maximum size (number of characters) that can be contained * in this * <code>TextField</code>. If the current contents of the * <code>TextField</code> are larger than * <code>maxSize</code>, the contents are truncated to fit. * * @param maxSize the new maximum size * @return assigned maximum capacity may be smaller than requested. * @throws IllegalArgumentException if maxSize is zero or less. * or if the contents after truncation would be illegal for the current input constraints * @see #getMaxSize() */ public int setMaxSize(int maxSize) { if ((this.text != null && maxSize < this.text.length()) || (maxSize < 1)) { throw new IllegalArgumentException(); } //#if tmp.useNativeTextBox if (this.midpTextBox != null) { this.maxSize = this.midpTextBox.setMaxSize(maxSize); return this.maxSize; } else { //#endif this.maxSize = maxSize; return maxSize; //#if tmp.useNativeTextBox } //#endif } /** * Gets the number of characters that are currently stored in this * <code>TextField</code>. * * @return number of characters in the TextField */ public int size() { if (this.text == null) { return 0; } else { return this.text.length(); } } /** * Gets the current input position. For some UIs this may block and ask * the user for the intended caret position, and on other UIs this may * simply return the current caret position. * When the direct input mode is used, this method simply returns the current cursor position (= non blocking). * * @return the current caret position, 0 if at the beginning */ public int getCaretPosition() { int curPos = 0; //#if polish.android curPos = this._androidTextField.getCursorPosition(); //#elif tmp.allowDirectInput if (this.enableDirectInput) { curPos = this.caretPosition; //#if tmp.useNativeTextBox } else if (this.midpTextBox != null) { curPos = this.midpTextBox.getCaretPosition(); //#endif } //#elif polish.blackberry curPos = this.editField.getInsertPositionOffset(); //#elif tmp.forceDirectInput curPos = this.caretPosition; //#elif polish.series40sdk20 || polish.series40sdk11 curPos = this.series40sdk20Field.getCaretPosition(); //#else //#ifdef tmp.useNativeTextBox if (this.midpTextBox != null) { curPos = this.midpTextBox.getCaretPosition(); } //#endif //#endif return curPos; } /** * Sets the caret position. * Please note that this operation requires the direct input mode to work. * * @param position the new caret position, 0 puts the caret at the start of the line, getString().length moves the caret to the end of the input. */ public void setCaretPosition(int position) { //#if polish.android try { AndroidTextField nativeField = this._androidTextField; if (nativeField == null) { this.caretPosition = position; } else { this.caretPosition = -1; nativeField.setCursorPosition(position); } } catch (IndexOutOfBoundsException e) { // ignore } //#elif polish.blackberry Object bbLock = Application.getEventLock(); synchronized ( bbLock ) { this.editField.setCursorPosition(position); } //#elif polish.series40sdk20 || polish.series40sdk11 synchronized ( this.series40sdk20Field) { this.series40sdk20Field.setCaret(position); } //#elif tmp.allowDirectInput || tmp.forceDirectInput this.caretPosition = position; if ( this.isInitialized && this.realTextLines != null ){ int row = 0; int col = 0; int passedCharacters = 0; String textLine = null; for (int i = 0; i < this.textLines.size(); i++) { textLine = this.realTextLines[i]; //this.textLines[i]; passedCharacters += textLine.length(); //System.out.println("passedCharacters=" + passedCharacters + ", line=" + textLine ); if (passedCharacters >= position ) { row = i; col = textLine.length() - (passedCharacters - position); break; } } //#debug System.out.println("setCaretPosition, position=" + position + ", row=" + row + ", col=" + col ); this.caretRow = row; this.caretColumn = col; textLine = this.textLines.getLine( row ); String firstPart; if (this.caretColumn < textLine.length()) { firstPart = textLine.substring(0, this.caretColumn); } else { firstPart = textLine; } if (this.isPassword) { this.caretX = stringWidth( "*" ) * firstPart.length(); } else { this.caretX = stringWidth( firstPart ); } this.internalY = this.caretRow * this.rowHeight; this.caretY = this.internalY; repaint(); } //#endif } //#if polish.android /** * Creates the native Android implementation for the text input. * Subclasses may override this is to use custom classes. Note that the <code>polish.android</code> preprocessing symbol needs to be checked: <code>//#if polish.android</code>. * @return new AndroidTextFieldImpl(TextField.this) by default. */ protected AndroidTextField createNativeAndroidTextField() { return new AndroidTextFieldImpl(TextField.this); } //#endif //#if polish.series40sdk20 || polish.series40sdk11 protected TextEditor createNativeNokiaTextField() { TextEditor editor = TextEditor.createTextEditor( 9999, TextField.ANY, 50, 50); editor.setVisible(true); editor.setTouchEnabled(true); editor.setSize(1, 1); editor.setMultiline(true); return editor; } //#endif /** * Sets the input constraints of the <code>TextField</code>. If * the the current contents * of the <code>TextField</code> do not match the new * <code>constraints</code>, the contents are * set to empty. * * @param constraints see input constraints * @throws IllegalArgumentException if constraints is not any of the ones specified in input constraints * @see #getConstraints() */ public void setConstraints(int constraints) { if (constraints == this.constraints) { // ignore return; } this.constraints = constraints; int fieldType = constraints & 0xffff; this.isUneditable = (constraints & UNEDITABLE) == UNEDITABLE; //#if polish.css.text-wrap this.animateTextWrap = this.isUneditable; //#endif //#if polish.android MidletBridge.getInstance().runOnUiThread( new Runnable() { public void run() { if ( (TextField.this.isShown) && (TextField.this._androidView != null) ) { // remove existing view first: AndroidDisplay.getInstance().onHide(TextField.this._androidView, TextField.this); } AndroidTextField nativeField = createNativeAndroidTextField(); TextField.this._androidTextField = nativeField; TextField.this._androidView = (View) nativeField; if (TextField.this.isShown) { AndroidDisplay.getInstance().onShow(TextField.this._androidView, TextField.this); } int caretPos = TextField.this.caretPosition; if (caretPos != -1) { TextField.this._androidTextField.setCursorPosition(caretPos); TextField.this.caretPosition = -1; } } }); //#endif //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field == null ) { this.series40sdk20Field = createNativeNokiaTextField(); //#= this.series40sdk20Field.setTextEditorListener(this); inputAction(this.series40sdk20Field, 0); } this.enableDirectInput = true; //#endif //#if polish.blackberry int filterType = TextFilter.DEFAULT; long bbStyle = Field.FOCUSABLE; if (this.isUneditable) { bbStyle |= Field.READONLY; } else { bbStyle |= Field.EDITABLE; } if ( fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) { bbStyle |= BasicEditField.FILTER_REAL_NUMERIC; filterType = TextFilter.REAL_NUMERIC; } else if (fieldType == NUMERIC) { bbStyle |= BasicEditField.FILTER_INTEGER; filterType = TextFilter.INTEGER; } else if (fieldType == PHONENUMBER) { bbStyle |= BasicEditField.FILTER_PHONE; filterType = TextFilter.PHONE; } else if (fieldType == EMAILADDR ) { bbStyle |= BasicEditField.FILTER_EMAIL; filterType = TextFilter.EMAIL; } else if ( fieldType == URL ) { bbStyle |= BasicEditField.FILTER_URL; filterType = TextFilter.URL; } if ((constraints & SENSITIVE) == SENSITIVE) { bbStyle |= BasicEditField.NO_LEARNING; } if ((constraints & NON_PREDICTIVE) == NON_PREDICTIVE) { bbStyle |= BasicEditField.NO_LEARNING; } if(this.noNewLine){ bbStyle |= BasicEditField.NO_NEWLINE; } if(this.noComplexInput){ bbStyle |= BasicEditField.NO_COMPLEX_INPUT; } if (this.editField != null) { // remove the old edit field from the blackberry screen: Object bbLock = Application.getEventLock(); synchronized ( bbLock ) { Manager manager = this._bbField.getManager(); if (manager != null) { manager.delete(this._bbField); } if (this.isFocused) { getScreen().notifyFocusSet(this); } } } int max = this.maxSize; if (fieldType == FIXED_POINT_DECIMAL) { int possibleGroupingSeparators = (max - this.numberOfDecimalFractions) / 3; max = max + 1 + possibleGroupingSeparators; // this is for the dot and the grouping separator } this.isPassword = false; if ((constraints & PASSWORD) == PASSWORD) { this.isPassword = true; this.editField = new PolishPasswordEditField( null, getString(), max, bbStyle ); }else if((bbStyle & BasicEditField.FILTER_EMAIL) == BasicEditField.FILTER_EMAIL) { this.editField = new PolishEmailAddressEditField( null, getString(), max, bbStyle ); } else { Style fieldStyle = getStyle(); if ( (fieldStyle != null) && (fieldStyle.getBooleanProperty("text-wrap") != null) && (fieldStyle.getBooleanProperty("text-wrap").booleanValue() == false) ) { this.editField = new PolishOneLineField( null, getString(), max, bbStyle ); //#if polish.css.max-lines fieldStyle.addAttribute("max-lines", new Integer(1)); //#endif //#if polish.css.max-height if (fieldStyle.getFont() != null) { fieldStyle.addAttribute("max-height", new Dimension(fieldStyle.getFont().getHeight())); } //#endif } else { this.editField = new PolishEditField(null, getString(), max, bbStyle); } } if ( fieldType == FIXED_POINT_DECIMAL) { this.editField.setFilter( new FixedPointDecimalTextFilter()); } else { this.editField.setFilter(TextFilter.get(filterType)); } if (this.style != null) { this.editField.setStyle( this.style ); } //# this.editField.setChangeListener( this ); this._bbField = (Field) this.editField; //#elif tmp.useNativeTextBox if (this.midpTextBox != null) { this.midpTextBox.setConstraints(constraints); } if ((constraints & PASSWORD) == PASSWORD) { this.isPassword = true; } //#endif //#ifdef tmp.directInput this.characters = CHARACTERS; this.isEmail = false; this.isUrl = false; if ((constraints & PASSWORD) == PASSWORD) { this.isPassword = true; } if (fieldType == NUMERIC || fieldType == PHONENUMBER) { this.isNumeric = true; this.inputMode = MODE_NUMBERS; //#ifndef polish.hasPointerEvents this.enableDirectInput = true; //#endif } else { this.isNumeric = false; } if (fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) { this.isNumeric = true; this.isDecimal = true; this.inputMode = MODE_NUMBERS; } else { this.isDecimal = false; } if (fieldType == EMAILADDR) { this.isEmail = true; this.characters = EMAIL_CHARACTERS; } if (fieldType == URL) { this.isUrl = true; } if ((constraints & INITIAL_CAPS_WORD) == INITIAL_CAPS_WORD) { this.inputMode = MODE_FIRST_UPPERCASE; this.nextCharUppercase = true; } //#if tmp.useInputInfo updateInfo(); //#endif //#endif //#if !tmp.suppressCommands //#if (polish.TextField.suppressDeleteCommand != true) removeCommand( DELETE_CMD ); //#endif //#if polish.TextField.suppressClearCommand != true removeCommand( CLEAR_CMD ); //#endif //#if tmp.directInput && tmp.supportsSymbolEntry && polish.TextField.suppressAddSymbolCommand != true removeCommand( ENTER_SYMBOL_CMD ); //#endif //#endif // set item commands: //#if !tmp.suppressCommands if(!this.suppressCommands) { if (this.isFocused) { getScreen().removeItemCommands( this ); } // add default text field item-commands: //#if (polish.TextField.suppressDeleteCommand != true) && !polish.blackberry if (!this.isUneditable) { //#ifdef polish.i18n.useDynamicTranslations String delLabel = Locale.get("polish.command.delete"); if ( delLabel != DELETE_CMD.getLabel()) { DELETE_CMD = new Command( delLabel, Command.CANCEL, DELETE_PRIORITY ); } //#endif this.addCommand(DELETE_CMD); } //#endif //#if polish.TextField.suppressClearCommand != true if (!this.isUneditable) { //#ifdef polish.i18n.useDynamicTranslations String clearLabel = Locale.get("polish.command.clear"); if ( clearLabel != CLEAR_CMD.getLabel()) { CLEAR_CMD = new Command( clearLabel, Command.ITEM, CLEAR_PRIORITY ); } //#endif this.addCommand(CLEAR_CMD); } //#endif //#if tmp.directInput && tmp.supportsSymbolEntry && polish.TextField.suppressAddSymbolCommand != true if (!this.isNumeric) { if (!this.isUneditable) { //#ifdef polish.i18n.useDynamicTranslations String enterSymbolLabel = Locale.get("polish.command.entersymbol"); if ( enterSymbolLabel != ENTER_SYMBOL_CMD.getLabel()) { ENTER_SYMBOL_CMD = new Command( enterSymbolLabel, Command.ITEM, ENTER_SYMBOL_PRIORITY ); } //#endif this.addCommand(ENTER_SYMBOL_CMD); } } //#endif } this.itemCommandListener = this; if (this.isFocused) { showCommands(); } // end of if !tmp.suppressCommands: //#endif // if ( (constraints & UNEDITABLE) == UNEDITABLE) { // // deactivate this field: // super.setAppearanceMode( Item.PLAIN ); // if (this.isInitialised && this.isFocused && this.parent instanceof Container) { // ((Container)this.parent).requestDefocus( this ); // } // } else { // super.setAppearanceMode( Item.INTERACTIVE ); // } } /** * Sets a blackberry field to selectable. * Used to prevent fields to be selectable if they should not be shown. * You should check for the 'polish.blackberry' preprocessing symbol when using this method: * <pre> * //#if polish.blackberry * </pre> * * @param editable true, if the textfield should be selectable, otherwise false */ public void activate(boolean editable) { //#if polish.blackberry Object bbLock = Application.getEventLock(); synchronized (bbLock) { if (editable) { if(this._bbField == null) { setConstraints(this.constraints); } if (this.isFocused) { Display.getInstance().notifyFocusSet(this); } } else { if (this._bbField != null) { Manager manager = this._bbField.getManager(); manager.delete(this._bbField); this.editField = null; this._bbField = null; } } } //#endif } /** * Allows to set a BlackBerry textfield to be editable * You should check for the 'polish.blackberry' preprocessing symbol when using this method: * <pre> * //#if polish.blackberry * </pre> * * @param editable true when this field should be editable (the default behavior). */ public void setEditable(boolean editable) { //#if polish.blackberry this._bbField.setEditable(editable); //#endif } /** * Gets the current input constraints of the <code>TextField</code>. * * @return the current constraints value (see input constraints) * @see #setConstraints(int) */ public int getConstraints() { return this.constraints; } /** * Sets a hint to the implementation as to the input mode that should be * used when the user initiates editing of this <code>TextField</code>. The * <code>characterSubset</code> parameter names a subset of Unicode * characters that is used by the implementation to choose an initial * input mode. If <code>null</code> is passed, the implementation should * choose a default input mode. * * * <p>When the direct input mode is used, J2ME Polish will ignore this call completely.</p> * * @param characterSubset a string naming a Unicode character subset, or null * @since MIDP 2.0 */ public void setInitialInputMode( String characterSubset) { //#if tmp.useNativeTextBox if (this.midpTextBox == null) { createTextBox(); } //#if !polish.midp1 this.midpTextBox.setInitialInputMode( characterSubset ); //#endif //#endif } /* (non-Javadoc) * @see de.enough.polish.ui.Item#paintContent(int, int, int, int, javax.microedition.lcdui.Graphics) */ public void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) { String myText = this.text; //#if polish.blackberry if (this.isFocused && getScreen().isNativeUiShownFor(this)) { x--; // blackberry paints a border around the text that is one pixel wide this.editField.setPaintPosition( x + g.getTranslateX(), y + g.getTranslateY() ); } else { if (this.isUneditable || !this.isFocused) { //#if polish.TextField.showHelpText if(myText == null || myText.length() == 0) { this.helpItem.paint(x, y, leftBorder, rightBorder, g); } else //#endif super.paintContent(x, y, leftBorder, rightBorder, g); return; }else{ super.paintContent(x, y, leftBorder, rightBorder, g); } } //#elif polish.android // //#if polish.TextField.showHelpText // if(myText == null || myText.length() == 0) // { // this.helpItem.paint(x, y, leftBorder, rightBorder, g); // } // //#endif //#if polish.css.repaint-previous-screen // native views are not painted in screens that lie underneath a popup screen: Screen scr = getScreen(); if (scr != null && !scr.isShown()) { WrappedText wrappedText = getWrappedText(); if (myText != null && wrappedText.size() == 0) { int cw = this.contentWidth; TextUtil.wrap(myText, this.font, cw, cw, 0, null, 0, wrappedText ); } super.paintContent(x, y, leftBorder, rightBorder, g); } //#endif //#elif polish.series40sdk20 || polish.series40sdk11 //#if polish.TextField.showHelpText if(myText == null || myText.length() == 0) { this.helpItem.paint(x, y, leftBorder, rightBorder, g); } //#endif if ( ! isFocused() || this.isUneditable ) { super.paintContent(x, y, leftBorder, rightBorder, g); } else { if ( this.series40sdk20Field != null ) { Object object = Display.getInstance(); int textFieldHeight = getItemAreaHeight() - getPaddingBottom() - getPaddingTop() ; this.series40sdk20Field.setVisible(true); this.series40sdk20Field.setParent(object); this.series40sdk20Field.setPosition(x, y); this.series40sdk20Field.setSize(this.getAvailableContentWidth(), textFieldHeight); } } //#else if (this.isUneditable || !this.isFocused) { //#if polish.TextField.showHelpText if(myText == null || myText.length() == 0) { this.helpItem.paint(x, y, leftBorder, rightBorder, g); } else //#endif super.paintContent(x, y, leftBorder, rightBorder, g); return; } int availWidth = rightBorder-leftBorder; int availHeight = this.availableHeight; //#ifdef tmp.directInput //#ifdef tmp.allowDirectInput if ( this.enableDirectInput ) { //#endif // adjust text-start for input info abc|Abc|ABC|123 if it should be shown on the same line: //#if tmp.includeInputInfo && !polish.TextField.useExternalInfo if (this.isFocused && this.infoItem != null && this.isShowInputInfo) { int infoWidth = this.infoItem.getItemWidth( availWidth, availWidth, availHeight); if (this.infoItem.isLayoutRight) { int newRightBorder = rightBorder - infoWidth; this.infoItem.paint( newRightBorder, y, newRightBorder, rightBorder, g); rightBorder = newRightBorder; } else { // left aligned (center is not supported) this.infoItem.paint( x, y, leftBorder, rightBorder, g); x += infoWidth; leftBorder += infoWidth; } } //#endif //#if polish.TextField.showHelpText if(myText == null || myText.length() == 0) { this.helpItem.paint(x, y, leftBorder, rightBorder, g); } else //#endif if (this.isPassword && !(this.showCaret || this.isNumeric || this.caretChar == this.editingCaretChar)) { int cX = getCaretXPosition(x, rightBorder, availWidth); int cY = y + this.caretY; int clipX = g.getClipX(); int clipY = g.getClipY(); int clipWidth = g.getClipWidth(); int clipHeight = g.getClipHeight(); g.clipRect( x, y, cX - x, clipHeight ); super.paintContent(x, y, leftBorder, rightBorder, g); g.setClip( clipX, clipY, clipWidth, clipHeight ); int w = this.caretWidth; int starWidth = charWidth('*'); if (starWidth > w) { w = starWidth; } if (this.caretX + w < this.contentWidth) { g.clipRect( cX + w, y, clipWidth, clipHeight ); super.paintContent(x, y, leftBorder, rightBorder, g); g.setClip( clipX, clipY, clipWidth, clipHeight ); } if (cY > y) { g.clipRect( clipX, clipY, clipWidth, cY - clipY ); super.paintContent(x, y, leftBorder, rightBorder, g); g.setClip( clipX, clipY, clipWidth, clipHeight ); } int h = getFontHeight(); if (this.caretY + h < this.contentHeight) { g.clipRect( x, cY + h, clipWidth, clipHeight ); super.paintContent(x, y, leftBorder, rightBorder, g); g.setClip( clipX, clipY, clipWidth, clipHeight ); } g.setColor( this.textColor); int anchor = Graphics.TOP | Graphics.LEFT; //#if polish.Bugs.needsBottomOrientiationForStringDrawing cY += h; anchor = Graphics.BOTTOM | Graphics.LEFT; //#endif //#if polish.css.text-effect if (this.textEffect != null) { this.textEffect.drawChar( this.caretChar, cX, cY, anchor, g); } else { //#endif g.drawChar( this.caretChar, cX, cY, anchor ); //#if polish.css.text-effect } //#endif } else { super.paintContent(x, y, leftBorder, rightBorder, g); } //#ifdef polish.css.text-wrap if (this.useSingleLine) { x += this.xOffset; } //#endif if (this.showCaret) { //#ifdef polish.css.textfield-caret-color g.setColor( this.caretColor ); //#else g.setColor( this.textColor ); //#endif int cX = getCaretXPosition(x, rightBorder, availWidth); int cY = y + this.caretY; if (this.caretChar != this.editingCaretChar) { // draw background rectangle int w = this.caretWidth; if (this.isPassword) { int starWidth = charWidth('*'); if (starWidth > w) { w = starWidth; } } int h = getFontHeight(); g.fillRect( cX, cY, w, h); //display highlighted text in white color g.setColor( DrawUtil.getComplementaryColor(g.getColor()) ); int anchor = Graphics.TOP | Graphics.LEFT; //#if polish.Bugs.needsBottomOrientiationForStringDrawing cY += h; anchor = Graphics.BOTTOM | Graphics.LEFT; //#endif //#if polish.css.text-effect if (this.textEffect != null) { this.textEffect.drawChar( this.caretChar, cX, cY, anchor, g); } else { //#endif g.drawChar( this.caretChar, cX, cY, anchor ); //#if polish.css.text-effect } //#endif } else { g.drawLine( cX, cY, cX, cY + getFontHeight() - 2); } } //#if tmp.usePredictiveInput this.predictiveAccess.paintChoices(x, y, this.caretX, this.caretY, leftBorder, rightBorder, g); //#endif // g.setColor( 0xffffff ); // g.fillRect( x, y, 10, getFontHeight() ); // g.setColor( 0xff0000 ); // g.drawChar( this.caretChar, x, y, Graphics.LEFT | Graphics.TOP ); return; //#ifdef tmp.allowDirectInput } else { super.paintContent(x, y, leftBorder, rightBorder, g); } //#endif //#else super.paintContent(x, y, leftBorder, rightBorder, g); // no direct input possible, but paint caret if (this.showCaret && this.isFocused ) { //#ifndef polish.css.textfield-caret-color g.setColor( this.textColor ); //#else g.setColor( this.caretColor ); //#endif if (this.isLayoutCenter) { x = leftBorder + ((availWidth) >> 1) + (this.contentWidth >> 1) + 2; } else if (this.isLayoutRight){ x = rightBorder; } else { x += this.contentWidth + 2; } g.drawLine( x, y, x, y + getFontHeight() ); } //#endif // end of non-blackberry/android block //#endif } //#ifdef tmp.directInput /** * Calculates the exact horizontal caret position. * @param x the x position of this field * @param rightBorder the right border * @param availWidth the available width * @return the caret position */ private int getCaretXPosition(int x, int rightBorder, int availWidth) { int cX; //#if polish.i18n.rightToLeft if (this.isLayoutRight) { cX = rightBorder - this.caretX; } else //#endif { cX = x + this.caretX; } return cX; } //#endif /* (non-Javadoc) * @see de.enough.polish.ui.Item#initItem() */ protected void initContent(int firstLineWidth, int availWidth, int availHeight) { this.screen = getScreen(); //#if tmp.includeInputInfo if (this.infoItem != null && this.isFocused && this.isShowInputInfo) { int infoWidth = this.infoItem.getItemWidth(firstLineWidth, availWidth, availHeight); firstLineWidth -= infoWidth; availWidth -= infoWidth; } //#endif //#if polish.blackberry && polish.css.text-wrap if (this.isFocused) { this.useSingleLine = false; } //#endif //#if polish.android View nativeView = this._androidView; if (nativeView == null) { this.contentWidth = availWidth; this.contentHeight = getFontHeight(); } else { nativeView.requestLayout(); nativeView.measure( MeasureSpec.makeMeasureSpec(availWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(availHeight, MeasureSpec.AT_MOST) ); this.contentWidth = nativeView.getMeasuredWidth(); this.contentHeight = nativeView.getMeasuredHeight(); } //#else super.initContent(firstLineWidth, availWidth, availHeight); //#if polish.TextField.showHelpText UiAccess.init(this.helpItem, firstLineWidth, availWidth, availHeight); //#endif //#if tmp.includeInputInfo if (this.infoItem != null && this.isFocused && this.isShowInputInfo) { this.contentWidth += this.infoItem.itemWidth; if (this.contentHeight < this.infoItem.itemHeight) { this.contentHeight = this.infoItem.itemHeight; } } //#endif if (this.font == null) { this.font = Font.getDefaultFont(); } if (this.contentHeight < getFontHeight()) { this.contentHeight = getFontHeight(); } //#if polish.blackberry if (!this.isFocused) { return; } if(this.editField != null) { if (this.style != null) { this.editField.setStyle( this.style ); } // allowing native field to expand to the fully available width, // the content size does not need to be changed as the same font is being // used. this.editField.doLayout( availWidth, this.contentHeight ); // On some devices, like the 9000, after layout() the native EditField // grows larger than the maximum specified height, but only by a few // pixels. When that happens, we have to increase the content height accordingly. if ( this.editField.getExtent().height > this.contentHeight ) { this.contentHeight = this.editField.getExtent().height; } updateInternalArea(); } //#elif polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null && this.contentWidth > 0 && this.contentHeight > 0 ) { inputAction(this.series40sdk20Field, 0); } //#elif tmp.directInput this.rowHeight = getFontHeight() + this.paddingVertical; if (this.textLines == null || this.text == null || this.text.length() == 0) { this.caretX = 0; this.caretY = 0; this.caretPosition = 0; this.caretColumn = 0; this.caretRow = 0; this.originalRowText = ""; this.realTextLines = null; //#if polish.css.text-wrap if (this.useSingleLine) { this.xOffset = 0; } //#endif } else { // init the original text-lines with spaces and line-breaks: //System.out.println("TextField.initContent(): text=[" + this.text + "], (this.realTextLines == null): " + (this.realTextLines == null) + ", this.caretPosition=" + this.caretPosition + ", caretColumn=" + this.caretColumn + ", doSetCaretPos=" + this.doSetCaretPosition + ", hasBeenSet=" + this.caretPositionHasBeenSet); int length = this.textLines.size(); int textLength = this.text.length(); String[] realLines = this.realTextLines; if (realLines == null || realLines.length != length) { realLines = new String[ length ]; } boolean caretPositionHasBeenSet = false; int cp = this.caretPosition; // if (this.caretChar != this.editingCaretChar) { // cp++; // } int endOfLinePos = 0; for (int i = 0; i < length; i++) { String line = this.textLines.getLine(i); endOfLinePos += line.length(); if (endOfLinePos < textLength) { char c = this.text.charAt( endOfLinePos ); if (c == ' ' || c == '\t' || c == '\n') { line += c; endOfLinePos++; } } realLines[i] = line; if (!caretPositionHasBeenSet && ((endOfLinePos > cp) || (endOfLinePos == cp && i == length -1 )) ) { //System.out.println("TextField: caretPos=" + this.caretPosition + ", line=" + line + ", endOfLinePos=" + endOfLinePos ); this.caretRow = i; setCaretRow(line, line.length() - (endOfLinePos - cp) ); this.caretY = this.caretRow * this.rowHeight; caretPositionHasBeenSet = true; } } // for each line this.realTextLines = realLines; if (!caretPositionHasBeenSet) { //System.out.println("caret position has not been set before"); //this.caretPosition = this.text.length(); this.caretRow = 0; //this.realTextLines.length - 1; String caretRowText = this.realTextLines[ this.caretRow ]; int caretRowLength = caretRowText.length(); if (caretRowLength > 0 && caretRowText.charAt( caretRowLength-1) == '\n' ) { caretRowText = caretRowText.substring(0, caretRowLength-1); } setCaretRow( caretRowText, caretRowLength ); this.caretPosition = this.caretColumn; this.caretY = 0; // this.rowHeight * (this.realTextLines.length - 1); //System.out.println(this + ".initContent()/font3: caretX=" + this.caretX); //this.textLines[ this.textLines.length -1 ] += " "; this.textLines.setLine( 0, this.textLines.getLine(0) + " " ); } } // set the internal information so that big TextBoxes can still be scrolled // correctly: this.internalX = 0; this.internalY = this.caretY; this.internalWidth = this.contentWidth; this.internalHeight = this.rowHeight; this.screen = getScreen(); if (this.isFocused && this.parent instanceof Container ) { // ensure that the visible area of this TextField is shown: ((Container)this.parent).scroll(0, this, true); // problem: itemHeight is not yet set } // end if !polish.android //#endif //#endif } //#if tmp.directInput /** * Sets the caret row. * The fields originalRowText, caretColumn, caretRowFirstPart, caretX, caretRowLastPart and caretRowLastPartWidth * are being set. Note that the field caretRowLastPartWidth is only set whent the * layout is either center or right. * * @param line the new caret row text * @param column the column position of the caret */ private void setCaretRow( String line, int column ) { //#debug System.out.println("setCaretRow( line=\"" + line + "\", column=" + column + ")"); this.originalRowText = line; int length = line.length(); if (column > length ) { column = length; } this.caretColumn = column; boolean endsInLineBreak = (length >= 1) && (line.charAt(length-1) == '\n'); String caretRowFirstPart; if (column == length || ( endsInLineBreak && column == length -1 )) { if ( endsInLineBreak ) { caretRowFirstPart = line.substring( 0, length - 1); } else { caretRowFirstPart = line; } } else { caretRowFirstPart = line.substring( 0, column ); //this.caretRowLastPartWidth = this.font.stringWidth(this.caretRowLastPart);; } if (this.isPassword) { this.caretX = stringWidth( "*" ) * caretRowFirstPart.length(); } else { this.caretX = stringWidth(caretRowFirstPart); } //System.out.println("caretRowWidth=" + this.caretRowWidth + " for line=" + line); //#if polish.css.text-wrap if (this.useSingleLine) { if (this.caretX > this.availableTextWidth) { this.xOffset = this.availableTextWidth - this.caretX - this.caretWidth - 5; } else { this.xOffset = 0; } } //#endif //#debug System.out.println("setCaretRow() result: endsInLineBreak=" + endsInLineBreak + ", firstPart=[" + caretRowFirstPart + "]."); } //#endif //#ifdef polish.useDynamicStyles /* (non-Javadoc) * @see de.enough.polish.ui.Item#getCssSelector() */ protected String createCssSelector() { return "textfield"; } //#endif /* (non-Javadoc) * @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style) */ public void setStyle(Style style) { super.setStyle(style); if (this.font == null) { this.font = Font.getDefaultFont(); } //#ifdef polish.css.textfield-direct-input Boolean useDirectInputBool = style.getBooleanProperty("textfield-direct-input"); if (useDirectInputBool != null) { this.enableDirectInput = useDirectInputBool.booleanValue(); } //#endif //#if polish.css.textfield-show-length && tmp.directInput Boolean showBool = style.getBooleanProperty("textfield-show-length"); if (showBool != null) { this.showLength = showBool.booleanValue(); } //#endif //#ifdef polish.css.textfield-caret-flash Boolean flashCursorBool = style.getBooleanProperty( "textfield-caret-flash" ); if ( flashCursorBool != null ) { this.flashCaret = flashCursorBool.booleanValue(); if (!this.flashCaret) { this.showCaret = true; } } //#endif //#if tmp.usePredictiveInput //#if polish.css.predictive-containerstyle Style containerstyle = (Style) style.getObjectProperty("predictive-containerstyle"); if (containerstyle != null) { this.predictiveAccess.choicesContainer.setStyle( containerstyle ); } //#endif //#if polish.css.predictive-choicestyle Style choicestyle = (Style) style.getObjectProperty("predictive-choicestyle"); if (choicestyle != null) { this.predictiveAccess.choiceItemStyle = choicestyle; } //#endif //#if polish.css.predictive-choice-orientation Integer choiceorientation = style.getIntProperty("predictive-choice-orientation"); if (choiceorientation != null) { this.predictiveAccess.choiceOrientation = choiceorientation.intValue(); } //#endif //#endif //#if polish.android if (this._androidTextField != null) { this._androidTextField.setStyle(style); } //#endif //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null ) { this.series40sdk20Field.setFont(this.font); Color color = style.getColorProperty("font-color"); if ( color != null ) { this.series40sdk20Field.setForegroundColor(0xFF000000 | color.getColor()); } } //#endif } /* (non-Javadoc) * @see de.enough.polish.ui.StringItem#setStyle(de.enough.polish.ui.Style, boolean) */ public void setStyle(Style style, boolean resetStyle) { super.setStyle(style, resetStyle); //#ifdef polish.css.textfield-caret-color Color colorInt = style.getColorProperty("textfield-caret-color"); if (colorInt != null) { this.caretColor = colorInt.getColor(); } else if (this.caretColor == -1) { this.caretColor = this.textColor; } //#endif } //#ifdef tmp.directInput protected boolean isValidInput( char insertChar, int position, String myText ) { if (!this.isEmail) { return true; } // check valid input for email addresses: char lowerCaseInsertChar = Character.toLowerCase( insertChar ); boolean isValidInput = (insertChar >= '0' && insertChar <= '9') || ( lowerCaseInsertChar >= 'a' && lowerCaseInsertChar <= 'z' ) ; if (!isValidInput) { boolean isInLocalPart = true; // are we in the first/local part before the '@' in the address? String emailAddressText = myText; int atPosition = -1; int relativeCaretPosition = this.caretPosition; if (emailAddressText != null) { // extract single email address part when there are several email addresses (this can // only happen when a ChoiceTextField is used) int separatorPosition; while ( (separatorPosition = emailAddressText.indexOf(this.emailSeparatorChar)) != -1 ) { if (separatorPosition < this.caretPosition) { emailAddressText = emailAddressText.substring( separatorPosition + 1); relativeCaretPosition -= separatorPosition; } else { emailAddressText = emailAddressText.substring( 0, separatorPosition ); break; } } // check for the '@' sign as the separator between local part and domain name: atPosition = emailAddressText.indexOf('@'); isInLocalPart = ( atPosition == -1 ) || ( atPosition >= this.caretPosition ); } if (isInLocalPart) { boolean isAtFirstChar = (emailAddressText == null || relativeCaretPosition == 0); isValidInput = ( VALID_LOCAL_EMAIL_ADDRESS_CHARACTERS.indexOf( insertChar ) != -1 ) && !( (insertChar == '.') && isAtFirstChar) // the first char must not be a dot. && !(atPosition != -1 && insertChar == '@' && atPosition != position) // it's not allowed to enter two @ characters && !(insertChar == '@' && isAtFirstChar ); // the first character must not be the '@' sign } else { isValidInput = VALID_DOMAIN_CHARACTERS.indexOf( insertChar ) != -1; } if (!isValidInput) { //#debug System.out.println("email: invalid input!"); } } return isValidInput; } protected void commitCurrentCharacter() { //#debug System.out.println("comitting current character: " + this.caretChar); String myText; if (this.isPassword) { myText = this.passwordText; } else { myText = this.text; } char insertChar = this.caretChar; if (!isValidInput( insertChar, this.caretPosition, myText )) { return; } this.caretChar = this.editingCaretChar; // increase caret position after notifying itemstatelisteners in case they want to know the current caret position... this.caretPosition++; this.caretColumn++; if (this.isPassword) { this.caretX += stringWidth("*"); } else { this.caretX += this.caretWidth; } boolean nextCharInputHasChanged = false; //#if polish.TextField.suppressAutoInputModeChange if ( this.inputMode == MODE_FIRST_UPPERCASE && (insertChar == ' ' || ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)) )) { this.nextCharUppercase = true; } else { this.nextCharUppercase = false; } //#else nextCharInputHasChanged = this.nextCharUppercase; if ( ( (this.inputMode == MODE_FIRST_UPPERCASE || this.nextCharUppercase || this.prepareNextCharUppercase) && insertChar == ' ') //|| ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER))) ){ this.nextCharUppercase = true; this.prepareNextCharUppercase = false; } else if ( insertChar == '.' && !(this.isEmail || this.isUrl || (this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)) { this.prepareNextCharUppercase = true; } else { this.nextCharUppercase = false; } nextCharInputHasChanged = (this.nextCharUppercase != nextCharInputHasChanged); if ( this.inputMode == MODE_FIRST_UPPERCASE ) { this.inputMode = MODE_LOWERCASE; } //#endif //#if polish.css.textfield-show-length && tmp.useInputInfo if (this.showLength || nextCharInputHasChanged) { updateInfo(); } //#elif tmp.useInputInfo if (nextCharInputHasChanged) { updateInfo(); } //#endif notifyStateChanged(); //#ifdef polish.css.textfield-caret-flash if (!this.flashCaret) { repaint(); } //#endif } protected void insertCharacter( char insertChar, boolean append, boolean commit ) { if (append && this.text != null && this.text.length() >= this.maxSize ) { return; } //#debug System.out.println( "insertCharacter " + insertChar); // + ", append=" + append + ", commit=" + commit +", caretPos=" + this.caretPosition ); String myText = getString(); int cp = this.caretPosition; if (!isValidInput( insertChar, cp, myText )) { return; } if (myText == null || myText.length() == 0) { myText = "" + insertChar; } else if (append) { StringBuffer buffer = new StringBuffer( myText.length() + 1 ); buffer.append( myText.substring( 0, cp ) ) .append( insertChar ); if (cp < myText.length() ) { buffer.append( myText.substring( cp ) ); } myText = buffer.toString(); } else { // replace current caret char: StringBuffer buffer = new StringBuffer(myText.length()); buffer.append(myText.substring( 0, cp ) ).append( insertChar ); if (cp < myText.length() - 1) { buffer.append( myText.substring( this.caretPosition + 1 ) ); } myText = buffer.toString(); } //System.out.println("new text=[" + myText + "]" ); boolean nextCharInputHasChanged = false; if (commit) { this.caretPosition++; this.caretColumn++; //#if polish.TextField.suppressAutoInputModeChange if ( this.inputMode == MODE_FIRST_UPPERCASE && (insertChar == ' ' )) { this.nextCharUppercase = true; } else if ( insertChar == '.' && !(this.isEmail || this.isUrl)) { this.prepareNextCharUppercase = true; } else { this.nextCharUppercase = false; } //#else nextCharInputHasChanged = this.nextCharUppercase; if ( ( (this.inputMode == MODE_FIRST_UPPERCASE || this.nextCharUppercase || this.prepareNextCharUppercase) && insertChar == ' ') ){ this.nextCharUppercase = true; this.prepareNextCharUppercase = false; } else if ( insertChar == '.' && !(this.isEmail || this.isUrl)) { this.prepareNextCharUppercase = true; } else { this.nextCharUppercase = false; this.prepareNextCharUppercase = false; } nextCharInputHasChanged = (this.nextCharUppercase != nextCharInputHasChanged); if ( this.inputMode == MODE_FIRST_UPPERCASE ) { this.inputMode = MODE_LOWERCASE; } //#endif this.caretChar = this.editingCaretChar; } setString( myText ); if (!commit) { if (myText.length() == 1) { this.caretPosition = 0; } } else { notifyStateChanged(); } } //#endif //#if tmp.directInput && tmp.useInputInfo /** * Updates the information text */ public void updateInfo() { if (this.isUneditable || !this.isShowInputInfo) { // don't show info when this field is not editable return; } // # debug // System.out.println("update info: " + this.text ); String modeStr; switch (this.inputMode) { case MODE_LOWERCASE: if (this.nextCharUppercase) { modeStr = "Abc"; } else { modeStr = "abc"; } break; case MODE_FIRST_UPPERCASE: modeStr = "Abc"; break; case MODE_UPPERCASE: modeStr = "ABC"; break; case MODE_NATIVE: modeStr = "Nat."; break; default: modeStr = "123"; break; } //#if tmp.usePredictiveInput if(this.predictiveInput) { if(this.predictiveAccess.getInfo() != null) { modeStr = this.predictiveAccess.getInfo(); } //#if polish.TextField.includeInputInfo if(this.infoItem != null && this.infoItem.getStyle().layout == Graphics.RIGHT) { modeStr = PredictiveAccess.INDICATOR + modeStr; } else { modeStr = modeStr + PredictiveAccess.INDICATOR; } //#else modeStr = PredictiveAccess.INDICATOR + modeStr; //#endif } //#endif //#ifdef polish.css.textfield-show-length if (this.showLength) { int length = (this.text == null) ? 0 : this.text.length(); modeStr = length + " | " + modeStr; } //#endif //#if tmp.includeInputInfo if (this.infoItem == null) { //#if !polish.TextField.useExternalInfo //#style info, default this.infoItem = new StringItem( null, modeStr ); this.infoItem.screen = getScreen(); this.infoItem.parent = this; repaint(); //#endif } else { this.infoItem.setText(modeStr); } //System.out.println("setting info to [" + modeStr + "]"); //#else if (this.screen == null) { this.screen = getScreen(); } if (this.screen != null) { this.screen.setInfo( modeStr ); } //#endif } //#endif /* (non-Javadoc) * @see de.enough.polish.ui.StringItem#animate(long, de.enough.polish.ui.ClippingRegion) */ public void animate(long currentTime, ClippingRegion repaintRegion) { //#if tmp.usePredictiveInput this.predictiveAccess.animateChoices(currentTime, repaintRegion ); //#endif //#if polish.useNativeGui if (this.nativeItem != null) { this.nativeItem.animate(currentTime, repaintRegion); } //#endif super.animate(currentTime, repaintRegion); } //#if !polish.android /* (non-Javadoc) * @see de.enough.polish.ui.Item#animate() */ public boolean animate() { if (!this.isFocused) { return false; } long currentTime = System.currentTimeMillis(); //#if polish.blackberry //#if polish.Bugs.ItemStateListenerCalledTooEarly if (this.lastFieldChangedEvent != 0 && currentTime - this.lastFieldChangedEvent > 500) { this.lastFieldChangedEvent = 0; setString( this.editField.getText() ); notifyStateChanged(); getScreen().repaint(); return true; } //#endif //# return false; //#else //#if tmp.directInput synchronized ( this.lock ) { if (this.caretChar != this.editingCaretChar) { if ( !this.isKeyDown && (currentTime - this.lastInputTime) >= INPUT_TIMEOUT ) { commitCurrentCharacter(); } } else if (this.isKeyDown && this.deleteKeyRepeatCount != 0 && (this.deleteKeyRepeatCount % 3) == 0 && this.text != null && this.caretPosition > 0 ) { if (this.deleteKeyRepeatCount >= 9) { String myText = this.text; if (myText != null && myText.length() > 0) { setString(null); notifyStateChanged(); } } else if (this.caretPosition > 0){ String myText = getString(); int nextStop = this.caretPosition - 1; while (myText.charAt(nextStop) != ' ' && nextStop > 0) { nextStop--; } //System.out.println("next stop=" + nextStop + ", caretPosition=" + this.caretPosition); setString(myText.substring( 0, nextStop) + myText.substring( this.caretPosition ) ); notifyStateChanged(); } } } //#endif if (!this.flashCaret || this.isUneditable) { //System.out.println("TextField.animate(): flashCaret==false"); return false; } if ( currentTime - this.lastCaretSwitch > 500 ) { this.lastCaretSwitch = currentTime; this.showCaret = ! this.showCaret; return true; } else { return false; } //#endif } //#endif //#if !(polish.blackberry || polish.android) /* (non-Javadoc) * @see de.enough.polish.ui.Item#handleKeyPressed(int, int) */ protected boolean handleKeyPressed(int keyCode, int gameAction) { //#debug System.out.println("handleKeyPressed " + keyCode ); //#if tmp.useNativeTextBox //#if polish.TextField.passCharacterToNativeEditor if (keyCode >0) { String alphabet = null; if (keyCode == Canvas.KEY_POUND) { alphabet = charactersKeyPound; } else if (keyCode == Canvas.KEY_STAR) { alphabet = charactersKeyStar; } else { int index = keyCode - Canvas.KEY_NUM0; if (index >= 0 && index <= CHARACTERS.length) { alphabet = CHARACTERS[ index ]; } } if (alphabet != null && (alphabet.length() >= 0)) { if(this.keyDelayTimerTask==null || this.latestKey != keyCode){ this.keyPressCounter=0; this.passedChar = alphabet.charAt(this.keyPressCounter++); this.latestKey = keyCode; } else { this.passedChar = alphabet.charAt(this.keyPressCounter++); this.latestKey = keyCode; if (this.keyPressCounter == alphabet.length()){ this.keyPressCounter=0; } } if ((this.constraints & NUMERIC) == NUMERIC){ this.passedChar = (char)keyCode; } } } //#endif //#endif this.isKeyPressedHandled = false; //#ifndef tmp.directInput if (keyCode < 32 || keyCode > 126) { //#if polish.bugs.inversedGameActions if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM8) || (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM2) || (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM6) || (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM4) || (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5) || (this.screen.isSoftKey(keyCode, gameAction)) ) { return false; } //#else if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) || (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) || (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) || (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) || (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5) || (this.screen.isSoftKey(keyCode, gameAction)) ) { return false; } //#endif } //#elif !polish.blackberry if (this.inputMode == MODE_NATIVE) { if ((gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) || (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) || (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) || (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) || (!(gameAction == Canvas.FIRE && this.cskOpensNativeEditor) && this.screen.isSoftKey(keyCode, gameAction)) ) { return false; } } this.isKeyDown = true; //#endif //#if tmp.allowDirectInput if (this.enableDirectInput) { //#endif //#ifdef tmp.directInput //#if !polish.blackberry if ((this.inputMode == MODE_NATIVE) && (keyCode != KEY_CHANGE_MODE) //#if polish.key.ChangeNumericalAlphaInputModeKey:defined //#= && keyCode != ${polish.key.ChangeNumericalAlphaInputModeKey} //#endif ) { //#if tmp.useNativeTextBox //#if polish.TextField.passCharacterToNativeEditor this.lastTimeKeyPressed = System.currentTimeMillis(); if (this.keyDelayTimerTask==null && !((this.constraints & UNEDITABLE) == UNEDITABLE)){ final int localGameAction = gameAction; final int localKeyCode = keyCode; this.keyDelayTimerTask = new TimerTask(){ public void run() { if(System.currentTimeMillis()-TextField.this.lastTimeKeyPressed < (TextField.this.delayBetweenKeys+20) ) return; showTextBox(); if (TextField.this.midpTextBox!=null && (localGameAction != Canvas.FIRE || localKeyCode == Canvas.KEY_NUM5)){ String oldText =TextField.this.midpTextBox.getString(); if (oldText.length()==0 && !((TextField.this.constraints & INITIAL_CAPS_NEVER) == INITIAL_CAPS_NEVER)){ TextField.this.passedChar = Character.toUpperCase(TextField.this.passedChar); } TextField.this.midpTextBox.insert(String.valueOf(TextField.this.passedChar), TextField.this.getCaretPosition()); } TextField.this.keyDelayTimerTask.cancel(); TextField.this.keyDelayTimerTask = null; } }; this.keyDelayTimer.schedule(this.keyDelayTimerTask, 0,this.delayBetweenKeys); } //#else showTextBox(); //#endif return true; //#endif } //#endif synchronized ( this.lock ) { // if (this.text == null) { // in that case no mode change can be done with an empty textfield // return false; // } // else if (this.isUneditable) { return false; } boolean handled = false; //#if tmp.usePredictiveInput && !polish.key.ChangeNumericalAlphaInputModeKey:defined if ( (keyCode == KEY_CHANGE_MODE) && (!this.isNumeric) && (!this.isUneditable)) { if(this.lastTimePressed == -1) { this.nextMode = !this.predictiveInput; this.lastTimePressed = System.currentTimeMillis(); } else { if((System.currentTimeMillis() - this.lastTimePressed) > SWITCH_DELAY && TrieProvider.isPredictiveInstalled()) { if(this.nextMode != this.predictiveInput) { this.predictiveInput = !this.predictiveInput; this.nextMode = this.predictiveInput; updateInfo(); this.predictiveInput = !this.predictiveInput; } } } handled = true; } //#endif // Backspace //#ifdef polish.key.ClearKey:defined //#= if (keyCode == ${polish.key.ClearKey} //#else if ( keyCode == -8 || keyCode == 8 //#endif //#if polish.key.backspace:defined //#= || keyCode == ${polish.key.backspace} //#endif && !handled) { handled = handleKeyClear(keyCode, gameAction); } //#if polish.key.Menu:defined int menuKey = 0; //#= menuKey = ${polish.key.Menu}; if (keyCode == menuKey) { return false; } //#endif //#ifdef polish.key.ChangeNumericalAlphaInputModeKey:defined int changeNumericalAlphaInputModeKey = 0; //#= changeNumericalAlphaInputModeKey = ${polish.key.ChangeNumericalAlphaInputModeKey}; //#endif if (!handled && ((keyCode != KEY_CHANGE_MODE) //#if polish.key.maybeSupportsAsciiKeyMap || useAsciiKeyMap //#endif ) //#ifdef polish.key.ChangeNumericalAlphaInputModeKey:defined && !(keyCode == KEY_CHANGE_MODE && !this.isNumeric && !(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS)) && !(keyCode == changeNumericalAlphaInputModeKey && !this.isNumeric) //#endif ){ handled = handleKeyInsert(keyCode, gameAction); } // Navigate the caret if ( !handled && (gameAction == Canvas.UP || gameAction == Canvas.DOWN || gameAction == Canvas.LEFT || gameAction == Canvas.RIGHT || gameAction == Canvas.FIRE ) ) { handled = handleKeyNavigation(keyCode, gameAction); if (!handled && gameAction == Canvas.FIRE && this.defaultCommand != null) { notifyItemPressedStart(); handled = true; } } if(true) { this.isKeyPressedHandled = handled; return handled; } } //#endif //#if tmp.allowDirectInput } //#endif //#ifndef polish.hasPointerEvents String currentText = this.isPassword ? this.passwordText : this.text; if (this.enableDirectInput) { int currentLength = (this.text == null ? 0 : this.text.length()); if ( keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9) { if (currentLength >= this.maxSize) { // in numeric mode ignore 2,4,6 and 8 keys, so that they are not processed // by a parent component: this.isKeyPressedHandled = true; return true; } String newText = (currentText == null ? "" : currentText ) + (keyCode - 48); setString( newText ); notifyStateChanged(); this.isKeyPressedHandled = true; return true; } //#ifdef polish.key.ClearKey:defined //#= if ((keyCode == ${polish.key.ClearKey}) || (gameAction == Canvas.LEFT)) { //#else if (keyCode == -8 || gameAction == Canvas.LEFT) { //#endif if (currentLength > 0) { setString( currentText.substring(0, currentLength - 1) ); notifyStateChanged(); } this.isKeyPressedHandled = true; return true; } return false; } //#endif if ( keyCode >= 32 //#ifdef polish.key.ClearKey:defined //#= || (keyCode == ${polish.key.ClearKey}) //#else || (keyCode == -8 || keyCode == 8) //#endif //#if ${ isOS( Windows ) } || (gameAction != Canvas.DOWN && gameAction != Canvas.UP && gameAction != Canvas.LEFT && gameAction != Canvas.RIGHT) //#endif || (gameAction == Canvas.FIRE ) ) { //#if tmp.useNativeTextBox showTextBox(); //#endif return true; } else { return false; } } //#endif /** * Tries to interpret a key pressed event for inserting a character into this TextField. * @param keyCode the key code of the event * @param gameAction the associated game action * @return true when the key could be interpreted as a character */ protected boolean handleKeyInsert(int keyCode, int gameAction) { //#if tmp.directInput //#if tmp.usePredictiveInput if (this.predictiveInput) { return this.predictiveAccess.keyInsert(keyCode, gameAction); } //#endif int currentLength = (this.text == null ? 0 : this.text.length()); char insertChar = (char) (' ' + (keyCode - 32)); //#if tmp.supportsAsciiKeyMap try { String name = this.screen.getKeyName( keyCode ); if (name != null && name.length() == 1) { insertChar = name.charAt(0); } } catch (IllegalArgumentException e) { // ignore } //#if polish.key.maybeSupportsAsciiKeyMap if (!useAsciiKeyMap) { if (keyCode >= 32 && (keyCode < Canvas.KEY_NUM0 || keyCode > Canvas.KEY_NUM9) && (keyCode != Canvas.KEY_POUND && keyCode != Canvas.KEY_STAR) && (keyCode <= 126) // only allow ascii characters for the initial input... && ( !getScreen().isSoftKey(keyCode, gameAction) ) ) { useAsciiKeyMap = true; //#if tmp.usePredictiveInput this.predictiveInput = false; //#endif } } //#endif if (keyCode >= 32 //#if polish.key.maybeSupportsAsciiKeyMap && useAsciiKeyMap //#endif && this.inputMode != MODE_NUMBERS && !this.isNumeric && this.screen.isKeyboardAccessible() && !( (insertChar < 'a' || insertChar > 'z') && ( (gameAction == Canvas.UP && insertChar != '2' && keyCode == this.screen.getKeyCode(Canvas.UP) ) || (gameAction == Canvas.DOWN && insertChar != '8' && keyCode == this.screen.getKeyCode(Canvas.DOWN) ) || (gameAction == Canvas.LEFT && insertChar != '4' && keyCode == this.screen.getKeyCode(Canvas.LEFT) ) || (gameAction == Canvas.RIGHT && insertChar != '6' && keyCode == this.screen.getKeyCode(Canvas.RIGHT)) ) //|| (gameAction == Canvas.FIRE && keyCode == this.screen.getKeyCode(Canvas.FIRE) ) ) ) { if (this.nextCharUppercase || this.inputMode == MODE_UPPERCASE) { insertChar = Character.toUpperCase(insertChar); } insertCharacter( insertChar, true, true ); return true; } //#if polish.key.enter:defined //#= if ( keyCode == ${polish.key.enter} ) { //this.caretChar = '\n'; insertCharacter('\n', true, true ); //# return true; //# } //#endif //#endif if (this.inputMode == MODE_NUMBERS && !this.isUneditable) { if ( keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9 ) { if (currentLength >= this.maxSize) { // ignore this key event - also don't forward it to the parent component: return true; } insertChar = Integer.toString( keyCode - Canvas.KEY_NUM0 ).charAt( 0 ); insertCharacter(insertChar, true, true ); return true; } //#if polish.TextField.numerickeys.1:defined String numericKeyStr = ""; int foundNumber = -1; //#= numericKeyStr = "${polish.TextField.numerickeys.1}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 1; } //#= numericKeyStr = "${polish.TextField.numerickeys.2}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 2; } //#= numericKeyStr = "${polish.TextField.numerickeys.3}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 3; } //#= numericKeyStr = "${polish.TextField.numerickeys.4}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 4; } //#= numericKeyStr = "${polish.TextField.numerickeys.5}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 5; } //#= numericKeyStr = "${polish.TextField.numerickeys.6}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 6; } //#= numericKeyStr = "${polish.TextField.numerickeys.7}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 7; } //#= numericKeyStr = "${polish.TextField.numerickeys.8}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 8; } //#= numericKeyStr = "${polish.TextField.numerickeys.9}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 9; } //#= numericKeyStr = "${polish.TextField.numerickeys.0}"; if (numericKeyStr.indexOf(insertChar) != -1) { foundNumber = 0; } if (foundNumber != -1) { if (currentLength >= this.maxSize) { // ignore this key event - also don't forward it to the parent component: return true; } insertChar = Integer.toString( foundNumber ).charAt( 0 ); insertCharacter(insertChar, true, true ); return true; } //#endif if ( this.isDecimal ) { //System.out.println("handling key for DECIMAL TextField"); if (this.text == null || (currentLength < this.maxSize && ( keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR ) && this.text.indexOf( Locale.DECIMAL_SEPARATOR) == -1) ) { insertChar = Locale.DECIMAL_SEPARATOR; insertCharacter(insertChar, true, true ); return true; } } } if ( (!this.isNumeric) //this.inputMode != MODE_NUMBERS && !this.isUneditable && ((currentLength < this.maxSize) || ( currentLength == this.maxSize && this.caretChar != this.editingCaretChar && keyCode == this.lastKey)) && ( (keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9) || (keyCode == Canvas.KEY_POUND ) || (keyCode == Canvas.KEY_STAR ) //#if tmp.supportsSymbolEntry && polish.key.AddSymbolKey:defined //#= || (keyCode == ${polish.key.AddSymbolKey} ) //#endif //#if tmp.supportsSymbolEntry && polish.key.AddSymbolKey2:defined //#= || (keyCode == ${polish.key.AddSymbolKey2} ) //#endif )) { //#if tmp.supportsSymbolEntry && (polish.key.AddSymbolKey:defined || polish.key.AddSymbolKey2:defined) boolean showSymbolList = false; //#if polish.key.AddSymbolKey:defined //#= showSymbolList = (keyCode == ${polish.key.AddSymbolKey}); //#endif //#if polish.key.AddSymbolKey2:defined //#= showSymbolList = showSymbolList || (keyCode == ${polish.key.AddSymbolKey2}); //#endif if ( showSymbolList ) { showSymbolsList(); return true; } //#endif String alphabet; if (keyCode == Canvas.KEY_POUND) { alphabet = charactersKeyPound; } else if (keyCode == Canvas.KEY_STAR) { alphabet = charactersKeyStar; } else { alphabet = this.characters[ keyCode - Canvas.KEY_NUM0 ]; } if (alphabet == null || (alphabet.length() == 0)) { return false; } this.lastInputTime = System.currentTimeMillis(); char newCharacter; int alphabetLength = alphabet.length(); boolean appendNewCharacter = false; if (keyCode == this.lastKey && (this.caretChar != this.editingCaretChar)) { this.characterIndex++; if (this.characterIndex >= alphabetLength) { this.characterIndex = 0; } } else { // insert the last character into the text: if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); if (currentLength + 1 > this.maxSize) { return true; } } appendNewCharacter = true; this.characterIndex = 0; this.lastKey = keyCode; } newCharacter = alphabet.charAt( this.characterIndex ); //System.out.println("TextField.handleKeyPressed(): newCharacter=" + newCharacter + ", currentLength=" + currentLength + ", maxSize=" + this.maxSize + ", text.length()=" + this.text.length() ); if ( this.inputMode == MODE_UPPERCASE || this.nextCharUppercase ) { //#if polish.TextField.useDynamicCharset if(usesDynamicCharset && keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9) { alphabet = CHARACTERS_UPPER[ keyCode - Canvas.KEY_NUM0 ]; newCharacter = alphabet.charAt(this.characterIndex); } else //#endif { newCharacter = Character.toUpperCase(newCharacter); } } this.caretWidth = charWidth( newCharacter ); this.caretChar = newCharacter; if (alphabetLength == 1) { insertCharacter( newCharacter, true, true ); } else { insertCharacter( newCharacter, appendNewCharacter, false ); } return true; } //#endif return false; } protected boolean handleKeyClear(int keyCode, int gameAction) { //#if tmp.directInput if (this.isUneditable) { return false; } //#if tmp.usePredictiveInput if (this.predictiveInput) { return this.predictiveAccess.keyClear(keyCode, gameAction); } //#endif if ( this.text != null && this.text.length() > 0) { return deleteCurrentChar(); } //#endif return false; } protected boolean handleKeyMode(int keyCode, int gameAction) { //#if tmp.directInput //#if tmp.usePredictiveInput if (this.predictiveInput) { return this.predictiveAccess.keyMode(keyCode, gameAction); } //#endif //#if polish.key.ChangeNumericalAlphaInputModeKey:defined int changeNumericalAlphaInputModeKey = 0; //#= changeNumericalAlphaInputModeKey = ${polish.key.ChangeNumericalAlphaInputModeKey}; if (keyCode ==changeNumericalAlphaInputModeKey && !this.isNumeric && !this.isUneditable) { if (this.inputMode == MODE_NUMBERS) { this.inputMode = MODE_LOWERCASE; } else { this.inputMode = MODE_NUMBERS; } //#if tmp.useInputInfo updateInfo(); //#endif if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); } if (this.inputMode == MODE_FIRST_UPPERCASE) { this.nextCharUppercase = true; } else { this.nextCharUppercase = false; } return true; } //#endif //#if polish.key.supportsAsciiKeyMap.condition:defined && polish.key.shift:defined // there is a shift key responsible for switching the input mode which // is only used when the device is opened up - example includes the Nokia/E70. if (!this.screen.isKeyboardAccessible()) { //#endif if ( keyCode == KEY_CHANGE_MODE && !this.isNumeric && !this.isUneditable //#if polish.key.ChangeNumericalAlphaInputModeKey:defined && (!(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS)) //#endif ) { if (this.nextCharUppercase && this.inputMode == MODE_LOWERCASE) { this.nextCharUppercase = false; } else { this.inputMode++; } //#if polish.key.ChangeNumericalAlphaInputModeKey:defined if (this.inputMode > MODE_UPPERCASE) { //#if polish.TextField.allowNativeModeSwitch if (this.inputMode > MODE_NATIVE) { this.inputMode = MODE_LOWERCASE; } else { this.inputMode = MODE_NATIVE; } //#else this.inputMode = MODE_LOWERCASE; //#endif } //#elif polish.TextField.allowNativeModeSwitch if (this.inputMode > MODE_NATIVE) { this.inputMode = MODE_LOWERCASE; } //#else if (this.inputMode > MODE_NUMBERS) { this.inputMode = MODE_LOWERCASE; } //#endif //#if tmp.useInputInfo updateInfo(); //#endif if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); } if (this.inputMode == MODE_FIRST_UPPERCASE) { this.nextCharUppercase = true; } else { this.nextCharUppercase = false; } return true; } //#if polish.key.supportsAsciiKeyMap.condition:defined && polish.key.shift:defined } //#endif //#if polish.key.shift:defined if ( keyCode == KEY_SHIFT && !this.isNumeric && !this.isUneditable) { if (this.nextCharUppercase && this.inputMode == MODE_LOWERCASE) { this.nextCharUppercase = false; } else { int mode = this.inputMode + 1; if (mode >= MODE_NUMBERS) { mode = MODE_LOWERCASE; } if (mode == MODE_FIRST_UPPERCASE) { this.nextCharUppercase = true; } else { this.nextCharUppercase = false; } this.inputMode = mode; } //#if tmp.useInputInfo updateInfo(); //#endif return true; } //#endif //#endif return false; } protected boolean handleKeyNavigation(int keyCode, int gameAction) { //#if tmp.directInput if (this.realTextLines == null) { return false; } //#if tmp.usePredictiveInput if(this.predictiveInput && this.predictiveAccess.keyNavigation(keyCode, gameAction)) { return true; } //#endif char character = this.caretChar; boolean characterInserted = character != this.editingCaretChar; if (characterInserted) { commitCurrentCharacter(); } if (gameAction == Canvas.FIRE && this.defaultCommand != null && this.itemCommandListener != null) { this.itemCommandListener.commandAction(this.defaultCommand, this); return true; } else if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) { if (this.caretRow == 0) { return false; } // restore the text-line: this.caretRow--; this.caretY -= this.rowHeight; this.internalY = this.caretY; String fullLine = this.realTextLines[ this.caretRow ]; int previousCaretRowFirstLength = this.caretColumn; setCaretRow(fullLine, this.caretColumn ); this.caretPosition -= previousCaretRowFirstLength + (this.originalRowText.length() - this.caretColumn); this.internalX = 0; this.internalY = this.caretRow * this.rowHeight; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) { if (this.textLines == null || this.caretRow >= this.textLines.size() - 1) { return false; } String lastLine = this.originalRowText; int lastLineLength = lastLine.length(); this.caretRow++; this.caretY += this.rowHeight; this.internalY = this.caretY; int lastCaretRowLastPartLength = lastLineLength - this.caretColumn; String nextLine = this.realTextLines[ this.caretRow ]; setCaretRow( nextLine, this.caretColumn ); this.caretPosition += (lastCaretRowLastPartLength + this.caretColumn ); this.internalY = this.caretRow * this.rowHeight; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; //#if polish.i18n.rightToLeft } else if (gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) { //#else } else if (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) { //#endif int column = this.caretColumn; if (column > 0) { this.caretPosition--; column--; setCaretRow( this.originalRowText, column ); //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } else if ( this.caretRow > 0) { // this is just a visual line-break: //this.caretPosition--; this.caretRow--; String prevLine = this.realTextLines[ this.caretRow ]; int carColumn = prevLine.length(); boolean isOnNewlineChar = prevLine.charAt( carColumn - 1 ) == '\n'; if (isOnNewlineChar) { this.caretPosition--; carColumn--; } setCaretRow(prevLine, carColumn ); //System.out.println(this + ".handleKeyPressed()/font4: caretX=" + this.caretX); this.caretY -= this.rowHeight; this.internalY = this.caretY; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } //#if polish.i18n.rightToLeft } else if (gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) { //#else } else if ( gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) { //#endif //#ifdef polish.debug.debug if (this.isPassword) { //#debug System.out.println("originalRowText=" + this.originalRowText ); } //#endif if (characterInserted) { //System.out.println("right but character inserted"); return true; } boolean isOnNewlineChar = this.caretColumn < this.originalRowText.length() && this.originalRowText.charAt( this.caretColumn ) == '\n'; if (this.caretColumn < this.originalRowText.length() && !isOnNewlineChar ) { //System.out.println("right not in last column"); this.caretColumn++; this.caretPosition++; setCaretRow( this.originalRowText, this.caretColumn ); //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } else if (this.caretRow < this.realTextLines.length - 1) { //System.out.println("right in not the last row"); this.caretRow++; if (isOnNewlineChar) { this.caretPosition++; } this.originalRowText = this.realTextLines[ this.caretRow ]; if (characterInserted) { if (this.isPassword) { this.caretX = stringWidth("*"); } else { this.caretX = stringWidth( String.valueOf( character ) ); } //System.out.println(this + ".handleKeyPressed()/font6: caretX=" + this.caretX); this.caretColumn = 1; } else { setCaretRow( this.originalRowText, 0 ); } this.caretY += this.rowHeight; this.internalY = this.caretY; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } else if (characterInserted) { //System.out.println("right after character insertion"); // a character has been inserted at the last column of the last row: if (this.isPassword) { this.caretX += stringWidth("*"); } else { this.caretX += this.caretWidth; } this.caretColumn++; this.caretPosition++; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif return true; } } //#endif return false; } //#if !(polish.blackberry || polish.android) && tmp.directInput /* (non-Javadoc) * @see de.enough.polish.ui.Item#handleKeyRepeated(int, int) */ protected boolean handleKeyRepeated(int keyCode, int gameAction) { //#debug System.out.println("TextField.handleKeyRepeated( " + keyCode + ")"); if (keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9 ) { // ignore repeat events when the current input mode is numbers: if ( this.isNumeric || this.inputMode == MODE_NUMBERS ) { if (keyCode == Canvas.KEY_NUM0 && this.inputMode == PHONENUMBER) { if (this.caretPosition == 1 && this.text.charAt(0) == '0') { String str = getString(); if (str.length() > 0 && str.charAt(0) == '0') { str = str.substring(1); } setString( "+" + str ); return true; } } return false; } int currentLength = (this.text == null ? 0 : this.text.length()); if ( !this.isUneditable && currentLength <= this.maxSize ) { // enter number character: this.lastInputTime = System.currentTimeMillis(); char newCharacter = Integer.toString(keyCode - 48).charAt(0); this.caretWidth = charWidth( newCharacter ); if (newCharacter != this.caretChar) { //#if tmp.usePredictiveInput if (this.predictiveInput) { TextBuilder builder = this.predictiveAccess.getBuilder(); try { builder.keyClear(); this.predictiveAccess.openChoices(false); builder.addString("" + newCharacter); }catch(Exception e) { //#debug error System.out.println("unable to clear " + e); } setText(builder.getText().toString()); setCaretPosition(builder.getCaretPosition()); } else //#endif { this.caretChar = newCharacter; insertCharacter( newCharacter, false, false ); } } return true; } } //#ifdef polish.key.ClearKey:defined //#= if ( (keyCode == ${polish.key.ClearKey} //#else if ( (keyCode == -8 //#endif //#if polish.key.backspace:defined //#= || keyCode == ${polish.key.backspace} //#endif ) && this.caretPosition > 0 && this.text != null ) { this.deleteKeyRepeatCount++; } return false; //return super.handleKeyRepeated(keyCode, gameAction); } //#endif //#if !(polish.blackberry || polish.android) && tmp.directInput /* (non-Javadoc) * @see de.enough.polish.ui.Item#handleKeyReleased(int, int) */ protected boolean handleKeyReleased( int keyCode, int gameAction ) { //#debug System.out.println("handleKeyReleased " + keyCode ); if (!this.enableDirectInput) { return super.handleKeyReleased(keyCode, gameAction); } //#if tmp.useNativeTextBox && !(polish.Vendor == Samsung) if (this.skipKeyReleasedEvent) { this.skipKeyReleasedEvent = false; return true; } //#endif this.isKeyDown = false; this.deleteKeyRepeatCount = 0; //#if tmp.usePredictiveInput if (this.predictiveAccess.handleKeyReleased( keyCode, gameAction )) { return true; } //#endif int clearKey = //#if polish.key.ClearKey:defined //#= ${polish.key.ClearKey}; //#else -8; //#endif boolean clearKeyPressed = (keyCode == clearKey); //#if polish.key.ChangeNumericalAlphaInputModeKey:defined int changeNumericalAlphaInputModeKey = 0; //#= changeNumericalAlphaInputModeKey = polish.key.ChangeNumericalAlphaInputModeKey; //#endif if ( (keyCode == KEY_CHANGE_MODE && !this.isNumeric && !this.isUneditable) //#if polish.key.maybeSupportsAsciiKeyMap && (!useAsciiKeyMap) //#endif //#if polish.key.ChangeNumericalAlphaInputModeKey:defined || (keyCode == changeNumericalAlphaInputModeKey && !this.isNumeric && !this.isUneditable) && (!(KEY_CHANGE_MODE == Canvas.KEY_NUM0 && this.inputMode == MODE_NUMBERS) || keyCode == changeNumericalAlphaInputModeKey) //#endif ){ //#if tmp.usePredictiveInput && !polish.key.ChangeNumericalAlphaInputModeKey:defined if((System.currentTimeMillis() - this.lastTimePressed) > SWITCH_DELAY && TrieProvider.isPredictiveInstalled()) { this.lastTimePressed = -1; if(this.predictiveInput) { getPredictiveAccess().disablePredictiveInput(); } else { getPredictiveAccess().enablePredictiveInput(); } updateInfo(); return true; } //#endif //#if tmp.usePredictiveInput this.lastTimePressed = -1; //#endif return handleKeyMode(keyCode, gameAction) || clearKeyPressed; } return this.isKeyPressedHandled || clearKeyPressed || super.handleKeyReleased( keyCode, gameAction ); } //#endif //#if polish.hasPointerEvents && (!tmp.forceDirectInput || polish.javaplatform >= Android/1.5) /** * Handles the event when a pointer has been pressed at the specified position. * The default method translates the pointer-event into an artificial * pressing of the FIRE game-action, which is subsequently handled * bu the handleKeyPressed(-1, Canvas.FIRE) method. * This method needs should be overwritten only when the "polish.hasPointerEvents" * preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents". * * @param x the x position of the pointer pressing * @param y the y position of the pointer pressing * @return true when the pressing of the pointer was actually handled by this item. */ protected boolean handlePointerPressed( int x, int y ) { if (isInItemArea(x, y)) { //#if !tmp.forceDirectInput return notifyItemPressedStart(); //#endif } return super.handlePointerPressed(x, y); } //#endif //#if polish.hasPointerEvents /** * Handles the event when a pointer has been pressed at the specified position. * The default method translates the pointer-event into an artificial * pressing of the FIRE game-action, which is subsequently handled * bu the handleKeyPressed(-1, Canvas.FIRE) method. * This method needs should be overwritten only when the "polish.hasPointerEvents" * preprocessing symbol is defined: "//#ifdef polish.hasPointerEvents". * * @param x the x position of the pointer pressing * @param y the y position of the pointer pressing * @return true when the pressing of the pointer was actually handled by this item. */ protected boolean handlePointerReleased( int x, int y ) { repaint(); if (isInItemArea(x, y)) { //#if tmp.useNativeTextBox int fieldType = this.constraints & 0xffff; if (fieldType != FIXED_POINT_DECIMAL) { notifyItemPressedEnd(); //#if !polish.series40sdk20 && !polish.series40sdk11 showTextBox(); //#endif return true; } //#elif polish.TextField.useVirtualKeyboard Form keyboardView = KeyboardView.getInstance(getLabel(), this, getScreen()); Display.getInstance().setCurrent(keyboardView); return true; //#endif } return super.handlePointerReleased(x, y); } //#endif //#if polish.hasPointerEvents && (polish.showSoftKeyboardOnShowNotify != false) /* (non-Javadoc) * @see de.enough.polish.ui.Item#handleOnFocusSoftKeyboardDisplayBehavior() */ public void handleOnFocusSoftKeyboardDisplayBehavior() { //#if !polish.android DeviceControl.showSoftKeyboard(); //#endif } //#endif //#ifdef tmp.directInput /** * Removes the current character. * * @return true when a character could be deleted. */ private synchronized boolean deleteCurrentChar() { //#debug System.out.println("deleteCurrentChar: caretColumn=" + this.caretColumn + ", caretPosition=" + this.caretPosition + ", caretChar=" + this.caretChar ); String myText; if (this.isPassword) { myText = this.passwordText; } else { myText = this.text; } int position = this.caretPosition; if (this.caretChar != this.editingCaretChar) { myText = myText.substring( 0, position ) + myText.substring( position + 1); this.caretChar = this.editingCaretChar; this.caretPosition = position; setString( myText ); return true; } if (position > 0) { position--; myText = myText.substring( 0, position ) + myText.substring( position + 1); this.caretPosition = position; setString( myText ); //#if polish.css.textfield-show-length && tmp.useInputInfo if (this.showLength) { updateInfo(); } //#endif notifyStateChanged(); return true; } else { return false; } } //#endif //#if tmp.useNativeTextBox /** * Shows the TextBox for entering texts. */ protected void showTextBox() { //TODO: drubin better handling of textfield events. //(Currently this is the easiest method to overload if you want to tie into //"is editing mode" events.) that is triggered by both touch and commands if (this.midpTextBox == null) { createTextBox(); } if (StyleSheet.currentScreen != null) { this.screen = StyleSheet.currentScreen; } else if (this.screen == null) { this.screen = getScreen(); } StyleSheet.display.setCurrent( this.midpTextBox ); } //#endif //#if tmp.implementsCommandListener /* (non-Javadoc) * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable) */ public void commandAction(Command cmd, Displayable box) { //#if tmp.usePredictiveInput if (this.predictiveAccess.commandAction(cmd, box)) { return; } //#endif //#if tmp.supportsSymbolEntry if (box instanceof List) { if (cmd != StyleSheet.CANCEL_CMD) { int index = symbolsList.getSelectedIndex(); insert(definedSymbols[index],this.caretPosition); //insertCharacter( definedSymbols.charAt(index), true, true ); StyleSheet.currentScreen = this.screen; //#if tmp.updateDeleteCommand updateDeleteCommand( this.text ); //#endif } else { StyleSheet.currentScreen = this.screen; } StyleSheet.display.setCurrent( this.screen ); notifyStateChanged(); return; } //#endif //#if tmp.useNativeTextBox if (cmd == StyleSheet.CANCEL_CMD) { this.midpTextBox.setString( this.text ); this.skipKeyReleasedEvent = true; } else if (!this.isUneditable) { setString( this.midpTextBox.getString() ); setCaretPosition( size() ); notifyStateChanged(); this.skipKeyReleasedEvent = true; } StyleSheet.display.setCurrent( this.screen ); //#endif } //#endif //#if (!tmp.suppressCommands && !tmp.supportsSymbolEntry) || tmp.supportsSymbolEntry public void setItemCommandListener(ItemCommandListener l) { this.additionalItemCommandListener = l; } public ItemCommandListener getItemCommandListener() { return this.additionalItemCommandListener; } //#endif //#if tmp.supportsSymbolEntry public static void initSymbolsList() { if (symbolsList == null) { //#style textFieldSymbolList?, textFieldSymbolTable? symbolsList = new List( ENTER_SYMBOL_CMD.getLabel(), Choice.IMPLICIT ); for (int i = 0; i < definedSymbols.length; i++) { //#style textFieldSymbolItem? symbolsList.append( definedSymbols[i], null ); } //TODO check localization when using dynamic localization symbolsList.addCommand( StyleSheet.CANCEL_CMD ); } } private void showSymbolsList() { if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); } initSymbolsList(); symbolsList.setCommandListener( this ); StyleSheet.display.setCurrent( symbolsList ); } //#endif /* (non-Javadoc) * @see de.enough.polish.ui.ItemCommandListener#commandAction(javax.microedition.lcdui.Command, de.enough.polish.ui.Item) */ public void commandAction(Command cmd, Item item) { //#debug System.out.println("TextField.commandAction( " + cmd.getLabel() + ", " + this + " )"); //#if tmp.usePredictiveInput if (this.predictiveAccess.commandAction(cmd, item)) { return; } //#endif if (cmd.commandAction(this, null)) { return; } //#if tmp.implementsItemCommandListener //#if tmp.supportsSymbolEntry if (cmd == ENTER_SYMBOL_CMD ) { //#if polish.TextField.ignoreSymbolCommand Screen scr = getScreen(); if (scr != null & scr.getCommandListener() != null) { scr.getCommandListener().commandAction(cmd, scr); } //#else showSymbolsList(); //#endif return; } //#endif //#ifndef tmp.suppressCommands if ( cmd == DELETE_CMD ) { if (this.text != null && this.text.length() > 0) { //#ifdef tmp.directInput //#ifdef tmp.allowDirectInput if (this.enableDirectInput) { //#endif //#ifdef polish.key.ClearKey:defined //#= handleKeyClear(${polish.key.ClearKey},0); //#else handleKeyClear(-8,0); //#endif //#ifdef tmp.allowDirectInput } else { String myText = getString(); setString( myText.substring(0, myText.length() - 1)); notifyStateChanged(); } //#endif //#else String myText = getString(); setString( myText.substring(0, myText.length() - 1)); notifyStateChanged(); //#endif return; } } else if ( cmd == CLEAR_CMD ) { setString( null ); notifyStateChanged(); } else if ( this.additionalItemCommandListener != null ) { this.additionalItemCommandListener.commandAction(cmd, item); } else { // forward command to the screen's orginal command listener: Screen scr = getScreen(); if (scr != null) { CommandListener listener = scr.getCommandListener(); if (listener != null) { listener.commandAction(cmd, scr); } } } //#endif //#if polish.key.maybeSupportsAsciiKeyMap if (cmd == SWITCH_KEYBOARD_CMD) { useAsciiKeyMap = !useAsciiKeyMap; } //#endif //#endif } //#if (tmp.directInput && (polish.TextField.showInputInfo != false)) || polish.series40sdk20 || polish.series40sdk11 || polish.blackberry || polish.TextField.activateUneditableWithFire || polish.javaplatform >= Android/1.5 protected void defocus(Style originalStyle) { super.defocus(originalStyle); //#if polish.series40sdk20 || polish.series40sdk11 if (this.series40sdk20Field != null) { this.series40sdk20Field.setFocus(false); this.series40sdk20Field.setParent(null); String newText = this.series40sdk20Field.getContent(); String oldText = this.isPassword ? this.passwordText : this.text; setString( newText ); setInitialized(false); repaint(); notifyStateChanged(); } //#endif //#if polish.blackberry //#if polish.Bugs.ItemStateListenerCalledTooEarly String newText = this.editField.getText(); String oldText = this.isPassword ? this.passwordText : this.text; if (( this.lastFieldChangedEvent != 0) || (!newText.equals(oldText ) && !(oldText == null && newText.length()==0) )) { this.lastFieldChangedEvent = 0; setString( newText ); notifyStateChanged(); } //#endif Object bbLock = UiApplication.getEventLock(); synchronized (bbLock) { this.editField.focusRemove(); } //#if polish.hasPointerEvents && polish.TextField.hideSoftKeyboardOnDefocus DeviceControl.hideSoftKeyboard(); //#endif //#elif polish.TextField.showInputInfo != false && !tmp.includeInputInfo if (this.screen != null) { this.screen.setInfo((Item)null); } //#endif //#if tmp.directInput if (this.editingCaretChar != this.caretChar) { commitCurrentCharacter(); notifyStateChanged(); } //#endif } //#endif //#if tmp.directInput || !polish.TextField.suppressDeleteCommand || (polish.android && polish.android.autoFocus) protected Style focus(Style focStyle, int direction) { //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null ) { this.series40sdk20Field.setFocus(true); } //#endif //#if polish.android if (this.isShown) { DeviceControl.showSoftKeyboard(); } //#if !polish.TextField.keepCaretPosition setCaretPosition( getString().length() ); //#endif //#elif tmp.directInput || polish.blackberry || polish.series40sdk20 || polish.series40sdk11 //#ifdef tmp.allowDirectInput if (this.enableDirectInput) { //#endif //#if tmp.useInputInfo updateInfo(); //#endif //#if polish.TextField.jumpToStartOnFocus //#if !polish.blackberry if (this.caretPosition != 0) { //#endif setCaretPosition( 0 ); //#if !polish.blackberry } //#endif //#elif !polish.TextField.keepCaretPosition setCaretPosition( getString().length() ); //#endif //#ifdef tmp.allowDirectInput } //#endif //#endif Style unfocusedStyle = super.focus(focStyle, direction); //#if tmp.updateDeleteCommand && !(polish.blackberry || polish.android) updateDeleteCommand( this.text ); //#endif return unfocusedStyle; } //#endif //#if polish.blackberry /** * Notifies the TextField about changes in its native BlackBerry component. * @param field the native field * @param context the context of the change */ public void fieldChanged(Field field, int context) { if (context != FieldChangeListener.PROGRAMMATIC && this.isInitialized ) { //#if polish.Bugs.ItemStateListenerCalledTooEarly int fieldType = this.constraints & 0xffff; if (fieldType == NUMERIC || fieldType == DECIMAL || fieldType == FIXED_POINT_DECIMAL) { setString( this.editField.getText() ); notifyStateChanged(); } else { long currentTime = System.currentTimeMillis(); this.lastFieldChangedEvent = currentTime; Screen scr = getScreen(); if (scr != null) { scr.lastInteractionTime = currentTime; } } //#else setString( this.editField.getText() ); notifyStateChanged(); //#endif } } //#endif //#if polish.series40sdk11 public void multilineToggleFix(TextEditor textEditor) { Object parent = textEditor.getParent(); textEditor.setParent(null); textEditor.setParent(parent); } //#endif //#if polish.series40sdk20 || polish.series40sdk11 public void inputAction(TextEditor textEditor, int actions) { if (textEditor == null ) { return; } // If the text changes, make sure to update the Polish item as needed setText(textEditor.getContent()); notifyStateChanged(); // Switching from multi to single-line and vice-versa in SDK 1.1 does not work as expected. // As such, for now we only do this on SDK 2.0 devices. if ( getNumberOfLines() > 1 && textEditor.isMultiline() == false ) { textEditor.setMultiline(true); //#if polish.series40sdk11 multilineToggleFix(textEditor); //#endif } else if ( getNumberOfLines() <= 1 && textEditor.isMultiline() ) { textEditor.setMultiline(false); //#if polish.series40sdk11 multilineToggleFix(textEditor); //#endif } } //#endif /** * Sets the input mode for this TextField. * Is ignored when no direct input mode is used. * * @param inputMode the input mode */ public void setInputMode(int inputMode) { this.inputMode = inputMode; //#if tmp.directInput //#if tmp.useInputInfo if (this.isFocused) { updateInfo(); } //#endif if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); } if (inputMode == MODE_FIRST_UPPERCASE) { this.nextCharUppercase = true; } else { this.nextCharUppercase = false; } //#endif } /** * Returns the current input mode. * * @return the current input mode */ public int getInputMode() { return this.inputMode; } /** * (De)activates the input info element for this TextField. * Note that the input info cannot be shown when it is deactivated by setting the "polish.TextField.includeInputInfo" * preprocessing variable to "false". * * @param show true when the input info should be shown */ public void setShowInputInfo(boolean show) { this.isShowInputInfo = show; } /* * (non-Javadoc) * @see de.enough.polish.ui.StringItem#showNotify() */ protected void showNotify() { //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null && this.isFocused) { this.series40sdk20Field.setVisible(true); this.series40sdk20Field.setFocus(true); } //#endif //#if tmp.updateDeleteCommand updateDeleteCommand(this.text); //#endif //#if polish.TextField.useExternalInfo && !polish.blackberry if(this.isFocused && this.infoItem != null) { updateInfo(); } //#endif //#if polish.blackberry && polish.hasPointerEvents //#if polish.showSoftKeyboardOnShowNotify != false if (this.isFocused) { DeviceControl.showSoftKeyboard(); } //#endif //#endif super.showNotify(); } //#if (!polish.blackberry && tmp.directInput) || polish.series40sdk20 || polish.series40sdk11 /* (non-Javadoc) * @see de.enough.polish.ui.StringItem#hideNotify() */ protected void hideNotify() { //#if polish.series40sdk20 || polish.series40sdk11 if ( this.series40sdk20Field != null ) { this.series40sdk20Field.setVisible(false); this.series40sdk20Field.setFocus(false); } //#else if (this.caretChar != this.editingCaretChar) { commitCurrentCharacter(); } //#endif super.hideNotify(); } //#endif //#if tmp.usePredictiveInput public PredictiveAccess getPredictiveAccess() { return this.predictiveAccess; } public void setPredictiveAccess(PredictiveAccess predictive) { this.predictiveAccess = predictive; } //#endif /** * Checks if commands are currently suppressed by this TextField. * @return true when commands are suppressed */ public boolean isSuppressCommands() { return this.suppressCommands; } /** * Toggles the surpressing of commands for this TextField * This has no effect when commands are globally suppressed by settting * the preprocessing variable "polish.TextField.suppressCommands" to "true". * * @param suppressCommands true when commands should be suppressed */ public void setSuppressCommands(boolean suppressCommands) { this.suppressCommands = suppressCommands; setConstraints( this.constraints ); } //#if polish.TextField.showHelpText /** * Sets a help text for this TextField. The help text * appears when a TextField has no input yet and is * used to inform the user about the desired content * (e.g. "Insert name here ...") * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * @param text the help text * @see #setHelpStyle() * @see #setHelpStyle(Style) * @see #setHelpText(String,Style) */ public void setHelpText(String text) { this.helpItem.setText(text); } //#endif //#if polish.TextField.showHelpText /** * Sets a help text for this TextField and its style. The help text * appears when a TextField has no input yet and is * used to inform the user about the desired content * (e.g. "Insert name here ...") * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * This method can be used with preprocessing: * <pre> * //#style inputHelp * myTextField.setHelpText("Enter your Name..."); * </pre> * @param text the help text * @see #setHelpStyle() * @see #setHelpStyle(Style) * @see #setHelpText(String) */ public void setHelpText(String text, Style helpStyle) { this.helpItem.setText(text); if (helpStyle != null) { this.helpItem.setStyle(helpStyle); } //#if polish.android MidletBridge.getInstance().runOnUiThread( new Runnable() { public void run() { TextField.this._androidTextField.applyTextField(); } }); //#endif } //#endif //#if polish.TextField.showHelpText /** * Sets the help style for this TextField * with the use of style preprocessing e.g.: * <pre> * //#style myStyle * setHelpStyle(); * </pre> * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * @see #setHelpText(String) * @see #setHelpStyle(Style) */ public void setHelpStyle() { // nothing here } /** * Sets the style of the help text * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * @param style the style * @see #setHelpText(String) * @see #setHelpStyle() */ public void setHelpStyle(Style style) { if (this.helpItem != null) { this.helpItem.setStyle(style); //#if polish.android MidletBridge.getInstance().runOnUiThread( new Runnable() { public void run() { TextField.this._androidTextField.applyTextField(); } }); //#endif } } //#endif //#if polish.TextField.showHelpText /** * Retrieves the help text for this TextField. * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * @return the help text * @see #setHelpText(String) * @see #setHelpText(String,Style) */ public String getHelpText() { String text = null; if (this.helpItem != null) { text = this.helpItem.getText(); } return text; } //#endif //#if polish.TextField.showHelpText /** * Retrieves the help text for this TextField. * This method is only available when you have set the <code>polish.TextField.showHelpText</code> preprocessing variable to <code>true</code> * in the build.xml. * @return the help text * @see #setHelpText(String) * @see #setHelpText(String,Style) */ public Color getHelpTextColor() { if (!this.isStyleInitialized && this.style != null) { setStyle(this.style); } Style helpStyle = this.helpItem.getStyle(); if (helpStyle == null) { helpStyle = this.style; } if (helpStyle != null) { Color color = helpStyle.getColorProperty("font-color"); return color; } return new Color( 0x0 ); } //#endif //#if polish.TextField.useExternalInfo && !polish.blackberry /** * Returns the StringItem which is displaying the input info * @return the StringItem displaying the input info * @see #getInfoItem() */ public StringItem getInfoItem() { return this.infoItem; } /** * Sets the StringItem which should display the input info * @param infoItem the StringItem to display the input info * @see #setInfoItem(StringItem) */ public void setInfoItem(StringItem infoItem) { this.infoItem = infoItem; } //#endif //#if !polish.blackberry && tmp.supportsSymbolEntry /** * Returns the defined symbols as a String array * @return the string array */ public static String[] getDefinedSymbols() { return definedSymbols; } //#endif //#if polish.blackberry /* (non-Javadoc) * @see de.enough.polish.ui.Item#updateInternalArea() */ public void updateInternalArea() { int cursorPosition = this.editField.getCursorPosition(); // check if cursor is in visible area: int lineHeight = getLineHeight(); if (this.text != null) { this.internalX = 0; int size = this.textLines.size(); this.internalHeight = lineHeight; this.internalWidth = this.itemWidth; // assume last row by default: this.internalY = this.contentHeight - lineHeight; if (cursorPosition < this.text.length() - this.textLines.getLine(size-1).length()) { // cursor might not be in the last row: int endOfLinePos = 0; int textLength = this.text.length(); for (int i = 0; i < size; i++) { String line = this.textLines.getLine(i); endOfLinePos += line.length(); if (endOfLinePos < textLength) { char c = this.text.charAt( endOfLinePos ); if (c == ' ' || c == '\t' || c == '\n') { line += c; endOfLinePos++; } } if (cursorPosition <= endOfLinePos) { this.internalY = lineHeight * i; break; } } } if (this.parent instanceof Container) { int direction = Canvas.DOWN; if (cursorPosition > this.bbLastCursorPosition) { direction = Canvas.UP; } this.bbLastCursorPosition = cursorPosition; boolean scrolled = ((Container)this.parent).scroll(direction, this, true); if(scrolled) { repaintFully(); } } } else { this.internalX = NO_POSITION_SET; } } //#endif /** * Retrieves matching words for the specified textfield. * Note that you need to enable the predictive input mode using the preprocessing variable * <code>polish.TextField.usePredictiveInputMode</code>. * * @return ArrayList&lt;String&gt; of allowed words - null when no predictive mode is used */ public ArrayList getPredictiveMatchingWords() { //#if tmp.usePredictiveInput PredictiveAccess predictive = getPredictiveAccess(); return predictive.getResults(); //#else //# return null; //#endif } /** * Allows the given words for the specified textfield. * Note that you need to enable the predictive input mode using the preprocessing variable * <code>polish.TextField.usePredictiveInputMode</code>. * * @param words array of allowed words - use null to reset the allowed words to the default RMS dictionary */ public void setPredictiveDictionary(String[] words) { //#if tmp.usePredictiveInput PredictiveAccess predictive = getPredictiveAccess(); predictive.initPredictiveInput(words); setString(""); predictive.synchronize(); if(words == null) { predictive.setPredictiveType(PredictiveAccess.TRIE); } else { predictive.setPredictiveType(PredictiveAccess.ARRAY); } //#endif } //TODO andre: document public void setPredictiveInfo(String info) { //#if tmp.usePredictiveInput PredictiveAccess predictive = getPredictiveAccess(); predictive.setInfo(info); //#endif } /** * Set the word-not-found box in the textfield * * @param alert the alert */ public void setPredictiveWordNotFoundAlert(Alert alert) { //#if tmp.usePredictiveInput getPredictiveAccess().setAlert(alert); //#endif } /** * Returns true if the flag to open the native editor on CenterSoftKey press is set to true * @return true when the native editor is opened when FIRE is pressed */ public boolean isCskOpensNativeEditor() { return this.cskOpensNativeEditor; } /** * Sets the flag to open the native editor on CenterSoftKey press * @param cskOpensNativeEditor true when the native editor should be opened when FIRE is pressed */ public void setCskOpensNativeEditor(boolean cskOpensNativeEditor) { this.cskOpensNativeEditor = cskOpensNativeEditor; } /** * Sets the title to be displayed in the native textbox * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * Set if the textfield should accept only simple input. * * @param noComplexInput set if the textfield should accept only simple input */ public void setNoComplexInput(boolean noComplexInput){ this.noComplexInput= noComplexInput; this.setConstraints(this.constraints); } /** * Set if the textfield should accept the enter key as an input which results in a new line. * * @param noNewLine set if new lines should be ignored */ public void setNoNewLine(boolean noNewLine) { this.noNewLine = noNewLine; //#if polish.blackberry this.setConstraints(this.constraints); //#endif } /** * Checks if the textfield should accept the enter key as an input which results in a new line. * * @return true if new lines should be ignored */ public boolean isNoNewLine() { return this.noNewLine; } /** * Checks if this textfield is edtiable. * @return true when this field is editable */ public boolean isEditable() { return ((this.constraints & TextField.UNEDITABLE) != TextField.UNEDITABLE); } public boolean isConstraintsPhoneNumber() { return ((this.constraints & PHONENUMBER) == PHONENUMBER); } public boolean isConstraintsEmail() { return ((this.constraints & EMAILADDR) == EMAILADDR); } public boolean isConstraintsNumeric() { return ((this.constraints & NUMERIC) == NUMERIC); } public boolean isConstraintsDecimal() { return ((this.constraints & DECIMAL) == DECIMAL) || ((this.constraints & FIXED_POINT_DECIMAL) == FIXED_POINT_DECIMAL); } public boolean isConstraintsPassword() { return ((this.constraints & PASSWORD) == PASSWORD); } //#ifdef polish.TextField.additionalMethods:defined //#include ${polish.TextField.additionalMethods} //#endif }
414c4d6349fdc90188fab39bcd135a4f0503171c
6763f0f021b47582538987d4ba0a29c506bab3b7
/src/main/java/com/raitichan/MCTweet/config/MCTweetConfigGuiFactory.java
49f6cb8942d60a89a21d7c9360d6ed3b4bd8b59e
[]
no_license
raiti-chan/MCTweet
78dd254fd9929b24e6c8dec5f13bc4f002e63527
18f24d2bd7c1421a914dab7f04a57441f0ff4d7b
refs/heads/master
2020-12-30T13:28:56.085944
2017-05-28T02:19:20
2017-05-28T02:19:20
90,355,523
0
0
null
null
null
null
UTF-8
Java
false
false
3,622
java
package com.raitichan.MCTweet.config; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.client.IModGuiFactory; /** * MCTweet config gui factory. * <br>Created by Raiti-chan on 2017/05/13. * * @author Raiti-chan * @version 1.0.0 * @since 1.0.0 */ @SuppressWarnings("unused") public class MCTweetConfigGuiFactory implements IModGuiFactory { /** * Called when instantiated to initialize with the active minecraft instance. * * @param minecraftInstance the instance */ @Override public void initialize (Minecraft minecraftInstance) { } /** * Return the name of a class extending {@link GuiScreen}. This class will * be instantiated when the "config" button is pressed in the mod list. It will * have a single argument constructor - the "parent" screen, the same as all * Minecraft GUIs. The expected behaviour is that this screen will replace the * "mod list" screen completely, and will return to the mod list screen through * the parent link, once the appropriate action is taken from the config screen. * <p> * A null from this method indicates that the mod does not provide a "config" * button GUI screen, and the config button will be hidden/disabled. * <p> * This config GUI is anticipated to provide configuration to the mod in a friendly * visual way. It should not be abused to set internals such as IDs (they're gonna * keep disappearing anyway), but rather, interesting behaviours. This config GUI * is never run when a server game is running, and should be used to configure * desired behaviours that affect server state. Costs, mod game modes, stuff like that * can be changed here. * * @return A class that will be instantiated on clicks on the config button * or null if no GUI is desired. */ @Override public Class<? extends GuiScreen> mainConfigGuiClass () { return MCTweetConfigGuiScreen.class; } /** * Return a list of the "runtime" categories this mod wishes to populate with * GUI elements. * <p> * Runtime categories are created on demand and organized in a 'lite' tree format. * The parent represents the parent node in the tree. There is one special parent * 'Help' that will always list first, and is generally meant to provide Help type * content for mods. The remaining parents will sort alphabetically, though * this may change if there is a lot of alphabetic abuse. "AAA" is probably never a valid * category parent. * <p> * Runtime configuration itself falls into two flavours: in-game help, which is * generally non interactive except for the text it wishes to show, and client-only * affecting behaviours. This would include things like toggling minimaps, or cheat modes * or anything NOT affecting the behaviour of the server. Please don't abuse this to * change the state of the server in any way, this is intended to behave identically * when the server is local or remote. * * @return the set of options this mod wishes to have available, or empty if none */ @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories () { return null; } /** * Return an instance of a {@link RuntimeOptionGuiHandler} that handles painting the * right hand side option screen for the specified {@link RuntimeOptionCategoryElement}. * * @param element The element we wish to paint for * @return The Handler for painting it */ @SuppressWarnings("deprecation") @Override public RuntimeOptionGuiHandler getHandlerFor (RuntimeOptionCategoryElement element) { return null; } }
682a572aca0d971c9217a100abbdf11f974eaa3e
872601067d4ebaeeea4b90b966ec87583a2f8b4a
/Spring Core, Maven/Hands-on/885114/EngineAnalysis/EngineAnalysis/src/main/java/com/cts/engineAnalysis/SkeletonValidator.java
c2d6d1629a232df02c87357e21e21921d928574b
[]
no_license
VIJAYAJUPUDI/Stage1
ef36fb96157c2200457c4bddfc01f1d6b169ed5e
84087731d3ea7a5a966f80f5d8fab3e73bebce88
refs/heads/main
2023-03-04T19:25:14.105218
2021-02-12T08:52:05
2021-02-12T08:52:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,939
java
package com.cts.engineAnalysis; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; public class SkeletonValidator { public SkeletonValidator(){ validateClassName("com.cts.engineAnalysis.Car"); validateMethodSignature("getReport:void","com.cts.engineAnalysis.Car"); validateClassName("com.cts.engineAnalysis.DieselEngine"); validateMethodSignature("getPerformance:int","com.cts.engineAnalysis.DieselEngine"); validateClassName("com.cts.engineAnalysis.PetrolEngine"); validateMethodSignature("getPerformance:int","com.cts.engineAnalysis.PetrolEngine"); } private static final Logger LOG = Logger.getLogger("SkeletonValidator"); protected final boolean validateClassName(String className) { boolean iscorrect = false; try { Class.forName(className); iscorrect = true; LOG.info("Class Name " + className + " is correct"); } catch (ClassNotFoundException e) { LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the correct package " + "and class name as provided in the skeleton"); } catch (Exception e) { LOG.log(Level.SEVERE, "There is an error in validating the " + "Class Name. Please manually verify that the " + "Class name is same as skeleton before uploading"); } return iscorrect; } protected final void validateMethodSignature(String methodWithExcptn, String className) { Class cls = null; try { String[] actualmethods = methodWithExcptn.split(","); boolean errorFlag = false; String[] methodSignature; String methodName = null; String returnType = null; for (String singleMethod : actualmethods) { boolean foundMethod = false; methodSignature = singleMethod.split(":"); methodName = methodSignature[0]; returnType = methodSignature[1]; cls = Class.forName(className); Method[] methods = cls.getMethods(); for (Method findMethod : methods) { if (methodName.equals(findMethod.getName())) { foundMethod = true; if (!(findMethod.getReturnType().getName().equals(returnType))) { errorFlag = true; LOG.log(Level.SEVERE, " You have changed the " + "return type in '" + methodName + "' method. Please stick to the " + "skeleton provided"); } else { LOG.info("Method signature of " + methodName + " is valid"); } } } if (!foundMethod) { errorFlag = true; LOG.log(Level.SEVERE, " Unable to find the given public method " + methodName + ". Do not change the " + "given public method name. " + "Verify it with the skeleton"); } } if (!errorFlag) { LOG.info("Method signature is valid"); } } catch (Exception e) { LOG.log(Level.SEVERE, " There is an error in validating the " + "method structure. Please manually verify that the " + "Method signature is same as the skeleton before uploading"); } } }
021f43182ac840a822bb8412242fca229c95546f
9b832ed4de8a20e3eb3165cfd86dfcf2fa5affcd
/src/HttpServer/HttpEnum.java
e9c9fd6304597d6ff293fb97346f4ed53f715c27
[]
no_license
HugoDanielson/NovoNordisk
f52b85b2063f1ff1e0b3542bad4afdfd1cb62a02
f2918a338e15231b7b0c58d732388684f7cd1ea8
refs/heads/master
2023-01-06T04:01:51.799368
2020-10-22T03:12:06
2020-10-22T03:12:06
306,209,015
0
0
null
null
null
null
UTF-8
Java
false
false
599
java
package HttpServer; public class HttpEnum { public enum eHttpPath { COM1("/iiwa_com1"), COM2("/iiwa_com2"), COM3("/iiwa_com3"), COM4("/iiwa_com4"),COM5("/iiwa_com5"); private String path; private eHttpPath(String path) { this.path = path; } public String getValue() { return this.path; } // public static eHttpPath valueOf(String value) { // for (eHttpPath path : eHttpPath.values()) { // if (path.getValue().contentEquals(value)){ // return path; // } // } // return null; // } }; }
[ "danielbilik@DANIELBILIK4939" ]
danielbilik@DANIELBILIK4939
44d5c33243402e32a2ab1de91178cfb38dc78eb1
a86ef8b64b11209173fd1123fa387b4ae6194905
/src/com/linmalu/library/api/LinmaluBossbar.java
3506225e111e2c3e4461b4d14abd6227035ed035
[]
no_license
Linmalu/LinmaluLibrary_v1.7.9
2a9b4e424ccdc5fbbdf651a628eb235bef791511
12172799d1c41951d7427cd130b2bab37c58a864
refs/heads/master
2020-03-18T11:25:11.992714
2018-07-24T12:02:14
2018-07-24T12:02:14
134,670,061
0
0
null
null
null
null
UTF-8
Java
false
false
3,199
java
package com.linmalu.library.api; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.wrappers.WrappedDataWatcher; import com.linmalu.library.LinmaluLibrary; public class LinmaluBossbar implements Runnable { private static int bossbarID = 0; private static HashMap<Integer, Integer> schedule = new HashMap<>(); public static void sendMessage(String message) { for(Player player : Bukkit.getOnlinePlayers()) { new LinmaluBossbar(player, message, 100); } } public static void sendMessage(String message, float health) { for(Player player : Bukkit.getOnlinePlayers()) { new LinmaluBossbar(player, message, health); } } public static void sendMessage(Player player, String message) { new LinmaluBossbar(player, message, 100); } public static void sendMessage(Player player, String message, float health) { new LinmaluBossbar(player, message, health); } private Player player; private int taskId; @SuppressWarnings("deprecation") private LinmaluBossbar(Player player, String message, float health) { this.player = player; if(bossbarID == 0) { Zombie zombie = player.getWorld().spawn(new Location(player.getWorld(), 0, -100, 0), Zombie.class); bossbarID = zombie.getEntityId(); zombie.remove(); } health = health / 100 * 200; health = health > 200 ? 200 : health <= 0 ? 1 : health; ProtocolManager pm = ProtocolLibrary.getProtocolManager(); PacketContainer pc = pm.createPacket(PacketType.Play.Server.SPAWN_ENTITY_LIVING); StructureModifier<Integer> ints = pc.getIntegers(); ints.writeDefaults(); ints.write(0, bossbarID); ints.write(1, (int)EntityType.ENDER_DRAGON.getTypeId()); ints.write(2, player.getLocation().getBlockX() * 32); ints.write(3, (player.getLocation().getBlockY() - 300) * 32); ints.write(4, player.getLocation().getBlockZ() * 32); WrappedDataWatcher watcher = new WrappedDataWatcher(); watcher.setObject(0, (byte)0); watcher.setObject(6, health); watcher.setObject(10, message); pc.getDataWatcherModifier().writeDefaults(); pc.getDataWatcherModifier().write(0, watcher); try { pm.sendServerPacket(player, pc); } catch(Exception e) { e.printStackTrace(); } taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(LinmaluLibrary.getMain(), this, 20L); schedule.put(player.getEntityId(), taskId); } public void run() { int id = player.getEntityId(); if(schedule.containsKey(id) && schedule.get(id) != taskId) { return; } ProtocolManager pm = ProtocolLibrary.getProtocolManager(); PacketContainer pc = pm.createPacket(PacketType.Play.Server.ENTITY_DESTROY); pc.getIntegerArrays().write(0, new int[]{bossbarID}); try { pm.sendServerPacket(player, pc); } catch(Exception e) { e.printStackTrace(); } schedule.remove(id); } }
71dc72d8b8b7cc2fc32e6ff6bd31ab4d5ee85cce
33c8113d1b55222ec16ca382284de234bdfc4616
/app/src/main/java/com/example/restaurantsdemoapp/contract/MainActivityContract.java
6bd9f2ae614f665fcaa36ac5996aa79cf7196b5f
[]
no_license
yogeshMarutiPatil/RestaurantDemoApp
ede4308f3ff2b50b5c9011119b7b9d715e5f3b60
35cd056338981f3e3aeb1cca89be18f072edfbbd
refs/heads/master
2020-09-26T07:41:09.977449
2019-12-11T12:06:27
2019-12-11T12:06:27
226,206,220
0
0
null
null
null
null
UTF-8
Java
false
false
930
java
package com.example.restaurantsdemoapp.contract; import android.content.Context; import com.example.restaurantsdemoapp.model.adapter.RestaurantRecyclerViewAdapter; import com.example.restaurantsdemoapp.model.pojo.Restaurant; import java.util.List; public interface MainActivityContract { interface Model { public List<Restaurant> getRestaurantData(Context context, List<Restaurant> restaurantList); public boolean sortingOption(int id, Context context, List<Restaurant> restaurantList, RestaurantRecyclerViewAdapter mAdapter); } interface View { public void setupUI(); public void getRestaurantData(); } interface Presenter { public List<Restaurant> getRestaurantData(Context context, List<Restaurant> restaurantList); public boolean sortingOption(int id, Context context, List<Restaurant> restaurantList, RestaurantRecyclerViewAdapter mAdapter); } }
17afc7ad83d60e577c93697b844090655bf69b01
a04a8bb40cb6682a26d4f43b5de2f8410fb6d269
/src/main/java/cz/fit/dpo/mvcshooter/designPatterns/controller/commandPattern/concreteCommands/MoveCannonDownCommand.java
94834044f1dd0bcbc48546410524e463d984ef3c
[]
no_license
RANJEL/DesignPatternsSeminarJob-MVC_Shooter_Game
5e179c252f39a91749125378ddc1e37c7cd0eacb
e55a469069ded0c139f427d08211668d938b425d
refs/heads/master
2020-03-27T16:23:37.179032
2018-08-31T10:19:01
2018-08-31T10:19:01
146,778,735
0
0
null
null
null
null
UTF-8
Java
false
false
458
java
package cz.fit.dpo.mvcshooter.designPatterns.controller.commandPattern.concreteCommands; import cz.fit.dpo.mvcshooter.designPatterns.controller.commandPattern.AbstractCommand; import cz.fit.dpo.mvcshooter.model.Model; public class MoveCannonDownCommand extends AbstractCommand { public MoveCannonDownCommand(Model itsReceiver) { super(itsReceiver); } @Override public void execute() { itsReceiver.moveCannonDown(); } }
9f55e01d625ce20df8c5c4d8a8fef9bf0439f13a
4ddff7c87688a7b6ec2ea6d0e4d699c91ef73fd2
/src/main/java/com/zzc/modules/sysmgr/user/base/entity/UserOrgPositionRelation.java
342daf3ee5c7ad3a43808482db4c081af646a82f
[]
no_license
1033132510/SCM
56146e99e840c912d1a17f763250d9ab170e7d3c
6a4b8d4bc8685bb5167bd14021f3129a9f5bab91
refs/heads/master
2021-01-21T12:15:23.021648
2017-05-19T08:14:45
2017-05-19T08:14:45
91,782,654
0
0
null
null
null
null
UTF-8
Java
false
false
786
java
package com.zzc.modules.sysmgr.user.base.entity; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; /** * Created by wufan on 2015/11/12. */ @Entity @Table(name = "SYS_USER_ORG_POSITION") public class UserOrgPositionRelation { @EmbeddedId private UserOrgPositionRelationPK id; @Column(name = "DESCRIPTION", length = 200) private String description; public UserOrgPositionRelationPK getId() { return id; } public void setId(UserOrgPositionRelationPK id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
[ "lenovo" ]
lenovo
dd19f611261b0f44a36b6431dd2ba94155bc93f2
e96ae2301d33421d08b6413fdc2f35a6b4c5df5c
/src/com/windows3/po/ProductDetail.java
1ff3a1350feb1a4f8bd0e990d8e3b10f937d80cf
[]
no_license
windows3/spring_mybatis_2_mvc
938f7efb2b10ecd9e14b66c74c053d5859a5e977
dfc86b20149e2854d912c29e2bf8e98e651ae74b
refs/heads/master
2020-04-05T02:57:36.163408
2018-11-07T05:46:34
2018-11-07T05:46:34
156,490,838
0
0
null
null
null
null
UTF-8
Java
false
false
1,480
java
package com.windows3.po; import java.io.Serializable; /** * Created by 3 on 2018/1/20. */ public class ProductDetail implements Serializable { private Integer id; private Integer productId; private String smallImage; private String bigImage; private String productCaption; public ProductDetail() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getSmallImage() { return smallImage; } public void setSmallImage(String smallImage) { this.smallImage = smallImage; } public String getBigImage() { return bigImage; } public void setBigImage(String bigImage) { this.bigImage = bigImage; } public String getProductCaption() { return productCaption; } public void setProductCaption(String productCaption) { this.productCaption = productCaption; } @Override public String toString() { return "ProductDetailDao{" + "id=" + id + ", productId=" + productId + ", smallImage='" + smallImage + '\'' + ", bigImage='" + bigImage + '\'' + ", productCaption='" + productCaption + '\'' + '}'; } }
a6eaa8496059559dabbd9797c72deb8867eb8ace
08542aed048e8cc31c1f111c7c002a070264f900
/src/com/android/settings/ConfirmLockPassword.java
0e802dc81982fb6381d4833b52ea894fd180cbf4
[]
no_license
thehacker911/LG_Launcher
f2922ccf435e0f7c6d616cfbb68735d51c4efd6a
91696e501e9d56f1941137dd685539e0a5b5743d
refs/heads/master
2020-05-18T03:41:01.096277
2014-02-26T15:39:52
2014-02-26T15:39:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,794
java
package com.android.settings; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.android.internal.widget.LockPatternUtils; import com.android.internal.widget.PasswordEntryKeyboardHelper; import com.android.internal.widget.PasswordEntryKeyboardView; public class ConfirmLockPassword extends PreferenceActivity { public Intent getIntent() { Intent localIntent = new Intent(super.getIntent()); localIntent.putExtra(":android:show_fragment", ConfirmLockPasswordFragment.class.getName()); localIntent.putExtra(":android:no_headers", true); return localIntent; } protected boolean isValidFragment(String paramString) { return ConfirmLockPasswordFragment.class.getName().equals(paramString); } public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); CharSequence localCharSequence = getText(2131428314); showBreadCrumbs(localCharSequence, localCharSequence); } public static class ConfirmLockPasswordFragment extends Fragment implements TextWatcher, View.OnClickListener, TextView.OnEditorActionListener { private Button mContinueButton; private Handler mHandler = new Handler(); private TextView mHeaderText; private PasswordEntryKeyboardHelper mKeyboardHelper; private PasswordEntryKeyboardView mKeyboardView; private LockPatternUtils mLockPatternUtils; private TextView mPasswordEntry; private void handleNext() { String str = this.mPasswordEntry.getText().toString(); if (this.mLockPatternUtils.checkPassword(str)) { Intent localIntent = new Intent(); localIntent.putExtra("password", str); getActivity().setResult(-1, localIntent); getActivity().finish(); return; } showError(2131428328); } private void showError(int paramInt) { this.mHeaderText.setText(paramInt); this.mHeaderText.announceForAccessibility(this.mHeaderText.getText()); this.mPasswordEntry.setText(null); this.mHandler.postDelayed(new Runnable() { public void run() { ConfirmLockPassword.ConfirmLockPasswordFragment.this.mHeaderText.setText(2131428314); } } , 3000L); } public void afterTextChanged(Editable paramEditable) { Button localButton = this.mContinueButton; if (this.mPasswordEntry.getText().length() > 0); for (boolean bool = true; ; bool = false) { localButton.setEnabled(bool); return; } } public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } public void onClick(View paramView) { switch (paramView.getId()) { default: return; case 2131230763: handleNext(); return; case 2131230762: } getActivity().setResult(0); getActivity().finish(); } public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); this.mLockPatternUtils = new LockPatternUtils(getActivity()); } public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) { int i = this.mLockPatternUtils.getKeyguardStoredPasswordQuality(); View localView = paramLayoutInflater.inflate(2130968600, null); localView.findViewById(2131230762).setOnClickListener(this); this.mContinueButton = ((Button)localView.findViewById(2131230763)); this.mContinueButton.setOnClickListener(this); this.mContinueButton.setEnabled(false); this.mPasswordEntry = ((TextView)localView.findViewById(2131230761)); this.mPasswordEntry.setOnEditorActionListener(this); this.mPasswordEntry.addTextChangedListener(this); this.mKeyboardView = ((PasswordEntryKeyboardView)localView.findViewById(2131230764)); this.mHeaderText = ((TextView)localView.findViewById(2131230759)); int j; int k; label156: int m; label204: int n; label239: PreferenceActivity localPreferenceActivity; if ((262144 == i) || (327680 == i) || (393216 == i)) { j = 1; TextView localTextView1 = this.mHeaderText; if (j == 0) break label296; k = 2131428314; localTextView1.setText(k); Activity localActivity = getActivity(); this.mKeyboardHelper = new PasswordEntryKeyboardHelper(localActivity, this.mKeyboardView, this.mPasswordEntry); PasswordEntryKeyboardHelper localPasswordEntryKeyboardHelper = this.mKeyboardHelper; if (j == 0) break label303; m = 0; localPasswordEntryKeyboardHelper.setKeyboardMode(m); this.mKeyboardView.requestFocus(); n = this.mPasswordEntry.getInputType(); TextView localTextView2 = this.mPasswordEntry; if (j == 0) break label309; localTextView2.setInputType(n); if ((localActivity instanceof PreferenceActivity)) { localPreferenceActivity = (PreferenceActivity)localActivity; if (j == 0) break label316; } } label296: label303: label309: label316: for (int i1 = 2131428314; ; i1 = 2131428316) { CharSequence localCharSequence = getText(i1); localPreferenceActivity.showBreadCrumbs(localCharSequence, localCharSequence); return localView; j = 0; break; k = 2131428316; break label156; m = 1; break label204; n = 18; break label239; } } public boolean onEditorAction(TextView paramTextView, int paramInt, KeyEvent paramKeyEvent) { if ((paramInt == 0) || (paramInt == 6) || (paramInt == 5)) { handleNext(); return true; } return false; } public void onPause() { super.onPause(); this.mKeyboardView.requestFocus(); } public void onResume() { super.onResume(); this.mKeyboardView.requestFocus(); } public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3) { } } } /* Location: C:\dex 2 jar\classes-dex2jar.jar * Qualified Name: com.android.settings.ConfirmLockPassword * JD-Core Version: 0.6.2 */
934f5acd4198edf04eebf7c9e2834b9736bc7fdb
d340ca98ec67ca00f44d52dd222ff1bfce45a23b
/VariantDriftPrototype/src/main/java/de/hub/mse/variantsync/variantdrift/experiments/algorithms/nwm/alg/merge/Merger.java
2c5662349f4b2e872077d709940b695c0073f16b
[]
no_license
AlexanderSchultheiss/variant-drift
e6f45dc027dd6a9d922ca98825afd60e54fcd3c5
4dba0cbd373adcb485dd45437e95447eaa7957ff
refs/heads/master
2023-02-06T19:38:28.409815
2020-09-24T09:09:30
2020-09-24T09:09:30
298,225,102
1
0
null
null
null
null
UTF-8
Java
false
false
4,217
java
package de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.alg.merge; import java.util.ArrayList; import java.util.HashSet; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.common.AlgoUtil; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Element; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Tuple; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.alg.Matchable; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.domain.Model; import de.hub.mse.variantsync.variantdrift.experiments.algorithms.nwm.execution.RunResult; public abstract class Merger { protected ArrayList<Model> models; private Model mergedModel = null; private ArrayList<Tuple> mergedTuples; public Merger(ArrayList<Model> models) { this.models = models; } public Merger(){ this.models = new ArrayList<Model>(); } protected abstract Matchable getMatch(); public abstract RunResult getRunResult(int numOfModels); private ArrayList<Element> makeElementsFromMatchTuples(ArrayList<Tuple> match){ ArrayList<Element> retVal = new ArrayList<Element>(); for(Tuple t:match){ retVal.add(new Element(t)); } return retVal; } private ArrayList<Element> getNotMatchedElementsFromModel(Model m, HashSet<Element> ignoreList){ ArrayList<Element> nonIgnored = new ArrayList<Element>(); for(Element elem:m.getElements()){ boolean canBeAdded = true; for(Element bue:elem.getBasedUponElements()){ if(ignoreList.contains(bue)) { canBeAdded = false; break; } } if(canBeAdded) nonIgnored.add(elem); } return nonIgnored; } private ArrayList<Element> getNonMatchedElements(){ ArrayList<Tuple> match = getMatch().getTuplesInMatch(); ArrayList<Element> retVal = new ArrayList<Element>(); HashSet<Element> matchedElements = new HashSet<Element>(); for(Tuple t:match){ for(Element elem:t.sortedElements()) matchedElements.add(elem); } for(Model m: getMatch().getModels()){ retVal.addAll(getNotMatchedElementsFromModel(m, matchedElements)); } return retVal; } public void refreshResultTuplesWeight(Model merged) { // int numOfSourceModels = 0; ArrayList<Model> srcModels = getMatch().getModels(); // for(Model m: getMatch().getModels()){ // numOfSourceModels += m.getMergedFrom(); // } Tuple t = null; for(Element e:merged.getElements()){ if(e.getBasedUponElements().size() > 1){ t = e.getContaingTuple(); t.setWeight(t.calcWeight(srcModels)); } } } public Model mergeMatchedModels(){ //System.out.println("distro before:"); //RunResult rr = new RunResult(0, null, null, getMatch().getTuplesInMatch()); //System.out.println(rr); if(this.mergedModel != null) return this.mergedModel ; ArrayList<Tuple> matchTuples = getMatch().getTuplesInMatch(); ArrayList<Element> elements = makeElementsFromMatchTuples(matchTuples); elements.addAll(getNonMatchedElements()); // Collections.sort(elements, new Comparator<Element>() { // @Override // public int compare(Element e1, Element e2) { // // TODO Auto-generated method stub // return e1.toPrint().compareTo(e2.toPrint()); // } // }); StringBuilder sb = new StringBuilder(); sb.append("merged models: "); String modelId = ""; int numOfSourceModels = 0; for(Model m: getMatch().getModels()){ modelId = modelId+m.getId(); sb.append(m.getId()).append(","); numOfSourceModels += m.getMergedFrom(); } //System.out.println(sb.toString()); Model merged = new Model(modelId,elements); for(Element e:elements){ e.setModelId(modelId); } merged.setMergedFrom(numOfSourceModels); //refreshResultTuplesWeight(numOfSourceModels, merged); this.mergedModel = merged; return merged; } public ArrayList<Tuple> extractMerge(){ if(this.mergedTuples != null) return this.mergedTuples; ArrayList<Tuple> tpls = new ArrayList<Tuple>(); Model m = mergeMatchedModels(); for(Element e:m.getElements()){ if(e.getBasedUponElements().size() > 1 || AlgoUtil.COMPUTE_RESULTS_CLASSICALLY){ tpls.add(e.getContaingTuple()); } } this.mergedTuples = tpls; return tpls; } }
0c8a664754ced5e001617ba0d630d64c9069f414
2d7433ffc30c3a320bd46faae52aacf5b05216f3
/app/src/main/java/com/sam_chordas/android/stockhawk/widget/DetailWidgetProvider.java
43aea57847843f70aa91cb35d75539f851438abb
[]
no_license
nvh0412/StockHawk
af8c070cc4f389762a56130af939b0dbaeb4f9b9
111dca766b279dc8ea2b9de1be26a67bb70559d8
refs/heads/master
2020-04-06T03:47:54.017811
2016-09-14T17:02:07
2016-09-14T17:02:07
67,299,730
0
0
null
2016-09-03T16:18:44
2016-09-03T16:18:44
null
UTF-8
Java
false
false
2,379
java
package com.sam_chordas.android.stockhawk.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.TaskStackBuilder; import android.widget.RemoteViews; import com.sam_chordas.android.stockhawk.R; import com.sam_chordas.android.stockhawk.service.StockTaskService; import com.sam_chordas.android.stockhawk.ui.MyStocksActivity; /** * Created by HoaNV on 9/13/16. */ public class DetailWidgetProvider extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { for (int appWidgetId : appWidgetIds) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_detail); Intent intent = new Intent(context, MyStocksActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.widget, pendingIntent); // Set up the collection setRemoteAdapter(context, views); Intent clickIntentTemplate = new Intent(context, MyStocksActivity.class); PendingIntent clickPendingIntent = TaskStackBuilder.create(context) .addNextIntentWithParentStack(clickIntentTemplate) .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); views.setPendingIntentTemplate(R.id.widget_list, clickPendingIntent); views.setEmptyView(R.id.widget_list, R.id.widget_empty); appWidgetManager.updateAppWidget(appWidgetId, views); } } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); if (StockTaskService.ACTION_DATE_UPDATED.equals(intent.getAction())) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int[] appWidgetIds = appWidgetManager.getAppWidgetIds( new ComponentName(context, getClass())); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list); } } private void setRemoteAdapter(Context context, @NonNull final RemoteViews views) { views.setRemoteAdapter(R.id.widget_list, new Intent(context, DetailWidgetRemoteViewsService.class)); } }
7657972bb3e025a17e5c55a176303cf644ca6a3d
f03081503b10bfd96216cb564b1050120c66aa70
/app/src/androidTest/java/com/example/sam/randommusichttp/ExampleInstrumentedTest.java
34d8b9031ef68feb6f9aa9f5170afc180fedce96
[]
no_license
ntv168/RandomChannelHttp
a3da3f43a1133ee12a3da085e48c8a6c945e8c0b
dd71769f61b6f70246f4326cd3ef2621df3a0f6d
refs/heads/master
2021-07-08T18:12:18.934192
2017-10-08T16:06:43
2017-10-08T16:06:43
106,122,511
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package com.example.sam.randommusichttp; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.sam.randommusichttp", appContext.getPackageName()); } }
[ "yolovelee" ]
yolovelee
f107968883cddcfdc89a8fb9572cd040997dffb6
ba1c4635e8ca406241300cffc5a5ae16d8047c1f
/src/es/workast/utils/WorkastException.java
48a96540c523cf30aba523e7b48c9af00b763838
[]
no_license
ncornag/workast
686dd1ae0d46c4753e8e79cb62aef88d229a47b3
9a5f1b46d34a73f331747dd881822a7986d517c4
refs/heads/master
2021-01-22T12:13:08.830627
2008-09-25T22:20:01
2015-12-02T15:04:02
32,228,769
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
1,606
java
package es.workast.utils; import org.springframework.context.NoSuchMessageException; import org.springframework.context.support.AbstractMessageSource; /** * TODO Documentar * * @author Nicolás Cornaglia */ public class WorkastException extends RuntimeException { private static final long serialVersionUID = 1L; protected WorkastException() { super(); } public WorkastException(String messageKey, Object... messageArgs) { super(resolveMessage(messageKey, messageArgs)); } public WorkastException(Throwable cause) { super(cause); } public WorkastException(Throwable cause, String messageKey, Object... messageArgs) { super(resolveMessage(messageKey, messageArgs), cause); } private static String resolveMessage(String messageKey, Object[] messageArgs) { AbstractMessageSource ms = MessageUtils.getMessageSource(); String resolved = null; if (ms != null) { try { resolved = ms.getMessage(messageKey, messageArgs, MessageUtils.DEFAULT_LOCALE); } catch (NoSuchMessageException e) { resolved = copyArgs(messageKey, messageArgs); } } else { resolved = copyArgs(messageKey, messageArgs); } return resolved; } private static String copyArgs(String messageKey, Object[] messageArgs) { String resolved = messageKey + (messageArgs.length > 0 ? ":" : ""); for (Object arg : messageArgs) { resolved = resolved + ", " + arg; } return resolved; } }
c7120a7c6cb61b812535116d442f10f241bae63c
b1db7cf979aaed9a60e376fe2a61e020b66f84e0
/src/java/com/jilit/irp/persistence/dto/HobbiesMasterId.java
76838550152fbe0b86ff219f3ff747cd8b011944
[]
no_license
livcoding/CLXRegistration_OLD
c2a569c0c05c46b9fbb6e176ffc1fd9ca3ebd7e1
a167f29d20d9c9f1de0e4e78bfca6317f837bc4d
refs/heads/master
2023-06-21T11:14:20.595579
2021-07-23T07:26:29
2021-07-23T07:26:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
899
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 com.jilit.irp.persistence.dto; /** * * @author ashok.singh */ public class HobbiesMasterId implements java.io.Serializable { private String clientid; private String hobbyname; public HobbiesMasterId() { } public HobbiesMasterId(String clientid, String hobbyname) { this.clientid = clientid; this.hobbyname = hobbyname; } public String getClientid() { return clientid; } public void setClientid(String clientid) { this.clientid = clientid; } public String getHobbyname() { return hobbyname; } public void setHobbyname(String hobbyname) { this.hobbyname = hobbyname; } }