blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f6b763ebb963614e54b0484bc9371141f2cb411a | 28,776,280,940,472 | 0a4a1d5a7f190cb904d3b0c96bc5202d4f431fcc | /aidan-spring-06-spring-jdbc/src/main/java/org/aidan/dao/UserDao.java | 4cdeeff4506365a59eb80bce044db9ea28ecf3e0 | []
| no_license | huxiaoning/aidan-code | https://github.com/huxiaoning/aidan-code | 02f7ee0250474f5d9acaa84b1aba492138ae8ee5 | 8f6a0bcc40412e86d56fd7477a0a764f1670580b | refs/heads/master | 2020-03-27T09:03:05.222000 | 2018-12-24T05:44:16 | 2018-12-24T05:44:16 | 146,309,921 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.aidan.dao;
import org.aidan.dao.base.BaseDao;
import org.aidan.entity.User;
/**
* @author Aidan
* @创建时间:2018/11/26 12:16 PM
* @描述: CustomersDao
*/
public interface UserDao extends BaseDao<User> {
}
| UTF-8 | Java | 231 | java | UserDao.java | Java | [
{
"context": "Dao;\nimport org.aidan.entity.User;\n\n/**\n * @author Aidan\n * @创建时间:2018/11/26 12:16 PM\n * @描述: CustomersDao",
"end": 110,
"score": 0.8201172351837158,
"start": 105,
"tag": "NAME",
"value": "Aidan"
}
]
| null | []
| package org.aidan.dao;
import org.aidan.dao.base.BaseDao;
import org.aidan.entity.User;
/**
* @author Aidan
* @创建时间:2018/11/26 12:16 PM
* @描述: CustomersDao
*/
public interface UserDao extends BaseDao<User> {
}
| 231 | 0.705069 | 0.64977 | 13 | 15.692307 | 15.298992 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 9 |
60d3fe4b1fc81c3bd0c035355dfffb0637140808 | 927,712,966,665 | 9adcff56c1f3a39482efe48dc9d5678959a70217 | /src/main/java/br/com/lubarino/jarvis/services/UserService.java | 283fe4cef87e6050b61f667dbf167687ee6a8b24 | []
| no_license | lubarinobr/advremember | https://github.com/lubarinobr/advremember | 60378963b01b77d9516284803ecf20312ddc5047 | ea435e1aadc9ac23c8a0833fe3f8bbf74e3d4c2e | refs/heads/master | 2020-06-23T17:21:59.847000 | 2019-07-24T19:12:46 | 2019-07-24T19:12:46 | 198,695,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.lubarino.jarvis.services;
import br.com.lubarino.jarvis.domains.User;
public interface UserService {
void save(User user);
User findByUsername(String username);
} | UTF-8 | Java | 188 | java | UserService.java | Java | []
| null | []
| package br.com.lubarino.jarvis.services;
import br.com.lubarino.jarvis.domains.User;
public interface UserService {
void save(User user);
User findByUsername(String username);
} | 188 | 0.765957 | 0.765957 | 9 | 20 | 18.427032 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 9 |
5e4bc92a94a42077174bccdfc6c7e8b1bb6af2d0 | 16,174,846,838,578 | f4796194c75b7586b10f22ba3ff1d55643bb7ccf | /app/src/main/java/com/guanglun/atouch/DBManager/KeyMouse.java | e6dbdc8dae558ba7350880be3f24ed289ebd44e5 | []
| no_license | summer20100514/ATouch | https://github.com/summer20100514/ATouch | f720abd3c7b60de6050746af2c6734ea0da71268 | 3f0b6aff27f21c91de2ff0f822fa44d7eb4f544a | refs/heads/master | 2021-01-16T15:28:02.881000 | 2019-06-04T13:47:03 | 2019-06-04T13:47:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.guanglun.atouch.DBManager;
public class KeyMouse {
public int ID;
public String Name = null;
public String Description = null;
public int KeyCode;
public int PX;
public int PY;
public void SetID(int id)
{
this.ID = id;
}
public void SetName(String name)
{
this.Name = name;
}
public void SetKeyCode(int kc)
{
this.KeyCode = kc;
}
public void SetDescription(String description)
{
this.Description = description;
}
public void SetPosition(int px,int py)
{
this.PX = px;
this.PY = py;
}
public KeyMouse()
{
}
public KeyMouse(int id,String name,String description,int kc,int px,int py)
{
this.ID = id;
this.Name = name;
this.Description = description;
this.KeyCode = kc;
this.PX = px;
this.PY = py;
}
} | UTF-8 | Java | 923 | java | KeyMouse.java | Java | []
| null | []
| package com.guanglun.atouch.DBManager;
public class KeyMouse {
public int ID;
public String Name = null;
public String Description = null;
public int KeyCode;
public int PX;
public int PY;
public void SetID(int id)
{
this.ID = id;
}
public void SetName(String name)
{
this.Name = name;
}
public void SetKeyCode(int kc)
{
this.KeyCode = kc;
}
public void SetDescription(String description)
{
this.Description = description;
}
public void SetPosition(int px,int py)
{
this.PX = px;
this.PY = py;
}
public KeyMouse()
{
}
public KeyMouse(int id,String name,String description,int kc,int px,int py)
{
this.ID = id;
this.Name = name;
this.Description = description;
this.KeyCode = kc;
this.PX = px;
this.PY = py;
}
} | 923 | 0.56013 | 0.56013 | 51 | 17.117647 | 16.377468 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false | 9 |
deafbd2b312f67fbc9a0b3b070990eff17ad6099 | 18,794,776,910,550 | a309b3700e8a3c5fcd5c9d5a8a944e0224abb0ca | /app/src/main/java/com/wander/model/Attractions.java | a325a76f110cb0937a2b4f6965c87f72ec1730c3 | []
| no_license | wander0552/QuestWorld | https://github.com/wander0552/QuestWorld | e1582785c3e07fcbf7abc41bda819a5ee5432486 | 685e2bcf2fe5b3bcb963b124bc3dcd4f27aedbac | refs/heads/master | 2021-01-23T06:49:33.851000 | 2016-01-11T10:25:55 | 2016-01-11T10:25:55 | 38,626,308 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wander.model;
import com.amap.api.maps2d.model.LatLng;
import com.lidroid.xutils.db.annotation.Table;
/**
* Created by wander on 2015/5/13.
* Email:18955260352@163.com
*/
@Table(name = "attractions",execAfterTableCreated = "CREATE UNIQUE INDEX ATTRACTIONS_INDEX ON ATTRACTIONS(id)")
public class Attractions {
private String category;
private String id;
private String name;
private String name_en;
private double Lat;
private double Lng;
private String attraction_type;
private String user_score;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getName_en() {
return name_en;
}
public void setName_en(String name_en) {
this.name_en = name_en;
}
public double getLat() {
return Lat;
}
public void setLat(double lat) {
Lat = lat;
}
public double getLng() {
return Lng;
}
public void setLng(double lng) {
Lng = lng;
}
public String getAttraction_type() {
return attraction_type;
}
public void setAttraction_type(String attraction_type) {
this.attraction_type = attraction_type;
}
public String getUser_score() {
return user_score;
}
public void setUser_score(String user_score) {
this.user_score = user_score;
}
@Override
public String toString() {
return "Attractions{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", latLng=" + Lat+","+Lng +
'}';
}
}
| UTF-8 | Java | 1,929 | java | Attractions.java | Java | [
{
"context": "oid.xutils.db.annotation.Table;\n\n/**\n * Created by wander on 2015/5/13.\n * Email:18955260352@163.com\n */\n\n@",
"end": 140,
"score": 0.9994500875473022,
"start": 134,
"tag": "USERNAME",
"value": "wander"
},
{
"context": "\n\n/**\n * Created by wander on 2015/5/13.\n * Email:18955260352@163.com\n */\n\n@Table(name = \"attractions\",execAfterTableCr",
"end": 183,
"score": 0.9998778104782104,
"start": 164,
"tag": "EMAIL",
"value": "18955260352@163.com"
}
]
| null | []
| package com.wander.model;
import com.amap.api.maps2d.model.LatLng;
import com.lidroid.xutils.db.annotation.Table;
/**
* Created by wander on 2015/5/13.
* Email:<EMAIL>
*/
@Table(name = "attractions",execAfterTableCreated = "CREATE UNIQUE INDEX ATTRACTIONS_INDEX ON ATTRACTIONS(id)")
public class Attractions {
private String category;
private String id;
private String name;
private String name_en;
private double Lat;
private double Lng;
private String attraction_type;
private String user_score;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getName_en() {
return name_en;
}
public void setName_en(String name_en) {
this.name_en = name_en;
}
public double getLat() {
return Lat;
}
public void setLat(double lat) {
Lat = lat;
}
public double getLng() {
return Lng;
}
public void setLng(double lng) {
Lng = lng;
}
public String getAttraction_type() {
return attraction_type;
}
public void setAttraction_type(String attraction_type) {
this.attraction_type = attraction_type;
}
public String getUser_score() {
return user_score;
}
public void setUser_score(String user_score) {
this.user_score = user_score;
}
@Override
public String toString() {
return "Attractions{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", latLng=" + Lat+","+Lng +
'}';
}
}
| 1,917 | 0.575428 | 0.564023 | 94 | 19.521276 | 18.434893 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340426 | false | false | 9 |
e4390228d688f102022dc434205dcc6df683ef2c | 8,203,387,549,605 | 449bf149e85ea2c77390828c7fb42ee43bd06e5f | /src/main/java/gol/CellState.java | 215025bed89cb6d7ada962902802dbb9b5f64371 | []
| no_license | Kors/game-of-life | https://github.com/Kors/game-of-life | d9e64422a16ea6c665f5a668a6e60ce28237adb3 | fe91255058351435a0c89bd885c1666e2bf0c05e | refs/heads/master | 2021-01-12T14:59:27.259000 | 2016-10-23T19:36:08 | 2016-10-23T19:36:08 | 71,658,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gol;
/**
* @author K.ilya
*/
public enum CellState {
DEAD, ALIVE, DIEING, BEARING, UNKNOWN;
public static CellState valueOf(int stateNum) {
for (CellState val : CellState.values())
if (val.ordinal() == stateNum)
return val;
return UNKNOWN;
}
}
| UTF-8 | Java | 270 | java | CellState.java | Java | [
{
"context": "package gol;\n\n/**\n * @author K.ilya\n */\npublic enum CellState {\n\tDEAD, ALIVE, DIEING,",
"end": 35,
"score": 0.9998615980148315,
"start": 29,
"tag": "NAME",
"value": "K.ilya"
}
]
| null | []
| package gol;
/**
* @author K.ilya
*/
public enum CellState {
DEAD, ALIVE, DIEING, BEARING, UNKNOWN;
public static CellState valueOf(int stateNum) {
for (CellState val : CellState.values())
if (val.ordinal() == stateNum)
return val;
return UNKNOWN;
}
}
| 270 | 0.666667 | 0.666667 | 15 | 17 | 16.004166 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.466667 | false | false | 9 |
b8acc26778ec96cd89dbfddbde4144e7aa7a3371 | 8,203,387,548,834 | 39b2a48f899dabcc887178af039c402a43cd934b | /pwgen/src/main/java/com/antiso/jpwgen/server/PwgenServiceImpl.java | 1cb7fdae12ca50b81c1a0bd4a3e86c2b2e13d033 | []
| no_license | antiso/pwgen-gae | https://github.com/antiso/pwgen-gae | f8e822554cc0925d6a155708367094753589eff6 | a7f7117815da2a07b3b559aace022cf52643ee06 | refs/heads/master | 2021-01-22T02:42:57.831000 | 2013-12-16T06:43:08 | 2013-12-16T06:43:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.antiso.jpwgen.server;
import com.antiso.jpwgen.client.PwgenService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import de.rrze.jpwgen.utils.PwHelper;
public class PwgenServiceImpl extends RemoteServiceServlet implements PwgenService {
/**
*
*/
private static final long serialVersionUID = -2727656404203371528L;
public String[] generatePasswords(String [] options) throws IllegalArgumentException {
return PwHelper.process(
options, null).toArray(new String []{});
}
}
| UTF-8 | Java | 518 | java | PwgenServiceImpl.java | Java | []
| null | []
| package com.antiso.jpwgen.server;
import com.antiso.jpwgen.client.PwgenService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import de.rrze.jpwgen.utils.PwHelper;
public class PwgenServiceImpl extends RemoteServiceServlet implements PwgenService {
/**
*
*/
private static final long serialVersionUID = -2727656404203371528L;
public String[] generatePasswords(String [] options) throws IllegalArgumentException {
return PwHelper.process(
options, null).toArray(new String []{});
}
}
| 518 | 0.777992 | 0.741313 | 20 | 24.9 | 29.56163 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | false | false | 9 |
61e2155e6c4c9927216ff317195b641c0a622289 | 10,857,677,325,722 | 83e96da5d08caf567aea196f9022a21abe647337 | /app/src/main/java/com/ouyangzn/github/utils/Log.java | b7ab46c65bcd81ee53aef61b6fd4f976f8c70673 | [
"Apache-2.0"
]
| permissive | ouyangzn/SimpleGitHub | https://github.com/ouyangzn/SimpleGitHub | ed72cc9ab3d93fcf57b95dadfa4994fe637e560a | 5373a9b1e8fc8eff16d54c20a2b0afff8d1a2804 | refs/heads/master | 2021-06-18T03:38:48.035000 | 2017-06-11T13:56:00 | 2017-06-11T13:56:00 | 67,411,931 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2016. ouyangzn <ouyangzn@163.com>
* 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.ouyangzn.github.utils;
import com.ouyangzn.github.BuildConfig;
/**
* <p>日志类,用于代替android提供的Log,以达到更好的控制日志打印的目的
* 用{@link #LOG_LEVER}来控制最低打印的日志等级,{@link #LOG_LEVER}可在application中自由设置
* <p>开发中调试所需打印的日志最高等级不应超过<pre>Log.d();</pre>
*
* @author ouyangzn
*/
public class Log {
public final static short VERBOSE = android.util.Log.VERBOSE;
public final static short DEBUG = android.util.Log.DEBUG;
public final static short INFO = android.util.Log.INFO;
public final static short WARN = android.util.Log.WARN;
public final static short ERROR = android.util.Log.ERROR;
/** 打印log日志的最低等级 */
public static short LOG_LEVER = VERBOSE;
private Log() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/** verbose和debug等级的日志是否要打印 */
// public static boolean DEBUG = BuildConfig.DEBUG;
public static void v(String tag, String msg) {
if (BuildConfig.DEBUG && LOG_LEVER <= VERBOSE)
android.util.Log.v(tag, msg);
}
public static void v(String tag, String msg, Throwable tr) {
if (BuildConfig.DEBUG && LOG_LEVER <= VERBOSE)
android.util.Log.v(tag, msg, tr);
}
public static void d(String tag, String msg) {
if (BuildConfig.DEBUG && LOG_LEVER <= DEBUG)
android.util.Log.d(tag, msg);
}
public static void d(String tag, String msg, Throwable tr) {
if (BuildConfig.DEBUG && LOG_LEVER <= DEBUG)
android.util.Log.d(tag, msg, tr);
}
public static void i(String tag, String msg) {
if (LOG_LEVER <= INFO || BuildConfig.DEBUG)
android.util.Log.i(tag, msg);
}
public static void i(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= INFO || BuildConfig.DEBUG)
android.util.Log.i(tag, msg, tr);
}
public static void w(String tag, String msg) {
if (LOG_LEVER <= WARN || BuildConfig.DEBUG)
android.util.Log.w(tag, msg);
}
public static void w(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= WARN || BuildConfig.DEBUG)
android.util.Log.w(tag, msg, tr);
}
public static void e(String tag, String msg) {
if (LOG_LEVER <= ERROR || BuildConfig.DEBUG)
android.util.Log.e(tag, msg);
}
public static void e(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= ERROR || BuildConfig.DEBUG)
android.util.Log.e(tag, msg, tr);
}
}
| UTF-8 | Java | 3,306 | java | Log.java | Java | [
{
"context": "/*\n * Copyright (c) 2016. ouyangzn <ouyangzn@163.com>\n * Licensed under the Apache",
"end": 35,
"score": 0.9997057318687439,
"start": 27,
"tag": "USERNAME",
"value": "ouyangzn"
},
{
"context": "/*\n * Copyright (c) 2016. ouyangzn <ouyangzn@163.com>\n * Licensed under the Apache License, Version 2.",
"end": 55,
"score": 0.9999234080314636,
"start": 39,
"tag": "EMAIL",
"value": "ouyangzn@163.com"
},
{
"context": "试所需打印的日志最高等级不应超过<pre>Log.d();</pre>\n * \n * @author ouyangzn\n */\npublic class Log {\n\n public final static s",
"end": 883,
"score": 0.9996866583824158,
"start": 875,
"tag": "USERNAME",
"value": "ouyangzn"
}
]
| null | []
| /*
* Copyright (c) 2016. ouyangzn <<EMAIL>>
* 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.ouyangzn.github.utils;
import com.ouyangzn.github.BuildConfig;
/**
* <p>日志类,用于代替android提供的Log,以达到更好的控制日志打印的目的
* 用{@link #LOG_LEVER}来控制最低打印的日志等级,{@link #LOG_LEVER}可在application中自由设置
* <p>开发中调试所需打印的日志最高等级不应超过<pre>Log.d();</pre>
*
* @author ouyangzn
*/
public class Log {
public final static short VERBOSE = android.util.Log.VERBOSE;
public final static short DEBUG = android.util.Log.DEBUG;
public final static short INFO = android.util.Log.INFO;
public final static short WARN = android.util.Log.WARN;
public final static short ERROR = android.util.Log.ERROR;
/** 打印log日志的最低等级 */
public static short LOG_LEVER = VERBOSE;
private Log() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/** verbose和debug等级的日志是否要打印 */
// public static boolean DEBUG = BuildConfig.DEBUG;
public static void v(String tag, String msg) {
if (BuildConfig.DEBUG && LOG_LEVER <= VERBOSE)
android.util.Log.v(tag, msg);
}
public static void v(String tag, String msg, Throwable tr) {
if (BuildConfig.DEBUG && LOG_LEVER <= VERBOSE)
android.util.Log.v(tag, msg, tr);
}
public static void d(String tag, String msg) {
if (BuildConfig.DEBUG && LOG_LEVER <= DEBUG)
android.util.Log.d(tag, msg);
}
public static void d(String tag, String msg, Throwable tr) {
if (BuildConfig.DEBUG && LOG_LEVER <= DEBUG)
android.util.Log.d(tag, msg, tr);
}
public static void i(String tag, String msg) {
if (LOG_LEVER <= INFO || BuildConfig.DEBUG)
android.util.Log.i(tag, msg);
}
public static void i(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= INFO || BuildConfig.DEBUG)
android.util.Log.i(tag, msg, tr);
}
public static void w(String tag, String msg) {
if (LOG_LEVER <= WARN || BuildConfig.DEBUG)
android.util.Log.w(tag, msg);
}
public static void w(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= WARN || BuildConfig.DEBUG)
android.util.Log.w(tag, msg, tr);
}
public static void e(String tag, String msg) {
if (LOG_LEVER <= ERROR || BuildConfig.DEBUG)
android.util.Log.e(tag, msg);
}
public static void e(String tag, String msg, Throwable tr) {
if (LOG_LEVER <= ERROR || BuildConfig.DEBUG)
android.util.Log.e(tag, msg, tr);
}
}
| 3,297 | 0.639031 | 0.635523 | 95 | 32.010525 | 25.6164 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747368 | false | false | 9 |
4ec14ecdaa9a850eb2632076c4400de79e34a99d | 5,832,565,603,712 | fd725385947711c936c8ca2980ac1f26e428eeca | /src/main/java/net/obvj/tasks/api/Task.java | d5825cc974e346cbeec2cf946587e9a46adecb96 | [
"Apache-2.0"
]
| permissive | oswaldobapvicjr/hazelcast-testdrive | https://github.com/oswaldobapvicjr/hazelcast-testdrive | 581b38fb3177ec7e72a0a9f77db5a9b19216e02f | 6ba7060c9ef015f3ff99556f3565ca3129c7eab9 | refs/heads/master | 2023-01-09T03:54:08.905000 | 2019-12-15T03:08:52 | 2019-12-15T03:08:52 | 164,012,907 | 2 | 0 | Apache-2.0 | false | 2022-12-27T14:47:53 | 2019-01-03T19:13:26 | 2022-09-20T12:53:45 | 2022-12-27T14:47:48 | 32 | 1 | 0 | 1 | Java | false | false | package net.obvj.tasks.api;
import com.hazelcast.nio.serialization.DataSerializable;
public interface Task extends Runnable, DataSerializable
{
long getId();
}
| UTF-8 | Java | 174 | java | Task.java | Java | []
| null | []
| package net.obvj.tasks.api;
import com.hazelcast.nio.serialization.DataSerializable;
public interface Task extends Runnable, DataSerializable
{
long getId();
}
| 174 | 0.752874 | 0.752874 | 8 | 19.75 | 22.835007 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
23eb8a58baf389c062672d2fbd0e9b976c5ddc79 | 23,776,939,008,046 | 73f2c64cb5371bf76ecb4ca4e4ef01757786d977 | /src/main/java/com/gmail/carmonespi/app/entity/Turno.java | b46b7070c4a568f61509f93ec45225c6d94d9b65 | [
"MIT"
]
| permissive | Aaroncarmona/gts | https://github.com/Aaroncarmona/gts | b04e7ecee8d6968854b4b0dc9aa26cce7517d5cc | d3d0d1205205a5289581aea1d00f1b5cdd0d3f3a | refs/heads/master | 2020-03-27T17:04:33.146000 | 2018-08-31T02:19:05 | 2018-08-31T02:19:05 | 146,827,250 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gmail.carmonespi.app.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="turnos")
public class Turno implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String turno;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTurno() {
return turno;
}
public void setTurno(String turno) {
this.turno = turno;
}
private static final long serialVersionUID = 1L;
}
| UTF-8 | Java | 676 | java | Turno.java | Java | []
| null | []
| package com.gmail.carmonespi.app.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="turnos")
public class Turno implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String turno;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTurno() {
return turno;
}
public void setTurno(String turno) {
this.turno = turno;
}
private static final long serialVersionUID = 1L;
}
| 676 | 0.755917 | 0.754438 | 36 | 17.777779 | 16.301178 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.972222 | false | false | 9 |
003bec650858ffdcc44928dea46e537f0c0d5190 | 19,688,130,085,247 | 3915c3610dc096b62b210ef8fcfd61f7369c4d91 | /src/main/java/stc/lesson12/Main.java | ab996c7688bd6e0501a3c6ea37c0ea05af38815b | []
| no_license | MikhailMorin/STC14 | https://github.com/MikhailMorin/STC14 | cc8bbb9793eba0fe396cb87f215b44259c1f67bd | 61893f259a8ac77e910db9c23912849c7c590c2f | refs/heads/master | 2020-04-16T21:14:24.330000 | 2019-02-11T14:43:43 | 2019-02-11T14:43:43 | 165,917,703 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stc.lesson12;
import org.apache.log4j.Logger;
import stc.lesson12.dao.*;
import stc.lesson12.entitie.*;
import java.sql.*;
import java.util.Collection;
public class Main {
private static final Logger LOGGER =
Logger.getLogger(Main.class);
private static final String URL = "jdbc:postgresql://localhost:5432/postgres";
private static final String LOGIN = "postgres";
private static final String PASS = "masterkey";
public static void main(String[] args) throws ClassNotFoundException, SQLException, SQLStatementException {
Class.forName("org.postgresql.Driver");
LOGGER.info("START");
Connection connection = DriverManager.getConnection(URL, LOGIN, PASS);
test(connection);
connection.close();
}
/**
* Небольшая демонстрация работы с БД через DAO
* @param connection - соединение с БД
* @throws SQLException
*/
private static void test(Connection connection) throws SQLStatementException {
PersonDAO pDao = new PersonDAOImpl(connection);
SubjectDAO sDao = new SubjectDAOImpl(connection);
Collection<Person> pCol;
Collection<Subject> pSubj;
pCol = pDao.getAllPersons();
for (Person person : pCol) {
System.out.println(person);
Collection<Subject> sCol = sDao.getSubjectsByPerson(person);
sCol.forEach(LOGGER::debug);
}
pSubj = sDao.getAllSubjects();
for (Subject subject : pSubj) {
System.out.println(subject);
pCol = pDao.getPersonsBySubject(subject);
pCol.forEach(LOGGER::debug);
}
}
}
| UTF-8 | Java | 1,710 | java | Main.java | Java | [
{
"context": "ostgres\";\n private static final String PASS = \"masterkey\";\n\n public static void main(String[] args) thr",
"end": 450,
"score": 0.9991210103034973,
"start": 441,
"tag": "PASSWORD",
"value": "masterkey"
}
]
| null | []
| package stc.lesson12;
import org.apache.log4j.Logger;
import stc.lesson12.dao.*;
import stc.lesson12.entitie.*;
import java.sql.*;
import java.util.Collection;
public class Main {
private static final Logger LOGGER =
Logger.getLogger(Main.class);
private static final String URL = "jdbc:postgresql://localhost:5432/postgres";
private static final String LOGIN = "postgres";
private static final String PASS = "<PASSWORD>";
public static void main(String[] args) throws ClassNotFoundException, SQLException, SQLStatementException {
Class.forName("org.postgresql.Driver");
LOGGER.info("START");
Connection connection = DriverManager.getConnection(URL, LOGIN, PASS);
test(connection);
connection.close();
}
/**
* Небольшая демонстрация работы с БД через DAO
* @param connection - соединение с БД
* @throws SQLException
*/
private static void test(Connection connection) throws SQLStatementException {
PersonDAO pDao = new PersonDAOImpl(connection);
SubjectDAO sDao = new SubjectDAOImpl(connection);
Collection<Person> pCol;
Collection<Subject> pSubj;
pCol = pDao.getAllPersons();
for (Person person : pCol) {
System.out.println(person);
Collection<Subject> sCol = sDao.getSubjectsByPerson(person);
sCol.forEach(LOGGER::debug);
}
pSubj = sDao.getAllSubjects();
for (Subject subject : pSubj) {
System.out.println(subject);
pCol = pDao.getPersonsBySubject(subject);
pCol.forEach(LOGGER::debug);
}
}
}
| 1,711 | 0.65343 | 0.646811 | 51 | 31.588236 | 25.060066 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607843 | false | false | 9 |
6d820f3c546f7387906991c36422474061c7a3d3 | 20,014,547,600,677 | 033b9adcab966377890ad870ed78d4fe9a424fde | /src/main/java/com/marble/play/BasicDiceShape.java | 9fd568140057191dd1be3347b15eb21e126ce647 | []
| no_license | cafecoffee/marbleRefactoring | https://github.com/cafecoffee/marbleRefactoring | a38cb957d92bf851f5a73bd077cee34afa87fcb9 | 4f748e19cb60a1514e77f75a6ff3c7b0e83b2404 | refs/heads/master | 2018-11-12T09:07:34.557000 | 2018-09-10T12:20:30 | 2018-09-10T12:20:30 | 142,884,979 | 0 | 0 | null | false | 2018-08-24T13:59:49 | 2018-07-30T14:13:20 | 2018-08-23T13:49:47 | 2018-08-24T13:59:48 | 21 | 0 | 0 | 0 | Java | false | null | package com.marble.play;
public class BasicDiceShape implements DiceShape {
public String shape() {
return "basicDiceShape";
}
}
| UTF-8 | Java | 147 | java | BasicDiceShape.java | Java | []
| null | []
| package com.marble.play;
public class BasicDiceShape implements DiceShape {
public String shape() {
return "basicDiceShape";
}
}
| 147 | 0.687075 | 0.687075 | 8 | 17.375 | 17.463802 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
b1ffa75c4fb51facc724ff25b0fd92abc1093a89 | 14,568,529,072,434 | d2afef76aaf9b23f8ba4e0bc781face116f8c68b | /app/src/main/java/com/example/android/popularmovies/database/FavouriteDao.java | bf093cb0487c7a1c6aeebdd9b5600be2b92dbdd2 | []
| no_license | okpalaChidiebere/PopularMovies | https://github.com/okpalaChidiebere/PopularMovies | 6e310c07eec279b20279e856fedb60e01cec3a65 | b3af508efc725008849ede43bbf1e05c22463455 | refs/heads/master | 2022-07-05T08:28:15.178000 | 2020-05-14T20:50:46 | 2020-05-14T20:50:46 | 256,478,407 | 0 | 0 | null | false | 2020-05-14T20:50:47 | 2020-04-17T10:58:08 | 2020-05-13T07:27:58 | 2020-05-14T20:50:46 | 276 | 0 | 0 | 0 | Java | false | false | package com.example.android.popularmovies.database;
import com.example.android.popularmovies.model.Favourite;
import com.example.android.popularmovies.model.Movies;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
@Dao
public interface FavouriteDao {
@Query("SELECT movies.movie_id, movies.title, movies.thumbnail, movies.overview, movies.rating, movies.release_date, movies.api_movie_id\n" +
"FROM favourite\n" +
"INNER JOIN movies ON favourite.movie_id = movies.movie_id\n" +
"ORDER BY favourite.movie_id DESC")
LiveData<List<Movies>> getAllFavourite();
@Query("SELECT COUNT(movie_id) FROM favourite WHERE movie_id = :id LIMIT 1")
LiveData<Integer> getFavouriteById(int id);
@Query("DELETE FROM favourite WHERE movie_id = :id")
void deleteFavouriteByMovieId(int id);
@Insert
void insertFavourite(Favourite favourite);
@Query("DELETE FROM favourite")
void deleteAll();
}
| UTF-8 | Java | 1,080 | java | FavouriteDao.java | Java | []
| null | []
| package com.example.android.popularmovies.database;
import com.example.android.popularmovies.model.Favourite;
import com.example.android.popularmovies.model.Movies;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
@Dao
public interface FavouriteDao {
@Query("SELECT movies.movie_id, movies.title, movies.thumbnail, movies.overview, movies.rating, movies.release_date, movies.api_movie_id\n" +
"FROM favourite\n" +
"INNER JOIN movies ON favourite.movie_id = movies.movie_id\n" +
"ORDER BY favourite.movie_id DESC")
LiveData<List<Movies>> getAllFavourite();
@Query("SELECT COUNT(movie_id) FROM favourite WHERE movie_id = :id LIMIT 1")
LiveData<Integer> getFavouriteById(int id);
@Query("DELETE FROM favourite WHERE movie_id = :id")
void deleteFavouriteByMovieId(int id);
@Insert
void insertFavourite(Favourite favourite);
@Query("DELETE FROM favourite")
void deleteAll();
}
| 1,080 | 0.728704 | 0.727778 | 35 | 29.857143 | 30.469791 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
d1018b308f75e0ec33ffc7b9efb56697b9443c9e | 24,532,853,208,457 | 17e513fe562355e679f9372ebf969166573d4a1b | /Excise72.java | a1b53c55c7bf04c2e9dcb314601b2bb59bd7bae9 | []
| no_license | August1996/Java | https://github.com/August1996/Java | 466da40519dbeee3bba5d2f03f336785c7778663 | 1eefb5de5c03900f042cb7c75bf6f3f4ec8838e3 | refs/heads/master | 2016-05-21T00:32:10.052000 | 2016-04-18T03:25:03 | 2016-04-18T03:25:03 | 48,790,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //字符串与类型的转换
public class Excise72{
public static void main(String[] args) {
String s1 = "1.3";
String s2 = "ab1";
String s3 = "true";
System.out.println(Double.parseDouble(s1));
// System.out.println(Double.parseDouble(s2));
System.out.println(Boolean.parseBoolean(s3));
Double d1 = new Double(3.1415926);
String s4 = d1 + ""; //自动转换为字符串,产生垃圾值""
String s5 = String.valueOf(d1); //自动转换为字符串,不产生垃圾值
System.out.println(s4 + s5);
}
} | UTF-8 | Java | 524 | java | Excise72.java | Java | []
| null | []
| //字符串与类型的转换
public class Excise72{
public static void main(String[] args) {
String s1 = "1.3";
String s2 = "ab1";
String s3 = "true";
System.out.println(Double.parseDouble(s1));
// System.out.println(Double.parseDouble(s2));
System.out.println(Boolean.parseBoolean(s3));
Double d1 = new Double(3.1415926);
String s4 = d1 + ""; //自动转换为字符串,产生垃圾值""
String s5 = String.valueOf(d1); //自动转换为字符串,不产生垃圾值
System.out.println(s4 + s5);
}
} | 524 | 0.670354 | 0.612832 | 17 | 25.647058 | 17.766264 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.117647 | false | false | 9 |
a705ccb4f230a66119935f3f05052ea81e1a6d89 | 14,130,442,435,094 | 79db700c9f3fe738bb399aecfa55732540e1021b | /app/src/main/java/my/util/app/models/ServiceAddress.java | 3e0da591d1030b5827df7aa93059b7d119ca9b7a | []
| no_license | lakshmanraob/MyUtils | https://github.com/lakshmanraob/MyUtils | fb876c1c12d8f96cb4b4f7280aa8b505d670c67c | e1b4a7d99995a0c446795da9b44d364d77f6d7c3 | refs/heads/master | 2022-05-03T15:36:58.930000 | 2018-04-26T11:23:02 | 2018-04-26T11:23:02 | 95,186,399 | 0 | 0 | null | false | 2017-07-06T06:31:26 | 2017-06-23T05:33:48 | 2017-06-23T05:43:35 | 2017-07-06T06:31:26 | 1,276 | 0 | 0 | 0 | Java | null | null | package my.util.app.models;
public class ServiceAddress {
private String addressName;
private String streetAddress1;
private String streetAddress2;
private String city;
public ServiceAddress(String addressName,
String streetAddress1,
String streetAddress2,
String city) {
this.addressName = addressName;
this.streetAddress1 = streetAddress1;
this.streetAddress2 = streetAddress2;
this.city = city;
}
public String getAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
public String getStreetAddress1() {
return streetAddress1;
}
public void setStreetAddress1(String streetAddress1) {
this.streetAddress1 = streetAddress1;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| UTF-8 | Java | 1,221 | java | ServiceAddress.java | Java | []
| null | []
| package my.util.app.models;
public class ServiceAddress {
private String addressName;
private String streetAddress1;
private String streetAddress2;
private String city;
public ServiceAddress(String addressName,
String streetAddress1,
String streetAddress2,
String city) {
this.addressName = addressName;
this.streetAddress1 = streetAddress1;
this.streetAddress2 = streetAddress2;
this.city = city;
}
public String getAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
public String getStreetAddress1() {
return streetAddress1;
}
public void setStreetAddress1(String streetAddress1) {
this.streetAddress1 = streetAddress1;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| 1,221 | 0.626536 | 0.610156 | 51 | 22.941177 | 19.00094 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392157 | false | false | 9 |
a83f0e7526bb7b7a78204a2288b5230b14025881 | 29,815,663,000,208 | a6ec432b5503c9e77988aa60d7b890069bf27e8e | /oneDesktop/src/main/java/one/app/desktop/internal/CreateRealmForm.java | bd9219e77877f3af7faff928acb2858694651310 | []
| no_license | mxro/oneDesktop | https://github.com/mxro/oneDesktop | 8548dfb48b734f2d207f71c09bdbc1000e093440 | 94a0ba022bf5110fa0004f9c6bde60b676786fe2 | refs/heads/master | 2021-01-20T12:38:03.251000 | 2020-10-13T06:26:20 | 2020-10-13T06:26:20 | 5,060,332 | 0 | 0 | null | false | 2020-10-13T06:26:21 | 2012-07-15T21:54:43 | 2014-06-09T23:45:24 | 2020-10-13T06:26:21 | 41 | 2 | 0 | 0 | Java | false | false | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package one.app.desktop.internal;
import one.client.jre.OneJre;
import one.common.One;
import one.core.dsl.CoreDsl;
import one.core.dsl.callbacks.WhenRealmCreated;
import one.core.dsl.callbacks.WhenShutdown;
import one.core.dsl.callbacks.results.WithRealmCreatedResult;
/**
*
* @author mroh004
*/
public class CreateRealmForm extends javax.swing.JPanel {
/**
* Creates new form CreateRealmForm
*/
public CreateRealmForm() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
tilteField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
apiKeyField = new javax.swing.JTextField();
createRealmButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
outputLog = new javax.swing.JTextArea();
setLayout(new java.awt.BorderLayout());
jLabel1.setText("Title");
jLabel2.setText("API-Key");
createRealmButton.setText("Create");
createRealmButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createRealmButtonActionPerformed(evt);
}
});
outputLog.setColumns(20);
outputLog.setFont(new java.awt.Font("Courier New", 0, 13)); // NOI18N
outputLog.setRows(5);
jScrollPane1.setViewportView(outputLog);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(apiKeyField)
.addComponent(tilteField)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(createRealmButton)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tilteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(apiKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(createRealmButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
.addContainerGap())
);
add(jPanel1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void createRealmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createRealmButtonActionPerformed
String apiKey = apiKeyField.getText();
String title = tilteField.getText();
CoreDsl dsl = OneJre.init(apiKey);
createRealmButton.setEnabled(false);
dsl.createRealm(title).and(new WhenRealmCreated() {
@Override
public void thenDo(WithRealmCreatedResult wrcr) {
outputLog.setText( "Realm created successfully.\n"
+ " root : " + wrcr.root().getId() + "\n"
+ " secret : " + wrcr.secret() + "\n"
+ " secret (partner): " + wrcr.partnerSecret() + "\n"
+ " direct link : \n"
+ " https://token:" + wrcr.secret() + "@" + wrcr.root().getId().replaceFirst("https://", "") +outputLog.getText());
One.shutdown(wrcr.client()).and(new WhenShutdown() {
@Override
public void thenDo() {
createRealmButton.setEnabled(true);
}
});
}
});
}//GEN-LAST:event_createRealmButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField apiKeyField;
private javax.swing.JButton createRealmButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea outputLog;
private javax.swing.JTextField tilteField;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 6,524 | java | CreateRealmForm.java | Java | [
{
"context": "results.WithRealmCreatedResult;\n\n/**\n *\n * @author mroh004\n */\npublic class CreateRealmForm extends javax.swi",
"end": 397,
"score": 0.9360507130622864,
"start": 390,
"tag": "USERNAME",
"value": "mroh004"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package one.app.desktop.internal;
import one.client.jre.OneJre;
import one.common.One;
import one.core.dsl.CoreDsl;
import one.core.dsl.callbacks.WhenRealmCreated;
import one.core.dsl.callbacks.WhenShutdown;
import one.core.dsl.callbacks.results.WithRealmCreatedResult;
/**
*
* @author mroh004
*/
public class CreateRealmForm extends javax.swing.JPanel {
/**
* Creates new form CreateRealmForm
*/
public CreateRealmForm() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
tilteField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
apiKeyField = new javax.swing.JTextField();
createRealmButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
outputLog = new javax.swing.JTextArea();
setLayout(new java.awt.BorderLayout());
jLabel1.setText("Title");
jLabel2.setText("API-Key");
createRealmButton.setText("Create");
createRealmButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createRealmButtonActionPerformed(evt);
}
});
outputLog.setColumns(20);
outputLog.setFont(new java.awt.Font("Courier New", 0, 13)); // NOI18N
outputLog.setRows(5);
jScrollPane1.setViewportView(outputLog);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(apiKeyField)
.addComponent(tilteField)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(createRealmButton)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tilteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(apiKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(createRealmButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
.addContainerGap())
);
add(jPanel1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void createRealmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createRealmButtonActionPerformed
String apiKey = apiKeyField.getText();
String title = tilteField.getText();
CoreDsl dsl = OneJre.init(apiKey);
createRealmButton.setEnabled(false);
dsl.createRealm(title).and(new WhenRealmCreated() {
@Override
public void thenDo(WithRealmCreatedResult wrcr) {
outputLog.setText( "Realm created successfully.\n"
+ " root : " + wrcr.root().getId() + "\n"
+ " secret : " + wrcr.secret() + "\n"
+ " secret (partner): " + wrcr.partnerSecret() + "\n"
+ " direct link : \n"
+ " https://token:" + wrcr.secret() + "@" + wrcr.root().getId().replaceFirst("https://", "") +outputLog.getText());
One.shutdown(wrcr.client()).and(new WhenShutdown() {
@Override
public void thenDo() {
createRealmButton.setEnabled(true);
}
});
}
});
}//GEN-LAST:event_createRealmButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField apiKeyField;
private javax.swing.JButton createRealmButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea outputLog;
private javax.swing.JTextField tilteField;
// End of variables declaration//GEN-END:variables
}
| 6,524 | 0.630288 | 0.621091 | 146 | 43.684933 | 34.626728 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479452 | false | false | 9 |
3e8aee567591af45ab1340d07306585547fb7754 | 4,243,427,717,775 | 7132299dfc3fb5fc3a59919de0b98b8cc0bb5b4a | /rtm/src/main/java/com/nicholas/service/QueryService.java | d3a11235cb0c7df80425af73e2528174bec52050 | []
| no_license | haherer/jlw | https://github.com/haherer/jlw | a4188f290df6ce5ef1ee499acd686d06c622098e | 0e9cde5aff7d88c4501caa470106ea31958bd120 | refs/heads/main | 2023-08-18T11:30:48.445000 | 2021-10-18T09:14:40 | 2021-10-18T09:14:40 | 410,835,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nicholas.service;
import com.nicholas.domain.Level;
import com.nicholas.vo.DataVo;
import com.nicholas.vo.UserQueryVo;
import java.util.List;
public interface QueryService {
Object queryUserByToken(String token);
Level queryLevelByLevelId(Integer levelId);
List<DataVo> queryAllData(Integer pageNum , Integer pageSize);
}
| UTF-8 | Java | 370 | java | QueryService.java | Java | []
| null | []
| package com.nicholas.service;
import com.nicholas.domain.Level;
import com.nicholas.vo.DataVo;
import com.nicholas.vo.UserQueryVo;
import java.util.List;
public interface QueryService {
Object queryUserByToken(String token);
Level queryLevelByLevelId(Integer levelId);
List<DataVo> queryAllData(Integer pageNum , Integer pageSize);
}
| 370 | 0.743243 | 0.743243 | 17 | 19.764706 | 20.564188 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 9 |
b1bea48dc41d8264a63721b55b8ee1e1be878480 | 20,907,900,823,719 | 6c491c0531ce693d8921c139f16ba918e7e48320 | /src/test/java/JavaFeatures/ClassLevelLocking.java | 98f917fead57c5c960ed2aa8f1f96ae28ee7f791 | []
| no_license | snehalavhare/Incubation | https://github.com/snehalavhare/Incubation | 569be387fecca93fd174d9384089f2b55580818e | 18280cf5ed30b5038ffefe7db28b0f558168baa4 | refs/heads/master | 2020-03-25T02:22:15.604000 | 2018-08-17T11:42:25 | 2018-08-17T11:42:25 | 143,286,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package JavaFeatures;
class TableStatic
{
static synchronized void printTable(int n)
{
System.out.println("Table of " + n);
for(int i=1; i<=5; i++)
{
System.out.println(n*i);
}
try{
Thread.sleep(1000);
}catch(Exception e)
{System.out.println(e);}
}
}
class MyThread3 extends Thread
{
public void run(){
TableStatic.printTable(5);
}
}
class MyThread4 extends Thread
{
public void run(){
TableStatic.printTable(10);
}
}
class ClassLevelLocking
{
public static void main(String[] args) {
MyThread3 t1=new MyThread3();
MyThread4 t2=new MyThread4();
t1.start();
t2.start();
}
} | UTF-8 | Java | 691 | java | ClassLevelLocking.java | Java | []
| null | []
| package JavaFeatures;
class TableStatic
{
static synchronized void printTable(int n)
{
System.out.println("Table of " + n);
for(int i=1; i<=5; i++)
{
System.out.println(n*i);
}
try{
Thread.sleep(1000);
}catch(Exception e)
{System.out.println(e);}
}
}
class MyThread3 extends Thread
{
public void run(){
TableStatic.printTable(5);
}
}
class MyThread4 extends Thread
{
public void run(){
TableStatic.printTable(10);
}
}
class ClassLevelLocking
{
public static void main(String[] args) {
MyThread3 t1=new MyThread3();
MyThread4 t2=new MyThread4();
t1.start();
t2.start();
}
} | 691 | 0.59479 | 0.567294 | 51 | 12.568627 | 13.668706 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.627451 | false | false | 9 |
75f12b8799d9fd1d80fcf79131cd3739e45a9d11 | 20,066,087,237,576 | c3ae870cb9dafb44a1cd344f662528942ac6f8da | /chapter5/src/main/java/za/ac/cput/chapter5/Behavioural/Observer/RaceSubject.java | eb4e0eff36f0531a6883e8703f3b908179a55b7a | []
| no_license | 212023535/Chapter5Questions | https://github.com/212023535/Chapter5Questions | 17a73f123c8b3baec021a709b9400e95069f5306 | 86d45bf65ff9831bc595cf148bc2ebf42cbfb144 | refs/heads/master | 2020-05-07T12:12:19.728000 | 2015-03-12T19:16:36 | 2015-03-12T19:16:36 | 32,097,525 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package za.ac.cput.chapter5.Behavioural.Observer;
/**
* Created by student on 2015/03/12.
*/
public interface RaceSubject
{
public void addObserver(RaceObserver raceObserver);
public void removeObserver(RaceObserver raceObserver);
public void doNotify();
}
| UTF-8 | Java | 272 | java | RaceSubject.java | Java | [
{
"context": ".chapter5.Behavioural.Observer;\n\n/**\n * Created by student on 2015/03/12.\n */\npublic interface RaceSubject\n{",
"end": 76,
"score": 0.9669119715690613,
"start": 69,
"tag": "USERNAME",
"value": "student"
}
]
| null | []
| package za.ac.cput.chapter5.Behavioural.Observer;
/**
* Created by student on 2015/03/12.
*/
public interface RaceSubject
{
public void addObserver(RaceObserver raceObserver);
public void removeObserver(RaceObserver raceObserver);
public void doNotify();
}
| 272 | 0.753676 | 0.720588 | 11 | 23.727272 | 22.210115 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
abe911f0fb17f89b48893847a19941f074329bbe | 27,212,912,823,484 | 3be63766a89de97c63d45ff7cbe45b9a147965b6 | /Symagic/org/symagic/common/utilty/inventory/InventoryUtility.java | 5edae456c75d5569fdbc44f15b8d8b4f6eca0d8b | []
| no_license | hao3039032/Symagic | https://github.com/hao3039032/Symagic | 84b4c2f81c6d2f1b8e31c0c3a82d92850816c533 | 0094d346623bfdf50cb868695cbd83c95a613b01 | refs/heads/master | 2016-09-09T13:04:38.180000 | 2012-09-02T03:10:13 | 2012-09-02T03:10:13 | 4,873,727 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.symagic.common.utilty.inventory;
public class InventoryUtility {
public static boolean checkInventory( int inventory ){
return inventory != 0;
}
}
| UTF-8 | Java | 168 | java | InventoryUtility.java | Java | []
| null | []
| package org.symagic.common.utilty.inventory;
public class InventoryUtility {
public static boolean checkInventory( int inventory ){
return inventory != 0;
}
}
| 168 | 0.75 | 0.744048 | 9 | 17.666666 | 20.264912 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 9 |
6416d09b114d17129ce9e46b88d5cdf5c3d34ead | 8,315,056,686,926 | d71e879b3517cf4fccde29f7bf82cff69856cfcd | /ExtractedJars/Health_com.huawei.health/javafiles/com/google/android/gms/internal/zzaar$zzb$2.java | 026d08a7d24bb70f24610c69ede854c28657103b | [
"MIT"
]
| permissive | Andreas237/AndroidPolicyAutomation | https://github.com/Andreas237/AndroidPolicyAutomation | b8e949e072d08cf6c6166c3f15c9c63379b8f6ce | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | refs/heads/master | 2020-04-10T02:14:08.789000 | 2019-05-16T19:29:11 | 2019-05-16T19:29:11 | 160,739,088 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal;
import com.google.android.gms.common.ConnectionResult;
// Referenced classes of package com.google.android.gms.internal:
// zzaar, zzaau
class zzaar$zzb$2 extends zzaav.zza
{
public void zzwe()
{
zzaBF.zzg(new ConnectionResult(16, ((android.app.PendingIntent) (null))));
// 0 0:aload_0
// 1 1:getfield #18 <Field com.google.android.gms.common.internal.zzf$zzf zzaBF>
// 2 4:new #24 <Class ConnectionResult>
// 3 7:dup
// 4 8:bipush 16
// 5 10:aconst_null
// 6 11:invokespecial #27 <Method void ConnectionResult(int, android.app.PendingIntent)>
// 7 14:invokeinterface #33 <Method void com.google.android.gms.common.internal.zzf$zzf.zzg(ConnectionResult)>
// 8 19:return
}
final com.google.android.gms.common.internal.zzf.zzf zzaBF;
zzaar$zzb$2(zzaar.zzb zzb1, zzaau zzaau, com.google.android.gms.common.internal.zzf.zzf zzf)
{
zzaBF = zzf;
// 0 0:aload_0
// 1 1:aload_3
// 2 2:putfield #18 <Field com.google.android.gms.common.internal.zzf$zzf zzaBF>
super(zzaau);
// 3 5:aload_0
// 4 6:aload_2
// 5 7:invokespecial #21 <Method void zzaav$zza(zzaau)>
// 6 10:return
}
}
| UTF-8 | Java | 1,532 | java | zzaar$zzb$2.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9995672702789307,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal;
import com.google.android.gms.common.ConnectionResult;
// Referenced classes of package com.google.android.gms.internal:
// zzaar, zzaau
class zzaar$zzb$2 extends zzaav.zza
{
public void zzwe()
{
zzaBF.zzg(new ConnectionResult(16, ((android.app.PendingIntent) (null))));
// 0 0:aload_0
// 1 1:getfield #18 <Field com.google.android.gms.common.internal.zzf$zzf zzaBF>
// 2 4:new #24 <Class ConnectionResult>
// 3 7:dup
// 4 8:bipush 16
// 5 10:aconst_null
// 6 11:invokespecial #27 <Method void ConnectionResult(int, android.app.PendingIntent)>
// 7 14:invokeinterface #33 <Method void com.google.android.gms.common.internal.zzf$zzf.zzg(ConnectionResult)>
// 8 19:return
}
final com.google.android.gms.common.internal.zzf.zzf zzaBF;
zzaar$zzb$2(zzaar.zzb zzb1, zzaau zzaau, com.google.android.gms.common.internal.zzf.zzf zzf)
{
zzaBF = zzf;
// 0 0:aload_0
// 1 1:aload_3
// 2 2:putfield #18 <Field com.google.android.gms.common.internal.zzf$zzf zzaBF>
super(zzaau);
// 3 5:aload_0
// 4 6:aload_2
// 5 7:invokespecial #21 <Method void zzaav$zza(zzaau)>
// 6 10:return
}
}
| 1,522 | 0.612924 | 0.567885 | 43 | 34.627907 | 32.080585 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
8ec47b4eeedf7b4fbc2f2756d43a78f3f0912411 | 8,512,625,216,002 | 1f15ce1be85d7fb0f817771e3342ed9dec97551b | /src/main/java/horbunov/pet/social_network/dao/AbstractDao.java | 025ebfe2dc6ac5c0c58cdfc72f9acd8c57d8344a | []
| no_license | romanhorbunov/SocialNetwork | https://github.com/romanhorbunov/SocialNetwork | 2ef0c1b3c7a13bcaa8afc507f4bcb3d883f7b27c | 701ae343c1ae1128df76116dd2e5eca848b4b204 | refs/heads/master | 2020-05-21T12:52:08.991000 | 2019-05-12T15:09:16 | 2019-05-12T15:09:16 | 186,053,146 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package horbunov.pet.social_network.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
@Transactional
public abstract class AbstractDao<T> implements GenericDao<T> {
SessionFactory sessionFactory;
public AbstractDao() {
}
@Autowired
public AbstractDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public T create(T t) {
Session session = sessionFactory.getCurrentSession();
session.save(t);
session.flush();
return t;
}
@Override
public T read(Class<T> tClass, Long id) {
Session session = sessionFactory.getCurrentSession();
T t = (T) session.get(tClass, id);
session.flush();
return t;
}
public T read(T t) {
return t;
}
@Override
public T update(T t) {
Session session = sessionFactory.getCurrentSession();
session.update(t);
session.flush();
return t;
}
@Override
public T delete(T t) {
Session session = sessionFactory.getCurrentSession();
session.delete(t);
return t;
}
@Override
public List<T> readAll(Class<T> tClass) {
Session session = sessionFactory.getCurrentSession();
List<T> result = session.createCriteria(tClass).list();
return result;
}
}
| UTF-8 | Java | 1,596 | java | AbstractDao.java | Java | []
| null | []
| package horbunov.pet.social_network.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
@Transactional
public abstract class AbstractDao<T> implements GenericDao<T> {
SessionFactory sessionFactory;
public AbstractDao() {
}
@Autowired
public AbstractDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public T create(T t) {
Session session = sessionFactory.getCurrentSession();
session.save(t);
session.flush();
return t;
}
@Override
public T read(Class<T> tClass, Long id) {
Session session = sessionFactory.getCurrentSession();
T t = (T) session.get(tClass, id);
session.flush();
return t;
}
public T read(T t) {
return t;
}
@Override
public T update(T t) {
Session session = sessionFactory.getCurrentSession();
session.update(t);
session.flush();
return t;
}
@Override
public T delete(T t) {
Session session = sessionFactory.getCurrentSession();
session.delete(t);
return t;
}
@Override
public List<T> readAll(Class<T> tClass) {
Session session = sessionFactory.getCurrentSession();
List<T> result = session.createCriteria(tClass).list();
return result;
}
}
| 1,596 | 0.651629 | 0.651629 | 69 | 22.130434 | 20.766411 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 9 |
6e1e0b87b13d0adfc7a361e7b3915978040bac22 | 1,803,886,304,201 | a93cf2e10426efa75652777b5ed49129f699578b | /app/src/main/java/com/vishwas/database114/DBHelper.java | 3040cfbae5cf6afbf6df0b2cd8503dddc3cd91c8 | []
| no_license | Vishwas7/AndroidDataBase11.4 | https://github.com/Vishwas7/AndroidDataBase11.4 | 7b76361c41ff178fc7fb5dda75a44c8d89e7e3b6 | 1d0cc80d89d32f8fa413c399fdea918b2f7df130 | refs/heads/master | 2021-07-01T04:10:18.344000 | 2017-09-16T18:32:33 | 2017-09-16T18:32:33 | 103,775,017 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vishwas.database114;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Vishwas on 9/4/2017.
* creating class DBHelper and extending with SQLiteOpenHelper..
* and implementing onCreate and onUpgrade methods and one construction..
*/
public class DBHelper extends SQLiteOpenHelper {
//data base name
private static final String THE_NAME_OF_DATABASE = " Employee.db";
//table name
private static final String THE_NAME_OF_TABLE = "employee_table";
//column
private static final String column_1 = "id";
private static final String column_2 = "firstname";
private static final String column_3 = "lastname";
public DBHelper(Context context) {
super(context, THE_NAME_OF_DATABASE, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + THE_NAME_OF_TABLE + " ("+column_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+column_2+ " TEXT, " + column_3 + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + THE_NAME_OF_TABLE);
onCreate(db);
}
boolean insertData(String firstName, String lastName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(column_2, firstName);
contentValues.put(column_3, lastName);
long result = db.insert(THE_NAME_OF_TABLE, null, contentValues);
return result != -1;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select * from " + THE_NAME_OF_TABLE, null);
}
public boolean updateData(String id, String firstname, String lastname) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(column_1, id);
contentValues.put(column_2,firstname );
contentValues.put(column_3, lastname);
db.update(THE_NAME_OF_TABLE, contentValues, column_1 + " = ?", new String[]{id});
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(THE_NAME_OF_TABLE, column_1 + " = ?", new String[]{id});
}
} | UTF-8 | Java | 2,513 | java | DBHelper.java | Java | [
{
"context": "tabase.sqlite.SQLiteOpenHelper;\n\n/**\n * Created by Vishwas on 9/4/2017.\n * creating class DBHelper and exten",
"end": 259,
"score": 0.9992534518241882,
"start": 252,
"tag": "NAME",
"value": "Vishwas"
},
{
"context": "2,firstname );\n contentValues.put(column_3, lastname);\n\n db.update(THE_NAME_OF_TABLE, contentVa",
"end": 2203,
"score": 0.9028654098510742,
"start": 2195,
"tag": "NAME",
"value": "lastname"
}
]
| null | []
| package com.vishwas.database114;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Vishwas on 9/4/2017.
* creating class DBHelper and extending with SQLiteOpenHelper..
* and implementing onCreate and onUpgrade methods and one construction..
*/
public class DBHelper extends SQLiteOpenHelper {
//data base name
private static final String THE_NAME_OF_DATABASE = " Employee.db";
//table name
private static final String THE_NAME_OF_TABLE = "employee_table";
//column
private static final String column_1 = "id";
private static final String column_2 = "firstname";
private static final String column_3 = "lastname";
public DBHelper(Context context) {
super(context, THE_NAME_OF_DATABASE, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + THE_NAME_OF_TABLE + " ("+column_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+column_2+ " TEXT, " + column_3 + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + THE_NAME_OF_TABLE);
onCreate(db);
}
boolean insertData(String firstName, String lastName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(column_2, firstName);
contentValues.put(column_3, lastName);
long result = db.insert(THE_NAME_OF_TABLE, null, contentValues);
return result != -1;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select * from " + THE_NAME_OF_TABLE, null);
}
public boolean updateData(String id, String firstname, String lastname) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(column_1, id);
contentValues.put(column_2,firstname );
contentValues.put(column_3, lastname);
db.update(THE_NAME_OF_TABLE, contentValues, column_1 + " = ?", new String[]{id});
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(THE_NAME_OF_TABLE, column_1 + " = ?", new String[]{id});
}
} | 2,513 | 0.676482 | 0.666932 | 72 | 33.916668 | 30.188183 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.763889 | false | false | 9 |
1566f198139d0ed01f328341a03b87916080839c | 7,172,595,413,244 | 8e5dd688eccda80003bd57699aa3d67224d30cfe | /Bomberman/src/Misc/Level.java | 0a0231cb5f95e923f1ce409a5ecfcab019f886c1 | []
| no_license | Pr3roxDLC/Bomberman | https://github.com/Pr3roxDLC/Bomberman | 3be04890f42c10d4f56771b3abc9f29cdde482c9 | 4334d29bb3bd1f1bcd0af480c90bf592b97a0e26 | refs/heads/master | 2023-04-28T20:49:51.381000 | 2020-06-14T22:35:49 | 2020-06-14T22:35:49 | 251,045,831 | 0 | 0 | null | false | 2023-04-14T18:01:50 | 2020-03-29T14:00:48 | 2020-06-14T22:35:59 | 2023-04-14T18:01:49 | 295 | 0 | 0 | 1 | Java | false | false | package Misc;
import java.util.*;
public class Level {
public Level(List<String> data) {
}
}
| UTF-8 | Java | 106 | java | Level.java | Java | []
| null | []
| package Misc;
import java.util.*;
public class Level {
public Level(List<String> data) {
}
}
| 106 | 0.622642 | 0.622642 | 14 | 6.571429 | 10.083326 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
ae6c10ac598c56ee04955734b180f233fc32f766 | 29,824,252,913,462 | 57989cddbdff767a4695b1a1cdc5082747ce388a | /app/src/main/java/box/chronos/userk/brain/adapters/CategoryAdapter.java | e0b336b13843db2ffdef84144a96d6fe9264cd76 | []
| no_license | GiovanniBalestrieri/ChronosBeta | https://github.com/GiovanniBalestrieri/ChronosBeta | 4f7392993a82a43d3c11dcebc33806351577cb17 | e591515a3b2b5ef26d813f176058351b50fdcc38 | refs/heads/master | 2021-01-20T12:29:01.175000 | 2017-07-18T00:24:50 | 2017-07-18T00:24:50 | 90,368,569 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package box.chronos.userk.brain.adapters;
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.squareup.picasso.Picasso;
import java.util.List;
import box.chronos.userk.brain.R;
import box.chronos.userk.brain.objects.Category;
import static box.chronos.userk.brain.serverRequest.AppUrls.IMAGE_URL;
import static box.chronos.userk.brain.utils.constants.AppConstant.PARENTESI_DX;
import static box.chronos.userk.brain.utils.constants.AppConstant.PARENTESI_SX;
/**
* Created by ChronosTeam on 27/02/2017.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder>{
private Context mContext;
private RecyclerView recyclerView;
private CategoryAdapter adapter;
private List<Category> list;
//private final RecyclerView recyclerView;
//private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public CategoryAdapter(Context mContext, List<Category> mList, RecyclerView recyclerView) {
this.mContext = mContext;
this.recyclerView = recyclerView;
this.list = mList;
}
public CategoryAdapter(Context mContext, List<Category> mList) {
this.mContext = mContext;
this.list = mList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView cat_id;
public TextView shop_name;
public ImageView thumbnail;
public ImageView shop_logo;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title_cat_card);
cat_id = (TextView) view.findViewById(R.id.card_id_text);
//shop_name = (TextView) view.findViewById(R.id.shop_top_card_info);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail_cat_card_b);
//shop_logo = (ImageView) view.findViewById(R.id.shop_logo_card_article);
}
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_card_v2, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Category cat = list.get(position);
holder.title.setText(cat.getCat_name() + PARENTESI_SX + cat.getCount() + PARENTESI_DX);
//holder.cat_id.setText(cat.getCat_id());
//holder.shop_name.setText(cat.getCat_photo_active());
String urlImage = IMAGE_URL + list.get(position).getCat_photo_active();
int width= mContext.getResources().getDisplayMetrics().widthPixels;
// loading Categories using Picasso library
Picasso.with(mContext).load(urlImage)
//.placeholder(R.drawable.scarpa_d)
.centerCrop().resize(width,width)
.into(holder.thumbnail);
/*
Glide.with(mContext)
.load(offerList.get(position).getDrawable_thumb())
//.placeholder(R.drawable.piwo_48)
//.transform(new CircleTransform(context))
.into(holder.thumbnail);
*/
/*
} else {
// make sure Glide doesn't load anything into this view until told otherwise
Glide.clear(holder.imageView);
// remove the placeholder (optional); read comments below
holder.imageView.setImageDrawable(null);
}
*/
// thumbnail image
//Log.d("ADAPTER", " URL: " + urlImage);
//holder.thumbnail.setImageResource(offerList.get(position).getDrawable_thumb());
}
/*
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Comment " , Toast.LENGTH_SHORT).show();
if (v instanceof ImageView){
mListener.onTomato((ImageView)v);
} else {
mListener.onPotato(v);
}
}
*/
@Override
public int getItemCount() {
return list.size();
}
}
| UTF-8 | Java | 4,406 | java | CategoryAdapter.java | Java | [
{
"context": "ants.AppConstant.PARENTESI_SX;\n\n\n/**\n * Created by ChronosTeam on 27/02/2017.\n */\npublic class CategoryAdapter e",
"end": 689,
"score": 0.9996111989021301,
"start": 678,
"tag": "USERNAME",
"value": "ChronosTeam"
}
]
| null | []
| package box.chronos.userk.brain.adapters;
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.squareup.picasso.Picasso;
import java.util.List;
import box.chronos.userk.brain.R;
import box.chronos.userk.brain.objects.Category;
import static box.chronos.userk.brain.serverRequest.AppUrls.IMAGE_URL;
import static box.chronos.userk.brain.utils.constants.AppConstant.PARENTESI_DX;
import static box.chronos.userk.brain.utils.constants.AppConstant.PARENTESI_SX;
/**
* Created by ChronosTeam on 27/02/2017.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder>{
private Context mContext;
private RecyclerView recyclerView;
private CategoryAdapter adapter;
private List<Category> list;
//private final RecyclerView recyclerView;
//private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public CategoryAdapter(Context mContext, List<Category> mList, RecyclerView recyclerView) {
this.mContext = mContext;
this.recyclerView = recyclerView;
this.list = mList;
}
public CategoryAdapter(Context mContext, List<Category> mList) {
this.mContext = mContext;
this.list = mList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView cat_id;
public TextView shop_name;
public ImageView thumbnail;
public ImageView shop_logo;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title_cat_card);
cat_id = (TextView) view.findViewById(R.id.card_id_text);
//shop_name = (TextView) view.findViewById(R.id.shop_top_card_info);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail_cat_card_b);
//shop_logo = (ImageView) view.findViewById(R.id.shop_logo_card_article);
}
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_card_v2, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Category cat = list.get(position);
holder.title.setText(cat.getCat_name() + PARENTESI_SX + cat.getCount() + PARENTESI_DX);
//holder.cat_id.setText(cat.getCat_id());
//holder.shop_name.setText(cat.getCat_photo_active());
String urlImage = IMAGE_URL + list.get(position).getCat_photo_active();
int width= mContext.getResources().getDisplayMetrics().widthPixels;
// loading Categories using Picasso library
Picasso.with(mContext).load(urlImage)
//.placeholder(R.drawable.scarpa_d)
.centerCrop().resize(width,width)
.into(holder.thumbnail);
/*
Glide.with(mContext)
.load(offerList.get(position).getDrawable_thumb())
//.placeholder(R.drawable.piwo_48)
//.transform(new CircleTransform(context))
.into(holder.thumbnail);
*/
/*
} else {
// make sure Glide doesn't load anything into this view until told otherwise
Glide.clear(holder.imageView);
// remove the placeholder (optional); read comments below
holder.imageView.setImageDrawable(null);
}
*/
// thumbnail image
//Log.d("ADAPTER", " URL: " + urlImage);
//holder.thumbnail.setImageResource(offerList.get(position).getDrawable_thumb());
}
/*
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Comment " , Toast.LENGTH_SHORT).show();
if (v instanceof ImageView){
mListener.onTomato((ImageView)v);
} else {
mListener.onPotato(v);
}
}
*/
@Override
public int getItemCount() {
return list.size();
}
}
| 4,406 | 0.650704 | 0.64798 | 134 | 31.880596 | 27.978949 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514925 | false | false | 9 |
61f0e050715e485e478843c613e796aa8e5f0ac1 | 5,308,579,593,501 | 45f91c670df18546278fb32c945d54c751b44361 | /src/main/java/com/qfedu/service/UserService.java | c268e915d10dcbc49cc3e85bee6599dc0898b022 | []
| no_license | Ifengyuan/mushroom | https://github.com/Ifengyuan/mushroom | d05eb0a5935f8c09aef8bc1af01913b9247d0672 | 6863fd6b11cb4f871f5553393415a2db8653b8b6 | refs/heads/master | 2020-04-24T15:22:14.102000 | 2019-03-02T13:35:29 | 2019-03-02T13:35:29 | 172,063,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qfedu.service;
import com.qfedu.pojo.User;
import com.qfedu.vo.JsonBean;
import com.qfedu.vo.ResultVo;
public interface UserService {
JsonBean login(String username, String password);
ResultVo insertUser(User user);
}
| UTF-8 | Java | 241 | java | UserService.java | Java | []
| null | []
| package com.qfedu.service;
import com.qfedu.pojo.User;
import com.qfedu.vo.JsonBean;
import com.qfedu.vo.ResultVo;
public interface UserService {
JsonBean login(String username, String password);
ResultVo insertUser(User user);
}
| 241 | 0.767635 | 0.767635 | 11 | 20.90909 | 17.090425 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 9 |
c34ede66123879673cabb0161fee68bd0f7b6946 | 249,108,108,119 | 94157bb99e7830a5161d49fb5fa241e79df1e8c4 | /acorn_android/Day3/HW1/app/src/main/java/com/example/user/hw1/MainActivity.java | 007bdccca872408316db3f18955208280bc3b45e | []
| no_license | isooo/pre_academy | https://github.com/isooo/pre_academy | 9d94b0b913554b81bda02b43d9c031e5b373c14e | 8471aad7184b9704a3d79d05ee7a3a763955c177 | refs/heads/master | 2020-04-03T09:15:45.886000 | 2018-10-29T08:42:45 | 2018-10-29T08:42:45 | 154,764,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.user.hw1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et1 = (EditText)findViewById(R.id.editText1);
final EditText et2 = (EditText)findViewById(R.id.editText2);
final int [] num = {2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5};
Button button1 = (Button)findViewById(R.id.button1);
final TextView textView1 = (TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int tot = 0;
char [] etChar = (et1.getText().toString() + et2.getText().toString()).toCharArray();
for(int i = 0 ; i < etChar.length - 1 ; i++) {
final String et1 = ((EditText)findViewById(R.id.editText1)).getText().toString();
int sum = num[i] * Character.getNumericValue(etChar[i]);
tot += sum;
System.out.println(etChar[i] + " || " + num[i] + " || " + sum + " || " + tot);
}
String msg = "";
if(Character.getNumericValue(etChar[etChar.length - 1]) == ((11 - (tot % 11)) % 10)) {
msg ="주민번호를 올바르게 입력함";
} else {
msg ="주민번호가 비정상입니다";
}
textView1.append(msg);
}
});//setOnClickListener()
}
}
| UTF-8 | Java | 1,846 | java | MainActivity.java | Java | []
| null | []
| package com.example.user.hw1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et1 = (EditText)findViewById(R.id.editText1);
final EditText et2 = (EditText)findViewById(R.id.editText2);
final int [] num = {2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5};
Button button1 = (Button)findViewById(R.id.button1);
final TextView textView1 = (TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int tot = 0;
char [] etChar = (et1.getText().toString() + et2.getText().toString()).toCharArray();
for(int i = 0 ; i < etChar.length - 1 ; i++) {
final String et1 = ((EditText)findViewById(R.id.editText1)).getText().toString();
int sum = num[i] * Character.getNumericValue(etChar[i]);
tot += sum;
System.out.println(etChar[i] + " || " + num[i] + " || " + sum + " || " + tot);
}
String msg = "";
if(Character.getNumericValue(etChar[etChar.length - 1]) == ((11 - (tot % 11)) % 10)) {
msg ="주민번호를 올바르게 입력함";
} else {
msg ="주민번호가 비정상입니다";
}
textView1.append(msg);
}
});//setOnClickListener()
}
}
| 1,846 | 0.556667 | 0.535556 | 50 | 35 | 29.87842 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.88 | false | false | 9 |
92203a93830317c06f2fc4e3c149cb2ab4255c5e | 30,906,584,730,730 | 60c10267890c162620201da931184981553b3ff7 | /platform/lang-impl/src/com/intellij/execution/impl/TypeTemplatesConfigurable.java | 0ec4e7b25e606d074ffb887be7b08ad163725896 | [
"Apache-2.0"
]
| permissive | soucod/jdksoucod-ideasc-2010 | https://github.com/soucod/jdksoucod-ideasc-2010 | 83ece81ecc27c7a9666a999c5166c0d544e59b63 | ec263374d9cee8080e7200130b65fa4889969f98 | refs/heads/master | 2020-12-02T20:25:59.866000 | 2020-01-02T17:42:14 | 2020-01-02T17:42:14 | 231,110,230 | 0 | 0 | Apache-2.0 | false | 2020-11-16T02:42:20 | 2019-12-31T15:26:43 | 2020-01-05T15:44:45 | 2020-11-16T02:42:10 | 164,990 | 0 | 0 | 1 | Java | false | false | /*
* 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.execution.impl;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditorConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.ui.TabbedPaneWrapper;
import javax.swing.*;
/**
* @author dyoma
*/
class TypeTemplatesConfigurable implements Configurable {
private final ConfigurationType myType;
private final Configurable[] myConfigurables;
private TabbedPaneWrapper myTabbedPane;
public TypeTemplatesConfigurable(final ConfigurationType type, final RunManagerImpl runManager, Project project) {
myType = type;
myConfigurables = new Configurable[getFactories().length];
myTabbedPane = new TabbedPaneWrapper(project);
final ConfigurationFactory[] factories = getFactories();
for (int i = 0; i < factories.length; i++) {
final ConfigurationFactory factory = factories[i];
final RunnerAndConfigurationSettings template = runManager.getConfigurationTemplate(factory);
final Configurable configurable = new TemplateConfigurable(template);
myConfigurables[i] = configurable;
myTabbedPane.addTab(factory.getName(), configurable.getIcon(), configurable.createComponent(), null);
}
}
private ConfigurationFactory[] getFactories() {
return myType.getConfigurationFactories();
}
public String getDisplayName() {
return ExecutionBundle.message("template.settings.configurable.display.name");
}
public Icon getIcon() {
return myType.getIcon();
}
public String getHelpTopic() {
final int index = myTabbedPane.getSelectedIndex();
return myConfigurables[index].getHelpTopic();
}
public JComponent createComponent() {
return myTabbedPane.getComponent();
}
public boolean isModified() {
for (final Configurable configurable : myConfigurables) {
if (configurable.isModified()) return true;
}
return false;
}
public void apply() throws ConfigurationException {
for (final Configurable configurable : myConfigurables) {
configurable.apply();
}
}
public void reset() {
for (final Configurable configurable : myConfigurables) {
configurable.reset();
}
}
public void disposeUIResources() {
for (int i = 0; i < myConfigurables.length; i++) {
final Configurable configurable = myConfigurables[i];
configurable.disposeUIResources();
myConfigurables[i] = null;
}
myTabbedPane = null;
}
public static Configurable createConfigurable(final ConfigurationType type, final Project project) {
final ConfigurationFactory[] factories = type.getConfigurationFactories();
final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
return factories.length == 1
? new TemplateConfigurable(runManager.getConfigurationTemplate(factories[0]))
: new TypeTemplatesConfigurable(type, runManager, project);
}
private static class TemplateConfigurable extends SettingsEditorConfigurable<RunnerAndConfigurationSettings> {
private final RunnerAndConfigurationSettings myTemplate;
public TemplateConfigurable(RunnerAndConfigurationSettings template) {
super(new ConfigurationSettingsEditorWrapper(template), template);
myTemplate = template;
}
public String getDisplayName() {
return myTemplate.getConfiguration().getName();
}
public Icon getIcon() {
return myTemplate.getConfiguration().getType().getIcon();
}
public String getHelpTopic() {
return null;
}
}
}
| UTF-8 | Java | 4,442 | java | TypeTemplatesConfigurable.java | Java | [
{
"context": "aneWrapper;\n\nimport javax.swing.*;\n\n/**\n * @author dyoma\n */\nclass TypeTemplatesConfigurable implements Co",
"end": 1184,
"score": 0.9993829727172852,
"start": 1179,
"tag": "USERNAME",
"value": "dyoma"
}
]
| null | []
| /*
* 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.execution.impl;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditorConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.ui.TabbedPaneWrapper;
import javax.swing.*;
/**
* @author dyoma
*/
class TypeTemplatesConfigurable implements Configurable {
private final ConfigurationType myType;
private final Configurable[] myConfigurables;
private TabbedPaneWrapper myTabbedPane;
public TypeTemplatesConfigurable(final ConfigurationType type, final RunManagerImpl runManager, Project project) {
myType = type;
myConfigurables = new Configurable[getFactories().length];
myTabbedPane = new TabbedPaneWrapper(project);
final ConfigurationFactory[] factories = getFactories();
for (int i = 0; i < factories.length; i++) {
final ConfigurationFactory factory = factories[i];
final RunnerAndConfigurationSettings template = runManager.getConfigurationTemplate(factory);
final Configurable configurable = new TemplateConfigurable(template);
myConfigurables[i] = configurable;
myTabbedPane.addTab(factory.getName(), configurable.getIcon(), configurable.createComponent(), null);
}
}
private ConfigurationFactory[] getFactories() {
return myType.getConfigurationFactories();
}
public String getDisplayName() {
return ExecutionBundle.message("template.settings.configurable.display.name");
}
public Icon getIcon() {
return myType.getIcon();
}
public String getHelpTopic() {
final int index = myTabbedPane.getSelectedIndex();
return myConfigurables[index].getHelpTopic();
}
public JComponent createComponent() {
return myTabbedPane.getComponent();
}
public boolean isModified() {
for (final Configurable configurable : myConfigurables) {
if (configurable.isModified()) return true;
}
return false;
}
public void apply() throws ConfigurationException {
for (final Configurable configurable : myConfigurables) {
configurable.apply();
}
}
public void reset() {
for (final Configurable configurable : myConfigurables) {
configurable.reset();
}
}
public void disposeUIResources() {
for (int i = 0; i < myConfigurables.length; i++) {
final Configurable configurable = myConfigurables[i];
configurable.disposeUIResources();
myConfigurables[i] = null;
}
myTabbedPane = null;
}
public static Configurable createConfigurable(final ConfigurationType type, final Project project) {
final ConfigurationFactory[] factories = type.getConfigurationFactories();
final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
return factories.length == 1
? new TemplateConfigurable(runManager.getConfigurationTemplate(factories[0]))
: new TypeTemplatesConfigurable(type, runManager, project);
}
private static class TemplateConfigurable extends SettingsEditorConfigurable<RunnerAndConfigurationSettings> {
private final RunnerAndConfigurationSettings myTemplate;
public TemplateConfigurable(RunnerAndConfigurationSettings template) {
super(new ConfigurationSettingsEditorWrapper(template), template);
myTemplate = template;
}
public String getDisplayName() {
return myTemplate.getConfiguration().getName();
}
public Icon getIcon() {
return myTemplate.getConfiguration().getType().getIcon();
}
public String getHelpTopic() {
return null;
}
}
}
| 4,442 | 0.746961 | 0.743359 | 129 | 33.434109 | 29.903421 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.496124 | false | false | 9 |
1fedf8afb8c3f2cc66d2df74dbab56844aa56e90 | 33,380,485,871,076 | aeafc64816969baca393a1f94673220305c1a412 | /PageTable.java | 6acdd489a7fe5c295acf424d687364a12b63a0df | []
| no_license | kyleplump/cs1550-project03 | https://github.com/kyleplump/cs1550-project03 | 9b3417de6c74f955ed4f6c304bec6a8e915cbda3 | f65598a72f2150c8d5399d964e9dfd484d7ae4a8 | refs/heads/master | 2018-01-10T02:44:08.808000 | 2016-03-29T00:09:37 | 2016-03-29T00:09:37 | 53,985,273 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class PageTable{
private Page[] pageTable;
// constructor to initialize a new page table
public PageTable(int numFrames){
pageTable = new Page[numFrames];
}
// returns the page at the given index
public Page getIndex(int index){
Page pageToReturn = pageTable[index];
return pageToReturn;
}
// determines is page table is full
public boolean isFull(){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == null){
return false;
}
}
return true;
}
public void addPage(Page newPage){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == null){
// add the page to the first available slot
pageTable[i] = newPage;
break;
}
}
}
// replaces a page
public void replacePage(Page pageToBeReplaced, Page newPage){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == pageToBeReplaced){
pageTable[i] = newPage;
break;
}
}
}
// set all reference bits to 0 after refresh during NRU
public void resetReferenceBits(){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
pageTable[i].setReferenceBit();
}
}
}
// returns a page based on its address
public Page getPageByAddress(String address){
Page pageToReturn = null;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i].getAddress() == address){
pageToReturn = pageTable[i];
break;
}
}
return pageToReturn;
}
// returns if an entry is in the table
public boolean isInTable(String address){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
if(pageTable[i].getAddress().equals(address)){
return true;
}
}
}
return false;
}
// find which page to evict based off its timestamp (used in the aging algo.)
public Page findTimestampToEvict(){
Page pageToEvict = null;
int numLeadingZeros = 0;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i].getTimestamp() != null){
numLeadingZeros = pageTable[i].getLeadingZeros();
// if we haven't picked a page to evict, or the one we did pick has less
// leading zeros than the current one, change the page to evict
if((pageToEvict == null) || (pageToEvict.getLeadingZeros() < numLeadingZeros)){
pageToEvict = pageTable[i];
}
}
}
return pageToEvict;
}
public void pushReferenceBits(){
int bit = 0;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
bit = pageTable[i].getReferenceBit();
pageTable[i].pushReferenceBit(bit);
}
}
}
} | UTF-8 | Java | 3,590 | java | PageTable.java | Java | []
| null | []
| public class PageTable{
private Page[] pageTable;
// constructor to initialize a new page table
public PageTable(int numFrames){
pageTable = new Page[numFrames];
}
// returns the page at the given index
public Page getIndex(int index){
Page pageToReturn = pageTable[index];
return pageToReturn;
}
// determines is page table is full
public boolean isFull(){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == null){
return false;
}
}
return true;
}
public void addPage(Page newPage){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == null){
// add the page to the first available slot
pageTable[i] = newPage;
break;
}
}
}
// replaces a page
public void replacePage(Page pageToBeReplaced, Page newPage){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] == pageToBeReplaced){
pageTable[i] = newPage;
break;
}
}
}
// set all reference bits to 0 after refresh during NRU
public void resetReferenceBits(){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
pageTable[i].setReferenceBit();
}
}
}
// returns a page based on its address
public Page getPageByAddress(String address){
Page pageToReturn = null;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i].getAddress() == address){
pageToReturn = pageTable[i];
break;
}
}
return pageToReturn;
}
// returns if an entry is in the table
public boolean isInTable(String address){
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
if(pageTable[i].getAddress().equals(address)){
return true;
}
}
}
return false;
}
// find which page to evict based off its timestamp (used in the aging algo.)
public Page findTimestampToEvict(){
Page pageToEvict = null;
int numLeadingZeros = 0;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i].getTimestamp() != null){
numLeadingZeros = pageTable[i].getLeadingZeros();
// if we haven't picked a page to evict, or the one we did pick has less
// leading zeros than the current one, change the page to evict
if((pageToEvict == null) || (pageToEvict.getLeadingZeros() < numLeadingZeros)){
pageToEvict = pageTable[i];
}
}
}
return pageToEvict;
}
public void pushReferenceBits(){
int bit = 0;
for(int i = 0; i < pageTable.length; i ++){
if(pageTable[i] != null){
bit = pageTable[i].getReferenceBit();
pageTable[i].pushReferenceBit(bit);
}
}
}
} | 3,590 | 0.455432 | 0.452368 | 140 | 24.65 | 20.594009 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328571 | false | false | 9 |
3d48a95c2e47c3a36c15372d7dcd41cdd8f6781e | 34,050,500,740,156 | cf48ce038d533d30b8765c31f342260f3b6cfd9b | /BridgeDemo/src/CalcAbstraction.java | 9ff41585e2af9535de9053634ea314feae51ed08 | []
| no_license | MichalSousedik/Design-patterns | https://github.com/MichalSousedik/Design-patterns | 03225328824dc71319e047f31ebcab23b6739387 | fd7755ff485300491a49812da56b01565b51bab7 | refs/heads/master | 2020-07-02T07:29:52.798000 | 2019-08-09T11:52:31 | 2019-08-09T11:52:31 | 201,457,645 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public abstract class CalcAbstraction {
private CalcImplementation calcImplementation;
public CalcAbstraction(CalcImplementation calcImplementation) {
this.calcImplementation = calcImplementation;
}
public int plus(int x, int y) {return calcImplementation.plus(x,y);}
}
| UTF-8 | Java | 323 | java | CalcAbstraction.java | Java | []
| null | []
|
public abstract class CalcAbstraction {
private CalcImplementation calcImplementation;
public CalcAbstraction(CalcImplementation calcImplementation) {
this.calcImplementation = calcImplementation;
}
public int plus(int x, int y) {return calcImplementation.plus(x,y);}
}
| 323 | 0.696594 | 0.696594 | 11 | 27.181818 | 27.715496 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
bf348731c197ac4629a1fab61980d22706a111d7 | 35,330,400,987,732 | 472bc829787f89c6a612a2e472ee199c3c20ef10 | /src/main/java/com/flipkart/ranger/healthservice/monitor/RollingWindowHealthQueue.java | c59389bd4b558c2c2a061facd192f97682730c76 | [
"Apache-2.0"
]
| permissive | flipkart-incubator/ranger | https://github.com/flipkart-incubator/ranger | 6821358bcbcce43b688956b0d0fde32b4d0f6c34 | 91d3068eef7984c8101727e41e8f5fe756319d48 | refs/heads/master | 2023-07-05T11:59:11.381000 | 2020-02-10T13:46:15 | 2020-02-10T13:46:15 | 30,753,901 | 30 | 21 | Apache-2.0 | false | 2022-11-16T10:28:29 | 2015-02-13T11:38:16 | 2022-10-26T14:34:57 | 2022-11-16T10:28:26 | 651 | 26 | 21 | 10 | Java | false | false | /**
* Copyright 2016 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.ranger.healthservice.monitor;
import com.flipkart.ranger.healthcheck.HealthcheckStatus;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReference;
/**
* This class may be used to keep track of health in a rolling window
* Maintains a queue of {@link HealthcheckStatus}s of size {@code rollingWindowSize}
*/
public class RollingWindowHealthQueue {
/* size of the rolling window */
private Integer rollingWindowSize;
/* maximum failures allowed in the window */
private Integer maxFailures;
/* current failures in the window */
private final AtomicReference<Integer> currentFailuresCount = new AtomicReference<>();
/* queue of health statuses */
private Queue<HealthcheckStatus> statusQueue;
/**
* @param rollingWindowSize size of the rolling window to be maintained
* @param maxFailures maximum failures allowed in the window
*/
public RollingWindowHealthQueue(Integer rollingWindowSize, Integer maxFailures) {
this.rollingWindowSize = rollingWindowSize;
this.maxFailures = maxFailures;
this.currentFailuresCount.set(0);
statusQueue = new LinkedList<>();
if (rollingWindowSize <= 0) {
throw new UnsupportedOperationException("rollingWindowSize cant be <= 0");
}
if (maxFailures > rollingWindowSize) {
throw new UnsupportedOperationException("maxFailures cant be greater than the rollingWindowSize");
}
}
/**
* dequeues the latest incoming status, enqueues the latest health status
* updates the failure counts accordingly
*
* @param currentHealthStatus current health status coming from outside
* @return <code>true</code> if the current failures in the queue are less than the maxFailure
* <code>false</code> if the current failures in the queue are more than or equal to the maxFailures
*/
public boolean checkInRollingWindow(HealthcheckStatus currentHealthStatus) {
HealthcheckStatus oldestStatus;
if (currentHealthStatus == HealthcheckStatus.healthy) {
if (statusQueue.size() == rollingWindowSize) {
oldestStatus = statusQueue.remove();
if (oldestStatus == HealthcheckStatus.unhealthy) {
currentFailuresCount.getAndSet(currentFailuresCount.get() - 1);
}
}
statusQueue.add(currentHealthStatus);
} else {
if (statusQueue.size() == rollingWindowSize) {
oldestStatus = statusQueue.remove();
if (oldestStatus == HealthcheckStatus.healthy) {
currentFailuresCount.getAndSet(currentFailuresCount.get() + 1);
}
} else {
currentFailuresCount.getAndSet(currentFailuresCount.get() + 1);
}
statusQueue.add(currentHealthStatus);
}
return currentFailuresCount.get() < maxFailures;
}
}
| UTF-8 | Java | 3,638 | java | RollingWindowHealthQueue.java | Java | []
| null | []
| /**
* Copyright 2016 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flipkart.ranger.healthservice.monitor;
import com.flipkart.ranger.healthcheck.HealthcheckStatus;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReference;
/**
* This class may be used to keep track of health in a rolling window
* Maintains a queue of {@link HealthcheckStatus}s of size {@code rollingWindowSize}
*/
public class RollingWindowHealthQueue {
/* size of the rolling window */
private Integer rollingWindowSize;
/* maximum failures allowed in the window */
private Integer maxFailures;
/* current failures in the window */
private final AtomicReference<Integer> currentFailuresCount = new AtomicReference<>();
/* queue of health statuses */
private Queue<HealthcheckStatus> statusQueue;
/**
* @param rollingWindowSize size of the rolling window to be maintained
* @param maxFailures maximum failures allowed in the window
*/
public RollingWindowHealthQueue(Integer rollingWindowSize, Integer maxFailures) {
this.rollingWindowSize = rollingWindowSize;
this.maxFailures = maxFailures;
this.currentFailuresCount.set(0);
statusQueue = new LinkedList<>();
if (rollingWindowSize <= 0) {
throw new UnsupportedOperationException("rollingWindowSize cant be <= 0");
}
if (maxFailures > rollingWindowSize) {
throw new UnsupportedOperationException("maxFailures cant be greater than the rollingWindowSize");
}
}
/**
* dequeues the latest incoming status, enqueues the latest health status
* updates the failure counts accordingly
*
* @param currentHealthStatus current health status coming from outside
* @return <code>true</code> if the current failures in the queue are less than the maxFailure
* <code>false</code> if the current failures in the queue are more than or equal to the maxFailures
*/
public boolean checkInRollingWindow(HealthcheckStatus currentHealthStatus) {
HealthcheckStatus oldestStatus;
if (currentHealthStatus == HealthcheckStatus.healthy) {
if (statusQueue.size() == rollingWindowSize) {
oldestStatus = statusQueue.remove();
if (oldestStatus == HealthcheckStatus.unhealthy) {
currentFailuresCount.getAndSet(currentFailuresCount.get() - 1);
}
}
statusQueue.add(currentHealthStatus);
} else {
if (statusQueue.size() == rollingWindowSize) {
oldestStatus = statusQueue.remove();
if (oldestStatus == HealthcheckStatus.healthy) {
currentFailuresCount.getAndSet(currentFailuresCount.get() + 1);
}
} else {
currentFailuresCount.getAndSet(currentFailuresCount.get() + 1);
}
statusQueue.add(currentHealthStatus);
}
return currentFailuresCount.get() < maxFailures;
}
}
| 3,638 | 0.679494 | 0.675646 | 91 | 38.978024 | 30.537306 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340659 | false | false | 9 |
6fc9c0bf5b418cce22f3738b702dc54dc15dfb3e | 31,198,642,466,400 | 3c1c0d1d5e69c9480c6a7fd8e16697dc6212ad89 | /src/main/java/com/example/demo/processordDemo/datastructure/FindMinNumInArray.java | be1879b2c719042d3fe17bf11f26e00dee59bd77 | []
| no_license | thirdSunShine/deepStu | https://github.com/thirdSunShine/deepStu | ea008d5ddafa15f6562c427a3033372f87c8ae1a | 18aa9307b62b481ef2ebe3c2888f58de59e4086a | refs/heads/master | 2023-05-24T07:52:04.356000 | 2021-06-14T14:16:15 | 2021-06-14T14:16:15 | 376,502,382 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.processordDemo.datastructure;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class FindMinNumInArray {
public static void main(String[] args) {
Integer[] arrays = new Integer[10];
for (int i = 0 ; i < 10; i++){
arrays[i] = new Random().nextInt(10);
}
int min = findMinNumInArray(arrays);
System.out.println(min);
}
private static int findMinNumInArray(Integer[] arrays) {
List<Integer> ints = Arrays.asList(arrays);
System.out.println("original array:" + ints);
int temp = arrays[0];
for (int i = 1 ;i<arrays.length;i++){
if (arrays[i] < temp){
temp = arrays[i];
}
}
return temp;
}
}
| UTF-8 | Java | 803 | java | FindMinNumInArray.java | Java | []
| null | []
| package com.example.demo.processordDemo.datastructure;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class FindMinNumInArray {
public static void main(String[] args) {
Integer[] arrays = new Integer[10];
for (int i = 0 ; i < 10; i++){
arrays[i] = new Random().nextInt(10);
}
int min = findMinNumInArray(arrays);
System.out.println(min);
}
private static int findMinNumInArray(Integer[] arrays) {
List<Integer> ints = Arrays.asList(arrays);
System.out.println("original array:" + ints);
int temp = arrays[0];
for (int i = 1 ;i<arrays.length;i++){
if (arrays[i] < temp){
temp = arrays[i];
}
}
return temp;
}
}
| 803 | 0.56787 | 0.556662 | 30 | 25.766666 | 19.27984 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566667 | false | false | 9 |
bed25374982aec9776f9f1218de0ecec35261293 | 31,198,642,467,764 | 9aa2561234e40efea8da197ed81374c66818211f | /src/main/java/com/deutscheboerse/risk/dave/model/MongoModel.java | f98132f029e33642fab65d0e57faea3286caa9f9 | [
"Apache-2.0"
]
| permissive | halajos/DAVe-MarginLoader | https://github.com/halajos/DAVe-MarginLoader | 437d26a9ea8523a5d321a32f8e7cb1b8c5120cc1 | 736f02c5db2fc83df7ed61c5a2f1373a279ffb5c | refs/heads/master | 2021-01-14T08:21:07.660000 | 2017-02-22T10:12:37 | 2017-02-22T10:12:37 | 81,944,548 | 0 | 0 | null | true | 2017-02-14T12:47:45 | 2017-02-14T12:47:45 | 2017-02-07T09:35:53 | 2017-02-14T12:04:23 | 164 | 0 | 0 | 0 | null | null | null | package com.deutscheboerse.risk.dave.model;
import io.vertx.core.json.JsonObject;
public interface MongoModel {
String getHistoryCollection();
String getLatestCollection();
JsonObject getLatestQueryParams();
JsonObject getHistoryUniqueIndex();
JsonObject getLatestUniqueIndex();
}
| UTF-8 | Java | 303 | java | MongoModel.java | Java | []
| null | []
| package com.deutscheboerse.risk.dave.model;
import io.vertx.core.json.JsonObject;
public interface MongoModel {
String getHistoryCollection();
String getLatestCollection();
JsonObject getLatestQueryParams();
JsonObject getHistoryUniqueIndex();
JsonObject getLatestUniqueIndex();
}
| 303 | 0.775578 | 0.775578 | 11 | 26.545454 | 16.411547 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 9 |
e7e5fd1466f70cfba653b200806f7f4d7395751f | 26,774,826,181,454 | f19044a4f216bc2094021b0b617b33dffba15424 | /app/src/main/java/com/demayx/wa/bean/other/RecentlistBean.java | 531237e7236e05ceda4ac50dae8ec373305d724d | []
| no_license | HelloChenJinJun/wale_app | https://github.com/HelloChenJinJun/wale_app | 995ea4c6c5d85b519aa5d7cc375cc5b6e0cb24e1 | e35810ba922d33acca8b20bad2dbd01fda365c0b | refs/heads/master | 2018-11-26T20:35:17.370000 | 2018-09-05T05:44:11 | 2018-09-05T05:44:11 | 147,446,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demayx.wa.bean.other;
import java.util.List;
/**
* Created by MyPC on 2018/4/21.
*/
public class RecentlistBean {
/**
* code : 200
* desc : 成功
* data : [{"nick_name":"qwe","product_name":"小米电脑","issue_id":12,"issue_no":12,"avatar":"https://avatar.boiko.cn/avatar/","total_count":50,"finished_at":"2018-04-20T16:30:53+08:00"}]
*/
private int code;
private String desc;
private List<DataBean> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* nick_name : qwe
* product_name : 小米电脑
* issue_id : 12
* issue_no : 12
* avatar : https://avatar.boiko.cn/avatar/
* total_count : 50
* finished_at : 2018-04-20T16:30:53+08:00
*/
private String nick_name;
private String product_name;
private int issue_id;
private int issue_no;
private String avatar;
private int total_count;
private String finished_at;
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getIssue_id() {
return issue_id;
}
public void setIssue_id(int issue_id) {
this.issue_id = issue_id;
}
public int getIssue_no() {
return issue_no;
}
public void setIssue_no(int issue_no) {
this.issue_no = issue_no;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
public String getFinished_at() {
return finished_at;
}
public void setFinished_at(String finished_at) {
this.finished_at = finished_at;
}
}
}
| UTF-8 | Java | 2,692 | java | RecentlistBean.java | Java | [
{
"context": ".other;\n\nimport java.util.List;\n\n/**\n * Created by MyPC on 2018/4/21.\n */\n\npublic class RecentlistBean {\n",
"end": 81,
"score": 0.9995828866958618,
"start": 77,
"tag": "USERNAME",
"value": "MyPC"
},
{
"context": "200\n * desc : 成功\n * data : [{\"nick_name\":\"qwe\",\"product_name\":\"小米电脑\",\"issue_id\":12,\"issue_no\":1",
"end": 206,
"score": 0.9088131785392761,
"start": 203,
"tag": "USERNAME",
"value": "qwe"
},
{
"context": "lass DataBean {\n /**\n * nick_name : qwe\n * product_name : 小米电脑\n * issue_i",
"end": 925,
"score": 0.9983556270599365,
"start": 922,
"tag": "USERNAME",
"value": "qwe"
}
]
| null | []
| package com.demayx.wa.bean.other;
import java.util.List;
/**
* Created by MyPC on 2018/4/21.
*/
public class RecentlistBean {
/**
* code : 200
* desc : 成功
* data : [{"nick_name":"qwe","product_name":"小米电脑","issue_id":12,"issue_no":12,"avatar":"https://avatar.boiko.cn/avatar/","total_count":50,"finished_at":"2018-04-20T16:30:53+08:00"}]
*/
private int code;
private String desc;
private List<DataBean> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* nick_name : qwe
* product_name : 小米电脑
* issue_id : 12
* issue_no : 12
* avatar : https://avatar.boiko.cn/avatar/
* total_count : 50
* finished_at : 2018-04-20T16:30:53+08:00
*/
private String nick_name;
private String product_name;
private int issue_id;
private int issue_no;
private String avatar;
private int total_count;
private String finished_at;
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getIssue_id() {
return issue_id;
}
public void setIssue_id(int issue_id) {
this.issue_id = issue_id;
}
public int getIssue_no() {
return issue_no;
}
public void setIssue_no(int issue_no) {
this.issue_no = issue_no;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
public String getFinished_at() {
return finished_at;
}
public void setFinished_at(String finished_at) {
this.finished_at = finished_at;
}
}
}
| 2,692 | 0.528817 | 0.507111 | 119 | 21.453781 | 22.612091 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.319328 | false | false | 9 |
74a1709c57abfdfe95daa484a6d72bab180fbb3e | 11,759,620,521,149 | 8df0fc0b6358cce79ea29402929c138cd33c1edd | /app/src/main/java/com/example/potigianim/model/SynchronizeOrderResponse.java | d0ca23adc7133f3024162e86dec4540359aba900 | []
| no_license | gonzalezgustavo/potigianim | https://github.com/gonzalezgustavo/potigianim | 433c6f2a48a90f308c73e76c4291e19aa2de4f4c | 76ca407367350b18236c898d53231208d3ac5cbf | refs/heads/master | 2023-08-05T14:01:52.975000 | 2019-10-26T21:51:15 | 2019-10-26T21:51:15 | 244,698,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.potigianim.model;
import java.util.List;
public class SynchronizeOrderResponse {
private String headerMessage;
private int headerReturnCode;
private List<SynchronizeOrderDetail> detailInfo;
public String getHeaderMessage() {
return headerMessage;
}
public void setHeaderMessage(String headerMessage) {
this.headerMessage = headerMessage;
}
public int getHeaderReturnCode() {
return headerReturnCode;
}
public void setHeaderReturnCode(int headerReturnCode) {
this.headerReturnCode = headerReturnCode;
}
public List<SynchronizeOrderDetail> getDetailInfo() {
return detailInfo;
}
public void setDetailInfo(List<SynchronizeOrderDetail> detailInfo) {
this.detailInfo = detailInfo;
}
}
| UTF-8 | Java | 816 | java | SynchronizeOrderResponse.java | Java | []
| null | []
| package com.example.potigianim.model;
import java.util.List;
public class SynchronizeOrderResponse {
private String headerMessage;
private int headerReturnCode;
private List<SynchronizeOrderDetail> detailInfo;
public String getHeaderMessage() {
return headerMessage;
}
public void setHeaderMessage(String headerMessage) {
this.headerMessage = headerMessage;
}
public int getHeaderReturnCode() {
return headerReturnCode;
}
public void setHeaderReturnCode(int headerReturnCode) {
this.headerReturnCode = headerReturnCode;
}
public List<SynchronizeOrderDetail> getDetailInfo() {
return detailInfo;
}
public void setDetailInfo(List<SynchronizeOrderDetail> detailInfo) {
this.detailInfo = detailInfo;
}
}
| 816 | 0.710784 | 0.710784 | 33 | 23.727272 | 21.968674 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
ddb23f87624855f831328f46aeab4f8e148c76d7 | 12,343,736,070,280 | a930674aa2971e75b4b0b8d3b2e5434218f51e7a | /app/src/main/java/com/zncm/jmxandroid/view/QQSportStepView.java | e6230653992da0a04edfc8c2344bbc4d66936245 | []
| no_license | Dminter/JmxAndroid | https://github.com/Dminter/JmxAndroid | e57e4fa9b011d2859caca0d32ad1d51c95dc0720 | ee7e72eed34a87da0bf5e8f0ac1b8a9d0306a499 | refs/heads/master | 2020-05-20T20:46:09.581000 | 2018-11-15T02:16:12 | 2018-11-15T02:16:12 | 84,521,586 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zncm.jmxandroid.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import com.zncm.jmxandroid.R;
/**
* Created by jiaomx on 2017/5/12.
*
* QQ运动动画
*/
public class QQSportStepView extends View {
private int outerColor;
private int innerColor;
private int borderWidth;
private int stepTextSize;
private int stepTextColor;
int mCurrentStep = 50;
int mStepMax =200;
Paint paint;
Paint innerPaint;
Paint textPaint;
public QQSportStepView(Context context) {
super(context);
}
public QQSportStepView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.QQStepView);
outerColor = typedArray.getColor(R.styleable.QQStepView_outerColor,outerColor);
innerColor = typedArray.getColor(R.styleable.QQStepView_innerColor,innerColor);
borderWidth = (int) typedArray.getDimension(R.styleable.QQStepView_borderWidth,borderWidth);
stepTextSize = (int) typedArray.getDimension(R.styleable.QQStepView_stepTextSize,stepTextSize);
stepTextColor = typedArray.getColor(R.styleable.QQStepView_stepTextColor,stepTextColor);
typedArray.recycle();
paint = new Paint();
// paint.setColor(outerColor);
int[] mGradientColors = {Color.GREEN, Color.YELLOW, Color.RED};
Shader shader = new SweepGradient(0,1000,mGradientColors,null);
paint.setShader(shader);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(borderWidth);
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
innerPaint = new Paint();
innerPaint.setColor(innerColor);
innerPaint.setStrokeWidth(borderWidth);
innerPaint.setStyle(Paint.Style.STROKE);
innerPaint.setStrokeCap(Paint.Cap.ROUND);
innerPaint.setAntiAlias(true);
textPaint = new Paint();
Shader shader2 = new SweepGradient(0,1000,mGradientColors,null);
textPaint.setShader(shader2);
textPaint.setColor(stepTextColor);
textPaint.setTextSize(stepTextSize);
textPaint.setStyle(Paint.Style.STROKE);
textPaint.setAntiAlias(true);
}
public QQSportStepView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = getWidth()/2;
int radius = getWidth()/2-borderWidth/2;
RectF rectF = new RectF(center-radius,center-radius,center+radius,center+radius);
canvas.drawArc(rectF,135,270,false,paint);
if (mStepMax==0){
return;
}
float sweepAngle = (float)mCurrentStep/mStepMax;
canvas.drawArc(rectF,135,sweepAngle*270,false,innerPaint);
String stepText = mCurrentStep+"";
Rect textRect = new Rect();
textPaint.getTextBounds(stepText,0,stepText.length(),textRect);
int dx = getWidth()/2-textRect.width()/2;
Paint.FontMetricsInt fontMetricsInt = textPaint.getFontMetricsInt();
int dy = (fontMetricsInt.bottom-fontMetricsInt.top)/2-fontMetricsInt.bottom;
int baseLine = getHeight()/2+dy;
canvas.drawText(stepText,dx,baseLine,textPaint);
}
public void setmCurrentStep(int mCurrentStep) {
this.mCurrentStep = mCurrentStep;
invalidate();
}
public void setmStepMax(int mStepMax) {
this.mStepMax = mStepMax;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width>height?height:width,width>height?height:width);
}
}
| UTF-8 | Java | 4,461 | java | QQSportStepView.java | Java | [
{
"context": "\n\nimport com.zncm.jmxandroid.R;\n\n/**\n * Created by jiaomx on 2017/5/12.\n *\n * QQ运动动画\n */\n\npublic class QQSp",
"end": 492,
"score": 0.9995259046554565,
"start": 486,
"tag": "USERNAME",
"value": "jiaomx"
}
]
| null | []
| package com.zncm.jmxandroid.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import com.zncm.jmxandroid.R;
/**
* Created by jiaomx on 2017/5/12.
*
* QQ运动动画
*/
public class QQSportStepView extends View {
private int outerColor;
private int innerColor;
private int borderWidth;
private int stepTextSize;
private int stepTextColor;
int mCurrentStep = 50;
int mStepMax =200;
Paint paint;
Paint innerPaint;
Paint textPaint;
public QQSportStepView(Context context) {
super(context);
}
public QQSportStepView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.QQStepView);
outerColor = typedArray.getColor(R.styleable.QQStepView_outerColor,outerColor);
innerColor = typedArray.getColor(R.styleable.QQStepView_innerColor,innerColor);
borderWidth = (int) typedArray.getDimension(R.styleable.QQStepView_borderWidth,borderWidth);
stepTextSize = (int) typedArray.getDimension(R.styleable.QQStepView_stepTextSize,stepTextSize);
stepTextColor = typedArray.getColor(R.styleable.QQStepView_stepTextColor,stepTextColor);
typedArray.recycle();
paint = new Paint();
// paint.setColor(outerColor);
int[] mGradientColors = {Color.GREEN, Color.YELLOW, Color.RED};
Shader shader = new SweepGradient(0,1000,mGradientColors,null);
paint.setShader(shader);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(borderWidth);
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
innerPaint = new Paint();
innerPaint.setColor(innerColor);
innerPaint.setStrokeWidth(borderWidth);
innerPaint.setStyle(Paint.Style.STROKE);
innerPaint.setStrokeCap(Paint.Cap.ROUND);
innerPaint.setAntiAlias(true);
textPaint = new Paint();
Shader shader2 = new SweepGradient(0,1000,mGradientColors,null);
textPaint.setShader(shader2);
textPaint.setColor(stepTextColor);
textPaint.setTextSize(stepTextSize);
textPaint.setStyle(Paint.Style.STROKE);
textPaint.setAntiAlias(true);
}
public QQSportStepView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = getWidth()/2;
int radius = getWidth()/2-borderWidth/2;
RectF rectF = new RectF(center-radius,center-radius,center+radius,center+radius);
canvas.drawArc(rectF,135,270,false,paint);
if (mStepMax==0){
return;
}
float sweepAngle = (float)mCurrentStep/mStepMax;
canvas.drawArc(rectF,135,sweepAngle*270,false,innerPaint);
String stepText = mCurrentStep+"";
Rect textRect = new Rect();
textPaint.getTextBounds(stepText,0,stepText.length(),textRect);
int dx = getWidth()/2-textRect.width()/2;
Paint.FontMetricsInt fontMetricsInt = textPaint.getFontMetricsInt();
int dy = (fontMetricsInt.bottom-fontMetricsInt.top)/2-fontMetricsInt.bottom;
int baseLine = getHeight()/2+dy;
canvas.drawText(stepText,dx,baseLine,textPaint);
}
public void setmCurrentStep(int mCurrentStep) {
this.mCurrentStep = mCurrentStep;
invalidate();
}
public void setmStepMax(int mStepMax) {
this.mStepMax = mStepMax;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width>height?height:width,width>height?height:width);
}
}
| 4,461 | 0.692791 | 0.682686 | 144 | 29.923611 | 27.190449 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.861111 | false | false | 9 |
ca4b82003aca11070926bd83027cb10562d4caa1 | 8,993,661,539,437 | 63da8c25c3d2b606c36cf36fd6f652292b0c1968 | /src/main/java/com/test/feedreader/controller/resource/FeedResource.java | 149b0ec64305d9a850fdc5f08c96755120882dec | []
| no_license | srinivas-d-12/feedreader | https://github.com/srinivas-d-12/feedreader | 01c99a73f478aa7c7ded888a24080af9369abf2e | 69e815546cecd6367399d61bd0911544806b1ad0 | refs/heads/master | 2021-08-16T14:42:51.829000 | 2017-11-20T01:57:41 | 2017-11-20T01:57:41 | 111,339,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.feedreader.controller.resource;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.test.feedreader.controller.FeedController;
import com.test.feedreader.model.Feed;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.core.Relation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static com.test.feedreader.controller.support.LinkBuilderWrapper.relativeRel;
import static com.test.feedreader.controller.support.LinkBuilderWrapper.relativeSelfRel;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/**
* Created by sdhruvakumar.
*/
@Relation(value = "feed", collectionRelation = "feeds")
public class FeedResource extends ResourceSupport {
public static final Assembler ASSEMBLER = new Assembler();
private static final String ARTICLES = "articles";
private final String uuid;
private final String name;
private final String description;
public FeedResource(Feed feed) {
this.uuid = feed.getId().toString();
this.name = feed.getName();
this.description = feed.getDescription();
}
@JsonProperty("id")
public String getUuid() {
return this.uuid;
}
@JsonProperty
public String getName() {
return name;
}
@JsonProperty
public String getDescription() {
return description;
}
public static class Assembler implements ResourceAssembler<Feed, FeedResource> {
private Assembler() {
}
public FeedResource toResource(Feed feed) {
FeedResource feedResource = new FeedResource(feed);
feedResource.add(relativeSelfRel(linkTo(methodOn(FeedController.class).getById(feed.getId()))));
feedResource
.add(relativeRel(linkTo(methodOn(FeedController.class).getById(feed.getId())).slash(ARTICLES), ARTICLES));
return feedResource;
}
}
public static class CollectionAssembler
implements ResourceAssembler<Collection<Feed>, Resources<FeedResource>> {
public CollectionAssembler() {
}
@Override
public Resources<FeedResource> toResource(Collection<Feed> feeds) {
List<FeedResource> resources =
feeds.stream().map(FeedResource.ASSEMBLER::toResource).collect(Collectors.toList());
return new Resources<>(resources);
}
}
}
| UTF-8 | Java | 2,658 | java | FeedResource.java | Java | [
{
"context": "ControllerLinkBuilder.methodOn;\n\n/**\n * Created by sdhruvakumar.\n */\n@Relation(value = \"feed\", collectionRelation",
"end": 848,
"score": 0.9995462894439697,
"start": 836,
"tag": "USERNAME",
"value": "sdhruvakumar"
}
]
| null | []
| package com.test.feedreader.controller.resource;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.test.feedreader.controller.FeedController;
import com.test.feedreader.model.Feed;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.core.Relation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static com.test.feedreader.controller.support.LinkBuilderWrapper.relativeRel;
import static com.test.feedreader.controller.support.LinkBuilderWrapper.relativeSelfRel;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/**
* Created by sdhruvakumar.
*/
@Relation(value = "feed", collectionRelation = "feeds")
public class FeedResource extends ResourceSupport {
public static final Assembler ASSEMBLER = new Assembler();
private static final String ARTICLES = "articles";
private final String uuid;
private final String name;
private final String description;
public FeedResource(Feed feed) {
this.uuid = feed.getId().toString();
this.name = feed.getName();
this.description = feed.getDescription();
}
@JsonProperty("id")
public String getUuid() {
return this.uuid;
}
@JsonProperty
public String getName() {
return name;
}
@JsonProperty
public String getDescription() {
return description;
}
public static class Assembler implements ResourceAssembler<Feed, FeedResource> {
private Assembler() {
}
public FeedResource toResource(Feed feed) {
FeedResource feedResource = new FeedResource(feed);
feedResource.add(relativeSelfRel(linkTo(methodOn(FeedController.class).getById(feed.getId()))));
feedResource
.add(relativeRel(linkTo(methodOn(FeedController.class).getById(feed.getId())).slash(ARTICLES), ARTICLES));
return feedResource;
}
}
public static class CollectionAssembler
implements ResourceAssembler<Collection<Feed>, Resources<FeedResource>> {
public CollectionAssembler() {
}
@Override
public Resources<FeedResource> toResource(Collection<Feed> feeds) {
List<FeedResource> resources =
feeds.stream().map(FeedResource.ASSEMBLER::toResource).collect(Collectors.toList());
return new Resources<>(resources);
}
}
}
| 2,658 | 0.708427 | 0.708427 | 86 | 29.906977 | 29.597544 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418605 | false | false | 9 |
144b3d8b2bbd492ae204ba00681611dc494be92a | 15,195,594,323,080 | 1144e7e27c91a8e1ba546b1b10c32344cdc51a75 | /pollux-common/src/main/java/com/polluxframework/common/util/ReflectionUtils.java | f89d420583b800e1f26c17a8d38654487b2bc4aa | [
"Apache-2.0"
]
| permissive | pollux0508/pollux | https://github.com/pollux0508/pollux | d2354f2c9a3ac3c313f3b3c1879d8fd7869be82e | 26834f2c4034e3de5766fd8e83c83c342c6f5f08 | refs/heads/master | 2021-08-16T06:22:12.722000 | 2018-12-12T00:40:46 | 2018-12-12T00:40:46 | 145,957,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.polluxframework.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Map;
/**
* @author zhumin0508
* created in 2018/9/7 9:04
* modified By:
*/
public class ReflectionUtils {
private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
private ReflectionUtils() {
}
/**
* 根据字段名获取指定对象的的field字段对应的get方法值,如果获取不成功则返回默认值
*
* @param target 目标对象
* @param field 字段名称
* @param defaultValue 默认值
* @return 返回目标对象的值
*/
public static Object getFieldValueByName(Object target, String field, Object defaultValue) {
try {
return getFieldValueByName(target, field);
} catch (ReflectiveOperationException e) {
logger.warn("找不到匹配的方法或调用目标异常", e);
}
return defaultValue;
}
/**
* 根据字段名获取指定对象的的field字段对应的get方法值
*
* @param target 目标对象
* @param field 字段名称
* @return 返回目标对象的值
* @throws ReflectiveOperationException 获取值时可能由于某些原型会抛出无法找到匹配的方法等异常
*/
public static Object getFieldValueByName(Object target, String field) throws ReflectiveOperationException {
String methodName = "get" + StringUtils.toUpperCaseFirstLetter(field);
Method method = target.getClass().getMethod(methodName);
return method.invoke(target);
}
/**
* 根据字段名获取指定Map的的field字段对应的值
*
* @param target 目标Map对象
* @param field 字段名称
* @param defaultValue 默认值
* @return 返回目标对象的值
*/
public static Object getFieldValueByName(Map<String, Object> target, String field, Object defaultValue) {
Object value = target.get(field);
if(value==null){
logger.warn("Map对象中找不到对应的值");
return defaultValue;
}
return value;
}
}
| UTF-8 | Java | 2,030 | java | ReflectionUtils.java | Java | [
{
"context": "lect.Method;\nimport java.util.Map;\n\n/**\n * @author zhumin0508\n * created in 2018/9/7 9:04\n * modified By:\n */\n",
"end": 181,
"score": 0.9995319247245789,
"start": 171,
"tag": "USERNAME",
"value": "zhumin0508"
}
]
| null | []
| package com.polluxframework.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Map;
/**
* @author zhumin0508
* created in 2018/9/7 9:04
* modified By:
*/
public class ReflectionUtils {
private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
private ReflectionUtils() {
}
/**
* 根据字段名获取指定对象的的field字段对应的get方法值,如果获取不成功则返回默认值
*
* @param target 目标对象
* @param field 字段名称
* @param defaultValue 默认值
* @return 返回目标对象的值
*/
public static Object getFieldValueByName(Object target, String field, Object defaultValue) {
try {
return getFieldValueByName(target, field);
} catch (ReflectiveOperationException e) {
logger.warn("找不到匹配的方法或调用目标异常", e);
}
return defaultValue;
}
/**
* 根据字段名获取指定对象的的field字段对应的get方法值
*
* @param target 目标对象
* @param field 字段名称
* @return 返回目标对象的值
* @throws ReflectiveOperationException 获取值时可能由于某些原型会抛出无法找到匹配的方法等异常
*/
public static Object getFieldValueByName(Object target, String field) throws ReflectiveOperationException {
String methodName = "get" + StringUtils.toUpperCaseFirstLetter(field);
Method method = target.getClass().getMethod(methodName);
return method.invoke(target);
}
/**
* 根据字段名获取指定Map的的field字段对应的值
*
* @param target 目标Map对象
* @param field 字段名称
* @param defaultValue 默认值
* @return 返回目标对象的值
*/
public static Object getFieldValueByName(Map<String, Object> target, String field, Object defaultValue) {
Object value = target.get(field);
if(value==null){
logger.warn("Map对象中找不到对应的值");
return defaultValue;
}
return value;
}
}
| 2,030 | 0.723086 | 0.714115 | 67 | 23.955223 | 25.22699 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.358209 | false | false | 9 |
c84975c5c69eaabd868fa560d2dd04cbe21b44a9 | 33,621,004,038,065 | 34f8d4ba30242a7045c689768c3472b7af80909c | /jdk-12/src/jdk.internal.vm.compiler/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java | 2253297cf1b18c45a41cacc97120825f5238a837 | [
"Apache-2.0"
]
| permissive | lovelycheng/JDK | https://github.com/lovelycheng/JDK | 5b4cc07546f0dbfad15c46d427cae06ef282ef79 | 19a6c71e52f3ecd74e4a66be5d0d552ce7175531 | refs/heads/master | 2023-04-08T11:36:22.073000 | 2022-09-04T01:53:09 | 2022-09-04T01:53:09 | 227,544,567 | 0 | 0 | null | true | 2019-12-12T07:18:30 | 2019-12-12T07:18:29 | 2019-12-12T06:24:59 | 2019-11-24T12:36:46 | 177,316 | 0 | 0 | 0 | null | false | false | /*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.hotspot.meta;
import static org.graalvm.compiler.core.common.GraalOptions.AlwaysInlineVTableStubs;
import static org.graalvm.compiler.core.common.GraalOptions.InlineVTableStubs;
import static org.graalvm.compiler.core.common.GraalOptions.OmitHotExceptionStacktrace;
import static org.graalvm.compiler.hotspot.meta.HotSpotForeignCallsProviderImpl.OSR_MIGRATION_END;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_KLASS_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_MIRROR_HANDLE_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_MIRROR_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.COMPRESSED_HUB_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.DISPLACED_MARK_WORD_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.HUB_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.HUB_WRITE_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.KLASS_LAYOUT_HELPER_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION;
import static jdk.internal.vm.compiler.word.LocationIdentity.any;
import java.lang.ref.Reference;
import java.util.EnumMap;
import org.graalvm.compiler.api.directives.GraalDirectives;
import org.graalvm.compiler.core.common.CompressEncoding;
import org.graalvm.compiler.core.common.GraalOptions;
import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor;
import org.graalvm.compiler.core.common.spi.ForeignCallsProvider;
import org.graalvm.compiler.core.common.type.ObjectStamp;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.core.common.type.StampFactory;
import org.graalvm.compiler.core.common.type.StampPair;
import org.graalvm.compiler.debug.DebugCloseable;
import org.graalvm.compiler.debug.DebugHandlersFactory;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.graph.NodeInputList;
import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
import org.graalvm.compiler.hotspot.nodes.BeginLockScopeNode;
import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePostWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePreWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1PostWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1PreWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1ReferentFieldReadBarrier;
import org.graalvm.compiler.hotspot.nodes.HotSpotCompressionNode;
import org.graalvm.compiler.hotspot.nodes.HotSpotDirectCallTargetNode;
import org.graalvm.compiler.hotspot.nodes.HotSpotIndirectCallTargetNode;
import org.graalvm.compiler.hotspot.nodes.SerialArrayRangeWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.SerialWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.aot.InitializeKlassNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveConstantNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveDynamicConstantNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveMethodAndLoadCountersNode;
import org.graalvm.compiler.hotspot.nodes.profiling.ProfileNode;
import org.graalvm.compiler.hotspot.nodes.type.HotSpotNarrowOopStamp;
import org.graalvm.compiler.hotspot.nodes.type.KlassPointerStamp;
import org.graalvm.compiler.hotspot.nodes.type.MethodPointerStamp;
import org.graalvm.compiler.hotspot.replacements.AssertionSnippets;
import org.graalvm.compiler.hotspot.replacements.ClassGetHubNode;
import org.graalvm.compiler.hotspot.replacements.HashCodeSnippets;
import org.graalvm.compiler.hotspot.replacements.HubGetClassNode;
import org.graalvm.compiler.hotspot.replacements.IdentityHashCodeNode;
import org.graalvm.compiler.hotspot.replacements.InstanceOfSnippets;
import org.graalvm.compiler.hotspot.replacements.KlassLayoutHelperNode;
import org.graalvm.compiler.hotspot.replacements.LoadExceptionObjectSnippets;
import org.graalvm.compiler.hotspot.replacements.MonitorSnippets;
import org.graalvm.compiler.hotspot.replacements.NewObjectSnippets;
import org.graalvm.compiler.hotspot.replacements.ObjectCloneSnippets;
import org.graalvm.compiler.hotspot.replacements.StringToBytesSnippets;
import org.graalvm.compiler.hotspot.replacements.UnsafeLoadSnippets;
import org.graalvm.compiler.hotspot.replacements.WriteBarrierSnippets;
import org.graalvm.compiler.hotspot.replacements.aot.ResolveConstantSnippets;
import org.graalvm.compiler.hotspot.replacements.arraycopy.HotSpotArraycopySnippets;
import org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets;
import org.graalvm.compiler.hotspot.stubs.ForeignCallSnippets;
import org.graalvm.compiler.hotspot.word.KlassPointer;
import org.graalvm.compiler.nodes.AbstractBeginNode;
import org.graalvm.compiler.nodes.AbstractDeoptimizeNode;
import org.graalvm.compiler.nodes.CompressionNode.CompressionOp;
import org.graalvm.compiler.nodes.ComputeObjectAddressNode;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.FixedNode;
import org.graalvm.compiler.nodes.GetObjectAddressNode;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.LogicNode;
import org.graalvm.compiler.nodes.LoweredCallTargetNode;
import org.graalvm.compiler.nodes.NodeView;
import org.graalvm.compiler.nodes.ParameterNode;
import org.graalvm.compiler.nodes.SafepointNode;
import org.graalvm.compiler.nodes.StartNode;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.UnwindNode;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.calc.AddNode;
import org.graalvm.compiler.nodes.calc.FloatingNode;
import org.graalvm.compiler.nodes.calc.IntegerDivRemNode;
import org.graalvm.compiler.nodes.calc.IsNullNode;
import org.graalvm.compiler.nodes.calc.RemNode;
import org.graalvm.compiler.nodes.debug.StringToBytesNode;
import org.graalvm.compiler.nodes.debug.VerifyHeapNode;
import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode;
import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode.BytecodeExceptionKind;
import org.graalvm.compiler.nodes.extended.ForeignCallNode;
import org.graalvm.compiler.nodes.extended.GetClassNode;
import org.graalvm.compiler.nodes.extended.GuardedUnsafeLoadNode;
import org.graalvm.compiler.nodes.extended.LoadHubNode;
import org.graalvm.compiler.nodes.extended.LoadMethodNode;
import org.graalvm.compiler.nodes.extended.OSRLocalNode;
import org.graalvm.compiler.nodes.extended.OSRLockNode;
import org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode;
import org.graalvm.compiler.nodes.extended.OSRStartNode;
import org.graalvm.compiler.nodes.extended.RawLoadNode;
import org.graalvm.compiler.nodes.extended.StoreHubNode;
import org.graalvm.compiler.nodes.java.ClassIsAssignableFromNode;
import org.graalvm.compiler.nodes.java.DynamicNewArrayNode;
import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode;
import org.graalvm.compiler.nodes.java.InstanceOfDynamicNode;
import org.graalvm.compiler.nodes.java.InstanceOfNode;
import org.graalvm.compiler.nodes.java.LoadExceptionObjectNode;
import org.graalvm.compiler.nodes.java.MethodCallTargetNode;
import org.graalvm.compiler.nodes.java.MonitorExitNode;
import org.graalvm.compiler.nodes.java.MonitorIdNode;
import org.graalvm.compiler.nodes.java.NewArrayNode;
import org.graalvm.compiler.nodes.java.NewInstanceNode;
import org.graalvm.compiler.nodes.java.NewMultiArrayNode;
import org.graalvm.compiler.nodes.java.RawMonitorEnterNode;
import org.graalvm.compiler.nodes.memory.FloatingReadNode;
import org.graalvm.compiler.nodes.memory.HeapAccess.BarrierType;
import org.graalvm.compiler.nodes.memory.ReadNode;
import org.graalvm.compiler.nodes.memory.WriteNode;
import org.graalvm.compiler.nodes.memory.address.AddressNode;
import org.graalvm.compiler.nodes.spi.LoweringProvider;
import org.graalvm.compiler.nodes.spi.LoweringTool;
import org.graalvm.compiler.nodes.spi.StampProvider;
import org.graalvm.compiler.nodes.type.StampTool;
import org.graalvm.compiler.nodes.util.GraphUtil;
import org.graalvm.compiler.options.OptionValues;
import org.graalvm.compiler.replacements.DefaultJavaLoweringProvider;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopyNode;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopySnippets;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopyWithSlowPathNode;
import org.graalvm.compiler.replacements.nodes.AssertionNode;
import jdk.internal.vm.compiler.word.LocationIdentity;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.hotspot.HotSpotCallingConventionType;
import jdk.vm.ci.hotspot.HotSpotConstantReflectionProvider;
import jdk.vm.ci.hotspot.HotSpotResolvedJavaField;
import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.JavaType;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaField;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* HotSpot implementation of {@link LoweringProvider}.
*/
public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider {
protected final HotSpotGraalRuntimeProvider runtime;
protected final HotSpotRegistersProvider registers;
protected final HotSpotConstantReflectionProvider constantReflection;
protected InstanceOfSnippets.Templates instanceofSnippets;
protected NewObjectSnippets.Templates newObjectSnippets;
protected MonitorSnippets.Templates monitorSnippets;
protected WriteBarrierSnippets.Templates writeBarrierSnippets;
protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets;
protected UnsafeLoadSnippets.Templates unsafeLoadSnippets;
protected AssertionSnippets.Templates assertionSnippets;
protected ArrayCopySnippets.Templates arraycopySnippets;
protected StringToBytesSnippets.Templates stringToBytesSnippets;
protected HashCodeSnippets.Templates hashCodeSnippets;
protected ResolveConstantSnippets.Templates resolveConstantSnippets;
protected ProfileSnippets.Templates profileSnippets;
protected ObjectCloneSnippets.Templates objectCloneSnippets;
protected ForeignCallSnippets.Templates foreignCallSnippets;
public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers,
HotSpotConstantReflectionProvider constantReflection, TargetDescription target) {
super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops);
this.runtime = runtime;
this.registers = registers;
this.constantReflection = constantReflection;
}
@Override
public void initialize(OptionValues options, Iterable<DebugHandlersFactory> factories, HotSpotProviders providers, GraalHotSpotVMConfig config) {
super.initialize(options, factories, runtime, providers, providers.getSnippetReflection());
assert target == providers.getCodeCache().getTarget();
instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target);
newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config);
monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking);
writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config);
exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target);
unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target);
assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target);
arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target);
stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target);
hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target);
resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target);
profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target);
objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target);
foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target);
}
public MonitorSnippets.Templates getMonitorSnippets() {
return monitorSnippets;
}
@Override
@SuppressWarnings("try")
public void lower(Node n, LoweringTool tool) {
StructuredGraph graph = (StructuredGraph) n.graph();
try (DebugCloseable context = n.withNodeSourcePosition()) {
if (n instanceof Invoke) {
lowerInvoke((Invoke) n, tool, graph);
} else if (n instanceof LoadMethodNode) {
lowerLoadMethodNode((LoadMethodNode) n);
} else if (n instanceof GetClassNode) {
lowerGetClassNode((GetClassNode) n, tool, graph);
} else if (n instanceof StoreHubNode) {
lowerStoreHubNode((StoreHubNode) n, graph);
} else if (n instanceof OSRStartNode) {
lowerOSRStartNode((OSRStartNode) n);
} else if (n instanceof BytecodeExceptionNode) {
lowerBytecodeExceptionNode((BytecodeExceptionNode) n);
} else if (n instanceof InstanceOfNode) {
InstanceOfNode instanceOfNode = (InstanceOfNode) n;
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower(instanceOfNode, tool);
} else {
if (instanceOfNode.allowsNull()) {
ValueNode object = instanceOfNode.getValue();
LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor()));
LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY);
instanceOfNode.replaceAndDelete(newNode);
}
}
} else if (n instanceof InstanceOfDynamicNode) {
InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n;
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower(instanceOfDynamicNode, tool);
} else {
ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub();
if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) {
ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror));
instanceOfDynamicNode.setMirror(classGetHub);
}
if (instanceOfDynamicNode.allowsNull()) {
ValueNode object = instanceOfDynamicNode.getObject();
LogicNode newTypeCheck = graph.addOrUniqueWithInputs(
InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false));
LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY);
instanceOfDynamicNode.replaceAndDelete(newNode);
}
}
} else if (n instanceof ClassIsAssignableFromNode) {
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool);
}
} else if (n instanceof NewInstanceNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewInstanceNode) n, registers, tool);
}
} else if (n instanceof DynamicNewInstanceNode) {
DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n;
if (newInstanceNode.getClassClass() == null) {
JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class));
ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph);
newInstanceNode.setClassClass(classClass);
}
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower(newInstanceNode, registers, tool);
}
} else if (n instanceof NewArrayNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewArrayNode) n, registers, tool);
}
} else if (n instanceof DynamicNewArrayNode) {
DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n;
if (dynamicNewArrayNode.getVoidClass() == null) {
JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class));
ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph);
dynamicNewArrayNode.setVoidClass(voidClass);
}
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower(dynamicNewArrayNode, registers, tool);
}
} else if (n instanceof VerifyHeapNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((VerifyHeapNode) n, registers, tool);
}
} else if (n instanceof RawMonitorEnterNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool);
}
} else if (n instanceof MonitorExitNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
monitorSnippets.lower((MonitorExitNode) n, registers, tool);
}
} else if (n instanceof ArrayCopyNode) {
arraycopySnippets.lower((ArrayCopyNode) n, tool);
} else if (n instanceof ArrayCopyWithSlowPathNode) {
arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool);
} else if (n instanceof G1PreWriteBarrier) {
writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool);
} else if (n instanceof G1PostWriteBarrier) {
writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool);
} else if (n instanceof G1ReferentFieldReadBarrier) {
writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool);
} else if (n instanceof SerialWriteBarrier) {
writeBarrierSnippets.lower((SerialWriteBarrier) n, tool);
} else if (n instanceof SerialArrayRangeWriteBarrier) {
writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool);
} else if (n instanceof G1ArrayRangePreWriteBarrier) {
writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool);
} else if (n instanceof G1ArrayRangePostWriteBarrier) {
writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool);
} else if (n instanceof NewMultiArrayNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewMultiArrayNode) n, tool);
}
} else if (n instanceof LoadExceptionObjectNode) {
exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool);
} else if (n instanceof AssertionNode) {
assertionSnippets.lower((AssertionNode) n, tool);
} else if (n instanceof StringToBytesNode) {
if (graph.getGuardsStage().areDeoptsFixed()) {
stringToBytesSnippets.lower((StringToBytesNode) n, tool);
}
} else if (n instanceof IntegerDivRemNode) {
// Nothing to do for division nodes. The HotSpot signal handler catches divisions by
// zero and the MIN_VALUE / -1 cases.
} else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) {
/* No lowering, we generate LIR directly for these nodes. */
} else if (n instanceof ClassGetHubNode) {
lowerClassGetHubNode((ClassGetHubNode) n, tool);
} else if (n instanceof HubGetClassNode) {
lowerHubGetClassNode((HubGetClassNode) n, tool);
} else if (n instanceof KlassLayoutHelperNode) {
lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool);
} else if (n instanceof ComputeObjectAddressNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
lowerComputeObjectAddressNode((ComputeObjectAddressNode) n);
}
} else if (n instanceof IdentityHashCodeNode) {
hashCodeSnippets.lower((IdentityHashCodeNode) n, tool);
} else if (n instanceof ResolveDynamicConstantNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool);
}
} else if (n instanceof ResolveConstantNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveConstantNode) n, tool);
}
} else if (n instanceof ResolveMethodAndLoadCountersNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool);
}
} else if (n instanceof InitializeKlassNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((InitializeKlassNode) n, tool);
}
} else if (n instanceof ProfileNode) {
profileSnippets.lower((ProfileNode) n, tool);
} else {
super.lower(n, tool);
}
}
}
private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) {
/*
* Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any
* potential safepoints and above it's uses.
*/
for (Node use : n.usages().snapshot()) {
if (use instanceof FixedNode) {
FixedNode fixed = (FixedNode) use;
StructuredGraph graph = n.graph();
GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject()));
graph.addBeforeFixed(fixed, address);
AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset()));
use.replaceFirstInput(n, add);
} else {
throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n);
}
}
GraphUtil.unlinkFixedNode(n);
n.safeDelete();
}
private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
StructuredGraph graph = n.graph();
assert !n.getHub().isConstant();
AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset);
n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)));
}
private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
ValueNode hub = n.getHub();
GraalHotSpotVMConfig vmConfig = runtime.getVMConfig();
StructuredGraph graph = n.graph();
assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions());
AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset);
FloatingReadNode read = graph.unique(
new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT),
null, BarrierType.NONE));
if (vmConfig.classMirrorIsHandle) {
AddressNode address = createOffsetAddress(graph, read, 0);
read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE));
}
n.replaceAtUsagesAndDelete(read);
}
private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
StructuredGraph graph = n.graph();
assert !n.getValue().isConstant();
AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset);
FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE));
n.replaceAtUsagesAndDelete(read);
}
private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) {
if (invoke.callTarget() instanceof MethodCallTargetNode) {
MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget();
NodeInputList<ValueNode> parameters = callTarget.arguments();
ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0);
if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) {
ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool);
parameters.set(0, nonNullReceiver);
receiver = nonNullReceiver;
}
JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass());
LoweredCallTargetNode loweredCallTarget = null;
OptionValues options = graph.getOptions();
if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) {
HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod();
ResolvedJavaType receiverType = invoke.getReceiverType();
if (hsMethod.isInVirtualMethodTable(receiverType)) {
JavaKind wordKind = runtime.getTarget().wordJavaKind;
ValueNode hub = createReadHub(graph, receiver, tool);
ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType);
// We use LocationNode.ANY_LOCATION for the reads that access the
// compiled code entry as HotSpot does not guarantee they are final
// values.
int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset;
AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset);
ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE));
loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(),
signature, callTarget.targetMethod(),
HotSpotCallingConventionType.JavaCall, callTarget.invokeKind()));
graph.addBeforeFixed(invoke.asNode(), metaspaceMethod);
graph.addAfterFixed(metaspaceMethod, compiledEntry);
}
}
if (loweredCallTarget == null) {
loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(),
signature, callTarget.targetMethod(),
HotSpotCallingConventionType.JavaCall,
callTarget.invokeKind()));
}
callTarget.replaceAndDelete(loweredCallTarget);
}
}
private CompressEncoding getOopEncoding() {
return runtime.getVMConfig().getOopEncoding();
}
@Override
protected Stamp loadCompressedStamp(ObjectStamp stamp) {
return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding());
}
@Override
protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) {
return new HotSpotCompressionNode(op, value, getOopEncoding());
}
@Override
public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) {
HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f;
JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass());
return ConstantNode.forConstant(base, metaAccess, graph);
}
@Override
protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) {
/*
* Anchor the read of the element klass to the cfg, because it is only valid when arrayClass
* is an object class, which might not be the case in other parts of the compiled method.
*/
AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset);
return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor)));
}
@Override
protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) {
StructuredGraph graph = load.graph();
if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) {
unsafeLoadSnippets.lower(load, tool);
} else {
super.lowerUnsafeLoadNode(load, tool);
}
}
private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) {
StructuredGraph graph = loadMethodNode.graph();
HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod();
ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType());
graph.replaceFixed(loadMethodNode, metaspaceMethod);
}
private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) {
StampProvider stampProvider = tool.getStampProvider();
LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject()));
HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub));
getClass.replaceAtUsagesAndDelete(hubGetClass);
hub.lower(tool);
hubGetClass.lower(tool);
}
private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) {
WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue());
graph.replaceFixed(storeHub, hub);
}
@Override
public BarrierType fieldInitializationBarrier(JavaKind entryKind) {
return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE;
}
@Override
public BarrierType arrayInitializationBarrier(JavaKind entryKind) {
return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE;
}
private void lowerOSRStartNode(OSRStartNode osrStart) {
StructuredGraph graph = osrStart.graph();
if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) {
StartNode newStart = graph.add(new StartNode());
ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind))));
ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer));
migrationEnd.setStateAfter(osrStart.stateAfter());
newStart.setNext(migrationEnd);
FixedNode next = osrStart.next();
osrStart.setNext(null);
migrationEnd.setNext(next);
graph.setStart(newStart);
final int wordSize = target.wordSize;
// @formatter:off
// taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize)
// @formatter:on
int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize;
for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) {
int size = osrLocal.getStackKind().getSlotCount();
int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize;
AddressNode address = createOffsetAddress(graph, buffer, offset);
ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE));
osrLocal.replaceAndDelete(load);
graph.addBeforeFixed(migrationEnd, load);
}
// @formatter:off
// taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize);
// @formatter:on
final int lockCount = osrStart.stateAfter().locksSize();
final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize;
// first initialize the lock slots for all enters with the displaced marks read from the
// buffer
for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) {
MonitorIdNode monitorID = osrMonitorEnter.getMonitorId();
OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object();
final int index = lock.index();
final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize;
final int offsetLockObject = locksOffset - index * 2 * wordSize;
// load the displaced mark from the osr buffer
AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader);
ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE));
graph.addBeforeFixed(migrationEnd, loadDisplacedHeader);
// we need to initialize the stack slot for the lock
BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth()));
graph.addBeforeFixed(migrationEnd, beginLockScope);
// write the displaced mark to the correct stack slot
AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset);
WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE));
graph.addBeforeFixed(migrationEnd, writeStackSlot);
// load the lock object from the osr buffer
AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject);
ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE));
lock.replaceAndDelete(loadObject);
graph.addBeforeFixed(migrationEnd, loadObject);
}
osrStart.replaceAtUsagesAndDelete(newStart);
}
}
static final class Exceptions {
protected static final EnumMap<BytecodeExceptionKind, RuntimeException> cachedExceptions;
static {
cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class);
cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException()));
cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException()));
cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException()));
cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException()));
cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException()));
}
private static RuntimeException clearStackTrace(RuntimeException ex) {
ex.setStackTrace(new StackTraceElement[0]);
return ex;
}
}
public static final class RuntimeCalls {
public static final EnumMap<BytecodeExceptionKind, ForeignCallDescriptor> runtimeCalls;
static {
runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class);
runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class));
runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class));
runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class));
runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class));
runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class));
runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class));
runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class));
}
}
private void throwCachedException(BytecodeExceptionNode node) {
Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind());
assert exception != null;
StructuredGraph graph = node.graph();
FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph);
graph.replaceFixedWithFloating(node, exceptionNode);
}
private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) {
if (OmitHotExceptionStacktrace.getValue(node.getOptions())) {
throwCachedException(node);
return;
}
ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind());
assert descriptor != null;
StructuredGraph graph = node.graph();
ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments()));
graph.replaceFixedWithFixed(node, foreignCallNode);
}
private boolean addReadBarrier(RawLoadNode load) {
if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object &&
load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) {
ResolvedJavaType type = StampTool.typeOrNull(load.object());
if (type != null && !type.isArray()) {
return true;
}
}
return false;
}
private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) {
return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType));
}
private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) {
assert vtableEntryOffset > 0;
// We use LocationNode.ANY_LOCATION for the reads that access the vtable
// entry as HotSpot does not guarantee that this is a final value.
Stamp methodStamp = MethodPointerStamp.methodNonNull();
AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset);
ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE));
return metaspaceMethod;
}
@Override
protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) {
if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) {
return graph.unique(new LoadHubNode(tool.getStampProvider(), object));
}
assert !object.isConstant() || object.isNullConstant();
KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull();
if (runtime.getVMConfig().useCompressedClassPointers) {
hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding());
}
AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset);
LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION;
FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE));
if (runtime.getVMConfig().useCompressedClassPointers) {
return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding());
} else {
return memoryRead;
}
}
private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) {
assert !object.isConstant() || object.asConstant().isDefaultForKind();
ValueNode writeValue = value;
if (runtime.getVMConfig().useCompressedClassPointers) {
writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding());
}
AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset);
return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE));
}
@Override
protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) {
HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f;
BarrierType barrierType = BarrierType.NONE;
if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) &&
loadField.getName().equals("referent")) {
barrierType = BarrierType.PRECISE;
}
return barrierType;
}
@Override
public int fieldOffset(ResolvedJavaField f) {
return f.getOffset();
}
@Override
public int arrayLengthOffset() {
return runtime.getVMConfig().arrayOopDescLengthOffset();
}
@Override
protected final JavaKind getStorageKind(ResolvedJavaField field) {
return field.getJavaKind();
}
@Override
public ObjectCloneSnippets.Templates getObjectCloneSnippets() {
return objectCloneSnippets;
}
@Override
public ForeignCallSnippets.Templates getForeignCallSnippets() {
return foreignCallSnippets;
}
}
| UTF-8 | Java | 45,486 | java | DefaultHotSpotLoweringProvider.java | Java | []
| null | []
| /*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.hotspot.meta;
import static org.graalvm.compiler.core.common.GraalOptions.AlwaysInlineVTableStubs;
import static org.graalvm.compiler.core.common.GraalOptions.InlineVTableStubs;
import static org.graalvm.compiler.core.common.GraalOptions.OmitHotExceptionStacktrace;
import static org.graalvm.compiler.hotspot.meta.HotSpotForeignCallsProviderImpl.OSR_MIGRATION_END;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_KLASS_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_MIRROR_HANDLE_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_MIRROR_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.COMPRESSED_HUB_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.DISPLACED_MARK_WORD_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.HUB_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.HUB_WRITE_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.KLASS_LAYOUT_HELPER_LOCATION;
import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION;
import static jdk.internal.vm.compiler.word.LocationIdentity.any;
import java.lang.ref.Reference;
import java.util.EnumMap;
import org.graalvm.compiler.api.directives.GraalDirectives;
import org.graalvm.compiler.core.common.CompressEncoding;
import org.graalvm.compiler.core.common.GraalOptions;
import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor;
import org.graalvm.compiler.core.common.spi.ForeignCallsProvider;
import org.graalvm.compiler.core.common.type.ObjectStamp;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.core.common.type.StampFactory;
import org.graalvm.compiler.core.common.type.StampPair;
import org.graalvm.compiler.debug.DebugCloseable;
import org.graalvm.compiler.debug.DebugHandlersFactory;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.graph.NodeInputList;
import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
import org.graalvm.compiler.hotspot.HotSpotGraalRuntimeProvider;
import org.graalvm.compiler.hotspot.nodes.BeginLockScopeNode;
import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePostWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1ArrayRangePreWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1PostWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1PreWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.G1ReferentFieldReadBarrier;
import org.graalvm.compiler.hotspot.nodes.HotSpotCompressionNode;
import org.graalvm.compiler.hotspot.nodes.HotSpotDirectCallTargetNode;
import org.graalvm.compiler.hotspot.nodes.HotSpotIndirectCallTargetNode;
import org.graalvm.compiler.hotspot.nodes.SerialArrayRangeWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.SerialWriteBarrier;
import org.graalvm.compiler.hotspot.nodes.aot.InitializeKlassNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveConstantNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveDynamicConstantNode;
import org.graalvm.compiler.hotspot.nodes.aot.ResolveMethodAndLoadCountersNode;
import org.graalvm.compiler.hotspot.nodes.profiling.ProfileNode;
import org.graalvm.compiler.hotspot.nodes.type.HotSpotNarrowOopStamp;
import org.graalvm.compiler.hotspot.nodes.type.KlassPointerStamp;
import org.graalvm.compiler.hotspot.nodes.type.MethodPointerStamp;
import org.graalvm.compiler.hotspot.replacements.AssertionSnippets;
import org.graalvm.compiler.hotspot.replacements.ClassGetHubNode;
import org.graalvm.compiler.hotspot.replacements.HashCodeSnippets;
import org.graalvm.compiler.hotspot.replacements.HubGetClassNode;
import org.graalvm.compiler.hotspot.replacements.IdentityHashCodeNode;
import org.graalvm.compiler.hotspot.replacements.InstanceOfSnippets;
import org.graalvm.compiler.hotspot.replacements.KlassLayoutHelperNode;
import org.graalvm.compiler.hotspot.replacements.LoadExceptionObjectSnippets;
import org.graalvm.compiler.hotspot.replacements.MonitorSnippets;
import org.graalvm.compiler.hotspot.replacements.NewObjectSnippets;
import org.graalvm.compiler.hotspot.replacements.ObjectCloneSnippets;
import org.graalvm.compiler.hotspot.replacements.StringToBytesSnippets;
import org.graalvm.compiler.hotspot.replacements.UnsafeLoadSnippets;
import org.graalvm.compiler.hotspot.replacements.WriteBarrierSnippets;
import org.graalvm.compiler.hotspot.replacements.aot.ResolveConstantSnippets;
import org.graalvm.compiler.hotspot.replacements.arraycopy.HotSpotArraycopySnippets;
import org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets;
import org.graalvm.compiler.hotspot.stubs.ForeignCallSnippets;
import org.graalvm.compiler.hotspot.word.KlassPointer;
import org.graalvm.compiler.nodes.AbstractBeginNode;
import org.graalvm.compiler.nodes.AbstractDeoptimizeNode;
import org.graalvm.compiler.nodes.CompressionNode.CompressionOp;
import org.graalvm.compiler.nodes.ComputeObjectAddressNode;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.FixedNode;
import org.graalvm.compiler.nodes.GetObjectAddressNode;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.LogicNode;
import org.graalvm.compiler.nodes.LoweredCallTargetNode;
import org.graalvm.compiler.nodes.NodeView;
import org.graalvm.compiler.nodes.ParameterNode;
import org.graalvm.compiler.nodes.SafepointNode;
import org.graalvm.compiler.nodes.StartNode;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.UnwindNode;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.calc.AddNode;
import org.graalvm.compiler.nodes.calc.FloatingNode;
import org.graalvm.compiler.nodes.calc.IntegerDivRemNode;
import org.graalvm.compiler.nodes.calc.IsNullNode;
import org.graalvm.compiler.nodes.calc.RemNode;
import org.graalvm.compiler.nodes.debug.StringToBytesNode;
import org.graalvm.compiler.nodes.debug.VerifyHeapNode;
import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode;
import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode.BytecodeExceptionKind;
import org.graalvm.compiler.nodes.extended.ForeignCallNode;
import org.graalvm.compiler.nodes.extended.GetClassNode;
import org.graalvm.compiler.nodes.extended.GuardedUnsafeLoadNode;
import org.graalvm.compiler.nodes.extended.LoadHubNode;
import org.graalvm.compiler.nodes.extended.LoadMethodNode;
import org.graalvm.compiler.nodes.extended.OSRLocalNode;
import org.graalvm.compiler.nodes.extended.OSRLockNode;
import org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode;
import org.graalvm.compiler.nodes.extended.OSRStartNode;
import org.graalvm.compiler.nodes.extended.RawLoadNode;
import org.graalvm.compiler.nodes.extended.StoreHubNode;
import org.graalvm.compiler.nodes.java.ClassIsAssignableFromNode;
import org.graalvm.compiler.nodes.java.DynamicNewArrayNode;
import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode;
import org.graalvm.compiler.nodes.java.InstanceOfDynamicNode;
import org.graalvm.compiler.nodes.java.InstanceOfNode;
import org.graalvm.compiler.nodes.java.LoadExceptionObjectNode;
import org.graalvm.compiler.nodes.java.MethodCallTargetNode;
import org.graalvm.compiler.nodes.java.MonitorExitNode;
import org.graalvm.compiler.nodes.java.MonitorIdNode;
import org.graalvm.compiler.nodes.java.NewArrayNode;
import org.graalvm.compiler.nodes.java.NewInstanceNode;
import org.graalvm.compiler.nodes.java.NewMultiArrayNode;
import org.graalvm.compiler.nodes.java.RawMonitorEnterNode;
import org.graalvm.compiler.nodes.memory.FloatingReadNode;
import org.graalvm.compiler.nodes.memory.HeapAccess.BarrierType;
import org.graalvm.compiler.nodes.memory.ReadNode;
import org.graalvm.compiler.nodes.memory.WriteNode;
import org.graalvm.compiler.nodes.memory.address.AddressNode;
import org.graalvm.compiler.nodes.spi.LoweringProvider;
import org.graalvm.compiler.nodes.spi.LoweringTool;
import org.graalvm.compiler.nodes.spi.StampProvider;
import org.graalvm.compiler.nodes.type.StampTool;
import org.graalvm.compiler.nodes.util.GraphUtil;
import org.graalvm.compiler.options.OptionValues;
import org.graalvm.compiler.replacements.DefaultJavaLoweringProvider;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopyNode;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopySnippets;
import org.graalvm.compiler.replacements.arraycopy.ArrayCopyWithSlowPathNode;
import org.graalvm.compiler.replacements.nodes.AssertionNode;
import jdk.internal.vm.compiler.word.LocationIdentity;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.hotspot.HotSpotCallingConventionType;
import jdk.vm.ci.hotspot.HotSpotConstantReflectionProvider;
import jdk.vm.ci.hotspot.HotSpotResolvedJavaField;
import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.JavaType;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaField;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* HotSpot implementation of {@link LoweringProvider}.
*/
public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider {
protected final HotSpotGraalRuntimeProvider runtime;
protected final HotSpotRegistersProvider registers;
protected final HotSpotConstantReflectionProvider constantReflection;
protected InstanceOfSnippets.Templates instanceofSnippets;
protected NewObjectSnippets.Templates newObjectSnippets;
protected MonitorSnippets.Templates monitorSnippets;
protected WriteBarrierSnippets.Templates writeBarrierSnippets;
protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets;
protected UnsafeLoadSnippets.Templates unsafeLoadSnippets;
protected AssertionSnippets.Templates assertionSnippets;
protected ArrayCopySnippets.Templates arraycopySnippets;
protected StringToBytesSnippets.Templates stringToBytesSnippets;
protected HashCodeSnippets.Templates hashCodeSnippets;
protected ResolveConstantSnippets.Templates resolveConstantSnippets;
protected ProfileSnippets.Templates profileSnippets;
protected ObjectCloneSnippets.Templates objectCloneSnippets;
protected ForeignCallSnippets.Templates foreignCallSnippets;
public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers,
HotSpotConstantReflectionProvider constantReflection, TargetDescription target) {
super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops);
this.runtime = runtime;
this.registers = registers;
this.constantReflection = constantReflection;
}
@Override
public void initialize(OptionValues options, Iterable<DebugHandlersFactory> factories, HotSpotProviders providers, GraalHotSpotVMConfig config) {
super.initialize(options, factories, runtime, providers, providers.getSnippetReflection());
assert target == providers.getCodeCache().getTarget();
instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target);
newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config);
monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking);
writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config);
exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target);
unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target);
assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target);
arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target);
stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target);
hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target);
resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target);
profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target);
objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target);
foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target);
}
public MonitorSnippets.Templates getMonitorSnippets() {
return monitorSnippets;
}
@Override
@SuppressWarnings("try")
public void lower(Node n, LoweringTool tool) {
StructuredGraph graph = (StructuredGraph) n.graph();
try (DebugCloseable context = n.withNodeSourcePosition()) {
if (n instanceof Invoke) {
lowerInvoke((Invoke) n, tool, graph);
} else if (n instanceof LoadMethodNode) {
lowerLoadMethodNode((LoadMethodNode) n);
} else if (n instanceof GetClassNode) {
lowerGetClassNode((GetClassNode) n, tool, graph);
} else if (n instanceof StoreHubNode) {
lowerStoreHubNode((StoreHubNode) n, graph);
} else if (n instanceof OSRStartNode) {
lowerOSRStartNode((OSRStartNode) n);
} else if (n instanceof BytecodeExceptionNode) {
lowerBytecodeExceptionNode((BytecodeExceptionNode) n);
} else if (n instanceof InstanceOfNode) {
InstanceOfNode instanceOfNode = (InstanceOfNode) n;
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower(instanceOfNode, tool);
} else {
if (instanceOfNode.allowsNull()) {
ValueNode object = instanceOfNode.getValue();
LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor()));
LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY);
instanceOfNode.replaceAndDelete(newNode);
}
}
} else if (n instanceof InstanceOfDynamicNode) {
InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n;
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower(instanceOfDynamicNode, tool);
} else {
ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub();
if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) {
ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror));
instanceOfDynamicNode.setMirror(classGetHub);
}
if (instanceOfDynamicNode.allowsNull()) {
ValueNode object = instanceOfDynamicNode.getObject();
LogicNode newTypeCheck = graph.addOrUniqueWithInputs(
InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false));
LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY);
instanceOfDynamicNode.replaceAndDelete(newNode);
}
}
} else if (n instanceof ClassIsAssignableFromNode) {
if (graph.getGuardsStage().areDeoptsFixed()) {
instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool);
}
} else if (n instanceof NewInstanceNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewInstanceNode) n, registers, tool);
}
} else if (n instanceof DynamicNewInstanceNode) {
DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n;
if (newInstanceNode.getClassClass() == null) {
JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class));
ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph);
newInstanceNode.setClassClass(classClass);
}
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower(newInstanceNode, registers, tool);
}
} else if (n instanceof NewArrayNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewArrayNode) n, registers, tool);
}
} else if (n instanceof DynamicNewArrayNode) {
DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n;
if (dynamicNewArrayNode.getVoidClass() == null) {
JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class));
ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph);
dynamicNewArrayNode.setVoidClass(voidClass);
}
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower(dynamicNewArrayNode, registers, tool);
}
} else if (n instanceof VerifyHeapNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((VerifyHeapNode) n, registers, tool);
}
} else if (n instanceof RawMonitorEnterNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool);
}
} else if (n instanceof MonitorExitNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
monitorSnippets.lower((MonitorExitNode) n, registers, tool);
}
} else if (n instanceof ArrayCopyNode) {
arraycopySnippets.lower((ArrayCopyNode) n, tool);
} else if (n instanceof ArrayCopyWithSlowPathNode) {
arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool);
} else if (n instanceof G1PreWriteBarrier) {
writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool);
} else if (n instanceof G1PostWriteBarrier) {
writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool);
} else if (n instanceof G1ReferentFieldReadBarrier) {
writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool);
} else if (n instanceof SerialWriteBarrier) {
writeBarrierSnippets.lower((SerialWriteBarrier) n, tool);
} else if (n instanceof SerialArrayRangeWriteBarrier) {
writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool);
} else if (n instanceof G1ArrayRangePreWriteBarrier) {
writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool);
} else if (n instanceof G1ArrayRangePostWriteBarrier) {
writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool);
} else if (n instanceof NewMultiArrayNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
newObjectSnippets.lower((NewMultiArrayNode) n, tool);
}
} else if (n instanceof LoadExceptionObjectNode) {
exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool);
} else if (n instanceof AssertionNode) {
assertionSnippets.lower((AssertionNode) n, tool);
} else if (n instanceof StringToBytesNode) {
if (graph.getGuardsStage().areDeoptsFixed()) {
stringToBytesSnippets.lower((StringToBytesNode) n, tool);
}
} else if (n instanceof IntegerDivRemNode) {
// Nothing to do for division nodes. The HotSpot signal handler catches divisions by
// zero and the MIN_VALUE / -1 cases.
} else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) {
/* No lowering, we generate LIR directly for these nodes. */
} else if (n instanceof ClassGetHubNode) {
lowerClassGetHubNode((ClassGetHubNode) n, tool);
} else if (n instanceof HubGetClassNode) {
lowerHubGetClassNode((HubGetClassNode) n, tool);
} else if (n instanceof KlassLayoutHelperNode) {
lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool);
} else if (n instanceof ComputeObjectAddressNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
lowerComputeObjectAddressNode((ComputeObjectAddressNode) n);
}
} else if (n instanceof IdentityHashCodeNode) {
hashCodeSnippets.lower((IdentityHashCodeNode) n, tool);
} else if (n instanceof ResolveDynamicConstantNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool);
}
} else if (n instanceof ResolveConstantNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveConstantNode) n, tool);
}
} else if (n instanceof ResolveMethodAndLoadCountersNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool);
}
} else if (n instanceof InitializeKlassNode) {
if (graph.getGuardsStage().areFrameStatesAtDeopts()) {
resolveConstantSnippets.lower((InitializeKlassNode) n, tool);
}
} else if (n instanceof ProfileNode) {
profileSnippets.lower((ProfileNode) n, tool);
} else {
super.lower(n, tool);
}
}
}
private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) {
/*
* Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any
* potential safepoints and above it's uses.
*/
for (Node use : n.usages().snapshot()) {
if (use instanceof FixedNode) {
FixedNode fixed = (FixedNode) use;
StructuredGraph graph = n.graph();
GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject()));
graph.addBeforeFixed(fixed, address);
AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset()));
use.replaceFirstInput(n, add);
} else {
throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n);
}
}
GraphUtil.unlinkFixedNode(n);
n.safeDelete();
}
private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
StructuredGraph graph = n.graph();
assert !n.getHub().isConstant();
AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset);
n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)));
}
private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
ValueNode hub = n.getHub();
GraalHotSpotVMConfig vmConfig = runtime.getVMConfig();
StructuredGraph graph = n.graph();
assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions());
AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset);
FloatingReadNode read = graph.unique(
new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT),
null, BarrierType.NONE));
if (vmConfig.classMirrorIsHandle) {
AddressNode address = createOffsetAddress(graph, read, 0);
read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE));
}
n.replaceAtUsagesAndDelete(read);
}
private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) {
if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) {
return;
}
StructuredGraph graph = n.graph();
assert !n.getValue().isConstant();
AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset);
FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE));
n.replaceAtUsagesAndDelete(read);
}
private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) {
if (invoke.callTarget() instanceof MethodCallTargetNode) {
MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget();
NodeInputList<ValueNode> parameters = callTarget.arguments();
ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0);
if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) {
ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool);
parameters.set(0, nonNullReceiver);
receiver = nonNullReceiver;
}
JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass());
LoweredCallTargetNode loweredCallTarget = null;
OptionValues options = graph.getOptions();
if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) {
HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod();
ResolvedJavaType receiverType = invoke.getReceiverType();
if (hsMethod.isInVirtualMethodTable(receiverType)) {
JavaKind wordKind = runtime.getTarget().wordJavaKind;
ValueNode hub = createReadHub(graph, receiver, tool);
ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType);
// We use LocationNode.ANY_LOCATION for the reads that access the
// compiled code entry as HotSpot does not guarantee they are final
// values.
int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset;
AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset);
ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE));
loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(),
signature, callTarget.targetMethod(),
HotSpotCallingConventionType.JavaCall, callTarget.invokeKind()));
graph.addBeforeFixed(invoke.asNode(), metaspaceMethod);
graph.addAfterFixed(metaspaceMethod, compiledEntry);
}
}
if (loweredCallTarget == null) {
loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(),
signature, callTarget.targetMethod(),
HotSpotCallingConventionType.JavaCall,
callTarget.invokeKind()));
}
callTarget.replaceAndDelete(loweredCallTarget);
}
}
private CompressEncoding getOopEncoding() {
return runtime.getVMConfig().getOopEncoding();
}
@Override
protected Stamp loadCompressedStamp(ObjectStamp stamp) {
return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding());
}
@Override
protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) {
return new HotSpotCompressionNode(op, value, getOopEncoding());
}
@Override
public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) {
HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f;
JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass());
return ConstantNode.forConstant(base, metaAccess, graph);
}
@Override
protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) {
/*
* Anchor the read of the element klass to the cfg, because it is only valid when arrayClass
* is an object class, which might not be the case in other parts of the compiled method.
*/
AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset);
return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor)));
}
@Override
protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) {
StructuredGraph graph = load.graph();
if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) {
unsafeLoadSnippets.lower(load, tool);
} else {
super.lowerUnsafeLoadNode(load, tool);
}
}
private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) {
StructuredGraph graph = loadMethodNode.graph();
HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod();
ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType());
graph.replaceFixed(loadMethodNode, metaspaceMethod);
}
private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) {
StampProvider stampProvider = tool.getStampProvider();
LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject()));
HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub));
getClass.replaceAtUsagesAndDelete(hubGetClass);
hub.lower(tool);
hubGetClass.lower(tool);
}
private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) {
WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue());
graph.replaceFixed(storeHub, hub);
}
@Override
public BarrierType fieldInitializationBarrier(JavaKind entryKind) {
return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE;
}
@Override
public BarrierType arrayInitializationBarrier(JavaKind entryKind) {
return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE;
}
private void lowerOSRStartNode(OSRStartNode osrStart) {
StructuredGraph graph = osrStart.graph();
if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) {
StartNode newStart = graph.add(new StartNode());
ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind))));
ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer));
migrationEnd.setStateAfter(osrStart.stateAfter());
newStart.setNext(migrationEnd);
FixedNode next = osrStart.next();
osrStart.setNext(null);
migrationEnd.setNext(next);
graph.setStart(newStart);
final int wordSize = target.wordSize;
// @formatter:off
// taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize)
// @formatter:on
int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize;
for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) {
int size = osrLocal.getStackKind().getSlotCount();
int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize;
AddressNode address = createOffsetAddress(graph, buffer, offset);
ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE));
osrLocal.replaceAndDelete(load);
graph.addBeforeFixed(migrationEnd, load);
}
// @formatter:off
// taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize);
// @formatter:on
final int lockCount = osrStart.stateAfter().locksSize();
final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize;
// first initialize the lock slots for all enters with the displaced marks read from the
// buffer
for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) {
MonitorIdNode monitorID = osrMonitorEnter.getMonitorId();
OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object();
final int index = lock.index();
final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize;
final int offsetLockObject = locksOffset - index * 2 * wordSize;
// load the displaced mark from the osr buffer
AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader);
ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE));
graph.addBeforeFixed(migrationEnd, loadDisplacedHeader);
// we need to initialize the stack slot for the lock
BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth()));
graph.addBeforeFixed(migrationEnd, beginLockScope);
// write the displaced mark to the correct stack slot
AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset);
WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE));
graph.addBeforeFixed(migrationEnd, writeStackSlot);
// load the lock object from the osr buffer
AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject);
ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE));
lock.replaceAndDelete(loadObject);
graph.addBeforeFixed(migrationEnd, loadObject);
}
osrStart.replaceAtUsagesAndDelete(newStart);
}
}
static final class Exceptions {
protected static final EnumMap<BytecodeExceptionKind, RuntimeException> cachedExceptions;
static {
cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class);
cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException()));
cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException()));
cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException()));
cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException()));
cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException()));
}
private static RuntimeException clearStackTrace(RuntimeException ex) {
ex.setStackTrace(new StackTraceElement[0]);
return ex;
}
}
public static final class RuntimeCalls {
public static final EnumMap<BytecodeExceptionKind, ForeignCallDescriptor> runtimeCalls;
static {
runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class);
runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class));
runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class));
runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class));
runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class));
runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class));
runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class));
runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class));
}
}
private void throwCachedException(BytecodeExceptionNode node) {
Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind());
assert exception != null;
StructuredGraph graph = node.graph();
FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph);
graph.replaceFixedWithFloating(node, exceptionNode);
}
private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) {
if (OmitHotExceptionStacktrace.getValue(node.getOptions())) {
throwCachedException(node);
return;
}
ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind());
assert descriptor != null;
StructuredGraph graph = node.graph();
ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments()));
graph.replaceFixedWithFixed(node, foreignCallNode);
}
private boolean addReadBarrier(RawLoadNode load) {
if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object &&
load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) {
ResolvedJavaType type = StampTool.typeOrNull(load.object());
if (type != null && !type.isArray()) {
return true;
}
}
return false;
}
private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) {
return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType));
}
private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) {
assert vtableEntryOffset > 0;
// We use LocationNode.ANY_LOCATION for the reads that access the vtable
// entry as HotSpot does not guarantee that this is a final value.
Stamp methodStamp = MethodPointerStamp.methodNonNull();
AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset);
ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE));
return metaspaceMethod;
}
@Override
protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) {
if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) {
return graph.unique(new LoadHubNode(tool.getStampProvider(), object));
}
assert !object.isConstant() || object.isNullConstant();
KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull();
if (runtime.getVMConfig().useCompressedClassPointers) {
hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding());
}
AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset);
LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION;
FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE));
if (runtime.getVMConfig().useCompressedClassPointers) {
return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding());
} else {
return memoryRead;
}
}
private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) {
assert !object.isConstant() || object.asConstant().isDefaultForKind();
ValueNode writeValue = value;
if (runtime.getVMConfig().useCompressedClassPointers) {
writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding());
}
AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset);
return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE));
}
@Override
protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) {
HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f;
BarrierType barrierType = BarrierType.NONE;
if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) &&
loadField.getName().equals("referent")) {
barrierType = BarrierType.PRECISE;
}
return barrierType;
}
@Override
public int fieldOffset(ResolvedJavaField f) {
return f.getOffset();
}
@Override
public int arrayLengthOffset() {
return runtime.getVMConfig().arrayOopDescLengthOffset();
}
@Override
protected final JavaKind getStorageKind(ResolvedJavaField field) {
return field.getJavaKind();
}
@Override
public ObjectCloneSnippets.Templates getObjectCloneSnippets() {
return objectCloneSnippets;
}
@Override
public ForeignCallSnippets.Templates getForeignCallSnippets() {
return foreignCallSnippets;
}
}
| 45,486 | 0.711208 | 0.710219 | 802 | 55.71571 | 40.351898 | 195 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.955112 | false | false | 9 |
ed79a44774bc3610376cf5c23ec8b3ed2b28448b | 30,726,196,051,818 | 80b3f5e073a5818fb7932212979c9c7607ba167d | /src/util/FileHelper.java | ec6093fd34fff5f52da4960346fc15980ce865b8 | []
| no_license | kpcoder/sa | https://github.com/kpcoder/sa | 12bb44920af2a2d7a65a5910ff5c8f4023002f10 | 72897d70a417308c9a0e465f08f6277dfa11319b | refs/heads/master | 2017-12-07T00:29:51.234000 | 2017-04-21T05:18:58 | 2017-04-21T05:18:58 | 79,784,862 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import model.Comment;
import model.Sentiment;
import java.io.*;
import java.util.*;
public class FileHelper {
private static String trainDataFile = "F://tmining/trainData.txt";
private static String testDataFile = "F://tmining/testData.txt";
/**
* 存储分词后的所有评论
*/
public static void writeTrainData(List<Comment> comments){
write(comments,trainDataFile);
}
/**
* 存储分词后的所有评论
*/
public static void writeTestData(List<Comment> comments){
write(comments,testDataFile);
}
private static void write(List<Comment>comments, String filename){
try {
Writer writer = new FileWriter(new File(filename));
for(Comment comment:comments){
writer.write(comment.toString());
writer.write("\r\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Comment> readTrainData(int num){
return read(trainDataFile, num);
}
/**
* 取出分词后的所有测试评论
*/
public static List<Comment> readTestData(int num){
// Writer writer = new FileWriter(new File("F://tmining/testData2.txt"));
// writer.write("Positive 蔡 1 堂 1 代 1 小康 1 二郎腿 1 厦门 1 明亮 1 一组 1 美术馆 2 野 1 景 1 影 1 上照 1 变化 1 展 1 黑暗 1 4.0 1 玻璃房 1 脸 2 观众们 1 有意思 1");
// writer.write("\r\n");
// writer.write("Neutral 惊悚片 1 审美 1 可惜 1 注重 1 画面 1 安静 1 喜欢 1 没意思 1 阴郁 1");
// writer.write("\r\n");
// writer.write("Negative 还让 1 就有 1 想 1 评 1 本来 1 那么大 1 过节 1 孩子 2 差 1 扔了 1 直说 1");
// writer.write("\r\n");
// writer.flush();
// writer.close();
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("F://tmining/testData2.txt")));
return read(testDataFile, num);
}
/**
* 取出分词后的评论
* 格式:id 类名 词a 该词数量 词b 该词数量...(一行一条评论)
* @param num 负数表示全部读取,正数表示读取num条
*/
private static List<Comment> read(String filename, int num){
List<Comment> comments = new ArrayList<Comment>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
while (num!=0 &&(line = in.readLine()) != null) {
String[] splits = line.split(" ");
Comment comment = new Comment();
comment.setId(Integer.parseInt(splits[0]));
comment.setSentiment(Sentiment.valueOf(splits[1]));
Map<String,Integer> wordsAndFreq = new HashMap<String, Integer>();
for(int i=2;i<splits.length;i+=2){
wordsAndFreq.put(splits[i],Integer.parseInt(splits[i+1]));
}
comment.setWordsAndFreq(wordsAndFreq);
comments.add(comment);
num--;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return comments;
}
}
| UTF-8 | Java | 3,411 | java | FileHelper.java | Java | []
| null | []
| package util;
import model.Comment;
import model.Sentiment;
import java.io.*;
import java.util.*;
public class FileHelper {
private static String trainDataFile = "F://tmining/trainData.txt";
private static String testDataFile = "F://tmining/testData.txt";
/**
* 存储分词后的所有评论
*/
public static void writeTrainData(List<Comment> comments){
write(comments,trainDataFile);
}
/**
* 存储分词后的所有评论
*/
public static void writeTestData(List<Comment> comments){
write(comments,testDataFile);
}
private static void write(List<Comment>comments, String filename){
try {
Writer writer = new FileWriter(new File(filename));
for(Comment comment:comments){
writer.write(comment.toString());
writer.write("\r\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Comment> readTrainData(int num){
return read(trainDataFile, num);
}
/**
* 取出分词后的所有测试评论
*/
public static List<Comment> readTestData(int num){
// Writer writer = new FileWriter(new File("F://tmining/testData2.txt"));
// writer.write("Positive 蔡 1 堂 1 代 1 小康 1 二郎腿 1 厦门 1 明亮 1 一组 1 美术馆 2 野 1 景 1 影 1 上照 1 变化 1 展 1 黑暗 1 4.0 1 玻璃房 1 脸 2 观众们 1 有意思 1");
// writer.write("\r\n");
// writer.write("Neutral 惊悚片 1 审美 1 可惜 1 注重 1 画面 1 安静 1 喜欢 1 没意思 1 阴郁 1");
// writer.write("\r\n");
// writer.write("Negative 还让 1 就有 1 想 1 评 1 本来 1 那么大 1 过节 1 孩子 2 差 1 扔了 1 直说 1");
// writer.write("\r\n");
// writer.flush();
// writer.close();
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("F://tmining/testData2.txt")));
return read(testDataFile, num);
}
/**
* 取出分词后的评论
* 格式:id 类名 词a 该词数量 词b 该词数量...(一行一条评论)
* @param num 负数表示全部读取,正数表示读取num条
*/
private static List<Comment> read(String filename, int num){
List<Comment> comments = new ArrayList<Comment>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
while (num!=0 &&(line = in.readLine()) != null) {
String[] splits = line.split(" ");
Comment comment = new Comment();
comment.setId(Integer.parseInt(splits[0]));
comment.setSentiment(Sentiment.valueOf(splits[1]));
Map<String,Integer> wordsAndFreq = new HashMap<String, Integer>();
for(int i=2;i<splits.length;i+=2){
wordsAndFreq.put(splits[i],Integer.parseInt(splits[i+1]));
}
comment.setWordsAndFreq(wordsAndFreq);
comments.add(comment);
num--;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return comments;
}
}
| 3,411 | 0.55534 | 0.538884 | 92 | 32.684784 | 29.507526 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576087 | false | false | 9 |
a61ea2eaf4c7bcaa2b2e9ad296460b33f5f1a4ea | 17,360,257,868,522 | 6575228eda88d3d36248eede1d140b2044ab16b7 | /src/be/vdab/gui/Main.java | 1b7ca3c388af31a88239af22ad8f6f448cd74541 | []
| no_license | thaduc/vdab | https://github.com/thaduc/vdab | 386179aa032971de08d8ac8a78078595f5607008 | 4adaba7f76e9fd282302c4a180b901a9bdfe3f1e | refs/heads/master | 2021-01-22T15:23:10.923000 | 2016-10-04T07:29:48 | 2016-10-04T07:29:48 | 68,291,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.Container;
import java.awt.FlowLayout;
// w w w . j ava 2s .c o m
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
//contentPane.setLayout(null);
for (int i = 1; i <= 5; i++) {
contentPane.add(new JButton("Button " + i));
}
frame.pack();
frame.setVisible(true);
}
} | UTF-8 | Java | 605 | java | Main.java | Java | []
| null | []
| import java.awt.Container;
import java.awt.FlowLayout;
// w w w . j ava 2s .c o m
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
//contentPane.setLayout(null);
for (int i = 1; i <= 5; i++) {
contentPane.add(new JButton("Button " + i));
}
frame.pack();
frame.setVisible(true);
}
} | 605 | 0.636364 | 0.631405 | 23 | 24.391304 | 18.062065 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false | 9 |
532808b5bc8752622b05de61e6a1c39fa508d6ac | 5,892,695,197,810 | e97fd57a23e674e1f9ac57252b9dba8063795268 | /rockscript/src/main/java/io/rockscript/cqrs/commands/StartScriptExecutionCommand.java | b81efbee60a198e2e056839b744ebede1c6414df | [
"Apache-2.0"
]
| permissive | christian-posta/rockscript | https://github.com/christian-posta/rockscript | e36d4d654da8b5adfa49be8da637141075721244 | 71f8054d1ff0659bb820f469f96b1b5b50173623 | refs/heads/master | 2021-07-17T17:33:35.798000 | 2017-10-21T09:52:17 | 2017-10-21T09:52:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2017, RockScript.io. 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 io.rockscript.cqrs.commands;
import io.rockscript.engine.Configuration;
import io.rockscript.engine.impl.EngineScriptExecution;
import io.rockscript.cqrs.Command;
import java.util.LinkedHashMap;
import java.util.Map;
/** AsyncHttpRequest to start a new script execution.
* StartScriptExecutionCommand's are serializable with Gson */
public class StartScriptExecutionCommand extends Command<EngineStartScriptExecutionResponse> {
protected String scriptName;
protected String scriptId;
protected Object input;
public StartScriptExecutionCommand() {
}
public StartScriptExecutionCommand(Configuration configuration) {
super(configuration);
}
@Override
protected EngineStartScriptExecutionResponse execute(Configuration configuration) {
EngineScriptExecution engineScriptExecution = configuration
.getEngine()
.startScriptExecution(scriptName, scriptId, input);
return new EngineStartScriptExecutionResponse(engineScriptExecution);
}
public String getScriptName() {
return this.scriptName;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
/** (Optional, but this or {@link #scriptId(String)} is Required) the script
* for which the latest version will be started. */
public StartScriptExecutionCommand scriptName(String scriptName) {
this.scriptName = scriptName;
return this;
}
public String getScriptId() {
return this.scriptId;
}
public void setScriptId(String scriptId) {
this.scriptId = scriptId;
}
/** (Optional, but this or {@link #scriptName(String)} is Required) the specific
* script version that has to be started. */
public StartScriptExecutionCommand scriptId(String scriptId) {
this.scriptId = scriptId;
return this;
}
public Object getInput() {
return this.input;
}
public void setInput(Object input) {
this.input = input;
}
/** (Optional) the input data for the script that will be made
* available in the script under system.input */
public StartScriptExecutionCommand input(Object input) {
this.input = input;
return this;
}
public StartScriptExecutionCommand inputProperty(String propertyName, Object propertyValue) {
if (input==null) {
input = new LinkedHashMap<String,Object>();
}
if (!(input instanceof Map)) {
throw new RuntimeException("inputProperty can only be used with maps / script objects");
}
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) this.input;
objectMap.put(propertyName, propertyValue);
return this;
}
}
| UTF-8 | Java | 3,243 | java | StartScriptExecutionCommand.java | Java | []
| null | []
| /*
* Copyright (c) 2017, RockScript.io. 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 io.rockscript.cqrs.commands;
import io.rockscript.engine.Configuration;
import io.rockscript.engine.impl.EngineScriptExecution;
import io.rockscript.cqrs.Command;
import java.util.LinkedHashMap;
import java.util.Map;
/** AsyncHttpRequest to start a new script execution.
* StartScriptExecutionCommand's are serializable with Gson */
public class StartScriptExecutionCommand extends Command<EngineStartScriptExecutionResponse> {
protected String scriptName;
protected String scriptId;
protected Object input;
public StartScriptExecutionCommand() {
}
public StartScriptExecutionCommand(Configuration configuration) {
super(configuration);
}
@Override
protected EngineStartScriptExecutionResponse execute(Configuration configuration) {
EngineScriptExecution engineScriptExecution = configuration
.getEngine()
.startScriptExecution(scriptName, scriptId, input);
return new EngineStartScriptExecutionResponse(engineScriptExecution);
}
public String getScriptName() {
return this.scriptName;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
/** (Optional, but this or {@link #scriptId(String)} is Required) the script
* for which the latest version will be started. */
public StartScriptExecutionCommand scriptName(String scriptName) {
this.scriptName = scriptName;
return this;
}
public String getScriptId() {
return this.scriptId;
}
public void setScriptId(String scriptId) {
this.scriptId = scriptId;
}
/** (Optional, but this or {@link #scriptName(String)} is Required) the specific
* script version that has to be started. */
public StartScriptExecutionCommand scriptId(String scriptId) {
this.scriptId = scriptId;
return this;
}
public Object getInput() {
return this.input;
}
public void setInput(Object input) {
this.input = input;
}
/** (Optional) the input data for the script that will be made
* available in the script under system.input */
public StartScriptExecutionCommand input(Object input) {
this.input = input;
return this;
}
public StartScriptExecutionCommand inputProperty(String propertyName, Object propertyValue) {
if (input==null) {
input = new LinkedHashMap<String,Object>();
}
if (!(input instanceof Map)) {
throw new RuntimeException("inputProperty can only be used with maps / script objects");
}
@SuppressWarnings("unchecked")
Map<String, Object> objectMap = (Map<String, Object>) this.input;
objectMap.put(propertyName, propertyValue);
return this;
}
}
| 3,243 | 0.738205 | 0.735739 | 101 | 31.108912 | 27.376329 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435644 | false | false | 9 |
54609579cdc57014562785dd52fdf6df557bc89b | 738,734,442,282 | 3557536d7dbc678a0c97c472f8fc82c38cf99ccc | /src/net/Board/action/commentAction.java | 1268c1c59422849b9cfe3f220fc3e09e8e6284d6 | []
| no_license | ByeonJaeJeong/LOLSearch | https://github.com/ByeonJaeJeong/LOLSearch | 4ead42b45f11ec8a58cb98a6bfc147645f108f4d | c2366410bd1fe5c7c65f02557fd65a86d3cde9a4 | refs/heads/master | 2020-12-18T06:07:40.439000 | 2020-02-17T09:39:28 | 2020-02-17T09:39:28 | 235,319,692 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.Board.action;
import java.io.PrintWriter;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.Comment.db.commentBean;
import net.Comment.db.commentDAO;
public class commentAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
int w_num=Integer.parseInt(request.getParameter("w_num"));
String pageNum=request.getParameter("pageNum");
System.out.println(w_num);
commentBean cb=new commentBean();
cb.setBoard_num(w_num);
cb.setUser_id(request.getParameter("user_id"));
cb.setUser_nickname(request.getParameter("user_nickName"));
cb.setContent(request.getParameter("content"));
cb.setReg_date(new Timestamp(System.currentTimeMillis()));
cb.setProfile(request.getParameter("profile"));
System.out.println("profile="+request.getParameter("profile"));
commentDAO cdao=new commentDAO();
int check=cdao.insertcomment(cb);
if(check==1){
ActionForward forward=new ActionForward();
forward.setPath("view.net?w_num="+w_num+"&pageNum="+pageNum);
forward.setRedirect(true);
return forward;
}else{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out =response.getWriter();
out.print("<script>");
out.print("alert('데이터입력실패');");
out.print("history.go(-1);");
out.print("</script>");
return null;
}
}
}
| UTF-8 | Java | 1,544 | java | commentAction.java | Java | []
| null | []
| package net.Board.action;
import java.io.PrintWriter;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.Comment.db.commentBean;
import net.Comment.db.commentDAO;
public class commentAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
int w_num=Integer.parseInt(request.getParameter("w_num"));
String pageNum=request.getParameter("pageNum");
System.out.println(w_num);
commentBean cb=new commentBean();
cb.setBoard_num(w_num);
cb.setUser_id(request.getParameter("user_id"));
cb.setUser_nickname(request.getParameter("user_nickName"));
cb.setContent(request.getParameter("content"));
cb.setReg_date(new Timestamp(System.currentTimeMillis()));
cb.setProfile(request.getParameter("profile"));
System.out.println("profile="+request.getParameter("profile"));
commentDAO cdao=new commentDAO();
int check=cdao.insertcomment(cb);
if(check==1){
ActionForward forward=new ActionForward();
forward.setPath("view.net?w_num="+w_num+"&pageNum="+pageNum);
forward.setRedirect(true);
return forward;
}else{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out =response.getWriter();
out.print("<script>");
out.print("alert('데이터입력실패');");
out.print("history.go(-1);");
out.print("</script>");
return null;
}
}
}
| 1,544 | 0.74183 | 0.739216 | 47 | 31.553192 | 22.281382 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.255319 | false | false | 9 |
30a0ed0405f46106ce9b8ebd314c9cf20d31a5f9 | 32,401,233,291,886 | 369ef2198e854c8737b4906558ee764f51fce28a | /src/main/java/com/buaa/act/sdp/service/recommend/classification/LocalClassifier.java | 5970ce2308a7e47b9cf3108ad5a84bad2b17a727 | []
| no_license | yeluting/topcoder | https://github.com/yeluting/topcoder | 87bd39cd8fba8c5e2c0f44698c3dc30724ed7757 | 30a845fe0ba6c9d3ff95fac0428a7c30ac66ef57 | refs/heads/master | 2021-01-01T15:51:48.888000 | 2018-01-05T03:05:34 | 2018-01-05T03:05:34 | 97,714,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.buaa.act.sdp.service.recommend.classification;
import com.buaa.act.sdp.common.Constant;
import com.buaa.act.sdp.util.Maths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by yang on 2017/3/15.
*/
@Service
public class LocalClassifier {
@Autowired
private TcBayes tcBayes;
@Autowired
private TcJ48 tcJ48;
private List<Integer> neighborIndex;
public List<Integer> getNeighborIndex(double[][] features, int position) {
neighborIndex = Maths.getSimilarityChallenges(features, position);
return neighborIndex;
}
public List<Integer> getNeighbors() {
return neighborIndex;
}
public Map<String, Double> getRecommendResult(String challengeType, double[][] features, int position, List<String> winners) {
List<Integer> neighbors = new ArrayList<>(getNeighborIndex(features, position));
neighbors.add(position);
int k = neighbors.size();
double[][] data = new double[k][features[0].length];
List<String> winner = new ArrayList<>(k);
Maths.copy(features, data, winners, winner, neighbors);
Maths.normalization(data, 5);
return tcBayes.getRecommendResult(Constant.LOCAL_DIRECTORY + challengeType + "/" + position, data, k - 1, winner);
}
}
| UTF-8 | Java | 1,431 | java | LocalClassifier.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by yang on 2017/3/15.\n */\n@Service\npublic class LocalClas",
"end": 344,
"score": 0.8697037100791931,
"start": 340,
"tag": "USERNAME",
"value": "yang"
}
]
| null | []
| package com.buaa.act.sdp.service.recommend.classification;
import com.buaa.act.sdp.common.Constant;
import com.buaa.act.sdp.util.Maths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by yang on 2017/3/15.
*/
@Service
public class LocalClassifier {
@Autowired
private TcBayes tcBayes;
@Autowired
private TcJ48 tcJ48;
private List<Integer> neighborIndex;
public List<Integer> getNeighborIndex(double[][] features, int position) {
neighborIndex = Maths.getSimilarityChallenges(features, position);
return neighborIndex;
}
public List<Integer> getNeighbors() {
return neighborIndex;
}
public Map<String, Double> getRecommendResult(String challengeType, double[][] features, int position, List<String> winners) {
List<Integer> neighbors = new ArrayList<>(getNeighborIndex(features, position));
neighbors.add(position);
int k = neighbors.size();
double[][] data = new double[k][features[0].length];
List<String> winner = new ArrayList<>(k);
Maths.copy(features, data, winners, winner, neighbors);
Maths.normalization(data, 5);
return tcBayes.getRecommendResult(Constant.LOCAL_DIRECTORY + challengeType + "/" + position, data, k - 1, winner);
}
}
| 1,431 | 0.703005 | 0.693222 | 43 | 32.279068 | 31.377911 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860465 | false | false | 9 |
4d3d79a4f341412c7852e0b18fc3f78ced459e94 | 3,066,606,702,418 | d905e45cd9bd581c692068336ecaf38b99914bd7 | /app/markets/SimpleMarketsRepository.java | b439c7ac4f10f53d505449d0c8b2340d34ba6d38 | []
| no_license | teraluis/MSRM | https://github.com/teraluis/MSRM | 5add6c34d4027f334cba20b272bbf9e609adcd28 | f78964fc0dcfaa2c0da94c2302699225d59b448c | refs/heads/master | 2023-03-21T11:22:47.339000 | 2021-03-11T15:02:56 | 2021-03-11T15:02:56 | 346,739,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package markets;
import core.BaseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.api.db.Database;
import play.db.NamedDatabase;
import javax.inject.Inject;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class SimpleMarketsRepository extends BaseRepository<SimpleMarket, String> implements MarketsRepository {
protected final Database database;
protected static final Logger logger = LoggerFactory.getLogger(SimpleMarketsRepository.class);
@Inject
SimpleMarketsRepository(@NamedDatabase("crm") Database db) {
super(db, logger);
this.database = db;
}
@Override
protected PreparedStatement buildGetAllRequest(final Connection transaction, final String organization) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=?");
ps.setString(1, organization);
return ps;
}
@Override
protected PreparedStatement buildGetPageRequest(final Connection transaction, final String organization, final Integer offset, final Integer length) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=? LIMIT ? OFFSET ?");
ps.setString(1, organization);
ps.setInt(2, length);
ps.setInt(3, offset);
return ps;
}
@Override
public List<SimpleMarket> getFromEstablishment(final String organisation, final String establishmentId) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets WHERE uuid IN (SELECT markets_id FROM markets_establishments WHERE establishment_id = ?)");
ps.setString(1, establishmentId);
final ResultSet result = ps.executeQuery();
final List<SimpleMarket> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneItem(result, organisation));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<SimpleMarketEstablishment> getMarketEstablishmentByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_establishments WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketEstablishment> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketEstablishment(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketEstablishment parseOneMarketEstablishment(ResultSet result) throws SQLException {
try {
return new SimpleMarketEstablishment(
result.getString("establishment_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
public List<SimpleMarketPeople> getMarketPeopleByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_people WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketPeople> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketPeople(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<SimpleMarketPeople> getPeopleByRole(String organization, String marketId, String role) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_people WHERE markets_id = ? AND role = ?");
ps.setString(1, marketId);
ps.setString(2, role);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketPeople> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketPeople(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketPeople from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketPeople parseOneMarketPeople(ResultSet result) {
try {
return new SimpleMarketPeople(
result.getString("people_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
public List<SimpleMarketUser> getMarketUserByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_users WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketUser> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketUser(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketUser parseOneMarketUser(ResultSet result) {
try {
return new SimpleMarketUser(
result.getString("users_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
protected SimpleMarket parseOneItem(final ResultSet result, final String organization) throws SQLException {
final String uuid = result.getString("uuid");
final String name = result.getString("name");
final String marketNumber = result.getString("market_number");
final Optional<String> status = Optional.ofNullable(result.getString("status"));
final String customerRequirement = result.getString("customer_requirement");
final String agency = result.getString("agencie_id");
final String tenant = result.getString("tenant");
final LocalDate receiveDate = result.getDate("receive_date") != null ? result.getDate("receive_date").toLocalDate() : null;
final LocalDate responseDate = result.getDate("response_date") != null ? result.getDate("response_date").toLocalDate() : null;
final LocalDate returnDate = result.getDate("return_date") != null ? result.getDate("return_date").toLocalDate() : null;
final LocalDate startDate = result.getDate("start_date") != null ? result.getDate("start_date").toLocalDate() : null;
final Integer duration = result.getInt("duration");
final String publicationNumber = result.getString("publication_number");
final String origin = result.getString("origin");
final String estimateVolume = result.getString("estimate_volume");
final String missionOrderType = result.getString("mission_order_type");
final String deadlineModality = result.getString("deadline_modality");
final String dunningModality = result.getString("dunning_modality");
final String interventionCondition = result.getString("intervention_condition");
final String specificReportNaming = result.getString("specific_report_naming");
final String specificReportDisplay = result.getString("specific_report_display");
final String specificBilling = result.getString("specific_billing");
final String missionOrderBillingLink = result.getString("mission_order_billing_link");
final String billingFrequency = result.getString("billing_frequency");
final String warningPoint = result.getString("warning_point");
final String description = result.getString("description");
final String facturationAnalysis = result.getString("facturation_analysis");
return new SimpleMarket(
Optional.of(uuid),
name,
marketNumber,
status,
customerRequirement,
agency,
tenant,
facturationAnalysis,
Optional.ofNullable(receiveDate),
Optional.ofNullable(responseDate),
Optional.ofNullable(returnDate),
Optional.ofNullable(startDate),
Optional.ofNullable(duration),
Optional.ofNullable(publicationNumber),
Optional.ofNullable(origin),
Optional.ofNullable(estimateVolume),
Optional.ofNullable(missionOrderType),
Optional.ofNullable(deadlineModality),
Optional.ofNullable(dunningModality),
Optional.ofNullable(interventionCondition),
Optional.ofNullable(specificReportNaming),
Optional.ofNullable(specificReportDisplay),
Optional.ofNullable(specificBilling),
Optional.ofNullable(missionOrderBillingLink),
Optional.ofNullable(billingFrequency),
Optional.ofNullable(warningPoint),
Optional.ofNullable(description)
);
}
@Override
protected PreparedStatement buildGetRequest(final Connection transaction, final String organization, final String id) throws SQLException {
PreparedStatement ps;
if (organization != null) {
ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=? AND uuid=?");
ps.setString(1, organization);
} else {
ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE uuid=?");
}
ps.setString(2, id);
return ps;
}
@Override
protected PreparedStatement buildSearchRequest(final Connection transaction, final String organization, final String query) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE LOWER(\"name\")::tsvector @@ LOWER(?)::tsquery AND tenant=? LIMIT 100");
ps.setString(1, query);
ps.setString(2, organization);
return ps;
}
@Override
protected PreparedStatement buildSearchPageRequest(final Connection transaction, final String organization, final String query, final Integer offset, final Integer length) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE LOWER(\"name\")::tsvector @@ LOWER(?)::tsquery AND tenant=? LIMIT ? OFFSET ?");
ps.setString(1, query);
ps.setString(2, organization);
ps.setInt(3, length);
ps.setInt(4, offset);
return ps;
}
@Override
protected PreparedStatement buildAddRequest(final Connection transaction, final String organization, final SimpleMarket market) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets\"(uuid, name, market_number, status, tenant, facturation_analysis) values(?, ?, ?, ?, ?, ?)");
ps.setString(1, market.uuid);
ps.setString(2, market.name);
ps.setString(3, market.marketNumber);
ps.setString(4, market.status.orElse(null));
ps.setString(5, organization);
ps.setString(6, market.facturationAnalysis);
return ps;
}
@Override
protected PreparedStatement buildDeleteRequest(final Connection transaction, final String organization, final String id) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets\" WHERE uuid = ? AND tenant = ?");
ps.setString(1, id);
ps.setString(2, organization);
return ps;
}
@Override
protected PreparedStatement buildUpdateRequest(final Connection transaction, final String organization, final SimpleMarket item) throws SQLException {
throw new RuntimeException("Not implemented yet");
}
@Override
public List<Bpu> getBpuByMarket(String market) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"bpu\" WHERE market_id = ?");
ps.setString(1, market);
List<Bpu> items = new ArrayList<>();
final ResultSet result = ps.executeQuery();
while (result.next()) {
items.add(new Bpu(
Optional.ofNullable(result.getString("uuid")),
result.getString("file"),
result.getString("market_id")
));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get bpu by market from database", e);
return new ArrayList<>();
}
});
}
@Override
public Optional<Bpu> getBpu(String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"bpu\" WHERE uuid = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new Bpu(
Optional.ofNullable(result.getString("uuid")),
result.getString("file"),
result.getString("market_id")
));
}
return Optional.empty();
} catch (SQLException e) {
logger.error("Failed to get bpu by market from database", e);
return Optional.empty();
}
});
}
@Override
public Optional<String> addMarket(final String organization, final Market market) {
return database.withTransaction(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets\"(uuid, name, market_number, " +
"status, tenant, agencie_id, receive_date, response_date, return_date, start_date, " +
"duration, publication_number, customer_requirement, origin, estimate_volume, mission_order_type, " +
"deadline_modality, dunning_modality, intervention_condition, specific_report_naming, specific_report_display, " +
"specific_billing, mission_order_billing_link, billing_frequency, warning_point, description, facturation_analysis) " +
"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, market.uuid);
ps.setString(2, market.name);
ps.setString(3, market.marketNumber);
ps.setString(4, market.status.orElse(null));
ps.setString(5, organization);
ps.setString(6, market.agency.uuid);
ps.setDate(7, market.receiveDate.map(Date::valueOf).orElse(null));
ps.setDate(8, market.responseDate.map(Date::valueOf).orElse(null));
ps.setDate(9, market.returnDate.map(Date::valueOf).orElse(null));
ps.setDate(10, market.startDate.map(Date::valueOf).orElse(null));
ps.setInt(11, market.duration.orElse(0));
ps.setString(12, market.publicationNumber.orElse(null));
ps.setString(13, market.customerRequirement);
ps.setString(14, market.origin.orElse(null));
ps.setString(15, market.estimateVolume.orElse(null));
ps.setString(16, market.missionOrderType.orElse(null));
ps.setString(17, market.deadlineModality.orElse(null));
ps.setString(18, market.dunningModality.orElse(null));
ps.setString(19, market.interventionCondition.orElse(null));
ps.setString(20, market.specificReportNaming.orElse(null));
ps.setString(21, market.specificReportDisplay.orElse(null));
ps.setString(22, market.specificBilling.orElse(null));
ps.setString(23, market.missionOrderBillingLink.orElse(null));
ps.setString(24, market.billingFrequency.orElse(null));
ps.setString(25, market.warningPoint.orElse(null));
ps.setString(26, market.description.orElse(null));
ps.setString(27, market.facturationAnalysis);
ps.execute();
ps.close();
Optional<String> id = Optional.ofNullable(market.getId());
if (id.isPresent()) {
if (market.marketEstablishments != null && !market.marketEstablishments.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_establishments\"(markets_id, establishment_id, role) values(?, ?, ?)");
for (MarketEstablishment marketEstablishment : market.marketEstablishments) {
ps.setString(1, id.get());
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, marketEstablishment.role);
ps.addBatch();
}
ps.executeBatch();
ps.close();
}
if (market.marketPeoples != null && !market.marketPeoples.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_people\"(markets_id, people_id, role) values(?, ?, ?)");
for (MarketPeople marketPeople : market.marketPeoples) {
if (marketPeople.people != null) {
ps.setString(1, id.get());
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, marketPeople.role);
ps.addBatch();
}
}
ps.executeBatch();
ps.close();
}
if (market.marketUsers != null && !market.marketUsers.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_users\"(markets_id, users_id, role) values(?, ?, ?)");
for (MarketUser marketUser : market.marketUsers) {
ps.setString(1, id.get());
ps.setString(2, marketUser.user.login);
ps.setString(3, marketUser.role);
ps.addBatch();
}
ps.executeBatch();
ps.close();
}
}
return id;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
try {
transaction.rollback();
} catch (SQLException throwables) {
logger.error("Error during rollback : ", throwables);
}
return Optional.empty();
}
});
}
@Override
public void updateMarket(Market market) {
database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets\" SET name = ?, market_number = ?, " +
"status = ?, tenant = ?, agencie_id = ?, receive_date = ?, response_date = ?, return_date = ?, start_date = ?, " +
"duration = ?, publication_number = ?, customer_requirement = ?, origin = ?, estimate_volume = ?, mission_order_type = ?, " +
"deadline_modality = ?, dunning_modality = ?, intervention_condition = ?, specific_report_naming = ?, specific_report_display = ?, " +
"specific_billing = ?, mission_order_billing_link = ?, billing_frequency = ?, warning_point = ?, description = ?, facturation_analysis = ? where uuid = ?");
ps.setString(1, market.name);
ps.setString(2, market.marketNumber);
ps.setString(3, market.status.orElse(null));
ps.setString(4, market.tenant);
ps.setString(5, market.agency.uuid);
ps.setDate(6, market.receiveDate.map(Date::valueOf).orElse(null));
ps.setDate(7, market.responseDate.map(Date::valueOf).orElse(null));
ps.setDate(8, market.returnDate.map(Date::valueOf).orElse(null));
ps.setDate(9, market.startDate.map(Date::valueOf).orElse(null));
ps.setInt(10, market.duration.orElse(0));
ps.setString(11, market.publicationNumber.orElse(null));
ps.setString(12, market.customerRequirement);
ps.setString(13, market.origin.orElse(null));
ps.setString(14, market.estimateVolume.orElse(null));
ps.setString(15, market.missionOrderType.orElse(null));
ps.setString(16, market.deadlineModality.orElse(null));
ps.setString(17, market.dunningModality.orElse(null));
ps.setString(18, market.interventionCondition.orElse(null));
ps.setString(19, market.specificReportNaming.orElse(null));
ps.setString(20, market.specificReportDisplay.orElse(null));
ps.setString(21, market.specificBilling.orElse(null));
ps.setString(22, market.missionOrderBillingLink.orElse(null));
ps.setString(23, market.billingFrequency.orElse(null));
ps.setString(24, market.warningPoint.orElse(null));
ps.setString(25, market.description.orElse(null));
ps.setString(26, market.uuid);
ps.setString(27, market.facturationAnalysis);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Boolean addContact(MarketPeople marketPeople, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_people\"(markets_id, people_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, marketPeople.role);
ps.execute();
return true;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
return false;
}
});
}
@Override
public void updateContact(MarketPeople marketPeople, String uuid, String peopleUuid, String oldRole) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_people\" SET role = ?, people_id = ? WHERE markets_id = ? AND people_id = ? AND role = ?");
ps.setString(1, marketPeople.role);
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, uuid);
ps.setString(4, peopleUuid);
ps.setString(5, oldRole);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteContact(String uuid, String peopleUuid, String role) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_people\" WHERE markets_id = ? AND people_id = ? AND role = ?");
ps.setString(1, uuid);
ps.setString(2, peopleUuid);
ps.setString(3, role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Boolean addEstablishment(MarketEstablishment marketEstablishment, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_establishments\"(markets_id, establishment_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, marketEstablishment.role);
ps.execute();
return true;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
return false;
}
});
}
@Override
public void updateEstablishment(MarketEstablishment marketEstablishment, String uuid, String establishmentUuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_establishments\" SET role = ?, establishment_id = ? WHERE markets_id = ? AND establishment_id = ?");
ps.setString(1, marketEstablishment.role);
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, uuid);
ps.setString(4, establishmentUuid);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteAccount(String uuid, String establishmentId, String role) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_establishments\" WHERE markets_id = ? AND establishment_id = ? AND role = ?");
ps.setString(1, uuid);
ps.setString(2, establishmentId);
ps.setString(3, role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void addUser(MarketUser marketUser, String uuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_users\"(markets_id, users_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketUser.user.login);
ps.setString(3, marketUser.role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void updateUser(MarketUser marketUser, String uuid, String userUuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_users\" SET role = ?, users_id = ? WHERE markets_id = ? AND users_id = ?");
ps.setString(1, marketUser.role);
ps.setString(2, marketUser.user.login);
ps.setString(3, uuid);
ps.setString(4, userUuid);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteUser(String uuid, String userLogin) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_users\" WHERE markets_id = ? AND users_id = ?");
ps.setString(1, uuid);
ps.setString(2, userLogin);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Optional<String> addReferenceIfNotExist(String uuid, BpuReference reference) {
Optional<BpuReference> ref = database.withConnection(transaction -> {
if (reference.reference.isPresent() && reference.designation.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference = ? AND designation = ? AND market=?");
ps.setString(1, reference.reference.get());
ps.setString(2, reference.designation.get());
ps.setString(3, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else if (reference.reference.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference = ? AND market=? AND designation IS NULL");
ps.setString(1, reference.reference.get());
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else if (reference.designation.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE designation = ? AND market=? AND reference IS NULL");
ps.setString(1, reference.designation.get());
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else {
return Optional.empty();
}
});
if (!ref.isPresent()) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"market_references\"(reference, designation, market, price) VALUES (?, ?, ?, ?)");
ps.setString(1, reference.reference.orElse(null));
ps.setString(2, reference.designation.orElse(null));
ps.setString(3, uuid);
ps.setBigDecimal(4, reference.price);
ps.execute();
return reference.reference;
} catch (SQLException e) {
logger.error("Failed to insert reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
});
} else if (ref.get().price.compareTo(reference.price) != 0) {
return database.withConnection(transaction -> {
try {
if (ref.get().reference.isPresent() && ref.get().designation.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference = ? AND designation = ? AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.reference.get());
ps.setString(3, reference.designation.get());
ps.setString(4, uuid);
ps.execute();
return reference.reference;
} else if (ref.get().reference.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference = ? AND designation IS NULL AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.reference.get());
ps.setString(3, uuid);
ps.execute();
return reference.reference;
} else if (ref.get().designation.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference IS NULL AND designation = ? AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.designation.get());
ps.setString(3, uuid);
ps.execute();
return reference.reference;
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to insert reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
});
} else {
return ref.get().reference;
}
}
@Override
public List<BpuReference> getReferences(String uuid, String searchString) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference LIKE ? AND market = ?");
ps.setString(1, "%" + searchString + "%");
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
final List<BpuReference> references = new ArrayList<>();
while (result.next()) {
references.add(new BpuReference(Optional.ofNullable(result.getString("reference")), Optional.ofNullable(result.getString("designation")), result.getBigDecimal("price")));
}
return references;
} catch (SQLException e) {
logger.error("Failed to get references for market " + uuid + " from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<BpuReference> getReferencesFromDesignation(String uuid, String searchString) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE designation LIKE ? AND market = ?");
ps.setString(1, "%" + searchString + "%");
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
final List<BpuReference> references = new ArrayList<>();
while (result.next()) {
references.add(new BpuReference(Optional.ofNullable(result.getString("reference")), Optional.ofNullable(result.getString("designation")), result.getBigDecimal("price")));
}
return references;
} catch (SQLException e) {
logger.error("Failed to get references for market " + uuid + " from database", e);
return new ArrayList<>();
}
});
}
@Override
public Optional<String> addBpu(String organization, Bpu bpu) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"bpu\"(uuid, file, market_id, tenant) values(?, ?, ?, ?)");
ps.setString(1, bpu.uuid);
ps.setString(2, bpu.file);
ps.setString(3, bpu.market_id);
ps.setString(4, organization);
ps.execute();
return Optional.ofNullable(bpu.getId());
} catch (SQLException e) {
logger.error(String.format("Failed to get references for bpu %s from database", bpu.uuid), e);
return Optional.empty();
}
});
}
@Override
public void deleteBpu(String uuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"bpu\" WHERE uuid = ?");
ps.setString(1, uuid);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public List<MarketComment> getComments(String organization, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_comments\" WHERE id_market=?");
ps.setString(1, uuid);
final List<MarketComment> commentList = new LinkedList<>();
final ResultSet result = ps.executeQuery();
while (result.next()) {
commentList.add(new MarketComment(Optional.of(result.getString("uuid")),
result.getString("id_market"),
Optional.of(result.getString("id_user")),
result.getString("comment"),
new java.util.Date(result.getTimestamp("created").getTime())));
}
return commentList;
} catch (SQLException e) {
logger.error("Failed to get comments from market " + uuid, e);
return new LinkedList<>();
}
});
}
@Override
public Optional<MarketComment> addComment(String organization, MarketComment marketComment) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"market_comments\" (uuid, id_market, id_user, comment, created) VALUES (?, ?, ?, ?, ?)");
ps.setString(1, marketComment.uuid);
ps.setString(2, marketComment.idMarket);
ps.setString(3, marketComment.idUser.orElse(null));
ps.setString(4, marketComment.comment);
ps.setTimestamp(5, new Timestamp(marketComment.created.getTime()));
ps.execute();
return Optional.of(marketComment);
} catch (SQLException e) {
logger.error("Failed to add comment to market " + e.getMessage());
return Optional.empty();
}
});
}
}
| UTF-8 | Java | 41,415 | java | SimpleMarketsRepository.java | Java | []
| null | []
| package markets;
import core.BaseRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.api.db.Database;
import play.db.NamedDatabase;
import javax.inject.Inject;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class SimpleMarketsRepository extends BaseRepository<SimpleMarket, String> implements MarketsRepository {
protected final Database database;
protected static final Logger logger = LoggerFactory.getLogger(SimpleMarketsRepository.class);
@Inject
SimpleMarketsRepository(@NamedDatabase("crm") Database db) {
super(db, logger);
this.database = db;
}
@Override
protected PreparedStatement buildGetAllRequest(final Connection transaction, final String organization) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=?");
ps.setString(1, organization);
return ps;
}
@Override
protected PreparedStatement buildGetPageRequest(final Connection transaction, final String organization, final Integer offset, final Integer length) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=? LIMIT ? OFFSET ?");
ps.setString(1, organization);
ps.setInt(2, length);
ps.setInt(3, offset);
return ps;
}
@Override
public List<SimpleMarket> getFromEstablishment(final String organisation, final String establishmentId) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets WHERE uuid IN (SELECT markets_id FROM markets_establishments WHERE establishment_id = ?)");
ps.setString(1, establishmentId);
final ResultSet result = ps.executeQuery();
final List<SimpleMarket> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneItem(result, organisation));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<SimpleMarketEstablishment> getMarketEstablishmentByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_establishments WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketEstablishment> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketEstablishment(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketEstablishment parseOneMarketEstablishment(ResultSet result) throws SQLException {
try {
return new SimpleMarketEstablishment(
result.getString("establishment_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
public List<SimpleMarketPeople> getMarketPeopleByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_people WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketPeople> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketPeople(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<SimpleMarketPeople> getPeopleByRole(String organization, String marketId, String role) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_people WHERE markets_id = ? AND role = ?");
ps.setString(1, marketId);
ps.setString(2, role);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketPeople> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketPeople(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketPeople from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketPeople parseOneMarketPeople(ResultSet result) {
try {
return new SimpleMarketPeople(
result.getString("people_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
public List<SimpleMarketUser> getMarketUserByMarket(String uuid) {
return database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("SELECT * FROM markets_users WHERE markets_id = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
final List<SimpleMarketUser> items = new ArrayList<>();
while (result.next()) {
items.add(parseOneMarketUser(result));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get MarketEstablishment from database", e);
return new ArrayList<>();
}
});
}
private SimpleMarketUser parseOneMarketUser(ResultSet result) {
try {
return new SimpleMarketUser(
result.getString("users_id"),
result.getString("role")
);
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
@Override
protected SimpleMarket parseOneItem(final ResultSet result, final String organization) throws SQLException {
final String uuid = result.getString("uuid");
final String name = result.getString("name");
final String marketNumber = result.getString("market_number");
final Optional<String> status = Optional.ofNullable(result.getString("status"));
final String customerRequirement = result.getString("customer_requirement");
final String agency = result.getString("agencie_id");
final String tenant = result.getString("tenant");
final LocalDate receiveDate = result.getDate("receive_date") != null ? result.getDate("receive_date").toLocalDate() : null;
final LocalDate responseDate = result.getDate("response_date") != null ? result.getDate("response_date").toLocalDate() : null;
final LocalDate returnDate = result.getDate("return_date") != null ? result.getDate("return_date").toLocalDate() : null;
final LocalDate startDate = result.getDate("start_date") != null ? result.getDate("start_date").toLocalDate() : null;
final Integer duration = result.getInt("duration");
final String publicationNumber = result.getString("publication_number");
final String origin = result.getString("origin");
final String estimateVolume = result.getString("estimate_volume");
final String missionOrderType = result.getString("mission_order_type");
final String deadlineModality = result.getString("deadline_modality");
final String dunningModality = result.getString("dunning_modality");
final String interventionCondition = result.getString("intervention_condition");
final String specificReportNaming = result.getString("specific_report_naming");
final String specificReportDisplay = result.getString("specific_report_display");
final String specificBilling = result.getString("specific_billing");
final String missionOrderBillingLink = result.getString("mission_order_billing_link");
final String billingFrequency = result.getString("billing_frequency");
final String warningPoint = result.getString("warning_point");
final String description = result.getString("description");
final String facturationAnalysis = result.getString("facturation_analysis");
return new SimpleMarket(
Optional.of(uuid),
name,
marketNumber,
status,
customerRequirement,
agency,
tenant,
facturationAnalysis,
Optional.ofNullable(receiveDate),
Optional.ofNullable(responseDate),
Optional.ofNullable(returnDate),
Optional.ofNullable(startDate),
Optional.ofNullable(duration),
Optional.ofNullable(publicationNumber),
Optional.ofNullable(origin),
Optional.ofNullable(estimateVolume),
Optional.ofNullable(missionOrderType),
Optional.ofNullable(deadlineModality),
Optional.ofNullable(dunningModality),
Optional.ofNullable(interventionCondition),
Optional.ofNullable(specificReportNaming),
Optional.ofNullable(specificReportDisplay),
Optional.ofNullable(specificBilling),
Optional.ofNullable(missionOrderBillingLink),
Optional.ofNullable(billingFrequency),
Optional.ofNullable(warningPoint),
Optional.ofNullable(description)
);
}
@Override
protected PreparedStatement buildGetRequest(final Connection transaction, final String organization, final String id) throws SQLException {
PreparedStatement ps;
if (organization != null) {
ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE tenant=? AND uuid=?");
ps.setString(1, organization);
} else {
ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE uuid=?");
}
ps.setString(2, id);
return ps;
}
@Override
protected PreparedStatement buildSearchRequest(final Connection transaction, final String organization, final String query) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE LOWER(\"name\")::tsvector @@ LOWER(?)::tsquery AND tenant=? LIMIT 100");
ps.setString(1, query);
ps.setString(2, organization);
return ps;
}
@Override
protected PreparedStatement buildSearchPageRequest(final Connection transaction, final String organization, final String query, final Integer offset, final Integer length) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"markets\" WHERE LOWER(\"name\")::tsvector @@ LOWER(?)::tsquery AND tenant=? LIMIT ? OFFSET ?");
ps.setString(1, query);
ps.setString(2, organization);
ps.setInt(3, length);
ps.setInt(4, offset);
return ps;
}
@Override
protected PreparedStatement buildAddRequest(final Connection transaction, final String organization, final SimpleMarket market) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets\"(uuid, name, market_number, status, tenant, facturation_analysis) values(?, ?, ?, ?, ?, ?)");
ps.setString(1, market.uuid);
ps.setString(2, market.name);
ps.setString(3, market.marketNumber);
ps.setString(4, market.status.orElse(null));
ps.setString(5, organization);
ps.setString(6, market.facturationAnalysis);
return ps;
}
@Override
protected PreparedStatement buildDeleteRequest(final Connection transaction, final String organization, final String id) throws SQLException {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets\" WHERE uuid = ? AND tenant = ?");
ps.setString(1, id);
ps.setString(2, organization);
return ps;
}
@Override
protected PreparedStatement buildUpdateRequest(final Connection transaction, final String organization, final SimpleMarket item) throws SQLException {
throw new RuntimeException("Not implemented yet");
}
@Override
public List<Bpu> getBpuByMarket(String market) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"bpu\" WHERE market_id = ?");
ps.setString(1, market);
List<Bpu> items = new ArrayList<>();
final ResultSet result = ps.executeQuery();
while (result.next()) {
items.add(new Bpu(
Optional.ofNullable(result.getString("uuid")),
result.getString("file"),
result.getString("market_id")
));
}
return items;
} catch (SQLException e) {
logger.error("Failed to get bpu by market from database", e);
return new ArrayList<>();
}
});
}
@Override
public Optional<Bpu> getBpu(String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"bpu\" WHERE uuid = ?");
ps.setString(1, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new Bpu(
Optional.ofNullable(result.getString("uuid")),
result.getString("file"),
result.getString("market_id")
));
}
return Optional.empty();
} catch (SQLException e) {
logger.error("Failed to get bpu by market from database", e);
return Optional.empty();
}
});
}
@Override
public Optional<String> addMarket(final String organization, final Market market) {
return database.withTransaction(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets\"(uuid, name, market_number, " +
"status, tenant, agencie_id, receive_date, response_date, return_date, start_date, " +
"duration, publication_number, customer_requirement, origin, estimate_volume, mission_order_type, " +
"deadline_modality, dunning_modality, intervention_condition, specific_report_naming, specific_report_display, " +
"specific_billing, mission_order_billing_link, billing_frequency, warning_point, description, facturation_analysis) " +
"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, market.uuid);
ps.setString(2, market.name);
ps.setString(3, market.marketNumber);
ps.setString(4, market.status.orElse(null));
ps.setString(5, organization);
ps.setString(6, market.agency.uuid);
ps.setDate(7, market.receiveDate.map(Date::valueOf).orElse(null));
ps.setDate(8, market.responseDate.map(Date::valueOf).orElse(null));
ps.setDate(9, market.returnDate.map(Date::valueOf).orElse(null));
ps.setDate(10, market.startDate.map(Date::valueOf).orElse(null));
ps.setInt(11, market.duration.orElse(0));
ps.setString(12, market.publicationNumber.orElse(null));
ps.setString(13, market.customerRequirement);
ps.setString(14, market.origin.orElse(null));
ps.setString(15, market.estimateVolume.orElse(null));
ps.setString(16, market.missionOrderType.orElse(null));
ps.setString(17, market.deadlineModality.orElse(null));
ps.setString(18, market.dunningModality.orElse(null));
ps.setString(19, market.interventionCondition.orElse(null));
ps.setString(20, market.specificReportNaming.orElse(null));
ps.setString(21, market.specificReportDisplay.orElse(null));
ps.setString(22, market.specificBilling.orElse(null));
ps.setString(23, market.missionOrderBillingLink.orElse(null));
ps.setString(24, market.billingFrequency.orElse(null));
ps.setString(25, market.warningPoint.orElse(null));
ps.setString(26, market.description.orElse(null));
ps.setString(27, market.facturationAnalysis);
ps.execute();
ps.close();
Optional<String> id = Optional.ofNullable(market.getId());
if (id.isPresent()) {
if (market.marketEstablishments != null && !market.marketEstablishments.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_establishments\"(markets_id, establishment_id, role) values(?, ?, ?)");
for (MarketEstablishment marketEstablishment : market.marketEstablishments) {
ps.setString(1, id.get());
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, marketEstablishment.role);
ps.addBatch();
}
ps.executeBatch();
ps.close();
}
if (market.marketPeoples != null && !market.marketPeoples.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_people\"(markets_id, people_id, role) values(?, ?, ?)");
for (MarketPeople marketPeople : market.marketPeoples) {
if (marketPeople.people != null) {
ps.setString(1, id.get());
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, marketPeople.role);
ps.addBatch();
}
}
ps.executeBatch();
ps.close();
}
if (market.marketUsers != null && !market.marketUsers.isEmpty()) {
ps = transaction.prepareStatement("INSERT INTO \"markets_users\"(markets_id, users_id, role) values(?, ?, ?)");
for (MarketUser marketUser : market.marketUsers) {
ps.setString(1, id.get());
ps.setString(2, marketUser.user.login);
ps.setString(3, marketUser.role);
ps.addBatch();
}
ps.executeBatch();
ps.close();
}
}
return id;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
try {
transaction.rollback();
} catch (SQLException throwables) {
logger.error("Error during rollback : ", throwables);
}
return Optional.empty();
}
});
}
@Override
public void updateMarket(Market market) {
database.withConnection(transaction -> {
try {
PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets\" SET name = ?, market_number = ?, " +
"status = ?, tenant = ?, agencie_id = ?, receive_date = ?, response_date = ?, return_date = ?, start_date = ?, " +
"duration = ?, publication_number = ?, customer_requirement = ?, origin = ?, estimate_volume = ?, mission_order_type = ?, " +
"deadline_modality = ?, dunning_modality = ?, intervention_condition = ?, specific_report_naming = ?, specific_report_display = ?, " +
"specific_billing = ?, mission_order_billing_link = ?, billing_frequency = ?, warning_point = ?, description = ?, facturation_analysis = ? where uuid = ?");
ps.setString(1, market.name);
ps.setString(2, market.marketNumber);
ps.setString(3, market.status.orElse(null));
ps.setString(4, market.tenant);
ps.setString(5, market.agency.uuid);
ps.setDate(6, market.receiveDate.map(Date::valueOf).orElse(null));
ps.setDate(7, market.responseDate.map(Date::valueOf).orElse(null));
ps.setDate(8, market.returnDate.map(Date::valueOf).orElse(null));
ps.setDate(9, market.startDate.map(Date::valueOf).orElse(null));
ps.setInt(10, market.duration.orElse(0));
ps.setString(11, market.publicationNumber.orElse(null));
ps.setString(12, market.customerRequirement);
ps.setString(13, market.origin.orElse(null));
ps.setString(14, market.estimateVolume.orElse(null));
ps.setString(15, market.missionOrderType.orElse(null));
ps.setString(16, market.deadlineModality.orElse(null));
ps.setString(17, market.dunningModality.orElse(null));
ps.setString(18, market.interventionCondition.orElse(null));
ps.setString(19, market.specificReportNaming.orElse(null));
ps.setString(20, market.specificReportDisplay.orElse(null));
ps.setString(21, market.specificBilling.orElse(null));
ps.setString(22, market.missionOrderBillingLink.orElse(null));
ps.setString(23, market.billingFrequency.orElse(null));
ps.setString(24, market.warningPoint.orElse(null));
ps.setString(25, market.description.orElse(null));
ps.setString(26, market.uuid);
ps.setString(27, market.facturationAnalysis);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Boolean addContact(MarketPeople marketPeople, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_people\"(markets_id, people_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, marketPeople.role);
ps.execute();
return true;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
return false;
}
});
}
@Override
public void updateContact(MarketPeople marketPeople, String uuid, String peopleUuid, String oldRole) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_people\" SET role = ?, people_id = ? WHERE markets_id = ? AND people_id = ? AND role = ?");
ps.setString(1, marketPeople.role);
ps.setString(2, marketPeople.people.uuid);
ps.setString(3, uuid);
ps.setString(4, peopleUuid);
ps.setString(5, oldRole);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteContact(String uuid, String peopleUuid, String role) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_people\" WHERE markets_id = ? AND people_id = ? AND role = ?");
ps.setString(1, uuid);
ps.setString(2, peopleUuid);
ps.setString(3, role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Boolean addEstablishment(MarketEstablishment marketEstablishment, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_establishments\"(markets_id, establishment_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, marketEstablishment.role);
ps.execute();
return true;
} catch (SQLException e) {
logger.error("SQL ERROR", e);
return false;
}
});
}
@Override
public void updateEstablishment(MarketEstablishment marketEstablishment, String uuid, String establishmentUuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_establishments\" SET role = ?, establishment_id = ? WHERE markets_id = ? AND establishment_id = ?");
ps.setString(1, marketEstablishment.role);
ps.setString(2, marketEstablishment.establishment.uuid);
ps.setString(3, uuid);
ps.setString(4, establishmentUuid);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteAccount(String uuid, String establishmentId, String role) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_establishments\" WHERE markets_id = ? AND establishment_id = ? AND role = ?");
ps.setString(1, uuid);
ps.setString(2, establishmentId);
ps.setString(3, role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void addUser(MarketUser marketUser, String uuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"markets_users\"(markets_id, users_id, role) values(?, ?, ?)");
ps.setString(1, uuid);
ps.setString(2, marketUser.user.login);
ps.setString(3, marketUser.role);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void updateUser(MarketUser marketUser, String uuid, String userUuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"markets_users\" SET role = ?, users_id = ? WHERE markets_id = ? AND users_id = ?");
ps.setString(1, marketUser.role);
ps.setString(2, marketUser.user.login);
ps.setString(3, uuid);
ps.setString(4, userUuid);
ps.executeUpdate();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public void deleteUser(String uuid, String userLogin) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"markets_users\" WHERE markets_id = ? AND users_id = ?");
ps.setString(1, uuid);
ps.setString(2, userLogin);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public Optional<String> addReferenceIfNotExist(String uuid, BpuReference reference) {
Optional<BpuReference> ref = database.withConnection(transaction -> {
if (reference.reference.isPresent() && reference.designation.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference = ? AND designation = ? AND market=?");
ps.setString(1, reference.reference.get());
ps.setString(2, reference.designation.get());
ps.setString(3, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else if (reference.reference.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference = ? AND market=? AND designation IS NULL");
ps.setString(1, reference.reference.get());
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else if (reference.designation.isPresent()) {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE designation = ? AND market=? AND reference IS NULL");
ps.setString(1, reference.designation.get());
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
if (result.next()) {
return Optional.of(new BpuReference(reference.reference, reference.designation, result.getBigDecimal("price")));
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to get reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
} else {
return Optional.empty();
}
});
if (!ref.isPresent()) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"market_references\"(reference, designation, market, price) VALUES (?, ?, ?, ?)");
ps.setString(1, reference.reference.orElse(null));
ps.setString(2, reference.designation.orElse(null));
ps.setString(3, uuid);
ps.setBigDecimal(4, reference.price);
ps.execute();
return reference.reference;
} catch (SQLException e) {
logger.error("Failed to insert reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
});
} else if (ref.get().price.compareTo(reference.price) != 0) {
return database.withConnection(transaction -> {
try {
if (ref.get().reference.isPresent() && ref.get().designation.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference = ? AND designation = ? AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.reference.get());
ps.setString(3, reference.designation.get());
ps.setString(4, uuid);
ps.execute();
return reference.reference;
} else if (ref.get().reference.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference = ? AND designation IS NULL AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.reference.get());
ps.setString(3, uuid);
ps.execute();
return reference.reference;
} else if (ref.get().designation.isPresent()) {
final PreparedStatement ps = transaction.prepareStatement("UPDATE \"market_references\" SET price = ? WHERE reference IS NULL AND designation = ? AND market = ?");
ps.setBigDecimal(1, reference.price);
ps.setString(2, reference.designation.get());
ps.setString(3, uuid);
ps.execute();
return reference.reference;
} else {
return Optional.empty();
}
} catch (SQLException e) {
logger.error("Failed to insert reference " + reference + " for market " + uuid + " from database", e);
return Optional.empty();
}
});
} else {
return ref.get().reference;
}
}
@Override
public List<BpuReference> getReferences(String uuid, String searchString) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE reference LIKE ? AND market = ?");
ps.setString(1, "%" + searchString + "%");
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
final List<BpuReference> references = new ArrayList<>();
while (result.next()) {
references.add(new BpuReference(Optional.ofNullable(result.getString("reference")), Optional.ofNullable(result.getString("designation")), result.getBigDecimal("price")));
}
return references;
} catch (SQLException e) {
logger.error("Failed to get references for market " + uuid + " from database", e);
return new ArrayList<>();
}
});
}
@Override
public List<BpuReference> getReferencesFromDesignation(String uuid, String searchString) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_references\" WHERE designation LIKE ? AND market = ?");
ps.setString(1, "%" + searchString + "%");
ps.setString(2, uuid);
final ResultSet result = ps.executeQuery();
final List<BpuReference> references = new ArrayList<>();
while (result.next()) {
references.add(new BpuReference(Optional.ofNullable(result.getString("reference")), Optional.ofNullable(result.getString("designation")), result.getBigDecimal("price")));
}
return references;
} catch (SQLException e) {
logger.error("Failed to get references for market " + uuid + " from database", e);
return new ArrayList<>();
}
});
}
@Override
public Optional<String> addBpu(String organization, Bpu bpu) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"bpu\"(uuid, file, market_id, tenant) values(?, ?, ?, ?)");
ps.setString(1, bpu.uuid);
ps.setString(2, bpu.file);
ps.setString(3, bpu.market_id);
ps.setString(4, organization);
ps.execute();
return Optional.ofNullable(bpu.getId());
} catch (SQLException e) {
logger.error(String.format("Failed to get references for bpu %s from database", bpu.uuid), e);
return Optional.empty();
}
});
}
@Override
public void deleteBpu(String uuid) {
database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("DELETE FROM \"bpu\" WHERE uuid = ?");
ps.setString(1, uuid);
ps.execute();
} catch (SQLException e) {
logger.error("SQL ERROR", e);
}
return null;
});
}
@Override
public List<MarketComment> getComments(String organization, String uuid) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("SELECT * FROM \"market_comments\" WHERE id_market=?");
ps.setString(1, uuid);
final List<MarketComment> commentList = new LinkedList<>();
final ResultSet result = ps.executeQuery();
while (result.next()) {
commentList.add(new MarketComment(Optional.of(result.getString("uuid")),
result.getString("id_market"),
Optional.of(result.getString("id_user")),
result.getString("comment"),
new java.util.Date(result.getTimestamp("created").getTime())));
}
return commentList;
} catch (SQLException e) {
logger.error("Failed to get comments from market " + uuid, e);
return new LinkedList<>();
}
});
}
@Override
public Optional<MarketComment> addComment(String organization, MarketComment marketComment) {
return database.withConnection(transaction -> {
try {
final PreparedStatement ps = transaction.prepareStatement("INSERT INTO \"market_comments\" (uuid, id_market, id_user, comment, created) VALUES (?, ?, ?, ?, ?)");
ps.setString(1, marketComment.uuid);
ps.setString(2, marketComment.idMarket);
ps.setString(3, marketComment.idUser.orElse(null));
ps.setString(4, marketComment.comment);
ps.setTimestamp(5, new Timestamp(marketComment.created.getTime()));
ps.execute();
return Optional.of(marketComment);
} catch (SQLException e) {
logger.error("Failed to add comment to market " + e.getMessage());
return Optional.empty();
}
});
}
}
| 41,415 | 0.559797 | 0.554944 | 888 | 45.638512 | 40.015072 | 197 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.960586 | false | false | 9 |
e90004c8ee70a5354706644cb2489ceb7911a65c | 20,701,742,367,031 | dcd5c8fbf108addb29c2d8dc66d46294d2c82efa | /springboot-jpa/src/main/java/com/huzh/springbootjpa/repository/CityRepository.java | 05212e9f3f41f62ea04ccf3743e3b786ebee19ef | []
| no_license | JeeCoding/springboot-demo | https://github.com/JeeCoding/springboot-demo | 0af786a9aadf0aab1528156f57de275b1994ff1f | b6caec17fd9863f28b66387ef8c3dbf16114b029 | refs/heads/master | 2021-06-20T20:42:31.991000 | 2021-04-06T09:42:38 | 2021-04-06T09:42:38 | 202,357,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huzh.springbootjpa.repository;
import com.huzh.springbootjpa.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @ClassName CityRepository
* @Description TODO
* @Date 2019/8/2 17:42
* @Author huzh
* @Version 1.0
*/
public interface CityRepository extends JpaRepository<City, String> {
void deleteByCityId(String id);
City findByCityId(String id);
}
| UTF-8 | Java | 408 | java | CityRepository.java | Java | [
{
"context": "escription TODO\n * @Date 2019/8/2 17:42\n * @Author huzh\n * @Version 1.0\n */\npublic interface CityReposito",
"end": 243,
"score": 0.9997081756591797,
"start": 239,
"tag": "USERNAME",
"value": "huzh"
}
]
| null | []
| package com.huzh.springbootjpa.repository;
import com.huzh.springbootjpa.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @ClassName CityRepository
* @Description TODO
* @Date 2019/8/2 17:42
* @Author huzh
* @Version 1.0
*/
public interface CityRepository extends JpaRepository<City, String> {
void deleteByCityId(String id);
City findByCityId(String id);
}
| 408 | 0.752451 | 0.723039 | 18 | 21.666666 | 21.155508 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
5ddf9d1c19f8ad99a5e94b57d9ee85c9c198dd1b | 30,528,627,551,100 | f407829c24d878fbb9a20d15ab6be490c1ae2de0 | /src/main/java/bridge/sample/v1/Driver.java | cc398c0edf5b1a45c4264655c706580facf05952 | []
| no_license | JUGIstanbul/tasar-m-kal-plar--challenge-5 | https://github.com/JUGIstanbul/tasar-m-kal-plar--challenge-5 | 751c58b8dfd71e4f5028005c185918bbc48fdf49 | bbeda3472e429c6c80c577ca1cd6cc795aa3212e | refs/heads/master | 2023-01-02T00:19:24.229000 | 2020-10-27T17:22:53 | 2020-10-27T17:22:53 | 307,776,204 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bridge.sample.v1;
import bridge.sample.v1.Car;
import bridge.sample.v1.steering.CanDriveCar;
import bridge.sample.v1.steering.CarSteeringWheel;
public class Driver implements CanDriveCar {
private CarSteeringWheel steeringWheel;
@Override
public void handleWheel(CarSteeringWheel steeringWheel) {
this.steeringWheel = steeringWheel;
}
@Override
public void turnLeft() {
steeringWheel.turnLeft();
}
@Override
public void turnRight() {
steeringWheel.turnRight();
}
public void getIn(Car car) {
car.setDriver(this);
}
}
| UTF-8 | Java | 613 | java | Driver.java | Java | []
| null | []
| package bridge.sample.v1;
import bridge.sample.v1.Car;
import bridge.sample.v1.steering.CanDriveCar;
import bridge.sample.v1.steering.CarSteeringWheel;
public class Driver implements CanDriveCar {
private CarSteeringWheel steeringWheel;
@Override
public void handleWheel(CarSteeringWheel steeringWheel) {
this.steeringWheel = steeringWheel;
}
@Override
public void turnLeft() {
steeringWheel.turnLeft();
}
@Override
public void turnRight() {
steeringWheel.turnRight();
}
public void getIn(Car car) {
car.setDriver(this);
}
}
| 613 | 0.688418 | 0.681892 | 30 | 19.433332 | 18.480049 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
9bbcd249aef805c62ad5182c8a84383ae5a9095c | 17,428,977,346,279 | f64393da1d34bef40ef041c5a87e514a5a413ae0 | /app/src/main/java/android/bignerdranch/com/criminalintent/DatePickerActivity.java | d2ccfe97df2f675b1c126668be38fa3c4eeace7c | []
| no_license | develop025/CriminalIntent | https://github.com/develop025/CriminalIntent | 4000894a5a1178ddf041cf5a1acb2144926ee37d | ae97198cc7ca56215238c95c22f83d0414f82e6c | refs/heads/master | 2018-01-16T04:08:18.296000 | 2017-09-07T21:46:58 | 2017-09-07T21:46:58 | 83,163,747 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.bignerdranch.com.criminalintent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import java.util.Date;
public class DatePickerActivity extends SingleFragmentActivity {
private static final String EXTRA_DATE = "extraDate";
public static Intent newIntent(Context packageContext, Date extraDate) {
Intent intent = new Intent(packageContext, DatePickerActivity.class);
intent.putExtra(EXTRA_DATE, extraDate);
return intent;
}
@Override
protected Fragment createFragment() {
Date extraDate = (Date) getIntent().getSerializableExtra(EXTRA_DATE);
return DatePickerFragment.newInstance(extraDate);
}
}
| UTF-8 | Java | 736 | java | DatePickerActivity.java | Java | []
| null | []
| package android.bignerdranch.com.criminalintent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import java.util.Date;
public class DatePickerActivity extends SingleFragmentActivity {
private static final String EXTRA_DATE = "extraDate";
public static Intent newIntent(Context packageContext, Date extraDate) {
Intent intent = new Intent(packageContext, DatePickerActivity.class);
intent.putExtra(EXTRA_DATE, extraDate);
return intent;
}
@Override
protected Fragment createFragment() {
Date extraDate = (Date) getIntent().getSerializableExtra(EXTRA_DATE);
return DatePickerFragment.newInstance(extraDate);
}
}
| 736 | 0.744565 | 0.743207 | 24 | 29.666666 | 27.286545 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 9 |
baeeed31aa87b67f2d8828175b1e4e98b5124f96 | 128,849,088,344 | 7af76c9d634f584de1a8c6eaa6295af6d3547420 | /src/com/eas/elearning/business/AccountTask.java | 16eca63e63a8cae1dc510a0393ea0aea7bc31039 | []
| no_license | thuyttnd91/eLearning | https://github.com/thuyttnd91/eLearning | 6f1f71cfea7fd9cdf511ed21ae7275442d1dc658 | 41dc351ed3c37ce9b3f5838ffc8fb8eac9b127a1 | refs/heads/master | 2016-09-08T01:23:54.550000 | 2013-12-19T02:24:47 | 2013-12-19T02:24:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eas.elearning.business;
import org.holoeverywhere.widget.Toast;
import android.content.Context;
import com.eas.elearning.bean.ObjAccount;
import com.eas.elearning.network.ParamBuilder;
import com.eas.elearning.network.RestConnector;
import com.loopj.android.http.AsyncHttpResponseHandler;
public class AccountTask {
public static void Login(String url,String username,String password,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamLogin(username, password), handler);
}
public static void GetSchools(String url,AsyncHttpResponseHandler handler){
RestConnector.post(url,null, handler);
}
public static void Register(String url,ObjAccount obj,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamsRegister(obj), handler);
}
public static void Forget_Password(String url,String email,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamForgetPassword(email), handler);
}
public static void Update_Account(String url,ObjAccount obj,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamsUpdate(obj), handler);
}
public static void showSuccessToast(Context c,String message){
Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
}
public static void showFailToast(Context c,String message){
Toast.makeText(c,message , Toast.LENGTH_SHORT).show();
}
}
| UTF-8 | Java | 1,415 | java | AccountTask.java | Java | []
| null | []
| package com.eas.elearning.business;
import org.holoeverywhere.widget.Toast;
import android.content.Context;
import com.eas.elearning.bean.ObjAccount;
import com.eas.elearning.network.ParamBuilder;
import com.eas.elearning.network.RestConnector;
import com.loopj.android.http.AsyncHttpResponseHandler;
public class AccountTask {
public static void Login(String url,String username,String password,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamLogin(username, password), handler);
}
public static void GetSchools(String url,AsyncHttpResponseHandler handler){
RestConnector.post(url,null, handler);
}
public static void Register(String url,ObjAccount obj,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamsRegister(obj), handler);
}
public static void Forget_Password(String url,String email,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamForgetPassword(email), handler);
}
public static void Update_Account(String url,ObjAccount obj,AsyncHttpResponseHandler handler){
RestConnector.post(url, ParamBuilder.BuildParamsUpdate(obj), handler);
}
public static void showSuccessToast(Context c,String message){
Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
}
public static void showFailToast(Context c,String message){
Toast.makeText(c,message , Toast.LENGTH_SHORT).show();
}
}
| 1,415 | 0.810601 | 0.810601 | 35 | 39.42857 | 34.262253 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 9 |
5a9905922fb2c8fee2e4d58c6f238d9ecac9ea65 | 24,026,047,121,410 | 46258dcecccd125d24f55f5f8e9266a26fd4d3f1 | /StoryTime/src/com/storytime/client/skill/defense/TrapDefense.java | 3318748b3255e78fde23df1729a8e08abdcf6e5f | []
| no_license | cbchd/CSC495 | https://github.com/cbchd/CSC495 | f1c93260562bb11482e43b0837cc6a4c70522cdc | fe110d948fdbfbb93688202c87415c939083dabb | refs/heads/master | 2021-01-11T11:06:13.304000 | 2014-02-02T01:26:23 | 2014-02-02T01:26:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.storytime.client.skill.defense;
public class TrapDefense extends WordDefense {
private String type = "TRAP_DEFENSE";
@Override
public String getType() {
return type;
}
}
| UTF-8 | Java | 205 | java | TrapDefense.java | Java | []
| null | []
| package com.storytime.client.skill.defense;
public class TrapDefense extends WordDefense {
private String type = "TRAP_DEFENSE";
@Override
public String getType() {
return type;
}
}
| 205 | 0.692683 | 0.692683 | 12 | 15.083333 | 17.456892 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 9 |
fc93e84c3bc38357b51bfa6c1a32c0e03e5b5438 | 24,026,047,124,449 | f4ff65071ab3e0ea87299a715964c233f7662e57 | /HibernateEsempio/src/esempio/Hibernate_es1.java | 866751e7199ac9756f72c6684f919c158c758be1 | []
| no_license | francesca2/HibernateEsempi | https://github.com/francesca2/HibernateEsempi | 5765572d2986a80fd01d8960b95ab8e601d7fc35 | 9e83c73f5924bd82f5e028ff8cf27fa38a8ec17e | refs/heads/master | 2021-01-10T23:52:46.716000 | 2016-10-13T14:11:15 | 2016-10-13T14:11:15 | 70,813,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package esempio;
import hibernateUtil.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Indirizzo;
import model.Utente;
public class Hibernate_es1 {
public static void main(String[] args) {
Utente u1=new Utente();
u1.setNome("AAAAA");
u1.setCognome("aaaaa");
Indirizzo i1=new Indirizzo("Torino", "corso Vittorio");
u1.setIndirizzo(i1);
u1.addString("cccc");
u1.addString("mmmm");
u1.addString("rrrr");
// Utente u2=new Utente(13,"BBBBB","bbbbb");
Utente u2=new Utente();
u2.setNome("BBBBB");
u2.setCognome("bbbbb");
Indirizzo i=new Indirizzo("Torino", "corso Svizzera");
u2.setIndirizzo(i);
u2.addString("lll");
u2.addString("mmmm");
u2.addString("rrrr");
// Utente u3=new Utente();
// u3.setNome("CCCC");
// u3.setCognome("cccc");
Utente u=null;
// SessionFactory sf= new Configuration().configure().buildSessionFactory();
//
// Session session=sf.openSession();
//
// session.beginTransaction();
//per salvare i dati sulla tabella
// session.save(u1);
// session.save(u2);
// session.save(u3);
//per leggere un elemento dalla tabella di cui conosco l'id.
// u=session.get(Utente.class,14);
//per eliminare una riga
// session.delete(u2);
//
// session.getTransaction().commit();
// session.close();
//
// System.out.println(u.getNome()+ " " + u.getCognome());
Session session =HibernateUtil.openSession();
Transaction tx=null;
//Voglio gestire gli eventuali problemi che posso avere nel comunicare con il database
try{
tx=session.getTransaction();
tx.begin();
//lavori da fare
session.save(u1);
session.save(u2);
u=session.get(Utente.class, 3);
tx.commit();
}catch(Exception ex){
//Annulla ogni cosa che abbiamo fatto se c'è stato un problema. Mantiene il database ACID
tx.rollback();
}finally{
session.close();
}
System.out.println(u.getNome()+ " " + u.getIndirizzo().getCittà());
for(String s: u.getLista())
{
System.out.println(s);
}
}
}
| ISO-8859-1 | Java | 2,192 | java | Hibernate_es1.java | Java | []
| null | []
| package esempio;
import hibernateUtil.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import model.Indirizzo;
import model.Utente;
public class Hibernate_es1 {
public static void main(String[] args) {
Utente u1=new Utente();
u1.setNome("AAAAA");
u1.setCognome("aaaaa");
Indirizzo i1=new Indirizzo("Torino", "corso Vittorio");
u1.setIndirizzo(i1);
u1.addString("cccc");
u1.addString("mmmm");
u1.addString("rrrr");
// Utente u2=new Utente(13,"BBBBB","bbbbb");
Utente u2=new Utente();
u2.setNome("BBBBB");
u2.setCognome("bbbbb");
Indirizzo i=new Indirizzo("Torino", "corso Svizzera");
u2.setIndirizzo(i);
u2.addString("lll");
u2.addString("mmmm");
u2.addString("rrrr");
// Utente u3=new Utente();
// u3.setNome("CCCC");
// u3.setCognome("cccc");
Utente u=null;
// SessionFactory sf= new Configuration().configure().buildSessionFactory();
//
// Session session=sf.openSession();
//
// session.beginTransaction();
//per salvare i dati sulla tabella
// session.save(u1);
// session.save(u2);
// session.save(u3);
//per leggere un elemento dalla tabella di cui conosco l'id.
// u=session.get(Utente.class,14);
//per eliminare una riga
// session.delete(u2);
//
// session.getTransaction().commit();
// session.close();
//
// System.out.println(u.getNome()+ " " + u.getCognome());
Session session =HibernateUtil.openSession();
Transaction tx=null;
//Voglio gestire gli eventuali problemi che posso avere nel comunicare con il database
try{
tx=session.getTransaction();
tx.begin();
//lavori da fare
session.save(u1);
session.save(u2);
u=session.get(Utente.class, 3);
tx.commit();
}catch(Exception ex){
//Annulla ogni cosa che abbiamo fatto se c'è stato un problema. Mantiene il database ACID
tx.rollback();
}finally{
session.close();
}
System.out.println(u.getNome()+ " " + u.getIndirizzo().getCittà());
for(String s: u.getLista())
{
System.out.println(s);
}
}
}
| 2,192 | 0.649315 | 0.634703 | 86 | 23.465117 | 19.523806 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.325581 | false | false | 9 |
9cd495042379cbb836f523d02f890342d3f9941e | 31,001,074,006,552 | 1078dd74cf69fbdfaab29b577598d06d11acda6e | /src/com/data/api/createables/FlowTaskCreater.java | f14b22a2fe508cdca64e7829fa57133fb0bbac1e | []
| no_license | TaraLiang93/Razzle-Dazzle-Comics | https://github.com/TaraLiang93/Razzle-Dazzle-Comics | 5fd8f651464019a3bdf7e2e857b8cc7d80b4f135 | d7de0bd7072a7278485485e2d878c3df5ddaf4e8 | refs/heads/master | 2021-01-01T04:15:01.394000 | 2017-09-19T23:11:04 | 2017-09-19T23:11:04 | 97,151,226 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.data.api.createables;
import com.data.api.exceptions.CreateException;
import com.data.api.exceptions.FetchException;
import com.data.api.interfaces.Createable;
import com.data.structure.FlowTask;
/**
* Created by Zhenya on 4/27/16.
*/
public class FlowTaskCreater extends Createable<FlowTask> {
String flowTaskName;
int index;
public FlowTaskCreater(String flowTaskName, int index){
this.flowTaskName = flowTaskName;
this.index = index;
}
@Override
protected FlowTask getEntity() throws CreateException, FetchException {
FlowTask flowTask = new FlowTask();
flowTask.setFlowTaskName(flowTaskName); //set flowTaskName
flowTask.setIndex(index); // set index
return flowTask;
}
}
| UTF-8 | Java | 771 | java | FlowTaskCreater.java | Java | [
{
"context": "rt com.data.structure.FlowTask;\n\n/**\n * Created by Zhenya on 4/27/16.\n */\npublic class FlowTaskCreater exte",
"end": 234,
"score": 0.9084398150444031,
"start": 228,
"tag": "NAME",
"value": "Zhenya"
}
]
| null | []
| package com.data.api.createables;
import com.data.api.exceptions.CreateException;
import com.data.api.exceptions.FetchException;
import com.data.api.interfaces.Createable;
import com.data.structure.FlowTask;
/**
* Created by Zhenya on 4/27/16.
*/
public class FlowTaskCreater extends Createable<FlowTask> {
String flowTaskName;
int index;
public FlowTaskCreater(String flowTaskName, int index){
this.flowTaskName = flowTaskName;
this.index = index;
}
@Override
protected FlowTask getEntity() throws CreateException, FetchException {
FlowTask flowTask = new FlowTask();
flowTask.setFlowTaskName(flowTaskName); //set flowTaskName
flowTask.setIndex(index); // set index
return flowTask;
}
}
| 771 | 0.715953 | 0.709468 | 28 | 26.535715 | 22.84651 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false | 9 |
2eb93e1a5fdad98d0a25eb33cd5294dfc2111680 | 3,633,542,333,698 | 44739ab412c3e4d794a9e114100be8fd57ccbeae | /Gravity_simulator/src/com/me/gravity/Button.java | 67daadeacd01df192dccf693549089284a680fb6 | []
| no_license | Lactor/Particle-Simulator | https://github.com/Lactor/Particle-Simulator | 54c5498fa392b3e6ea8a7a90ad8de951105b4da3 | 81d8b720c50462066f7d7ee990502d6b129dd78e | refs/heads/master | 2016-09-16T04:37:16.484000 | 2013-04-13T12:33:31 | 2013-04-13T12:33:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.me.gravity;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Button {
Vector Pos;
Vector Size;
Sprite T;
public enum ID {ZERO, MASSUP, MASSDOWN,CHARGEUP, CHARGEDOWN,CLEAR, FORCE, WALLS, GREEN, BLUE, YELLOW, BUTUP, BUTDO};
ID id;
public Button(Vector Pos, Vector Size, ID id, Texture T)
{
this.Pos = Pos;
this.Size = Size;
this.id = id;
this.T = new Sprite(T);
this.T.setSize( (float)Size.x, (float)Size.y);
this.T.setOrigin((float)Size.x/2, (float)Size.y/2);
this.T.setPosition((float)Pos.x - T.getWidth()/2 , (float)Pos.y - T.getHeight()/2);
}
public void draw(SpriteBatch b)
{
T.draw(b);
}
public ID isTouched( Vector touch)
{
if(touch.x > Pos.x - Size.x/2 && touch.x < Pos.x + Size.x/2 &&
touch.y > Pos.y - Size.y/2 && touch.y < Pos.y + Size.y/2){
return id;}
return ID.ZERO;
}
public void move(float dx, float dy)
{
this.Pos.x += dx;
this.Pos.y += dy;
this.T.setPosition((float)Pos.x - T.getWidth()/2 , (float)Pos.y - T.getHeight()/2);
}
}
| UTF-8 | Java | 1,127 | java | Button.java | Java | []
| null | []
| package com.me.gravity;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Button {
Vector Pos;
Vector Size;
Sprite T;
public enum ID {ZERO, MASSUP, MASSDOWN,CHARGEUP, CHARGEDOWN,CLEAR, FORCE, WALLS, GREEN, BLUE, YELLOW, BUTUP, BUTDO};
ID id;
public Button(Vector Pos, Vector Size, ID id, Texture T)
{
this.Pos = Pos;
this.Size = Size;
this.id = id;
this.T = new Sprite(T);
this.T.setSize( (float)Size.x, (float)Size.y);
this.T.setOrigin((float)Size.x/2, (float)Size.y/2);
this.T.setPosition((float)Pos.x - T.getWidth()/2 , (float)Pos.y - T.getHeight()/2);
}
public void draw(SpriteBatch b)
{
T.draw(b);
}
public ID isTouched( Vector touch)
{
if(touch.x > Pos.x - Size.x/2 && touch.x < Pos.x + Size.x/2 &&
touch.y > Pos.y - Size.y/2 && touch.y < Pos.y + Size.y/2){
return id;}
return ID.ZERO;
}
public void move(float dx, float dy)
{
this.Pos.x += dx;
this.Pos.y += dy;
this.T.setPosition((float)Pos.x - T.getWidth()/2 , (float)Pos.y - T.getHeight()/2);
}
}
| 1,127 | 0.645963 | 0.635315 | 48 | 22.479166 | 26.723108 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.104167 | false | false | 9 |
cdbbc3a38f515df1724b9af1f659e3d3a4452a0b | 28,123,445,918,998 | 859ba60dbfac16ded1848d24536284039947bfde | /BinaryTree/BinaryTreeByArray.java | 9a5cfee6403281079db5bceb4161d3dc2726208f | []
| no_license | gaurishankar007/Semester3-Java | https://github.com/gaurishankar007/Semester3-Java | 5e9f5fac6e01e77eb59d466b71a98376c153c4c2 | 0fa6e58ed04649d7a14bd4b2ce5425161a441b5c | refs/heads/master | 2023-03-24T00:10:59.029000 | 2021-03-29T02:03:23 | 2021-03-29T02:03:23 | 338,025,985 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package binaryTree;
import java.util.Arrays;
public class BinaryTreeByArray {
int vertex = 7;
String tree [] = new String[vertex];
/*create root*/
public void Root(String root)
{
tree[0] = root;
}
/*create left son of root*/
public void Left(String child, int parent)
{
int index = (parent * 2) + 1;
if (tree[parent] == null) {
System.out.printf("Can't set child at %d, no parent found\n", index);
}
else {
tree[index] = child;
}
}
/*create right son of root*/
public void Right(String child, int parent)
{
int index = (parent * 2) + 2;
if (tree[parent] == null) {
System.out.printf("Can't set child at %d, no parent found\n", index);
}
else {
tree[index] = child;
}
}
public void child(String parent) {
int index = Arrays.binarySearch(tree, parent);
System.out.println(tree[(2*index)+1] + "<==Left " + parent + " Right==>" + tree[(2*index)+2]);
}
public void parent(String child) {
int index = Arrays.binarySearch(tree, child);
System.out.println("Parent of "+child+" is "+tree[(index-1)/2]+".");
}
public void printTree()
{
for (int i = 0; i < 7; i++) {
if (tree[i] != null)
System.out.print(tree[i]);
else
System.out.print("-");
}
}
public static void main(String[] args) {
BinaryTreeByArray obj = new BinaryTreeByArray();
obj.Root("A");
obj.Left("B", 0);
obj.Right("C", 0);
obj.Left("D", 1);
obj.Right("E", 1);
obj.Left("F", 2);
obj.Right("G", 2);
obj.child("B");
obj.parent("G");
obj.printTree();
}
} | UTF-8 | Java | 1,826 | java | BinaryTreeByArray.java | Java | []
| null | []
| package binaryTree;
import java.util.Arrays;
public class BinaryTreeByArray {
int vertex = 7;
String tree [] = new String[vertex];
/*create root*/
public void Root(String root)
{
tree[0] = root;
}
/*create left son of root*/
public void Left(String child, int parent)
{
int index = (parent * 2) + 1;
if (tree[parent] == null) {
System.out.printf("Can't set child at %d, no parent found\n", index);
}
else {
tree[index] = child;
}
}
/*create right son of root*/
public void Right(String child, int parent)
{
int index = (parent * 2) + 2;
if (tree[parent] == null) {
System.out.printf("Can't set child at %d, no parent found\n", index);
}
else {
tree[index] = child;
}
}
public void child(String parent) {
int index = Arrays.binarySearch(tree, parent);
System.out.println(tree[(2*index)+1] + "<==Left " + parent + " Right==>" + tree[(2*index)+2]);
}
public void parent(String child) {
int index = Arrays.binarySearch(tree, child);
System.out.println("Parent of "+child+" is "+tree[(index-1)/2]+".");
}
public void printTree()
{
for (int i = 0; i < 7; i++) {
if (tree[i] != null)
System.out.print(tree[i]);
else
System.out.print("-");
}
}
public static void main(String[] args) {
BinaryTreeByArray obj = new BinaryTreeByArray();
obj.Root("A");
obj.Left("B", 0);
obj.Right("C", 0);
obj.Left("D", 1);
obj.Right("E", 1);
obj.Left("F", 2);
obj.Right("G", 2);
obj.child("B");
obj.parent("G");
obj.printTree();
}
} | 1,826 | 0.5 | 0.489047 | 74 | 23.68919 | 20.850773 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72973 | false | false | 9 |
3803303d0147b9e78f125e5fb11d403ed04aa31e | 8,907,762,234,536 | 083ae73a80574786ebd646f1fec314d3543a23b9 | /src/main/java/it/polimi/ingsw/server/model/fsm/InterruptListener.java | 018ba58a7e99c692cc5c3736b2add51f4fa668fc | []
| no_license | andrea-amadei/ingswAM2021-Amadei-Buccoliero-Buttiglieri | https://github.com/andrea-amadei/ingswAM2021-Amadei-Buccoliero-Buttiglieri | a4794ba591a3f46f140144414a4ba14581ba42e1 | 6a4702ee195eec3ba937ddb24c5108dd09ab688c | refs/heads/master | 2023-06-07T12:34:45.439000 | 2021-07-02T13:03:44 | 2021-07-02T13:03:44 | 343,354,295 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.polimi.ingsw.server.model.fsm;
import it.polimi.ingsw.server.model.actions.Action;
/**
* Interface that defines methods for classes who can handle the interrupts.
*/
public interface InterruptListener {
/**
* Launches the interrupt.
* @param interrupt the interrupt action.
* @param priority the priority of the action.
*/
void launchInterrupt(Action interrupt, int priority);
}
| UTF-8 | Java | 423 | java | InterruptListener.java | Java | []
| null | []
| package it.polimi.ingsw.server.model.fsm;
import it.polimi.ingsw.server.model.actions.Action;
/**
* Interface that defines methods for classes who can handle the interrupts.
*/
public interface InterruptListener {
/**
* Launches the interrupt.
* @param interrupt the interrupt action.
* @param priority the priority of the action.
*/
void launchInterrupt(Action interrupt, int priority);
}
| 423 | 0.716312 | 0.716312 | 16 | 25.4375 | 24.738554 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
27ac936c9eb3da03a84aa323afd7912eddbf1ff9 | 8,907,762,234,208 | 32b72e1dc8b6ee1be2e80bb70a03a021c83db550 | /ast_results/ankidroid_Anki-Android/AnkiDroid/src/main/java/com/ichi2/anki/dialogs/CardBrowserMySearchesDialog.java | fad8ba91185a48851af92296e844ecae83c1f7e2 | []
| no_license | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | https://github.com/cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | d90c41a17e88fcd99d543124eeb6e93f9133cb4a | 0564143d92f8024ff5fa6b659c2baebf827582b1 | refs/heads/master | 2020-07-13T13:53:40.297000 | 2019-01-11T11:51:18 | 2019-01-11T11:51:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // isComment
package com.ichi2.anki.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ichi2.anki.R;
import com.ichi2.anki.analytics.AnalyticsDialogFragment;
import com.ichi2.ui.ButtonItemAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import timber.log.Timber;
public class isClassOrIsInterface extends AnalyticsDialogFragment {
// isComment
public static int isVariable = isIntegerConstant;
// isComment
public static int isVariable = isIntegerConstant;
private static MySearchesDialogListener isVariable;
private ButtonItemAdapter isVariable;
private HashMap<String, String> isVariable;
private ArrayList<String> isVariable;
private String isVariable;
public interface isClassOrIsInterface {
void isMethod(String isParameter);
void isMethod(String isParameter);
void isMethod(String isParameter, String isParameter);
}
public static CardBrowserMySearchesDialog isMethod(HashMap<String, String> isParameter, MySearchesDialogListener isParameter, String isParameter, int isParameter) {
isNameExpr = isNameExpr;
CardBrowserMySearchesDialog isVariable = new CardBrowserMySearchesDialog();
Bundle isVariable = new Bundle();
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod(isNameExpr);
return isNameExpr;
}
@Override
public Dialog isMethod(Bundle isParameter) {
super.isMethod(isNameExpr);
final Resources isVariable = isMethod();
Activity isVariable = isMethod();
final MaterialDialog.Builder isVariable = new MaterialDialog.Builder(isNameExpr);
int isVariable = isMethod().isMethod("isStringConstant");
if (isNameExpr == isNameExpr) {
isNameExpr = (HashMap<String, String>) isMethod().isMethod("isStringConstant");
isNameExpr = new ArrayList<>(isNameExpr.isMethod());
isNameExpr = new ButtonItemAdapter(isNameExpr);
// isComment
isNameExpr.isMethod();
isNameExpr.isMethod(isParameter -> {
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod(isNameExpr);
isMethod().isMethod();
}, isParameter -> {
isNameExpr.isMethod("isStringConstant", isNameExpr);
isMethod(isNameExpr);
});
isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr, null);
} else if (isNameExpr == isNameExpr) {
isNameExpr = isMethod().isMethod("isStringConstant");
isNameExpr.isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr.isFieldAccessExpr, (isParameter, isParameter) -> {
isNameExpr.isMethod("isStringConstant", isNameExpr, isNameExpr);
isNameExpr.isMethod(isNameExpr.isMethod(), isNameExpr);
});
}
MaterialDialog isVariable = isNameExpr.isMethod();
if (isNameExpr.isMethod() != null) {
LinearLayoutManager isVariable = (LinearLayoutManager) isNameExpr.isMethod().isMethod();
DividerItemDecoration isVariable = new DividerItemDecoration(isNameExpr.isMethod().isMethod(), isNameExpr.isMethod());
float isVariable = isNameExpr.isMethod().isFieldAccessExpr;
int isVariable = (int) (isIntegerConstant * isNameExpr + isDoubleConstant);
isNameExpr.isMethod().isMethod(isNameExpr, isIntegerConstant, isNameExpr, isNameExpr);
isNameExpr.isMethod().isMethod(isNameExpr);
}
return isNameExpr;
}
private void isMethod(String isParameter) {
Resources isVariable = isMethod();
new MaterialDialog.Builder(isMethod()).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod((isParameter, isParameter) -> {
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod();
isNameExpr.isMethod();
if (isNameExpr.isMethod() == isIntegerConstant) {
isMethod().isMethod();
}
}).isMethod();
}
}
| UTF-8 | Java | 5,122 | java | CardBrowserMySearchesDialog.java | Java | []
| null | []
| // isComment
package com.ichi2.anki.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ichi2.anki.R;
import com.ichi2.anki.analytics.AnalyticsDialogFragment;
import com.ichi2.ui.ButtonItemAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import timber.log.Timber;
public class isClassOrIsInterface extends AnalyticsDialogFragment {
// isComment
public static int isVariable = isIntegerConstant;
// isComment
public static int isVariable = isIntegerConstant;
private static MySearchesDialogListener isVariable;
private ButtonItemAdapter isVariable;
private HashMap<String, String> isVariable;
private ArrayList<String> isVariable;
private String isVariable;
public interface isClassOrIsInterface {
void isMethod(String isParameter);
void isMethod(String isParameter);
void isMethod(String isParameter, String isParameter);
}
public static CardBrowserMySearchesDialog isMethod(HashMap<String, String> isParameter, MySearchesDialogListener isParameter, String isParameter, int isParameter) {
isNameExpr = isNameExpr;
CardBrowserMySearchesDialog isVariable = new CardBrowserMySearchesDialog();
Bundle isVariable = new Bundle();
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod(isNameExpr);
return isNameExpr;
}
@Override
public Dialog isMethod(Bundle isParameter) {
super.isMethod(isNameExpr);
final Resources isVariable = isMethod();
Activity isVariable = isMethod();
final MaterialDialog.Builder isVariable = new MaterialDialog.Builder(isNameExpr);
int isVariable = isMethod().isMethod("isStringConstant");
if (isNameExpr == isNameExpr) {
isNameExpr = (HashMap<String, String>) isMethod().isMethod("isStringConstant");
isNameExpr = new ArrayList<>(isNameExpr.isMethod());
isNameExpr = new ButtonItemAdapter(isNameExpr);
// isComment
isNameExpr.isMethod();
isNameExpr.isMethod(isParameter -> {
isNameExpr.isMethod("isStringConstant", isNameExpr);
isNameExpr.isMethod(isNameExpr);
isMethod().isMethod();
}, isParameter -> {
isNameExpr.isMethod("isStringConstant", isNameExpr);
isMethod(isNameExpr);
});
isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr, null);
} else if (isNameExpr == isNameExpr) {
isNameExpr = isMethod().isMethod("isStringConstant");
isNameExpr.isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr.isFieldAccessExpr, (isParameter, isParameter) -> {
isNameExpr.isMethod("isStringConstant", isNameExpr, isNameExpr);
isNameExpr.isMethod(isNameExpr.isMethod(), isNameExpr);
});
}
MaterialDialog isVariable = isNameExpr.isMethod();
if (isNameExpr.isMethod() != null) {
LinearLayoutManager isVariable = (LinearLayoutManager) isNameExpr.isMethod().isMethod();
DividerItemDecoration isVariable = new DividerItemDecoration(isNameExpr.isMethod().isMethod(), isNameExpr.isMethod());
float isVariable = isNameExpr.isMethod().isFieldAccessExpr;
int isVariable = (int) (isIntegerConstant * isNameExpr + isDoubleConstant);
isNameExpr.isMethod().isMethod(isNameExpr, isIntegerConstant, isNameExpr, isNameExpr);
isNameExpr.isMethod().isMethod(isNameExpr);
}
return isNameExpr;
}
private void isMethod(String isParameter) {
Resources isVariable = isMethod();
new MaterialDialog.Builder(isMethod()).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod((isParameter, isParameter) -> {
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod();
isNameExpr.isMethod();
if (isNameExpr.isMethod() == isIntegerConstant) {
isMethod().isMethod();
}
}).isMethod();
}
}
| 5,122 | 0.706365 | 0.705584 | 111 | 45.144146 | 52.890476 | 378 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855856 | false | false | 9 |
96de4f5a6e4d7a9f219e11ad6d4ea619ccd00176 | 8,916,352,156,068 | cbc069a5e5046bc49045059578a565cc2d87d53e | /JavaClass/src/bankEx/BankMain.java | 14fc2d4495bdcf5a7f882cea11280776aba0af19 | []
| no_license | yunhyun/javaClass191205 | https://github.com/yunhyun/javaClass191205 | f81c080000bf12fec7bc0c6ac8b5d745703fabce | ef9e6ab6e9a20fd1251860a54f1fa107951c97a9 | refs/heads/master | 2020-09-25T10:04:47.686000 | 2020-01-02T07:50:20 | 2020-01-02T07:50:20 | 225,982,124 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bankEx;
import java.util.ArrayList;
import java.util.Scanner;
public class BankMain {
public static void main(String[] args) {
Client client = null;
Scanner scan = new Scanner(System.in);
ArrayList<Client> clientList = new ArrayList<Client>();
boolean run = true;
while(run) {
System.out.print("기능 선택 1.생성 2.조회 3.입금 4.출금");
int select = scan.nextInt();
switch(select) {
case 1:
int clientNumber = clientList.size()+1;
System.out.print("이름 : ");
String name = scan.next();
System.out.print("계좌 : ");
String accountNumber = scan.next();
System.out.print("입금액 : ");
int balance = scan.nextInt();
client = new Client(clientNumber, name, accountNumber, balance);
clientList.add(client);
break;
case 2:
for(int i=0;i<clientList.size();i++) {
System.out.println(clientList.get(i).toString());
}
break;
default:
System.out.println("없는 메뉴입니다.");
break;
}
}
}
}
| UTF-8 | Java | 1,001 | java | BankMain.java | Java | []
| null | []
| package bankEx;
import java.util.ArrayList;
import java.util.Scanner;
public class BankMain {
public static void main(String[] args) {
Client client = null;
Scanner scan = new Scanner(System.in);
ArrayList<Client> clientList = new ArrayList<Client>();
boolean run = true;
while(run) {
System.out.print("기능 선택 1.생성 2.조회 3.입금 4.출금");
int select = scan.nextInt();
switch(select) {
case 1:
int clientNumber = clientList.size()+1;
System.out.print("이름 : ");
String name = scan.next();
System.out.print("계좌 : ");
String accountNumber = scan.next();
System.out.print("입금액 : ");
int balance = scan.nextInt();
client = new Client(clientNumber, name, accountNumber, balance);
clientList.add(client);
break;
case 2:
for(int i=0;i<clientList.size();i++) {
System.out.println(clientList.get(i).toString());
}
break;
default:
System.out.println("없는 메뉴입니다.");
break;
}
}
}
}
| 1,001 | 0.642782 | 0.634352 | 42 | 21.595238 | 17.625818 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.642857 | false | false | 9 |
4b5eef9e1cc7720d3a5c9542bc1875d3795b7e1a | 16,638,703,320,313 | d73e7924784e44999b3243800c42d409f4de819f | /springBoot/src/main/java/com/local/springBoot/Items.java | 77bd15c2e4f993c2c5c83a62def0fff88f0188cf | []
| no_license | jhansi67/springbootwithmongoBasic | https://github.com/jhansi67/springbootwithmongoBasic | 3bb590d822b868452f141f96c68c9c524a072f5e | fe638e2e8b28cd3d3b9f5e19941bdc72727ed7c7 | refs/heads/master | 2020-03-22T11:06:05.173000 | 2018-07-12T05:15:21 | 2018-07-12T05:15:21 | 139,946,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.local.springBoot;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "items")
public class Items {
@Id
String id;
String itemName;
String itemDesc;
Double itemPrice;
String itemImage;
public Items() {
}
public Items(String id, String itemName, String itemDesc, Double itemPrice, String itemImage) {
super();
this.id = id;
this.itemName = itemName;
this.itemDesc = itemDesc;
this.itemPrice = itemPrice;
this.itemImage = itemImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getitemName() {
return itemName;
}
public void setitemName(String itemName) {
this.itemName = itemName;
}
public String getitemDesc() {
return itemDesc;
}
public void setitemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
public Double getitemPrice() {
return itemPrice;
}
public void setitemPrice(Double itemPrice) {
this.itemPrice = itemPrice;
}
public String getitemImage() {
return itemImage;
}
public void setitemImage(String itemImage) {
this.itemImage = itemImage;
}
}
| UTF-8 | Java | 1,379 | java | Items.java | Java | []
| null | []
| package com.local.springBoot;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "items")
public class Items {
@Id
String id;
String itemName;
String itemDesc;
Double itemPrice;
String itemImage;
public Items() {
}
public Items(String id, String itemName, String itemDesc, Double itemPrice, String itemImage) {
super();
this.id = id;
this.itemName = itemName;
this.itemDesc = itemDesc;
this.itemPrice = itemPrice;
this.itemImage = itemImage;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getitemName() {
return itemName;
}
public void setitemName(String itemName) {
this.itemName = itemName;
}
public String getitemDesc() {
return itemDesc;
}
public void setitemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
public Double getitemPrice() {
return itemPrice;
}
public void setitemPrice(Double itemPrice) {
this.itemPrice = itemPrice;
}
public String getitemImage() {
return itemImage;
}
public void setitemImage(String itemImage) {
this.itemImage = itemImage;
}
}
| 1,379 | 0.614213 | 0.614213 | 70 | 18.671429 | 18.551643 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 9 |
dbdfbd64c0fec73cb52208a1f8bc2362ec993b3d | 15,144,054,751,520 | 56456387c8a2ff1062f34780b471712cc2a49b71 | /com/google/android/gms/internal/zzea.java | 94a99461ed1de046da54ce0816f8711f35fc4174 | []
| no_license | nendraharyo/presensimahasiswa-sourcecode | https://github.com/nendraharyo/presensimahasiswa-sourcecode | 55d4b8e9f6968eaf71a2ea002e0e7f08d16c5a50 | 890fc86782e9b2b4748bdb9f3db946bfb830b252 | refs/heads/master | 2020-05-21T11:21:55.143000 | 2019-05-10T19:03:56 | 2019-05-10T19:03:56 | 186,022,425 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.internal;
import com.google.android.gms.ads.internal.client.AdRequestParcel;
import com.google.android.gms.common.internal.zzx;
import java.util.LinkedList;
class zzea
{
private final LinkedList zzAB;
private final int zzAC;
private final String zzpS;
private AdRequestParcel zzqH;
zzea(AdRequestParcel paramAdRequestParcel, String paramString, int paramInt)
{
zzx.zzz(paramAdRequestParcel);
zzx.zzz(paramString);
LinkedList localLinkedList = new java/util/LinkedList;
localLinkedList.<init>();
this.zzAB = localLinkedList;
this.zzqH = paramAdRequestParcel;
this.zzpS = paramString;
this.zzAC = paramInt;
}
String getAdUnitId()
{
return this.zzpS;
}
int getNetworkType()
{
return this.zzAC;
}
int size()
{
return this.zzAB.size();
}
void zzb(zzdv paramzzdv)
{
zzea.zza localzza = new com/google/android/gms/internal/zzea$zza;
localzza.<init>(this, paramzzdv);
this.zzAB.add(localzza);
AdRequestParcel localAdRequestParcel = this.zzqH;
localzza.zzh(localAdRequestParcel);
}
AdRequestParcel zzei()
{
return this.zzqH;
}
zzea.zza zzej()
{
return (zzea.zza)this.zzAB.remove();
}
}
/* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\android\gms\internal\zzea.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,456 | java | zzea.java | Java | [
{
"context": "ove();\n }\n}\n\n\n/* Location: C:\\Users\\haryo\\Desktop\\enjarify-master\\presensi-enjarify.jar!\\co",
"end": 1295,
"score": 0.9919406771659851,
"start": 1290,
"tag": "USERNAME",
"value": "haryo"
}
]
| null | []
| package com.google.android.gms.internal;
import com.google.android.gms.ads.internal.client.AdRequestParcel;
import com.google.android.gms.common.internal.zzx;
import java.util.LinkedList;
class zzea
{
private final LinkedList zzAB;
private final int zzAC;
private final String zzpS;
private AdRequestParcel zzqH;
zzea(AdRequestParcel paramAdRequestParcel, String paramString, int paramInt)
{
zzx.zzz(paramAdRequestParcel);
zzx.zzz(paramString);
LinkedList localLinkedList = new java/util/LinkedList;
localLinkedList.<init>();
this.zzAB = localLinkedList;
this.zzqH = paramAdRequestParcel;
this.zzpS = paramString;
this.zzAC = paramInt;
}
String getAdUnitId()
{
return this.zzpS;
}
int getNetworkType()
{
return this.zzAC;
}
int size()
{
return this.zzAB.size();
}
void zzb(zzdv paramzzdv)
{
zzea.zza localzza = new com/google/android/gms/internal/zzea$zza;
localzza.<init>(this, paramzzdv);
this.zzAB.add(localzza);
AdRequestParcel localAdRequestParcel = this.zzqH;
localzza.zzh(localAdRequestParcel);
}
AdRequestParcel zzei()
{
return this.zzqH;
}
zzea.zza zzej()
{
return (zzea.zza)this.zzAB.remove();
}
}
/* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\android\gms\internal\zzea.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ | 1,456 | 0.688187 | 0.683379 | 65 | 21.415384 | 23.396839 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446154 | false | false | 9 |
94cf06b72433fddb4866a82cc3ba3be057f996e9 | 32,478,542,704,176 | d38970b0bc8d9ce85e49017ac489cc5bf6c4ff1b | /src/main/java/com/blueway/ekor/uit/pages/impl/LoginPage.java | 8de968cdfe27a97255f5dfb6c419f01415be3afd | []
| no_license | wujuan321/uit | https://github.com/wujuan321/uit | ea8fb2909cb0bbfb4f55098a9c26801cf01c0748 | daa2bf44f43d955fd9579dd73df4a08b4e06a5a2 | refs/heads/master | 2021-01-02T09:16:37.037000 | 2017-08-18T08:30:12 | 2017-08-18T08:30:12 | 99,177,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.blueway.ekor.uit.pages.impl;
import com.blueway.ekor.uit.elements.ILoginPage;
/**
* 登录封装
*
* @author wujuan
*
*/
public class LoginPage extends HomePage implements ILoginPage {
/**
* 登录操作封装
*
* @param username
* @param password
*/
public static void login(String username, String password, String code) {
driver.type(TXT_USERNAME, username);
driver.type(TXT_PASSWORD, password);
driver.type(TXT_CODE, code);
driver.click(BNT_LOGIN);
}
/**
* 检查预期结果与实际结果是否一致
*
* @param excpet
* @param actual
*/
public static void checkUserName(String expected) {
String actual = driver.getText(SPAN_MSG);
driver.isTextCorrect(actual, expected);
}
//退出登录
public static void logout() {
driver.click(LN_QUIT);
}
}
| UTF-8 | Java | 824 | java | LoginPage.java | Java | [
{
"context": "t.elements.ILoginPage;\n\n/**\n * 登录封装\n * \n * @author wujuan\n * \n */\npublic class LoginPage extends HomePage i",
"end": 125,
"score": 0.9994990229606628,
"start": 119,
"tag": "USERNAME",
"value": "wujuan"
}
]
| null | []
| package com.blueway.ekor.uit.pages.impl;
import com.blueway.ekor.uit.elements.ILoginPage;
/**
* 登录封装
*
* @author wujuan
*
*/
public class LoginPage extends HomePage implements ILoginPage {
/**
* 登录操作封装
*
* @param username
* @param password
*/
public static void login(String username, String password, String code) {
driver.type(TXT_USERNAME, username);
driver.type(TXT_PASSWORD, password);
driver.type(TXT_CODE, code);
driver.click(BNT_LOGIN);
}
/**
* 检查预期结果与实际结果是否一致
*
* @param excpet
* @param actual
*/
public static void checkUserName(String expected) {
String actual = driver.getText(SPAN_MSG);
driver.isTextCorrect(actual, expected);
}
//退出登录
public static void logout() {
driver.click(LN_QUIT);
}
}
| 824 | 0.681462 | 0.681462 | 44 | 16.40909 | 19.050552 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 9 |
c22331e1aabdc6104fa7e5199abea2fa7e0b60ac | 317,827,598,001 | 303ce128469ab596d0bc5bbef5a87092cf120523 | /back/src/main/java/com/heeexy/example/service/impl/OrderServiceImpl.java | 82c75b41b1c76e21e12610bc11fe5a1a53cc2bba | []
| no_license | CGB-team/DC | https://github.com/CGB-team/DC | 0ed2e1a056784e3db6a0ad525406193a5020a399 | a1628e9f0a4df01c6323556fb15550ee5a26a5dc | refs/heads/master | 2023-01-06T14:43:58.062000 | 2020-11-04T12:54:46 | 2020-11-04T12:54:46 | 308,545,494 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.heeexy.example.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heeexy.example.dao.CartDao;
import com.heeexy.example.dao.OrderDao;
import com.heeexy.example.dao.OrderItemDao;
import com.heeexy.example.dao.OrderUserDao;
import com.heeexy.example.pojo.Cart;
import com.heeexy.example.pojo.Order;
import com.heeexy.example.pojo.OrderItem;
import com.heeexy.example.pojo.OrderUser;
import com.heeexy.example.service.OrderService;
import com.heeexy.example.service.UserService;
import com.heeexy.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
private OrderItemDao orderItemDao;
@Autowired
private OrderUserDao orderUserDao;
@Autowired
private UserService userService;
@Autowired
private CartDao cartDao;
@Override
public JSONObject loadCart(String userTicket) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw);
return CommonUtil.successJson(carts);
}
@Override
public JSONObject updateItemNum(JSONObject requestJson,String userTicket) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
Long itemId = requestJson.getLong("itemId");
Integer itemNum = requestJson.getInteger("itemNum");
cartDao.updateItemNum(itemId,itemNum);
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("item_id", itemId);
Cart cart = cartDao.selectOne(qw);
Long total = cart.getItemPrice()*cart.getItemNum();
return CommonUtil.successJson(total);
}
@Override
public JSONObject submitOrder(JSONObject requestJson,String username) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
Order order = new Order();
order.setOrderUserId(user_id);
String orderNum = user_id+""+System.currentTimeMillis();
System.out.println(orderNum);
order.setOrderNum(orderNum);
Integer orderTotal = requestJson.getInteger("cartTotal");
order.setOrderTotal(orderTotal);
String orderPayType = requestJson.getString("orderPaytype");
order.setOrderPaytype(orderPayType);
orderDao.insert(order);
QueryWrapper<Cart> qw1 = new QueryWrapper<>();
qw1.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw1);
for(Cart cart:carts){
OrderItem orderItem = new OrderItem();
orderItem.setItemId(cart.getItemId());
orderItem.setItemName(cart.getItemName());
orderItem.setItemPrice(cart.getItemPrice());
orderItem.setItemNum(cart.getItemNum());
orderItem.setOrderNum(orderNum);
orderItemDao.insert(orderItem);
}
QueryWrapper<OrderItem> qw2 = new QueryWrapper<>();
qw2.eq("order_num",orderNum);
List<OrderItem> orderItems = orderItemDao.selectList(qw2);
order.setOrderItems(orderItems);
return CommonUtil.successJson(order);
}
@Override
public JSONObject totalPrice() {
Long total = 0L;
Long user_id = 2232L; //从dc_user对象中找到user_id
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw);
for(int i=0; i< carts.size(); i++){
Cart cartTemp = carts.get(i);
total += cartTemp.getItemPrice()*cartTemp.getItemNum();
}
return CommonUtil.successJson(total);
}
}
| UTF-8 | Java | 4,199 | java | OrderServiceImpl.java | Java | []
| null | []
| package com.heeexy.example.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.heeexy.example.dao.CartDao;
import com.heeexy.example.dao.OrderDao;
import com.heeexy.example.dao.OrderItemDao;
import com.heeexy.example.dao.OrderUserDao;
import com.heeexy.example.pojo.Cart;
import com.heeexy.example.pojo.Order;
import com.heeexy.example.pojo.OrderItem;
import com.heeexy.example.pojo.OrderUser;
import com.heeexy.example.service.OrderService;
import com.heeexy.example.service.UserService;
import com.heeexy.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
private OrderItemDao orderItemDao;
@Autowired
private OrderUserDao orderUserDao;
@Autowired
private UserService userService;
@Autowired
private CartDao cartDao;
@Override
public JSONObject loadCart(String userTicket) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw);
return CommonUtil.successJson(carts);
}
@Override
public JSONObject updateItemNum(JSONObject requestJson,String userTicket) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
Long itemId = requestJson.getLong("itemId");
Integer itemNum = requestJson.getInteger("itemNum");
cartDao.updateItemNum(itemId,itemNum);
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("item_id", itemId);
Cart cart = cartDao.selectOne(qw);
Long total = cart.getItemPrice()*cart.getItemNum();
return CommonUtil.successJson(total);
}
@Override
public JSONObject submitOrder(JSONObject requestJson,String username) {
String wait_id = "在sys_user里找到跟dc_user关联的字段";
Long user_id = 2232L; //从dc_user对象中找到user_id
Order order = new Order();
order.setOrderUserId(user_id);
String orderNum = user_id+""+System.currentTimeMillis();
System.out.println(orderNum);
order.setOrderNum(orderNum);
Integer orderTotal = requestJson.getInteger("cartTotal");
order.setOrderTotal(orderTotal);
String orderPayType = requestJson.getString("orderPaytype");
order.setOrderPaytype(orderPayType);
orderDao.insert(order);
QueryWrapper<Cart> qw1 = new QueryWrapper<>();
qw1.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw1);
for(Cart cart:carts){
OrderItem orderItem = new OrderItem();
orderItem.setItemId(cart.getItemId());
orderItem.setItemName(cart.getItemName());
orderItem.setItemPrice(cart.getItemPrice());
orderItem.setItemNum(cart.getItemNum());
orderItem.setOrderNum(orderNum);
orderItemDao.insert(orderItem);
}
QueryWrapper<OrderItem> qw2 = new QueryWrapper<>();
qw2.eq("order_num",orderNum);
List<OrderItem> orderItems = orderItemDao.selectList(qw2);
order.setOrderItems(orderItems);
return CommonUtil.successJson(order);
}
@Override
public JSONObject totalPrice() {
Long total = 0L;
Long user_id = 2232L; //从dc_user对象中找到user_id
QueryWrapper<Cart> qw = new QueryWrapper<>();
qw.eq("user_id",user_id);
List<Cart> carts = cartDao.selectList(qw);
for(int i=0; i< carts.size(); i++){
Cart cartTemp = carts.get(i);
total += cartTemp.getItemPrice()*cartTemp.getItemNum();
}
return CommonUtil.successJson(total);
}
}
| 4,199 | 0.682229 | 0.676363 | 108 | 36.879631 | 20.075651 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.787037 | false | false | 9 |
fc4097fb72c1a13eefc5effef22d915f14d63f28 | 13,846,974,573,239 | 2428c597952aef58597e1237b50c574d8f5b9994 | /Dao/RmesDao.java | faca32ddd5944e6122f3dcdb57644b0801590ae2 | []
| no_license | handongopqwe/Hotel | https://github.com/handongopqwe/Hotel | 20dcb537c91f42afae4a24ac04731fa067217eed | cd68ef80a01f817d29d51bb149967ff1f3983178 | refs/heads/master | 2021-01-24T06:30:32.824000 | 2015-06-29T08:11:38 | 2015-06-29T08:11:38 | 38,236,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import entity.*;
import DBjavaCon.DBcon;
public class RmesDao {
public void pddCourse(RmesCourse ce){
DBcon db;
String sql="insert into Ruzhu (Rsh) values('"+ce.getSh()+"');";
try{
db=new DBcon();
db.doInsert(sql);
db.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public List<RuzhuCourse> getAll(String sql){
List<RuzhuCourse> list=new ArrayList<RuzhuCourse>();
RuzhuCourse c;
DBcon db;
ResultSet rs;
String sql1="select * from Ruzhu";
try{
db=new DBcon();
rs=db.doSelect(sql1);
while(rs.next()){
c=new RuzhuCourse(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),Integer.parseInt(rs.getString(5)),rs.getString(6));
list.add(c);
}
db.close(rs);
}catch (Exception e){
System.out.print(e.getMessage());
}
return list;
}
}
| UTF-8 | Java | 921 | java | RmesDao.java | Java | []
| null | []
| package dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import entity.*;
import DBjavaCon.DBcon;
public class RmesDao {
public void pddCourse(RmesCourse ce){
DBcon db;
String sql="insert into Ruzhu (Rsh) values('"+ce.getSh()+"');";
try{
db=new DBcon();
db.doInsert(sql);
db.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public List<RuzhuCourse> getAll(String sql){
List<RuzhuCourse> list=new ArrayList<RuzhuCourse>();
RuzhuCourse c;
DBcon db;
ResultSet rs;
String sql1="select * from Ruzhu";
try{
db=new DBcon();
rs=db.doSelect(sql1);
while(rs.next()){
c=new RuzhuCourse(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),Integer.parseInt(rs.getString(5)),rs.getString(6));
list.add(c);
}
db.close(rs);
}catch (Exception e){
System.out.print(e.getMessage());
}
return list;
}
}
| 921 | 0.67101 | 0.662324 | 40 | 22.025 | 23.463255 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.475 | false | false | 9 |
5f96a0dfe0251d21645b79af71912adeb02089c2 | 1,228,360,663,451 | 278abb4104700519a3b4b848be89058eb2c0998c | /src/main/java/com/jp/dtre/service/DailyTradeReportService.java | 4ae704df0c2cbd79fc8c85bf93fd2c4363f858ce | []
| no_license | betsyjacob/DailyTradeReportEngine | https://github.com/betsyjacob/DailyTradeReportEngine | 0aa640695c297819f4556ae266c337e33fa71bf0 | b3fd2ec928be2beef9ee4b4f6ff56b097d51cbdb | refs/heads/master | 2021-01-01T15:20:33.307000 | 2017-07-18T14:09:38 | 2017-07-18T14:09:38 | 97,595,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jp.dtre.service;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.jp.dtre.model.DailyTradeReportModel;
import com.jp.dtre.util.CommonUtils;
public class DailyTradeReportService {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
CommonUtils util = new CommonUtils();
public void readJsonData(String fileName) {
JSONParser parser = new JSONParser();
try {
URL in = DailyTradeReportService.class.getClassLoader().getResource(fileName);
File file = new File(in.getFile());
JSONArray a = (JSONArray) parser.parse(new FileReader(file));
Double totalBuy =0.0;
Double totalSell =0.0;
List<DailyTradeReportModel> totBuyList = new ArrayList<DailyTradeReportModel>();
List<DailyTradeReportModel> totSellList = new ArrayList<DailyTradeReportModel>();
Map<Date,List<DailyTradeReportModel>> mpBuyGroups = new HashMap<Date,List<DailyTradeReportModel>>();
Map<Date,List<DailyTradeReportModel>> mpSellGroups = new HashMap<Date,List<DailyTradeReportModel>>();
for (Object o : a) {
JSONObject jsonObject = (JSONObject) o;
String entity = (String) jsonObject.get("entity");
String action = (String) jsonObject.get("action");
Double agreedfx = (Double) jsonObject.get("agreedfx");
String currency = (String) jsonObject.get("currency");
Calendar instructiondate = util.getCalendarFormat((String) jsonObject.get("instructiondate"));
Calendar settlementdate = adjustSettlementDates(currency,(String) jsonObject.get("settlementdate"));
Long units = (Long) jsonObject.get("units");
Double unitprice = (Double) jsonObject.get("unitprice");
Double totalUSD = unitprice * units * agreedfx;
DailyTradeReportModel mdl = new DailyTradeReportModel(entity, action, agreedfx, currency,
instructiondate, settlementdate, units, unitprice,totalUSD);
List<DailyTradeReportModel> lst = new ArrayList<DailyTradeReportModel>();
if(action.equals("B")){
totBuyList.add(mdl);
totalBuy += totalUSD;
//grouping based on settlement Date
if(mpBuyGroups.containsKey(settlementdate.getTime())){
lst = (List<DailyTradeReportModel>) mpBuyGroups.get(settlementdate.getTime());
}
lst.add(mdl);
mpBuyGroups.put(settlementdate.getTime(), lst);
}else{
totSellList.add(mdl);
totalSell += totalUSD;
//grouping based on settlement Date
if(mpSellGroups.containsKey(settlementdate.getTime())){
lst = (List<DailyTradeReportModel>) mpSellGroups.get(settlementdate.getTime());
}
lst.add(mdl);
mpSellGroups.put(settlementdate.getTime(), lst);
}
}
util.generateHeader("TRADING REPORT BASED ON SETTLEMENT DATE");
showReport(mpBuyGroups,"Outgoing (BUY)");
showReport(mpSellGroups,"Incoming (SELL)");
util.generateHeader("SUMMARY (OVERALL) TRADING REPORT");
System.out.println("Total Amount Outgoing (BUY) : USD "+totalBuy+"\n");
System.out.println("Total Amount Incoming (SELL) : USD "+totalSell+"\n");
util.generateSubHeaderReport("Overall Outgoing (BUY) Ranking");
getRanking(totBuyList);
util.generateSubHeaderReport("Overall Incoming (SELL) Ranking");
getRanking(totSellList);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getRanking(List<DailyTradeReportModel> tradeSet) {
tradeSet.sort(Comparator.comparing(l -> ((DailyTradeReportModel) l).getTotAmount())
.thenComparing(l -> ((DailyTradeReportModel) l).getStrEntityName())
.reversed());
tradeSet.forEach(System.out::println);
}
public void showReport(Map<Date,List<DailyTradeReportModel>> mpData,String str){
Map<Date,List<DailyTradeReportModel>> buyGroups = new HashMap<Date,List<DailyTradeReportModel>>();
for (Entry<Date, List<DailyTradeReportModel>> entry : mpData.entrySet()) {
Date key = entry.getKey();
List<DailyTradeReportModel> value = entry.getValue();
Double totalVal = 0.0;
for(DailyTradeReportModel mdl :value){
totalVal += mdl.getTotAmount();
}
util.generateSubHeader("Report of : "+sdf.format(key));
System.out.println("Total Amount "+str+" : USD "+totalVal+"\n");
util.generateSubHeaderReport(str+" Ranking");
getRanking(value);
}
}
public Calendar adjustSettlementDates(String currency, String strDate){
Calendar cal = util.getCalendarFormat(strDate);
if(currency.equals("AED") || currency.equals("SAR")){
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY ){
cal.add(Calendar.DATE, 2);
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
cal.add(Calendar.DATE, 1);
}
}else{
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
cal.add(Calendar.DATE, 2);
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
cal.add(Calendar.DATE, 1);
}
}
return cal;
}
}
| UTF-8 | Java | 5,276 | java | DailyTradeReportService.java | Java | []
| null | []
| package com.jp.dtre.service;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.jp.dtre.model.DailyTradeReportModel;
import com.jp.dtre.util.CommonUtils;
public class DailyTradeReportService {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
CommonUtils util = new CommonUtils();
public void readJsonData(String fileName) {
JSONParser parser = new JSONParser();
try {
URL in = DailyTradeReportService.class.getClassLoader().getResource(fileName);
File file = new File(in.getFile());
JSONArray a = (JSONArray) parser.parse(new FileReader(file));
Double totalBuy =0.0;
Double totalSell =0.0;
List<DailyTradeReportModel> totBuyList = new ArrayList<DailyTradeReportModel>();
List<DailyTradeReportModel> totSellList = new ArrayList<DailyTradeReportModel>();
Map<Date,List<DailyTradeReportModel>> mpBuyGroups = new HashMap<Date,List<DailyTradeReportModel>>();
Map<Date,List<DailyTradeReportModel>> mpSellGroups = new HashMap<Date,List<DailyTradeReportModel>>();
for (Object o : a) {
JSONObject jsonObject = (JSONObject) o;
String entity = (String) jsonObject.get("entity");
String action = (String) jsonObject.get("action");
Double agreedfx = (Double) jsonObject.get("agreedfx");
String currency = (String) jsonObject.get("currency");
Calendar instructiondate = util.getCalendarFormat((String) jsonObject.get("instructiondate"));
Calendar settlementdate = adjustSettlementDates(currency,(String) jsonObject.get("settlementdate"));
Long units = (Long) jsonObject.get("units");
Double unitprice = (Double) jsonObject.get("unitprice");
Double totalUSD = unitprice * units * agreedfx;
DailyTradeReportModel mdl = new DailyTradeReportModel(entity, action, agreedfx, currency,
instructiondate, settlementdate, units, unitprice,totalUSD);
List<DailyTradeReportModel> lst = new ArrayList<DailyTradeReportModel>();
if(action.equals("B")){
totBuyList.add(mdl);
totalBuy += totalUSD;
//grouping based on settlement Date
if(mpBuyGroups.containsKey(settlementdate.getTime())){
lst = (List<DailyTradeReportModel>) mpBuyGroups.get(settlementdate.getTime());
}
lst.add(mdl);
mpBuyGroups.put(settlementdate.getTime(), lst);
}else{
totSellList.add(mdl);
totalSell += totalUSD;
//grouping based on settlement Date
if(mpSellGroups.containsKey(settlementdate.getTime())){
lst = (List<DailyTradeReportModel>) mpSellGroups.get(settlementdate.getTime());
}
lst.add(mdl);
mpSellGroups.put(settlementdate.getTime(), lst);
}
}
util.generateHeader("TRADING REPORT BASED ON SETTLEMENT DATE");
showReport(mpBuyGroups,"Outgoing (BUY)");
showReport(mpSellGroups,"Incoming (SELL)");
util.generateHeader("SUMMARY (OVERALL) TRADING REPORT");
System.out.println("Total Amount Outgoing (BUY) : USD "+totalBuy+"\n");
System.out.println("Total Amount Incoming (SELL) : USD "+totalSell+"\n");
util.generateSubHeaderReport("Overall Outgoing (BUY) Ranking");
getRanking(totBuyList);
util.generateSubHeaderReport("Overall Incoming (SELL) Ranking");
getRanking(totSellList);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getRanking(List<DailyTradeReportModel> tradeSet) {
tradeSet.sort(Comparator.comparing(l -> ((DailyTradeReportModel) l).getTotAmount())
.thenComparing(l -> ((DailyTradeReportModel) l).getStrEntityName())
.reversed());
tradeSet.forEach(System.out::println);
}
public void showReport(Map<Date,List<DailyTradeReportModel>> mpData,String str){
Map<Date,List<DailyTradeReportModel>> buyGroups = new HashMap<Date,List<DailyTradeReportModel>>();
for (Entry<Date, List<DailyTradeReportModel>> entry : mpData.entrySet()) {
Date key = entry.getKey();
List<DailyTradeReportModel> value = entry.getValue();
Double totalVal = 0.0;
for(DailyTradeReportModel mdl :value){
totalVal += mdl.getTotAmount();
}
util.generateSubHeader("Report of : "+sdf.format(key));
System.out.println("Total Amount "+str+" : USD "+totalVal+"\n");
util.generateSubHeaderReport(str+" Ranking");
getRanking(value);
}
}
public Calendar adjustSettlementDates(String currency, String strDate){
Calendar cal = util.getCalendarFormat(strDate);
if(currency.equals("AED") || currency.equals("SAR")){
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY ){
cal.add(Calendar.DATE, 2);
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
cal.add(Calendar.DATE, 1);
}
}else{
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
cal.add(Calendar.DATE, 2);
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
cal.add(Calendar.DATE, 1);
}
}
return cal;
}
}
| 5,276 | 0.709439 | 0.707544 | 147 | 34.891155 | 28.527855 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.292517 | false | false | 9 |
857b3087881d27acd2082f0e311600f6e006c6e1 | 5,368,709,183,621 | 2efa4164f32d646f0f4cac8e2fc1e5a5388b99c4 | /src/main/java/com/target/myretail/model/ProductPriceData.java | d57945638611103c2814b3596c05081b992a494a | []
| no_license | rdramana85/myretail | https://github.com/rdramana85/myretail | b45764b7b349629c3f54dadfffd322f5c603613a | ed581b3df8bf1a28760bfbaecf5ac6ebbf97222f | refs/heads/master | 2020-03-28T07:05:13.266000 | 2016-08-11T20:03:21 | 2016-08-11T20:03:21 | 65,260,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.target.myretail.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class ProductPriceData {
private Long productId;
@NotNull(message="price cannot be empty")
private Float price;
@NotNull(message="currency code cannot be empty")
@Size(min=3,message="currency code should have atleast 3 characters")
private String currencyCode;
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
@Override
public String toString() {
String str = "{\nProductId-->"+productId+"\n";
str += "Price-->"+price+" "+currencyCode+"\n";
return str;
}
}
| UTF-8 | Java | 1,019 | java | ProductPriceData.java | Java | []
| null | []
| package com.target.myretail.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class ProductPriceData {
private Long productId;
@NotNull(message="price cannot be empty")
private Float price;
@NotNull(message="currency code cannot be empty")
@Size(min=3,message="currency code should have atleast 3 characters")
private String currencyCode;
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
@Override
public String toString() {
String str = "{\nProductId-->"+productId+"\n";
str += "Price-->"+price+" "+currencyCode+"\n";
return str;
}
}
| 1,019 | 0.680079 | 0.678116 | 51 | 17.980392 | 18.784109 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.27451 | false | false | 9 |
2ee63df4b8b430948b1aa08ae94242595a253603 | 29,721,173,695,372 | d53a0471758ed5d63032bfb55abb27725bfd4ab8 | /app/src/main/java/com/firebase/androidchat/MainActivity.java | 2ff38fecacd3d49387357f15a6e1a2a4fe12448f | [
"MIT"
]
| permissive | rawatshona/ChatAppFirstBuild | https://github.com/rawatshona/ChatAppFirstBuild | dcec1cf9412b6ccfc81faf70bac8744ba15a1e3e | 92ff502e7c4b3b993baec9fcf8483943bb15498d | refs/heads/master | 2021-01-17T17:23:34.190000 | 2016-05-27T06:23:31 | 2016-05-27T06:23:31 | 59,831,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.firebase.androidchat;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.util.Random;
public class MainActivity extends ListActivity {
private static final String URL = "https://apptestfor.firebaseio.com/";
private String myUserName;
private Firebase refVariable;
private ChatListAdapter mChatListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isRegister();
setTitle("Chatting as " + myUserName);
refVariable = new Firebase(URL);
EditText inputText = (EditText) findViewById(R.id.messageInput);
inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
}
return true;
}
});
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
}
@Override
public void onStart() {
super.onStart();
final ListView listView = getListView();
mChatListAdapter = new ChatListAdapter(refVariable.limit(50), this, R.layout.chat_message, myUserName);
listView.setAdapter(mChatListAdapter);
mChatListAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
listView.setSelection(mChatListAdapter.getCount() - 1);
}
});
}
@Override
protected void onPause() {
super.onPause();
this.finish();
}
@Override
public void onStop() {
super.onStop();
mChatListAdapter.cleanup();
}
private void isRegister() {
SharedPreferences prefs = getApplication().getSharedPreferences("ChatPrefs", 0);
myUserName = prefs.getString("myusername", null);
if (myUserName == null) {
Intent i=new Intent(this,Registration.class);
startActivity(i);
}
}
private void sendMessage() {
EditText inputText = (EditText) findViewById(R.id.messageInput);
String input = inputText.getText().toString();
if (!input.equals("")) {
Chat chat = new Chat(input, myUserName);
refVariable.push().setValue(chat);
inputText.setText("");
}
}
}
| UTF-8 | Java | 3,269 | java | MainActivity.java | Java | [
{
"context": "//apptestfor.firebaseio.com/\";\n\n private String myUserName;\n private Firebase refVariable;\n\n private C",
"end": 784,
"score": 0.9921556711196899,
"start": 774,
"tag": "USERNAME",
"value": "myUserName"
},
{
"context": " isRegister();\n\n setTitle(\"Chatting as \" + myUserName);\n\n refVariable = new Firebase(URL);\n\n ",
"end": 1099,
"score": 0.9880416393280029,
"start": 1089,
"tag": "USERNAME",
"value": "myUserName"
},
{
"context": "Prefs\", 0);\n myUserName = prefs.getString(\"myusername\", null);\n if (myUserName == null) {\n ",
"end": 2773,
"score": 0.9988539218902588,
"start": 2763,
"tag": "USERNAME",
"value": "myusername"
}
]
| null | []
| package com.firebase.androidchat;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.util.Random;
public class MainActivity extends ListActivity {
private static final String URL = "https://apptestfor.firebaseio.com/";
private String myUserName;
private Firebase refVariable;
private ChatListAdapter mChatListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isRegister();
setTitle("Chatting as " + myUserName);
refVariable = new Firebase(URL);
EditText inputText = (EditText) findViewById(R.id.messageInput);
inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
}
return true;
}
});
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
}
@Override
public void onStart() {
super.onStart();
final ListView listView = getListView();
mChatListAdapter = new ChatListAdapter(refVariable.limit(50), this, R.layout.chat_message, myUserName);
listView.setAdapter(mChatListAdapter);
mChatListAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
listView.setSelection(mChatListAdapter.getCount() - 1);
}
});
}
@Override
protected void onPause() {
super.onPause();
this.finish();
}
@Override
public void onStop() {
super.onStop();
mChatListAdapter.cleanup();
}
private void isRegister() {
SharedPreferences prefs = getApplication().getSharedPreferences("ChatPrefs", 0);
myUserName = prefs.getString("myusername", null);
if (myUserName == null) {
Intent i=new Intent(this,Registration.class);
startActivity(i);
}
}
private void sendMessage() {
EditText inputText = (EditText) findViewById(R.id.messageInput);
String input = inputText.getText().toString();
if (!input.equals("")) {
Chat chat = new Chat(input, myUserName);
refVariable.push().setValue(chat);
inputText.setText("");
}
}
}
| 3,269 | 0.64454 | 0.643316 | 109 | 28.990826 | 25.022739 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568807 | false | false | 9 |
156d65606a855e810cc642ad37b68017780af439 | 6,614,249,689,127 | e777e2e3380ec20337d828ce3c5630743ff4c64f | /MerlionPortal/MerlionPortal-ejb/src/merlionportal/tms/routeoptimizationmodule/DijkstraSea.java | db61a6b5f23eeea2dce5a2936c2c0e2961c26ee7 | []
| no_license | xiaolongba0/merlionPortal | https://github.com/xiaolongba0/merlionPortal | a5afe9fbfc65cc02af237ee0e91d5ed9f120dd6e | ab194dd7644ad3243e8f8c4adee5992d5f2ff6e8 | refs/heads/master | 2020-04-15T03:27:47.836000 | 2014-11-13T08:34:30 | 2014-11-13T08:34:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 merlionportal.tms.routeoptimizationmodule;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import util.accessRightControl.Awesome;
/**
*
* @author Yuanbo
*/
@Stateless
@LocalBean
public class DijkstraSea {
private Awesome heap;
private static int[][] graph = new int[10][10];
public DijkstraSea() {
graph[0][5]=graph[5][0]=5000;
graph[0][3]=graph[3][0]=10000;
graph[3][5]=graph[5][3]=6000;
}
public boolean createConnection(Integer startId, Integer endId, Integer dest) {
System.out.println("Dij create Connection - Sea");
System.out.println("Start: " + startId + "End: " + endId + "Distance" + dest);
if (dest > 0) {
graph[startId][endId] = graph[endId][startId] = dest;
return true;
} else {
return false;
}
}
// public static void main(String[] args) {
// DijkstraLand dij = new DijkstraLand();
// // Source is node A (node 0) and destination is node F (node 5)
// System.out.println(dij.solve(6, 0, 5));
// }
public int solve(Integer numOfNodes, Integer source, Integer dest) {
heap = new Awesome();
heap.push(source, 0);
while (!heap.isEmpty()) {
int u = heap.pop();
if (u == dest) {
return heap.cost[dest];
}
for (int i = 0; i < numOfNodes; i++) {
if (graph[u][i] > 0) {
heap.push(i, heap.cost[u] + graph[u][i]);
}
}
}
return -1;
}
}
| UTF-8 | Java | 1,839 | java | DijkstraSea.java | Java | [
{
"context": "accessRightControl.Awesome;\r\n\r\n/**\r\n *\r\n * @author Yuanbo\r\n */\r\n@Stateless\r\n@LocalBean\r\npublic class Dijkstra",
"end": 371,
"score": 0.93620765209198,
"start": 365,
"tag": "NAME",
"value": "Yuanbo"
}
]
| null | []
| /*
* 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 merlionportal.tms.routeoptimizationmodule;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import util.accessRightControl.Awesome;
/**
*
* @author Yuanbo
*/
@Stateless
@LocalBean
public class DijkstraSea {
private Awesome heap;
private static int[][] graph = new int[10][10];
public DijkstraSea() {
graph[0][5]=graph[5][0]=5000;
graph[0][3]=graph[3][0]=10000;
graph[3][5]=graph[5][3]=6000;
}
public boolean createConnection(Integer startId, Integer endId, Integer dest) {
System.out.println("Dij create Connection - Sea");
System.out.println("Start: " + startId + "End: " + endId + "Distance" + dest);
if (dest > 0) {
graph[startId][endId] = graph[endId][startId] = dest;
return true;
} else {
return false;
}
}
// public static void main(String[] args) {
// DijkstraLand dij = new DijkstraLand();
// // Source is node A (node 0) and destination is node F (node 5)
// System.out.println(dij.solve(6, 0, 5));
// }
public int solve(Integer numOfNodes, Integer source, Integer dest) {
heap = new Awesome();
heap.push(source, 0);
while (!heap.isEmpty()) {
int u = heap.pop();
if (u == dest) {
return heap.cost[dest];
}
for (int i = 0; i < numOfNodes; i++) {
if (graph[u][i] > 0) {
heap.push(i, heap.cost[u] + graph[u][i]);
}
}
}
return -1;
}
}
| 1,839 | 0.537248 | 0.516041 | 61 | 28.147541 | 23.479908 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57377 | false | false | 9 |
0e42941515d0be28018f124e230b48ebbf5be939 | 30,846,455,135,941 | 53809474ce8e104eda3431cca1f82e8fd199e04f | /src/main/java/cz/zcu/fav/liks/ml/regression/SupervisedRegressionTrainer.java | ddfe671a433c0209c7e59bade0219bd1284bedb4 | []
| no_license | konkol/Brainy | https://github.com/konkol/Brainy | eca4e6125f40fd0490315cb52c864b9f58f9f225 | b8ab989148b1df32f67ddfaebb5c77581849ef2c | refs/heads/master | 2018-03-07T17:15:13.685000 | 2015-03-24T12:23:37 | 2015-03-24T12:23:37 | 45,413,659 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2012, Michal Konkol
* All rights reserved.
*/
package cz.zcu.fav.liks.ml.regression;
import cz.zcu.fav.liks.math.la.DoubleMatrix;
import cz.zcu.fav.liks.math.la.DoubleVector;
/**
* @author Michal Konkol
*
*/
public interface SupervisedRegressionTrainer {
public Regression train(DoubleMatrix data, DoubleVector values);
}
| UTF-8 | Java | 351 | java | SupervisedRegressionTrainer.java | Java | [
{
"context": "/**\n * Copyright (c) 2012, Michal Konkol\n * All rights reserved.\n */\npackage cz.zcu.fav.li",
"end": 40,
"score": 0.9998748898506165,
"start": 27,
"tag": "NAME",
"value": "Michal Konkol"
},
{
"context": "zcu.fav.liks.math.la.DoubleVector;\n\n/**\n * @author Michal Konkol\n *\n */\npublic interface SupervisedRegressionTrain",
"end": 228,
"score": 0.9998677372932434,
"start": 215,
"tag": "NAME",
"value": "Michal Konkol"
}
]
| null | []
| /**
* Copyright (c) 2012, <NAME>
* All rights reserved.
*/
package cz.zcu.fav.liks.ml.regression;
import cz.zcu.fav.liks.math.la.DoubleMatrix;
import cz.zcu.fav.liks.math.la.DoubleVector;
/**
* @author <NAME>
*
*/
public interface SupervisedRegressionTrainer {
public Regression train(DoubleMatrix data, DoubleVector values);
}
| 337 | 0.74359 | 0.732194 | 16 | 20.9375 | 21.043018 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 9 |
b41a1b2371afa45be6666f85c351d6b95c5f9fe3 | 8,211,977,530,940 | 995f73d30450a6dce6bc7145d89344b4ad6e0622 | /MATE-20_EMUI_11.0.0/src/main/java/ohos/media/common/sessioncore/delegate/IAVBrowserResultDelegate.java | 4630121e8ff527da1b11b5df87d72a7e7b3a5712 | []
| no_license | morningblu/HWFramework | https://github.com/morningblu/HWFramework | 0ceb02cbe42585d0169d9b6c4964a41b436039f5 | 672bb34094b8780806a10ba9b1d21036fd808b8e | refs/heads/master | 2023-07-29T05:26:14.603000 | 2021-09-03T05:23:34 | 2021-09-03T05:23:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ohos.media.common.sessioncore.delegate;
import java.util.List;
import ohos.media.common.sessioncore.AVElement;
public interface IAVBrowserResultDelegate {
void detachForRetrieveAsync();
void sendAVElement(AVElement aVElement);
void sendAVElementList(List<AVElement> list);
}
| UTF-8 | Java | 299 | java | IAVBrowserResultDelegate.java | Java | []
| null | []
| package ohos.media.common.sessioncore.delegate;
import java.util.List;
import ohos.media.common.sessioncore.AVElement;
public interface IAVBrowserResultDelegate {
void detachForRetrieveAsync();
void sendAVElement(AVElement aVElement);
void sendAVElementList(List<AVElement> list);
}
| 299 | 0.795987 | 0.795987 | 12 | 23.916666 | 21.175688 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
5eb6cc2ef98788a5bca5a05a7e9f70ff20b5c36e | 21,620,865,413,421 | fb4664da014bd7e173e8cb1307ac667b88e26322 | /OOP/src/taller2/profe/parte1/Main.java | 33ad2f2574a707af2f36dcd8fdfdb69fe7dad9a6 | []
| no_license | diegottc/OOP | https://github.com/diegottc/OOP | c98616cb269fc89142aea940e54e66146f8471df | 58795cd6feae456ef883c5a6b03bd34159106957 | refs/heads/master | 2021-01-20T14:48:41.478000 | 2017-05-31T02:02:44 | 2017-05-31T02:02:44 | 90,676,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package taller2.profe.parte1;
class Main {
public static void main(String[] args) {
/*IntList l1= new Vector();
l1.addAtBegin(0);
l1.addAtBegin(5);
l1.addAtBegin(3);
System.out.println(l1.size());
l1.remove();
System.out.println(l1.size());
System.out.println(l1.get(0));
System.out.println(l1.get(1));*/
IntList list = new LinkedList();
System.out.println("largo: "+list.size());
System.out.println(list);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
System.out.println("largo: "+list.size());
System.out.println(list);
System.out.println("Valor posición 0: "+list.get(0));
System.out.println("Valor posición 1: "+list.get(1));
System.out.println("Valor posición 2: "+list.get(2));
System.out.println("Valor posición 3: "+list.get(3));
System.out.println("Valor posición 4: "+list.get(4));
System.out.println("Valor posición 5: "+list.get(5));
System.out.println("Valor posición 6: "+list.get(6));
}
}
| UTF-8 | Java | 1,027 | java | Main.java | Java | []
| null | []
| package taller2.profe.parte1;
class Main {
public static void main(String[] args) {
/*IntList l1= new Vector();
l1.addAtBegin(0);
l1.addAtBegin(5);
l1.addAtBegin(3);
System.out.println(l1.size());
l1.remove();
System.out.println(l1.size());
System.out.println(l1.get(0));
System.out.println(l1.get(1));*/
IntList list = new LinkedList();
System.out.println("largo: "+list.size());
System.out.println(list);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
System.out.println("largo: "+list.size());
System.out.println(list);
System.out.println("Valor posición 0: "+list.get(0));
System.out.println("Valor posición 1: "+list.get(1));
System.out.println("Valor posición 2: "+list.get(2));
System.out.println("Valor posición 3: "+list.get(3));
System.out.println("Valor posición 4: "+list.get(4));
System.out.println("Valor posición 5: "+list.get(5));
System.out.println("Valor posición 6: "+list.get(6));
}
}
| 1,027 | 0.640196 | 0.604902 | 38 | 25.421053 | 18.7148 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.368421 | false | false | 9 |
4de05564b31efaab471e4cfd6903ce2015b286d7 | 28,673,201,715,307 | c32ba21f207d5b3e835654317eb99e1562491cc5 | /Kurs_Java/src/Chapter5/ChapterTask/Student.java | 89dd77fa030be419c77f346c2a9cff9925d0e77c | []
| no_license | 8DietmarBarbarossa8/Software-Security-of-Multimedia-Informatioin | https://github.com/8DietmarBarbarossa8/Software-Security-of-Multimedia-Informatioin | 0683330dbacc18d4b9cf28debb37d56670d31e8b | 421158711fe64f6d00276be0ae9f8762c9de4a01 | refs/heads/main | 2023-08-03T05:50:11.028000 | 2021-09-19T11:02:02 | 2021-09-19T11:02:02 | 401,323,300 | 7 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Chapter5.ChapterTask;
import java.util.Comparator;
import java.util.LinkedList;
public class Student {
private final String name;
private final int course;
public Student(String name, int course){
this.name = name;
this.course = course;
}
private String getName(){
return name;
}
private int getCourse(){
return course;
}
@Override
public String toString(){
return "Имя: " + getName() + " Курс: " + getCourse();
}
public static void printStudents(LinkedList<Student> students, int course){
System.out.println("Студенты " + course + " курса:");
for (Student student : students) {
if (student.getCourse() == course)
System.out.println(student.getName());
}
}
public static void toUnion(LinkedList<Student> set1, LinkedList<Student> set2){
set1.addAll(set2);
}
public static void toIntersect(LinkedList<Student> set1, LinkedList<Student> set2){
set1.retainAll(set2);
}
public static void printList(LinkedList<Student> students){
for (Student student : students) System.out.println(student);
}
public static Comparator<Student> comparator =
Comparator.comparingInt(Student::getCourse).thenComparing(Student::getName);
@Override
public boolean equals(Object o){
Student student = (Student) o;
return getName().equals(student.getName()) &&
getCourse() == student.getCourse();
}
} | UTF-8 | Java | 1,566 | java | Student.java | Java | []
| null | []
| package Chapter5.ChapterTask;
import java.util.Comparator;
import java.util.LinkedList;
public class Student {
private final String name;
private final int course;
public Student(String name, int course){
this.name = name;
this.course = course;
}
private String getName(){
return name;
}
private int getCourse(){
return course;
}
@Override
public String toString(){
return "Имя: " + getName() + " Курс: " + getCourse();
}
public static void printStudents(LinkedList<Student> students, int course){
System.out.println("Студенты " + course + " курса:");
for (Student student : students) {
if (student.getCourse() == course)
System.out.println(student.getName());
}
}
public static void toUnion(LinkedList<Student> set1, LinkedList<Student> set2){
set1.addAll(set2);
}
public static void toIntersect(LinkedList<Student> set1, LinkedList<Student> set2){
set1.retainAll(set2);
}
public static void printList(LinkedList<Student> students){
for (Student student : students) System.out.println(student);
}
public static Comparator<Student> comparator =
Comparator.comparingInt(Student::getCourse).thenComparing(Student::getName);
@Override
public boolean equals(Object o){
Student student = (Student) o;
return getName().equals(student.getName()) &&
getCourse() == student.getCourse();
}
} | 1,566 | 0.628072 | 0.622251 | 58 | 25.672413 | 25.387608 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37931 | false | false | 9 |
63fb57b860bbd1fd48f66c2f2d5512a2e6ee6be9 | 19,172,734,031,376 | 8e68dc6de6de8104bd0c9ce029634004e23be38a | /src/main/java/com/sep3/javaapplicationserver/controller/AccountController.java | 0c1ff3c183a689daeb95599d2b7443b35c6f30db | []
| no_license | SEP3-TAfAaTH/java-application-server | https://github.com/SEP3-TAfAaTH/java-application-server | 6a922eef1ffa85f5386b0b2d3eec2b41d066f7a5 | 2f0b4c928941f79002e6abe8a9aac9bb8fdb6478 | refs/heads/main | 2023-05-12T01:04:29.832000 | 2021-05-21T10:14:12 | 2021-05-21T10:14:12 | 337,047,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sep3.javaapplicationserver.controller;
import com.sep3.javaapplicationserver.model.Account;
import com.sep3.javaapplicationserver.repository.AccountRepository;
import com.sep3.javaapplicationserver.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
public AccountService accountService;
@Autowired
public AccountRepository accountRepository;
@GetMapping
public List<Account> listAll() {
return accountRepository.findAll();
}
@GetMapping("/{accountId}")
public Account getById(@PathVariable Long accountId) {
return accountService.findByIdOrFail(accountId);
}
@PostMapping("")
@ResponseStatus(HttpStatus.CREATED)
public Account add(@RequestBody Account account) {
accountService.findUniqueUsernameOrFail(account.getUsername());
return accountService.save(account);
}
@PutMapping("/{accountId}")
public Account update(@PathVariable Long accountId, @RequestBody Account accountToEdit) {
Account accountCurrent = accountService.findByIdOrFail(accountId);
if (!accountCurrent.getUsername().equals(accountToEdit.getUsername())) {
accountService.findUniqueUsernameOrFail(accountToEdit.getUsername());
return accountService.update(accountToEdit, accountCurrent);
}
return accountService.update(accountToEdit, accountCurrent);
}
}
| UTF-8 | Java | 1,643 | java | AccountController.java | Java | []
| null | []
| package com.sep3.javaapplicationserver.controller;
import com.sep3.javaapplicationserver.model.Account;
import com.sep3.javaapplicationserver.repository.AccountRepository;
import com.sep3.javaapplicationserver.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
public AccountService accountService;
@Autowired
public AccountRepository accountRepository;
@GetMapping
public List<Account> listAll() {
return accountRepository.findAll();
}
@GetMapping("/{accountId}")
public Account getById(@PathVariable Long accountId) {
return accountService.findByIdOrFail(accountId);
}
@PostMapping("")
@ResponseStatus(HttpStatus.CREATED)
public Account add(@RequestBody Account account) {
accountService.findUniqueUsernameOrFail(account.getUsername());
return accountService.save(account);
}
@PutMapping("/{accountId}")
public Account update(@PathVariable Long accountId, @RequestBody Account accountToEdit) {
Account accountCurrent = accountService.findByIdOrFail(accountId);
if (!accountCurrent.getUsername().equals(accountToEdit.getUsername())) {
accountService.findUniqueUsernameOrFail(accountToEdit.getUsername());
return accountService.update(accountToEdit, accountCurrent);
}
return accountService.update(accountToEdit, accountCurrent);
}
}
| 1,643 | 0.749848 | 0.747413 | 51 | 31.215687 | 27.737787 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 9 |
8044e40a82d2f0301cbff8a4581c4772518b618e | 14,637,248,555,883 | 4acdf39c71396859b97219c76e5cd824862a2361 | /src/app/src/main/java/edu/ramapo/philipglazman/kono/Player.java | e0340fca78f12bf41276183ad7f46d52a3294103 | []
| no_license | philipglazman/Kono-java | https://github.com/philipglazman/Kono-java | 3aff36e5c0b639023b72b7072db9961e302ce360 | 4786dc5dbb9c554a68e0b14007c2dca255cd7ecf | refs/heads/master | 2021-09-10T18:50:59.636000 | 2018-03-31T03:16:43 | 2018-03-31T03:16:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ramapo.philipglazman.kono;
/**
* Created by mango on 3/30/18.
*/
public class Player {
// Initial Coordinates
protected int initialRow;
protected int initialColumn;
// Final Coordinates
protected int finalRow;
protected int finalColumn;
/**
* Getter for initial row coordinate.
* @return row, integer.
*/
public int getInitialRow(){return initialRow;}
/**
* Getter for initial column coordinate.
* @return column, integer.
*/
public int getInitialColumn(){return initialColumn;}
}
| UTF-8 | Java | 572 | java | Player.java | Java | [
{
"context": " edu.ramapo.philipglazman.kono;\n\n/**\n * Created by mango on 3/30/18.\n */\n\npublic class Player {\n\n // In",
"end": 63,
"score": 0.9993223547935486,
"start": 58,
"tag": "USERNAME",
"value": "mango"
}
]
| null | []
| package edu.ramapo.philipglazman.kono;
/**
* Created by mango on 3/30/18.
*/
public class Player {
// Initial Coordinates
protected int initialRow;
protected int initialColumn;
// Final Coordinates
protected int finalRow;
protected int finalColumn;
/**
* Getter for initial row coordinate.
* @return row, integer.
*/
public int getInitialRow(){return initialRow;}
/**
* Getter for initial column coordinate.
* @return column, integer.
*/
public int getInitialColumn(){return initialColumn;}
}
| 572 | 0.652098 | 0.643357 | 28 | 19.392857 | 17.190819 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 9 |
0ff1c5555efd143219f0b37a31da5b69169fe821 | 14,697,378,110,322 | 345628621e37940437cba31f1895e93dbd4e7ed1 | /SpringBootDemo-master/chapter13/src/main/java/com/dudu/domain/LearnResource.java | ce139693397766bc0c7ad1f5ff8bc020e043cfd3 | [
"Apache-2.0"
]
| permissive | williamjie/sprintboot_test | https://github.com/williamjie/sprintboot_test | fb2e910a17c0d2ad14ca84f1a1116243b9760985 | 8f18c70304a694496e09a684a1116f14a0cceb4a | refs/heads/master | 2021-05-25T12:09:32.708000 | 2019-01-11T00:37:22 | 2019-01-11T00:37:22 | 127,389,708 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dudu.domain;
import javax.persistence.*;
@Table(name = "learn_resource")
public class LearnResource {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 作者
*/
private String author;
/**
* 描述
*/
private String title;
/**
* 地址链接
*/
private String url;
/**
* 获取ID
*
* @return id - ID
*/
public Long getId() {
return id;
}
/**
* 设置ID
*
* @param id ID
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取作者
*
* @return author - 作者
*/
public String getAuthor() {
return author;
}
/**
* 设置作者
*
* @param author 作者
*/
public void setAuthor(String author) {
this.author = author == null ? null : author.trim();
}
/**
* 获取描述
*
* @return title - 描述
*/
public String getTitle() {
return title;
}
/**
* 设置描述
*
* @param title 描述
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* 获取地址链接
*
* @return url - 地址链接
*/
public String getUrl() {
return url;
}
/**
* 设置地址链接
*
* @param url 地址链接
*/
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
} | UTF-8 | Java | 1,581 | java | LearnResource.java | Java | []
| null | []
| package com.dudu.domain;
import javax.persistence.*;
@Table(name = "learn_resource")
public class LearnResource {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 作者
*/
private String author;
/**
* 描述
*/
private String title;
/**
* 地址链接
*/
private String url;
/**
* 获取ID
*
* @return id - ID
*/
public Long getId() {
return id;
}
/**
* 设置ID
*
* @param id ID
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取作者
*
* @return author - 作者
*/
public String getAuthor() {
return author;
}
/**
* 设置作者
*
* @param author 作者
*/
public void setAuthor(String author) {
this.author = author == null ? null : author.trim();
}
/**
* 获取描述
*
* @return title - 描述
*/
public String getTitle() {
return title;
}
/**
* 设置描述
*
* @param title 描述
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* 获取地址链接
*
* @return url - 地址链接
*/
public String getUrl() {
return url;
}
/**
* 设置地址链接
*
* @param url 地址链接
*/
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
} | 1,581 | 0.449285 | 0.449285 | 100 | 13.7 | 13.191285 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.14 | false | false | 9 |
c1e4df2272f43739304f80ea8a4ec11e8c65367a | 21,079,699,502,237 | 2f58c2e3579be9ad51509b918389b55f9b42c1f3 | /src/main/java/com/demo/petshopping/serviceimpl/PetServiceImpl.java | 627b24f7e5ca0a0b18ce3eab8fd9e3df7fa7b1f5 | []
| no_license | LahariPotli/petshopping | https://github.com/LahariPotli/petshopping | a79e5a3fefb9bf85bab79987ed2a92d01c5cf3ce | d6c0615975875aff9fb7e3f41fe18fcd677416a0 | refs/heads/master | 2022-11-20T18:16:07.794000 | 2020-07-07T16:05:41 | 2020-07-07T16:05:41 | 277,724,208 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.petshopping.serviceimpl;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.petshopping.dao.PetsDao;
import com.demo.petshopping.dto.PetListResponseDto;
import com.demo.petshopping.dto.PetResponseDto;
import com.demo.petshopping.exception.PetNotFoundException;
import com.demo.petshopping.model.Pets;
import com.demo.petshopping.service.PetService;
/**
* @author lahari_Reddy
*
*/
@Service
public class PetServiceImpl implements PetService {
static Log logger = LogFactory.getLog(PetServiceImpl.class);
@Autowired
PetsDao petDao;
/**
*{@Inherit Doc}
*/
@Override
public PetListResponseDto getPetsByPetName(String petName) {
logger.info("inside get pets by petname in petserviceimpl");
PetListResponseDto petListResponseDto=new PetListResponseDto();
Optional<List<Pets>> petsOptional =petDao.findByPetName(petName);
if (!petsOptional.isPresent())
{
throw new PetNotFoundException("pet is not found with the requested pet name");
}
List<PetResponseDto> petResponseDto = petsOptional.get().stream()
.map(pets -> getPetResponseDto(pets)).collect(Collectors.toList());
petListResponseDto.setReponselistDto(petResponseDto);
petListResponseDto.setMessage("please find your list of pets");
petListResponseDto.setStatusCode(200);
return petListResponseDto;
}
private PetResponseDto getPetResponseDto(Pets pets)
{
PetResponseDto petResponseDto = new PetResponseDto();
BeanUtils.copyProperties(pets, petResponseDto);
return petResponseDto;
}
}
| UTF-8 | Java | 2,030 | java | PetServiceImpl.java | Java | [
{
"context": "emo.petshopping.service.PetService;\n/**\n * @author lahari_Reddy\n *\n */\n@Service\npublic class PetServiceImpl imple",
"end": 696,
"score": 0.9929619431495667,
"start": 684,
"tag": "USERNAME",
"value": "lahari_Reddy"
}
]
| null | []
|
package com.demo.petshopping.serviceimpl;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.petshopping.dao.PetsDao;
import com.demo.petshopping.dto.PetListResponseDto;
import com.demo.petshopping.dto.PetResponseDto;
import com.demo.petshopping.exception.PetNotFoundException;
import com.demo.petshopping.model.Pets;
import com.demo.petshopping.service.PetService;
/**
* @author lahari_Reddy
*
*/
@Service
public class PetServiceImpl implements PetService {
static Log logger = LogFactory.getLog(PetServiceImpl.class);
@Autowired
PetsDao petDao;
/**
*{@Inherit Doc}
*/
@Override
public PetListResponseDto getPetsByPetName(String petName) {
logger.info("inside get pets by petname in petserviceimpl");
PetListResponseDto petListResponseDto=new PetListResponseDto();
Optional<List<Pets>> petsOptional =petDao.findByPetName(petName);
if (!petsOptional.isPresent())
{
throw new PetNotFoundException("pet is not found with the requested pet name");
}
List<PetResponseDto> petResponseDto = petsOptional.get().stream()
.map(pets -> getPetResponseDto(pets)).collect(Collectors.toList());
petListResponseDto.setReponselistDto(petResponseDto);
petListResponseDto.setMessage("please find your list of pets");
petListResponseDto.setStatusCode(200);
return petListResponseDto;
}
private PetResponseDto getPetResponseDto(Pets pets)
{
PetResponseDto petResponseDto = new PetResponseDto();
BeanUtils.copyProperties(pets, petResponseDto);
return petResponseDto;
}
}
| 2,030 | 0.704926 | 0.703448 | 67 | 29.268656 | 26.479834 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.626866 | false | false | 9 |
93482ffa916e6586bbf521290b01f56ea28f1cc4 | 7,636,451,870,735 | fd67cf9851be0c30031ad62ba11f59ab6b47dd0f | /src/day49_Interface/IceCream.java | bd49a94c9c97e82df386cceb9f6d289fc2443d3e | []
| no_license | aygol/JavaProject | https://github.com/aygol/JavaProject | 47287c00434a05dfd364e22514b7d7a24c4e3fbb | a9221d285bdee58ab1a503f34ab522b1eef70a25 | refs/heads/master | 2021-01-14T04:36:31.294000 | 2020-02-23T22:15:58 | 2020-02-23T22:15:58 | 242,600,824 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day49_Interface;
public class IceCream implements Edible {
public void eat() {
System.out.println("eat with spoon!!!");
} public void drink(){
System.out.println("drink it if it has melt");
}
public void digest(){
System.out.println("Digesting icecream by leaking");
}
public static void main(String[] args) {
IceCream i1=new IceCream();
i1.drink();
i1.eat();
System.out.println(i1.toString());
i1.digest();
}
}
| UTF-8 | Java | 538 | java | IceCream.java | Java | []
| null | []
| package day49_Interface;
public class IceCream implements Edible {
public void eat() {
System.out.println("eat with spoon!!!");
} public void drink(){
System.out.println("drink it if it has melt");
}
public void digest(){
System.out.println("Digesting icecream by leaking");
}
public static void main(String[] args) {
IceCream i1=new IceCream();
i1.drink();
i1.eat();
System.out.println(i1.toString());
i1.digest();
}
}
| 538 | 0.55948 | 0.546468 | 20 | 25.799999 | 18.167553 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 9 |
07fece7f55ada2bfd6c694f4537d44642ecaeb2d | 7,636,451,868,100 | c37a1c3756037468f9770848f012e6b9c63cbd2f | /app/src/main/java/mx/itesm/csf/crud/Grafica/ProductosMasVendidos.java | 11c468acc47a8ea1d45871819a42f32a46ce6b85 | []
| no_license | iturbe/moviles | https://github.com/iturbe/moviles | 76a2c0a91bbfcfeab495d290a53aefba296dc2ca | 5e5189d954caf5967021ce9b0865455b5e5144e4 | refs/heads/master | 2021-01-20T00:37:14.848000 | 2017-05-09T04:46:29 | 2017-05-09T04:46:29 | 89,160,967 | 0 | 1 | null | false | 2017-05-09T04:46:30 | 2017-04-23T17:49:41 | 2017-04-23T17:49:56 | 2017-05-09T04:46:30 | 346 | 0 | 1 | 0 | Java | null | null | package mx.itesm.csf.crud.Grafica;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mx.itesm.csf.crud.Clientes.PrincipalClientes;
import mx.itesm.csf.crud.Controladores.Controlador;
import mx.itesm.csf.crud.Controladores.Servicios;
import mx.itesm.csf.crud.R;
public class ProductosMasVendidos extends AppCompatActivity {
List<BarEntry> entries = new ArrayList<>();
BarChart chart;
ProgressDialog barra_de_progreso;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_productos_mas_vendidos);
barra_de_progreso = new ProgressDialog(ProductosMasVendidos.this);
chart = (BarChart) findViewById(R.id.graficados);
cargarJSON();
}
// creamos nuestro método cargarJSON() con la librería Volley
private void cargarJSON()
{
barra_de_progreso.setMessage("Cargando datos...");
barra_de_progreso.setCancelable(false);
barra_de_progreso.show();
JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.GET, Servicios.PRODUCTOS_MAS_VENDIDOS,null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
barra_de_progreso.cancel();
Log.d("Objeto","respuesta : " + response.toString() + " " + response.length());
for(int i = 0 ; i < response.length(); i++) {
try {
if (i == 0) { //solo para el confirmation
JSONObject first = response.getJSONObject(i);
if (first.getString("codigo") == "01"){
Toast.makeText(getApplicationContext(), "Recibiendo datos...", Toast.LENGTH_SHORT).show();
}
} else {
JSONObject data = response.getJSONObject(i);
entries.add(new BarEntry(i, data.getInt("cantidad_total"), data.getString("nombre")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.d("size al acabar", "int " + entries.size());
BarDataSet dataset = new BarDataSet(entries, "Productos");
BarData bardata = new BarData(dataset);
chart.setData(bardata);
chart.animateY(5000);
dataset.setColors(ColorTemplate.COLORFUL_COLORS);
chart.getDescription().setText(""); // redundante ya que la descripción está en el top bar
chart.getLegend().setEnabled(false);
String[] values = new String[] {"Product1", "Product2", "Product3", "Product4", "Product5"};
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyAxisValueFormatter(values));
xAxis.setDrawAxisLine(false);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawLabels(false);
xAxis.setDrawGridLines(false);
//chart.setVisibleXRangeMaximum(5);
dataset.notifyDataSetChanged();
chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
@Override
public void onValueSelected(Entry e, Highlight h) {
Toast.makeText(getApplicationContext(), e.getData().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected() {
}
});
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
barra_de_progreso.cancel();
Log.d("Volley", "Error : " + error.getMessage());
}
}){
@Override
public Map< String, String > getHeaders() throws AuthFailureError {
HashMap< String, String > headers = new HashMap <> ();
String encodedCredentials = Base64.encodeToString("admin@tiendita.com:root".getBytes(), Base64.NO_WRAP);
headers.put("Authorization", "Basic " + encodedCredentials);
return headers;
}
};
Controlador.getInstance().agregaAlRequestQueue(reqData);
}
}
| UTF-8 | Java | 6,119 | java | ProductosMasVendidos.java | Java | [
{
"context": "tring encodedCredentials = Base64.encodeToString(\"admin@tiendita.com:root\".getBytes(), Base64.NO_WRAP);\n ",
"end": 5872,
"score": 0.9998346567153931,
"start": 5854,
"tag": "EMAIL",
"value": "admin@tiendita.com"
}
]
| null | []
| package mx.itesm.csf.crud.Grafica;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mx.itesm.csf.crud.Clientes.PrincipalClientes;
import mx.itesm.csf.crud.Controladores.Controlador;
import mx.itesm.csf.crud.Controladores.Servicios;
import mx.itesm.csf.crud.R;
public class ProductosMasVendidos extends AppCompatActivity {
List<BarEntry> entries = new ArrayList<>();
BarChart chart;
ProgressDialog barra_de_progreso;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_productos_mas_vendidos);
barra_de_progreso = new ProgressDialog(ProductosMasVendidos.this);
chart = (BarChart) findViewById(R.id.graficados);
cargarJSON();
}
// creamos nuestro método cargarJSON() con la librería Volley
private void cargarJSON()
{
barra_de_progreso.setMessage("Cargando datos...");
barra_de_progreso.setCancelable(false);
barra_de_progreso.show();
JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.GET, Servicios.PRODUCTOS_MAS_VENDIDOS,null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
barra_de_progreso.cancel();
Log.d("Objeto","respuesta : " + response.toString() + " " + response.length());
for(int i = 0 ; i < response.length(); i++) {
try {
if (i == 0) { //solo para el confirmation
JSONObject first = response.getJSONObject(i);
if (first.getString("codigo") == "01"){
Toast.makeText(getApplicationContext(), "Recibiendo datos...", Toast.LENGTH_SHORT).show();
}
} else {
JSONObject data = response.getJSONObject(i);
entries.add(new BarEntry(i, data.getInt("cantidad_total"), data.getString("nombre")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.d("size al acabar", "int " + entries.size());
BarDataSet dataset = new BarDataSet(entries, "Productos");
BarData bardata = new BarData(dataset);
chart.setData(bardata);
chart.animateY(5000);
dataset.setColors(ColorTemplate.COLORFUL_COLORS);
chart.getDescription().setText(""); // redundante ya que la descripción está en el top bar
chart.getLegend().setEnabled(false);
String[] values = new String[] {"Product1", "Product2", "Product3", "Product4", "Product5"};
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyAxisValueFormatter(values));
xAxis.setDrawAxisLine(false);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawLabels(false);
xAxis.setDrawGridLines(false);
//chart.setVisibleXRangeMaximum(5);
dataset.notifyDataSetChanged();
chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
@Override
public void onValueSelected(Entry e, Highlight h) {
Toast.makeText(getApplicationContext(), e.getData().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected() {
}
});
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
barra_de_progreso.cancel();
Log.d("Volley", "Error : " + error.getMessage());
}
}){
@Override
public Map< String, String > getHeaders() throws AuthFailureError {
HashMap< String, String > headers = new HashMap <> ();
String encodedCredentials = Base64.encodeToString("<EMAIL>:root".getBytes(), Base64.NO_WRAP);
headers.put("Authorization", "Basic " + encodedCredentials);
return headers;
}
};
Controlador.getInstance().agregaAlRequestQueue(reqData);
}
}
| 6,108 | 0.57269 | 0.569256 | 136 | 43.963234 | 30.209661 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 9 |
6d44ff064447fd5a7e2bf7a7fd3a6fab51166672 | 7,206,955,154,092 | 8edfff3461aa3d6ce47e5a779c2357b21645a25c | /src/stevejobs/Test9.java | 4a1c5aab491ada5e64e21cc498be97b622c679cc | []
| no_license | JPrasannanjaneyulu/abdulkalam | https://github.com/JPrasannanjaneyulu/abdulkalam | 64380617491443ee4b2815bf733e8451b92cf37c | 221caff6b195a4ee0b5cff9dabf67ee2a7db8a86 | refs/heads/master | 2020-06-05T19:30:16.671000 | 2019-07-29T06:50:36 | 2019-07-29T06:50:36 | 192,525,606 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stevejobs;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Test9 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","D:\\batch229\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com/mercuryregister.php");
driver.findElement(By.name("firstName")).sendKeys("Janjanam");
driver.findElement(By.name("lastName")).sendKeys("Prasannanjaneyulu");
driver.findElement(By.name("phone")).sendKeys("9912358366");
driver.findElement(By.name("userName")).sendKeys("j.prasannanjaneyulu131@gmail.com");
driver.findElement(By.name("address1")).sendKeys("2-99-A,Beside Sita Rama Picture Palace");
driver.findElement(By.name("address2")).sendKeys("Valaparla(PO),Martur(MD)");
driver.findElement(By.name("city")).sendKeys("Chilakaluripet");
driver.findElement(By.name("state")).sendKeys("Andhra Pradesh");
driver.findElement(By.name("postalCode")).sendKeys("523260");
Select s=new Select(driver.findElement(By.name("country")));
s.selectByVisibleText("INDIA");
List<WebElement> l=s.getOptions();
System.out.println(l.size());
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.close();
}
}
| UTF-8 | Java | 1,522 | java | Test9.java | Java | [
{
"context": "river.findElement(By.name(\"firstName\")).sendKeys(\"Janjanam\");\n\t\tdriver.findElement(By.name(\"lastName\")).send",
"end": 667,
"score": 0.9997823238372803,
"start": 659,
"tag": "NAME",
"value": "Janjanam"
},
{
"context": "driver.findElement(By.name(\"lastName\")).sendKeys(\"Prasannanjaneyulu\");\n\t\tdriver.findElement(By.name(\"phone\")).sendKey",
"end": 740,
"score": 0.9998123049736023,
"start": 723,
"tag": "NAME",
"value": "Prasannanjaneyulu"
},
{
"context": "driver.findElement(By.name(\"userName\")).sendKeys(\"j.prasannanjaneyulu131@gmail.com\");\n\t\tdriver.findElement(By.name(\"address1\")).send",
"end": 891,
"score": 0.9998838901519775,
"start": 859,
"tag": "EMAIL",
"value": "j.prasannanjaneyulu131@gmail.com"
}
]
| null | []
| package stevejobs;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class Test9 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","D:\\batch229\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com/mercuryregister.php");
driver.findElement(By.name("firstName")).sendKeys("Janjanam");
driver.findElement(By.name("lastName")).sendKeys("Prasannanjaneyulu");
driver.findElement(By.name("phone")).sendKeys("9912358366");
driver.findElement(By.name("userName")).sendKeys("<EMAIL>");
driver.findElement(By.name("address1")).sendKeys("2-99-A,Beside Sita Rama Picture Palace");
driver.findElement(By.name("address2")).sendKeys("Valaparla(PO),Martur(MD)");
driver.findElement(By.name("city")).sendKeys("Chilakaluripet");
driver.findElement(By.name("state")).sendKeys("Andhra Pradesh");
driver.findElement(By.name("postalCode")).sendKeys("523260");
Select s=new Select(driver.findElement(By.name("country")));
s.selectByVisibleText("INDIA");
List<WebElement> l=s.getOptions();
System.out.println(l.size());
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.close();
}
}
| 1,497 | 0.751643 | 0.732589 | 37 | 40.135136 | 28.106133 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.945946 | false | false | 9 |
40b465a40fdc88209a0f008fc168de3bc1b0bb5a | 24,163,486,046,911 | 54062206ed0b2bde71bbb42f14cdcbec9ef620bf | /Assignment11/HarvardLawyer.java | ff8f3cdad7710b2da75f22f6abb8b4d8f1664f81 | []
| no_license | generocha/ITC115 | https://github.com/generocha/ITC115 | 5cae89371c80993eb604bf706bbe5393d5de3665 | 49c7f4459cf08af3a2a900ef57aa35890bb9a7e6 | refs/heads/master | 2020-12-15T15:45:59.597000 | 2020-03-23T22:27:49 | 2020-03-23T22:27:49 | 235,162,130 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class HarvardLawyer extends Lawyer{
//**************************************
//
// The Class: HarvardLawyer
// Extends the Lawyer class
//
// By: Gene Rocha
// Date: 03/22/2020
//
//**************************************
// Harvard lawyers are like normal lawyers,
//but they make 20% more money than a normal lawyer
public double getSalary() {
return super.getSalary() * 1.20;
}
// Harvard lawyers they get 3 days more vacation
public int getVacationDays() {
return super.getVacationDays() + 3;
}
// Harvard lawyers have to fill out four of the lawyer's
// forms to go on vacation
public String getVacationForm() {
String formColor = "";
for(int i = 0; i < 4; i++) {
formColor += super.getVacationForm();
}
return formColor;
}
}
| UTF-8 | Java | 835 | java | HarvardLawyer.java | Java | [
{
"context": "rdLawyer\n\t// Extends the Lawyer class\n\t//\n\t// By: Gene Rocha \n\t// Date: 03/22/2020\n\t//\n\t//********************",
"end": 171,
"score": 0.999888002872467,
"start": 161,
"tag": "NAME",
"value": "Gene Rocha"
}
]
| null | []
|
public class HarvardLawyer extends Lawyer{
//**************************************
//
// The Class: HarvardLawyer
// Extends the Lawyer class
//
// By: <NAME>
// Date: 03/22/2020
//
//**************************************
// Harvard lawyers are like normal lawyers,
//but they make 20% more money than a normal lawyer
public double getSalary() {
return super.getSalary() * 1.20;
}
// Harvard lawyers they get 3 days more vacation
public int getVacationDays() {
return super.getVacationDays() + 3;
}
// Harvard lawyers have to fill out four of the lawyer's
// forms to go on vacation
public String getVacationForm() {
String formColor = "";
for(int i = 0; i < 4; i++) {
formColor += super.getVacationForm();
}
return formColor;
}
}
| 831 | 0.559281 | 0.538922 | 36 | 22.166666 | 18.014654 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.027778 | false | false | 9 |
52c934d9352af139908ef9416cebde89779d4292 | 18,433,999,663,686 | ea728d4763fbf16d488d5b3f39a0d05441bb73d1 | /src/main/java/com/creativityskills/producer/LoggerProducer.java | b293ce5cba58e2c60c2f558dfe866364cbb28ed6 | []
| no_license | john-on-Techs/sms-simulation | https://github.com/john-on-Techs/sms-simulation | 7228dd965aba360fec8c78ace1f30468b2435133 | 4df372107171ef86a10b1b480894665aca5ea732 | refs/heads/master | 2022-07-18T02:35:31.282000 | 2019-11-01T14:18:03 | 2019-11-01T14:18:03 | 218,997,783 | 0 | 0 | null | false | 2022-06-24T02:25:22 | 2019-11-01T14:09:49 | 2019-11-01T14:19:59 | 2022-06-24T02:25:19 | 35,656 | 0 | 0 | 4 | Java | false | false | package com.creativityskills.producer;
import org.jboss.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
public class LoggerProducer {
@Produces
public Logger produceLoger(InjectionPoint injectionPoint) {
return
Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}
| UTF-8 | Java | 390 | java | LoggerProducer.java | Java | []
| null | []
| package com.creativityskills.producer;
import org.jboss.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
public class LoggerProducer {
@Produces
public Logger produceLoger(InjectionPoint injectionPoint) {
return
Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}
| 390 | 0.751282 | 0.751282 | 14 | 26.857143 | 26.661522 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 9 |
6de4cb383adc8ed8d3eeff76fff3878d9bc8c1f5 | 12,695,923,360,318 | f6334c2a5189d677e8d8011261a59baa1b33edc0 | /src/controller/commands/SaveCommandTest.java | b59dadd9ae5e23f86a42cdc8458f611a35494884 | []
| no_license | ekiafa/LatexEditorProject | https://github.com/ekiafa/LatexEditorProject | f42b748cdd4de333a57885e678568893766ae0a0 | e2076bfac50a8bf55779c2c5ecbaaf95f63eb690 | refs/heads/main | 2023-03-07T07:22:16.558000 | 2021-02-26T16:24:37 | 2021-02-26T16:24:37 | 342,237,687 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller.commands;
import static org.junit.Assert.*;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import model.Document;
import org.junit.Assert;
import org.junit.Test;
import view.LatexEditorView;
import view.MainWindow;
public class SaveCommandTest {
private MainWindow window;
private EnableVersionsManagementCommand enableCom;
private EditCommand editCom;
private Document doc;
private SaveCommand saveCom;
private FileInputStream file;
private ObjectInputStream in;
public SaveCommandTest(){
window= new MainWindow();
enableCom= new EnableVersionsManagementCommand(window);
editCom= new EditCommand(window);
saveCom= new SaveCommand(window);
doc= new Document();
}
@Test
public void test() throws IOException, ClassNotFoundException {
window.setStrategy("Volatile");
window.setSavePath("/usr/home/students/stud15/cse53003/workspace/Latex/saveTest");
window.setLoadPath("/usr/home/students/stud15/cse53003/workspace/Latex/saveTest/Emptynull");
enableCom.execute();
window.getVersionsManager().setCurrentVersion(doc);
saveCom.execute();
try{
file = new FileInputStream(window.getLoadPath()+'/' +"0.ser");
in = new ObjectInputStream(file);
doc = (Document)in.readObject();
} catch (EOFException e) {
}
Assert.assertEquals(doc.getContents(),window.getVersionsManager().getCurrentDocument().getContents());
}
}
| UTF-8 | Java | 1,543 | java | SaveCommandTest.java | Java | []
| null | []
| package controller.commands;
import static org.junit.Assert.*;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import model.Document;
import org.junit.Assert;
import org.junit.Test;
import view.LatexEditorView;
import view.MainWindow;
public class SaveCommandTest {
private MainWindow window;
private EnableVersionsManagementCommand enableCom;
private EditCommand editCom;
private Document doc;
private SaveCommand saveCom;
private FileInputStream file;
private ObjectInputStream in;
public SaveCommandTest(){
window= new MainWindow();
enableCom= new EnableVersionsManagementCommand(window);
editCom= new EditCommand(window);
saveCom= new SaveCommand(window);
doc= new Document();
}
@Test
public void test() throws IOException, ClassNotFoundException {
window.setStrategy("Volatile");
window.setSavePath("/usr/home/students/stud15/cse53003/workspace/Latex/saveTest");
window.setLoadPath("/usr/home/students/stud15/cse53003/workspace/Latex/saveTest/Emptynull");
enableCom.execute();
window.getVersionsManager().setCurrentVersion(doc);
saveCom.execute();
try{
file = new FileInputStream(window.getLoadPath()+'/' +"0.ser");
in = new ObjectInputStream(file);
doc = (Document)in.readObject();
} catch (EOFException e) {
}
Assert.assertEquals(doc.getContents(),window.getVersionsManager().getCurrentDocument().getContents());
}
}
| 1,543 | 0.75243 | 0.742709 | 60 | 24.716667 | 23.915888 | 104 | false | false | 0 | 0 | 0 | 0 | 69 | 0.044718 | 1.583333 | false | false | 9 |
177af7fd5c4f4e939a460c77442466d9ac31bfcc | 4,217,657,923,063 | 6cd756bf890b53b748d41d14d6c460349a898c99 | /fr-designer-report-8.0/com/fr/design/actions/report/ReportPageAttrAction.java | ad608fefa86f8e597643efa79e1cdc4cf28cf1f3 | []
| no_license | jiangzhenjian/FineReport | https://github.com/jiangzhenjian/FineReport | 4208b347f3b7fe839fec97cc0cb67bd33d761ba8 | ca34e419b4f117684ecbfafdd6a1178cc94ce5c6 | refs/heads/master | 2021-01-07T20:53:20.460000 | 2017-01-22T03:25:11 | 2017-01-22T03:25:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi
package com.fr.design.actions.report;
import com.fr.base.BaseUtils;
import com.fr.design.actions.ReportComponentAction;
import com.fr.design.dialog.BasicDialog;
import com.fr.design.dialog.DialogActionAdapter;
import com.fr.design.mainframe.WorkSheetDesigner;
import com.fr.design.menu.KeySetUtils;
import com.fr.design.menu.MenuKeySet;
import com.fr.design.report.freeze.RepeatAndFreezeSettingPane;
import com.fr.page.ReportSettingsProvider;
import com.fr.report.worksheet.WorkSheet;
import javax.swing.SwingUtilities;
public class ReportPageAttrAction extends ReportComponentAction
{
private boolean returnValue;
public ReportPageAttrAction(WorkSheetDesigner worksheetdesigner)
{
super(worksheetdesigner);
setMenuKeySet(KeySetUtils.REPORT_PAGE);
setName((new StringBuilder()).append(getMenuKeySet().getMenuKeySetName()).append("...").toString());
setMnemonic(getMenuKeySet().getMnemonic());
setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/m_file/pageSetup.png"));
}
public boolean executeActionReturnUndoRecordNeeded()
{
WorkSheetDesigner worksheetdesigner = (WorkSheetDesigner)getEditingComponent();
if(worksheetdesigner == null)
{
return false;
} else
{
final WorkSheet tplECReport = (WorkSheet)worksheetdesigner.getTemplateReport();
final RepeatAndFreezeSettingPane attrPane = new RepeatAndFreezeSettingPane();
attrPane.populate(tplECReport.getReportPageAttr());
attrPane.populateWriteFrozenColumnRow(tplECReport.getReportSettings().getWriteFrozenColumnRow());
BasicDialog basicdialog = attrPane.showWindow(SwingUtilities.getWindowAncestor(worksheetdesigner));
basicdialog.addDialogActionListener(new DialogActionAdapter() {
final WorkSheet val$tplECReport;
final RepeatAndFreezeSettingPane val$attrPane;
final ReportPageAttrAction this$0;
public void doOk()
{
tplECReport.setReportPageAttr(attrPane.update());
tplECReport.getReportSettings().setWriteFrozenColumnRow(attrPane.updateWriteFrozenColumnRow());
returnValue = true;
}
{
this$0 = ReportPageAttrAction.this;
tplECReport = worksheet;
attrPane = repeatandfreezesettingpane;
super();
}
}
);
basicdialog.setVisible(true);
return returnValue;
}
}
}
| UTF-8 | Java | 2,785 | java | ReportPageAttrAction.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9996312856674194,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi
package com.fr.design.actions.report;
import com.fr.base.BaseUtils;
import com.fr.design.actions.ReportComponentAction;
import com.fr.design.dialog.BasicDialog;
import com.fr.design.dialog.DialogActionAdapter;
import com.fr.design.mainframe.WorkSheetDesigner;
import com.fr.design.menu.KeySetUtils;
import com.fr.design.menu.MenuKeySet;
import com.fr.design.report.freeze.RepeatAndFreezeSettingPane;
import com.fr.page.ReportSettingsProvider;
import com.fr.report.worksheet.WorkSheet;
import javax.swing.SwingUtilities;
public class ReportPageAttrAction extends ReportComponentAction
{
private boolean returnValue;
public ReportPageAttrAction(WorkSheetDesigner worksheetdesigner)
{
super(worksheetdesigner);
setMenuKeySet(KeySetUtils.REPORT_PAGE);
setName((new StringBuilder()).append(getMenuKeySet().getMenuKeySetName()).append("...").toString());
setMnemonic(getMenuKeySet().getMnemonic());
setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/m_file/pageSetup.png"));
}
public boolean executeActionReturnUndoRecordNeeded()
{
WorkSheetDesigner worksheetdesigner = (WorkSheetDesigner)getEditingComponent();
if(worksheetdesigner == null)
{
return false;
} else
{
final WorkSheet tplECReport = (WorkSheet)worksheetdesigner.getTemplateReport();
final RepeatAndFreezeSettingPane attrPane = new RepeatAndFreezeSettingPane();
attrPane.populate(tplECReport.getReportPageAttr());
attrPane.populateWriteFrozenColumnRow(tplECReport.getReportSettings().getWriteFrozenColumnRow());
BasicDialog basicdialog = attrPane.showWindow(SwingUtilities.getWindowAncestor(worksheetdesigner));
basicdialog.addDialogActionListener(new DialogActionAdapter() {
final WorkSheet val$tplECReport;
final RepeatAndFreezeSettingPane val$attrPane;
final ReportPageAttrAction this$0;
public void doOk()
{
tplECReport.setReportPageAttr(attrPane.update());
tplECReport.getReportSettings().setWriteFrozenColumnRow(attrPane.updateWriteFrozenColumnRow());
returnValue = true;
}
{
this$0 = ReportPageAttrAction.this;
tplECReport = worksheet;
attrPane = repeatandfreezesettingpane;
super();
}
}
);
basicdialog.setVisible(true);
return returnValue;
}
}
}
| 2,775 | 0.677917 | 0.674327 | 73 | 37.150684 | 30.869886 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520548 | false | false | 9 |
53531173f5cbf411d37d1c921fa490cfe24c443c | 30,897,994,775,993 | a1f248670f307a3b19e7fd06d33d208855cf197b | /org.aion.avm.tooling/test/org/aion/avm/tooling/AionBufferPerfTest.java | 64689568861dcb369d87d3de45d1dde71a75ed44 | [
"MIT"
]
| permissive | fulldecent/AVM | https://github.com/fulldecent/AVM | 748b16116273c7b39c494901a2c4b0affde65ee3 | cd2e8d4fbe5b5098a74486a23bb45107f3b39912 | refs/heads/master | 2020-06-03T15:36:39.481000 | 2019-06-04T19:31:48 | 2019-06-12T18:29:30 | 191,631,334 | 0 | 1 | null | true | 2019-06-12T19:20:45 | 2019-06-12T19:20:45 | 2019-06-12T18:47:19 | 2019-06-12T19:09:23 | 10,982 | 0 | 0 | 0 | null | false | false | package org.aion.avm.tooling;
import java.math.BigInteger;
import org.aion.types.AionAddress;
import org.aion.avm.core.AvmConfiguration;
import org.aion.avm.core.AvmImpl;
import org.aion.avm.core.CommonAvmFactory;
import org.aion.avm.core.dappreading.JarBuilder;
import org.aion.avm.tooling.poc.AionBufferPerfContract;
import org.aion.avm.core.util.CodeAndArguments;
import org.aion.avm.core.util.Helpers;
import org.aion.kernel.AvmTransactionResult;
import org.aion.kernel.TestingBlock;
import org.aion.kernel.TestingKernel;
import org.aion.kernel.TestingTransaction;
import org.aion.vm.api.interfaces.KernelInterface;
import org.aion.vm.api.interfaces.TransactionResult;
import org.junit.Assert;
import org.junit.Test;
public class AionBufferPerfTest {
private AionAddress from = TestingKernel.PREMINED_ADDRESS;
private long energyLimit = 100_000_000L;
private long energyPrice = 1;
private byte[] buildBufferPerfJar() {
return JarBuilder.buildJarForMainAndClassesAndUserlib(AionBufferPerfContract.class);
}
private TransactionResult deploy(KernelInterface kernel, AvmImpl avm, byte[] testJar){
byte[] testWalletArguments = new byte[0];
TestingTransaction createTransaction = TestingTransaction.create(from, kernel.getNonce(from), BigInteger.ZERO, new CodeAndArguments(testJar, testWalletArguments).encodeToBytes(), energyLimit, energyPrice);
TransactionResult createResult = avm.run(kernel, new TestingTransaction[] {createTransaction})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.SUCCESS, createResult.getResultCode());
return createResult;
}
private TransactionResult call(KernelInterface kernel, AvmImpl avm, AionAddress contract, AionAddress sender, byte[] args) {
TestingTransaction callTransaction = TestingTransaction.call(sender, contract, kernel.getNonce(sender), BigInteger.ZERO, args, energyLimit, 1L);
TransactionResult callResult = avm.run(kernel, new TestingTransaction[] {callTransaction})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.SUCCESS, callResult.getResultCode());
return callResult;
}
@Test
public void testBuffer() {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(">> Energy measurements for AionBuffer\n>>");
byte[] args;
TestingBlock block = new TestingBlock(new byte[32], 1, Helpers.randomAddress(), System.currentTimeMillis(), new byte[0]);
KernelInterface kernel = new TestingKernel(block);
AvmImpl avm = CommonAvmFactory.buildAvmInstanceForConfiguration(new StandardCapabilities(), new AvmConfiguration());
TransactionResult deployRes = deploy(kernel, avm, buildBufferPerfJar());
AionAddress contract = new AionAddress(deployRes.getReturnData());
args = ABIUtil.encodeMethodArguments("callPutByte");
AvmTransactionResult putByteResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putByte() : " + putByteResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetByte");
AvmTransactionResult getByteResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getByte() : " + getByteResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutChar");
AvmTransactionResult putCharResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putChar() : " + putCharResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetChar");
AvmTransactionResult getCharResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getChar() : " + getCharResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutShort");
AvmTransactionResult putShortResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putShort() : " + putShortResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetShort");
AvmTransactionResult getShortResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getShort() : " + getShortResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutInt");
AvmTransactionResult putIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putInt() : " + putIntResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetInt");
AvmTransactionResult getIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getInt() : " + getIntResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutFloat");
AvmTransactionResult putFloatResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putFloat() : " + putFloatResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetFloat");
AvmTransactionResult getFloatResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getFloat() : " + getFloatResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutLong");
AvmTransactionResult putLongResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putLong() : " + putLongResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetLong");
AvmTransactionResult getLongResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getLong() : " + getLongResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutDouble");
AvmTransactionResult putDoubleResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putDouble() : " + putDoubleResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetDouble");
AvmTransactionResult getDoubleResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getDouble() : " + getDoubleResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutAddress");
AvmTransactionResult putAddressResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putAddress() : " + putAddressResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callGetAddress");
AvmTransactionResult getAddressResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getAddress() : " + getAddressResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callPutBigInt");
AvmTransactionResult putBigIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putBigInt() : " + putBigIntResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callGetBigInt");
AvmTransactionResult getBigIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getBigInt() : " + getBigIntResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callTransferBytesToBuffer");
AvmTransactionResult putResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> put() : "
+ putResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS
+ " (for transfers of " + AionBufferPerfContract.TRANSFER_SIZE + " bytes)");
args = ABIUtil.encodeMethodArguments("callTransferBytesFromBuffer");
AvmTransactionResult getResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> get() : "
+ getResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS
+ " (for transfers of " + AionBufferPerfContract.TRANSFER_SIZE + " bytes)");
args = ABIUtil.encodeMethodArguments("callEquals");
AvmTransactionResult equalsResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> equals() : " + equalsResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
avm.shutdown();
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
}
| UTF-8 | Java | 9,584 | java | AionBufferPerfTest.java | Java | []
| null | []
| package org.aion.avm.tooling;
import java.math.BigInteger;
import org.aion.types.AionAddress;
import org.aion.avm.core.AvmConfiguration;
import org.aion.avm.core.AvmImpl;
import org.aion.avm.core.CommonAvmFactory;
import org.aion.avm.core.dappreading.JarBuilder;
import org.aion.avm.tooling.poc.AionBufferPerfContract;
import org.aion.avm.core.util.CodeAndArguments;
import org.aion.avm.core.util.Helpers;
import org.aion.kernel.AvmTransactionResult;
import org.aion.kernel.TestingBlock;
import org.aion.kernel.TestingKernel;
import org.aion.kernel.TestingTransaction;
import org.aion.vm.api.interfaces.KernelInterface;
import org.aion.vm.api.interfaces.TransactionResult;
import org.junit.Assert;
import org.junit.Test;
public class AionBufferPerfTest {
private AionAddress from = TestingKernel.PREMINED_ADDRESS;
private long energyLimit = 100_000_000L;
private long energyPrice = 1;
private byte[] buildBufferPerfJar() {
return JarBuilder.buildJarForMainAndClassesAndUserlib(AionBufferPerfContract.class);
}
private TransactionResult deploy(KernelInterface kernel, AvmImpl avm, byte[] testJar){
byte[] testWalletArguments = new byte[0];
TestingTransaction createTransaction = TestingTransaction.create(from, kernel.getNonce(from), BigInteger.ZERO, new CodeAndArguments(testJar, testWalletArguments).encodeToBytes(), energyLimit, energyPrice);
TransactionResult createResult = avm.run(kernel, new TestingTransaction[] {createTransaction})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.SUCCESS, createResult.getResultCode());
return createResult;
}
private TransactionResult call(KernelInterface kernel, AvmImpl avm, AionAddress contract, AionAddress sender, byte[] args) {
TestingTransaction callTransaction = TestingTransaction.call(sender, contract, kernel.getNonce(sender), BigInteger.ZERO, args, energyLimit, 1L);
TransactionResult callResult = avm.run(kernel, new TestingTransaction[] {callTransaction})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.SUCCESS, callResult.getResultCode());
return callResult;
}
@Test
public void testBuffer() {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(">> Energy measurements for AionBuffer\n>>");
byte[] args;
TestingBlock block = new TestingBlock(new byte[32], 1, Helpers.randomAddress(), System.currentTimeMillis(), new byte[0]);
KernelInterface kernel = new TestingKernel(block);
AvmImpl avm = CommonAvmFactory.buildAvmInstanceForConfiguration(new StandardCapabilities(), new AvmConfiguration());
TransactionResult deployRes = deploy(kernel, avm, buildBufferPerfJar());
AionAddress contract = new AionAddress(deployRes.getReturnData());
args = ABIUtil.encodeMethodArguments("callPutByte");
AvmTransactionResult putByteResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putByte() : " + putByteResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetByte");
AvmTransactionResult getByteResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getByte() : " + getByteResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutChar");
AvmTransactionResult putCharResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putChar() : " + putCharResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetChar");
AvmTransactionResult getCharResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getChar() : " + getCharResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutShort");
AvmTransactionResult putShortResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putShort() : " + putShortResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetShort");
AvmTransactionResult getShortResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getShort() : " + getShortResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutInt");
AvmTransactionResult putIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putInt() : " + putIntResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetInt");
AvmTransactionResult getIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getInt() : " + getIntResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutFloat");
AvmTransactionResult putFloatResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putFloat() : " + putFloatResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetFloat");
AvmTransactionResult getFloatResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getFloat() : " + getFloatResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutLong");
AvmTransactionResult putLongResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putLong() : " + putLongResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetLong");
AvmTransactionResult getLongResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getLong() : " + getLongResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutDouble");
AvmTransactionResult putDoubleResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putDouble() : " + putDoubleResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callGetDouble");
AvmTransactionResult getDoubleResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getDouble() : " + getDoubleResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
args = ABIUtil.encodeMethodArguments("callPutAddress");
AvmTransactionResult putAddressResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putAddress() : " + putAddressResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callGetAddress");
AvmTransactionResult getAddressResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getAddress() : " + getAddressResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callPutBigInt");
AvmTransactionResult putBigIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> putBigInt() : " + putBigIntResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callGetBigInt");
AvmTransactionResult getBigIntResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> getBigInt() : " + getBigIntResult.getEnergyUsed() / AionBufferPerfContract.BIG_ELT_COUNT);
args = ABIUtil.encodeMethodArguments("callTransferBytesToBuffer");
AvmTransactionResult putResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> put() : "
+ putResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS
+ " (for transfers of " + AionBufferPerfContract.TRANSFER_SIZE + " bytes)");
args = ABIUtil.encodeMethodArguments("callTransferBytesFromBuffer");
AvmTransactionResult getResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> get() : "
+ getResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS
+ " (for transfers of " + AionBufferPerfContract.TRANSFER_SIZE + " bytes)");
args = ABIUtil.encodeMethodArguments("callEquals");
AvmTransactionResult equalsResult = (AvmTransactionResult) call(kernel, avm, contract, from, args);
System.out.println(">> equals() : " + equalsResult.getEnergyUsed() / AionBufferPerfContract.NUM_ELEMENTS);
avm.shutdown();
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
}
| 9,584 | 0.696578 | 0.6947 | 151 | 62.4702 | 48.292404 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.437086 | false | false | 9 |
fad17bd1448abd877ec4238c7cea8d99c1ec0438 | 29,566,554,870,507 | 9b26770787a3d522a5d116ccd8f26a80b9ce81af | /src/main/java/com/inbravo/scribe/rest/service/crm/ns/v2k9/NSCRMV2K9Service.java | b0403e0d6c247778d1ffe2af300e6bc6562d079b | [
"MIT"
]
| permissive | inbravo/cad | https://github.com/inbravo/cad | 2441923e4a4aabbf2a6689b92b27a3b6e025d9c8 | 29ce62e1035427245ac21aa992bb524fc09f10c7 | refs/heads/master | 2020-12-24T08:00:43.196000 | 2016-09-01T06:32:32 | 2016-09-01T06:32:32 | 56,223,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* MIT License
*
* Copyright (c) 2016 Amit Dixit (github.com/inbravo)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inbravo.scribe.rest.service.crm.ns.v2k9;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.inbravo.scribe.exception.ScribeException;
import com.inbravo.scribe.exception.ScribeResponseCodes;
import com.inbravo.scribe.rest.constants.HTTPConstants;
import com.inbravo.scribe.rest.constants.CRMConstants.NSCRMObjectType;
import com.inbravo.scribe.rest.resource.ScribeObject;
import com.inbravo.scribe.rest.service.crm.ns.NSCRMGenericService;
import com.inbravo.scribe.rest.service.crm.ns.NetSuiteMessageFormatUtils;
import com.inbravo.scribe.rest.service.crm.ns.type.NSCRMFieldTypes;
import com.netsuite.webservices.activities.scheduling.PhoneCall;
import com.netsuite.webservices.activities.scheduling.Task;
import com.netsuite.webservices.activities.scheduling.TaskSearch;
import com.netsuite.webservices.activities.scheduling.types.PhoneCallStatus;
import com.netsuite.webservices.activities.scheduling.types.TaskStatus;
import com.netsuite.webservices.lists.employees.EmployeeSearch;
import com.netsuite.webservices.lists.relationships.Contact;
import com.netsuite.webservices.lists.relationships.ContactSearch;
import com.netsuite.webservices.lists.relationships.Customer;
import com.netsuite.webservices.lists.relationships.CustomerSearch;
import com.netsuite.webservices.lists.support.SupportCase;
import com.netsuite.webservices.lists.support.SupportCaseSearch;
import com.netsuite.webservices.platform.common.ContactSearchBasic;
import com.netsuite.webservices.platform.common.CustomerSearchBasic;
import com.netsuite.webservices.platform.common.EmployeeSearchBasic;
import com.netsuite.webservices.platform.common.OpportunitySearchBasic;
import com.netsuite.webservices.platform.common.SupportCaseSearchBasic;
import com.netsuite.webservices.platform.common.TaskSearchBasic;
import com.netsuite.webservices.platform.core.BooleanCustomFieldRef;
import com.netsuite.webservices.platform.core.CustomFieldList;
import com.netsuite.webservices.platform.core.CustomFieldRef;
import com.netsuite.webservices.platform.core.DateCustomFieldRef;
import com.netsuite.webservices.platform.core.DoubleCustomFieldRef;
import com.netsuite.webservices.platform.core.Duration;
import com.netsuite.webservices.platform.core.ListOrRecordRef;
import com.netsuite.webservices.platform.core.LongCustomFieldRef;
import com.netsuite.webservices.platform.core.MultiSelectCustomFieldRef;
import com.netsuite.webservices.platform.core.RecordRef;
import com.netsuite.webservices.platform.core.SearchBooleanCustomField;
import com.netsuite.webservices.platform.core.SearchBooleanField;
import com.netsuite.webservices.platform.core.SearchCustomField;
import com.netsuite.webservices.platform.core.SearchCustomFieldList;
import com.netsuite.webservices.platform.core.SearchDateCustomField;
import com.netsuite.webservices.platform.core.SearchDateField;
import com.netsuite.webservices.platform.core.SearchDoubleField;
import com.netsuite.webservices.platform.core.SearchEnumMultiSelectField;
import com.netsuite.webservices.platform.core.SearchLongCustomField;
import com.netsuite.webservices.platform.core.SearchLongField;
import com.netsuite.webservices.platform.core.SearchMultiSelectCustomField;
import com.netsuite.webservices.platform.core.SearchRecord;
import com.netsuite.webservices.platform.core.SearchStringCustomField;
import com.netsuite.webservices.platform.core.SearchStringField;
import com.netsuite.webservices.platform.core.SearchTextNumberField;
import com.netsuite.webservices.platform.core.StringCustomFieldRef;
import com.netsuite.webservices.platform.core.types.DurationUnit;
import com.netsuite.webservices.platform.core.types.SearchDateFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchDoubleFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchEnumMultiSelectFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchLongFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchMultiSelectFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchStringFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchTextNumberFieldOperator;
import com.netsuite.webservices.transactions.sales.Opportunity;
import com.netsuite.webservices.transactions.sales.OpportunitySearch;
/**
*
* @author amit.dixit
*
*/
public final class NSCRMV2K9Service implements NSCRMGenericService {
private static final Logger logger = Logger.getLogger(NSCRMV2K9Service.class.getName());
/**
*
* @param query
* @param order
* @param crmFieldsSeparator
* @param orderFieldsSeparator
* @return
* @throws Exception
*/
public final SearchRecord createCustomerSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create customer search */
final CustomerSearch customerSearch = new CustomerSearch();
/* Create customer search basic object to set search variable */
CustomerSearchBasic customerSearchBasic = new CustomerSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createCustomerSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/**
* Set the customerSearchBasic. We should not interpret NULL since we should support empty
* value itself. Let the client to decide what to do.
*/
customerSearchBasic =
this.updateCustomerSearchBasic(customerSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
customerSearch.setBasic(customerSearchBasic);
return customerSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createContactSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create contact search */
final ContactSearch contactSearch = new ContactSearch();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Create new contact search basic object */
ContactSearchBasic contactSearchBasic = new ContactSearchBasic();
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createContactSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update contact search object search */
contactSearchBasic =
this.updateContactSearchBasic(contactSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search basic in search object */
contactSearch.setBasic(contactSearchBasic);
return contactSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createSupportCaseSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create SupportCaseSearch */
final SupportCaseSearch supportCaseSearch = new SupportCaseSearch();
/* Create SupportCaseSearchBasic object to set search varialble */
SupportCaseSearchBasic supportCaseSearchBasic = new SupportCaseSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createSupportCaseSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update support case search object search */
supportCaseSearchBasic =
this.updateSupportCaseSearchBasic(supportCaseSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2],
splitSearchStringResult[1], crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
supportCaseSearch.setBasic(supportCaseSearchBasic);
return supportCaseSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createTaskSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create TaskSearch */
final TaskSearch taskSearch = new TaskSearch();
/* Create TaskSearchBasic object to set search varialble */
TaskSearchBasic taskSearchBasic = new TaskSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createTaskSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update task search object search */
taskSearchBasic =
this.updateTaskSearchBasic(taskSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
taskSearch.setBasic(taskSearchBasic);
return taskSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createOpportunitySearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create OpportunitySearch */
final OpportunitySearch opportunitySearch = new OpportunitySearch();
/* Create OpportunitySearchBasic object to set search varialble */
OpportunitySearchBasic opportunitySearchBasic = new OpportunitySearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createOpportunitySearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update opportunity search object search */
opportunitySearchBasic =
this.updateOpportunitySearchBasic(opportunitySearchBasic, splitSearchStringResult[0], splitSearchStringResult[2],
splitSearchStringResult[1], crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
opportunitySearch.setBasic(opportunitySearchBasic);
return opportunitySearch;
} else {
return null;
}
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final SupportCaseSearchBasic updateSupportCaseSearchBasic(final SupportCaseSearchBasic supportCaseSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateSupportCaseSearch cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = supportCaseSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
supportCaseSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
supportCaseSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(supportCaseSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return supportCaseSearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final OpportunitySearchBasic updateOpportunitySearchBasic(final OpportunitySearchBasic opportunitySearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateOpportunitySearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldOperator: " + cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = opportunitySearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
opportunitySearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
opportunitySearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(opportunitySearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return opportunitySearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final TaskSearchBasic updateTaskSearchBasic(final TaskSearchBasic taskSearchBasic, final String cRMFieldName, final String cRMFieldValue,
final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateTaskSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = taskSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
taskSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
taskSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(taskSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return taskSearchBasic;
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createEmployeeSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + " Operator: '" + HTTPConstants.orClause + "' is not supported by NS CRM");
}
/* Create new employee search */
final EmployeeSearch employeeSearch = new EmployeeSearch();
/* Create new employee search basic */
EmployeeSearchBasic employeeSearchBasic = new EmployeeSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createEmployeeSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update employee search object search */
employeeSearchBasic =
this.updateEmployeeSearchBasic(employeeSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Search this basis in employee search object */
employeeSearch.setBasic(employeeSearchBasic);
return employeeSearch;
} else {
return null;
}
}
/**
*
* @param customerSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final CustomerSearchBasic updateCustomerSearchBasic(final CustomerSearchBasic customerSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateCustomerSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
/* Split the cRMFieldName on the basis of seperator */
if (cRMFieldName != null && cRMFieldName.contains(crmFieldIntraSeparator)) {
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = customerSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
customerSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
customerSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(customerSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return customerSearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final EmployeeSearchBasic updateEmployeeSearchBasic(final EmployeeSearchBasic employeeSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateEmployeeSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = employeeSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
employeeSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
employeeSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(employeeSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return employeeSearchBasic;
}
private final Object getNormalFieldForSearchOperation(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue,
final String cRMFieldOperator, final String inputDateFormat) {
logger.debug("----Inside getNormalFieldForSearchOperation cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldType: " + cRMFieldType);
/* Create date formatter */
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_LONG_FIELD)) {
/* Create new search long field */
final SearchLongField searchLongField = new SearchLongField();
final SearchLongFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchLongFieldOperator.fromString(cRMFieldOperator);
searchLongField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchLongFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchLongField.setSearchValue(Long.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'int/long' format");
}
return searchLongField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_STRING_FIELD)) {
logger.info("----Inside getNormalFieldForSearchOperation SearchStringField, with operator: " + cRMFieldOperator);
/* Create new search string field */
final SearchStringField searchStringField = new SearchStringField();
final SearchStringFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchStringFieldOperator.fromString(cRMFieldOperator);
searchStringField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchStringFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchStringField.setSearchValue(cRMFieldValue);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'string' format");
}
return searchStringField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_BOOLEAN_FIELD)) {
/* TODO how to add operator? */
/* Create new search boolean field */
final SearchBooleanField searchBooleanField = new SearchBooleanField();
try {
/* Set value */
searchBooleanField.setSearchValue(Boolean.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
return searchBooleanField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DATE_FIELD)) {
/* Create new date boolean field */
final SearchDateField searchDateField = new SearchDateField();
final SearchDateFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchDateFieldOperator.fromString(cRMFieldOperator);
searchDateField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchDateFieldOperator '" + cRMFieldOperator + "'.");
}
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTime(simpleDateFormat.parse(cRMFieldValue));
/* Set value */
searchDateField.setSearchValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be od format: '"
+ inputDateFormat + "'");
}
return searchDateField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_TEXT_NUMBER_FIELD)) {
/* Create new text string field */
final SearchTextNumberField searchTextNumberField = new SearchTextNumberField();
final SearchTextNumberFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchTextNumberFieldOperator.fromString(cRMFieldOperator);
searchTextNumberField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchTextNumberField '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchTextNumberField.setSearchValue(cRMFieldValue);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be of format 'text'");
}
return searchTextNumberField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DOUBLE_FIELD)) {
/* Create new double string field */
final SearchDoubleField searchDoubleField = new SearchDoubleField();
final SearchDoubleFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchDoubleFieldOperator.fromString(cRMFieldOperator);
searchDoubleField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchDoubleFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchDoubleField.setSearchValue(Double.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be of format 'double'");
}
return searchDoubleField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_ENUM_MULTI_SELECT_FIELD)) {
/* Create new Search Enum Multi Select Field field */
final SearchEnumMultiSelectField searchEnumMultiSelectField = new SearchEnumMultiSelectField();
final SearchEnumMultiSelectFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchEnumMultiSelectFieldOperator.fromString(cRMFieldOperator);
searchEnumMultiSelectField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchEnumMultiSelectField '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
final String[] value = new String[1];
value[0] = cRMFieldValue;
searchEnumMultiSelectField.setSearchValue(value);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Value of CRM object field '" + cRMFieldName + "' should be of type: 'Select'");
}
return searchEnumMultiSelectField;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Customer createCustomer(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createCustomer");
/* Create new Customer */
final Customer customer = new Customer();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createCustomer, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createCustomer, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createCustomer, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
customer.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(customer, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in customer */
customer.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return customer;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Contact createContact(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createContact");
/* Create new contact */
final Contact contact = new Contact();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createContact, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createContact, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createContact, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
contact.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(contact, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in customer */
contact.setCustomFieldList(newCustomFieldList);
}
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return contact;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Opportunity createOpportunity(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createOpportunity");
/* Create new opportunity */
final Opportunity opportunity = new Opportunity();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createOpportunity, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createOpportunity, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createOpportunity, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
opportunity.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(opportunity, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in opportunity */
opportunity.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return opportunity;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws Exception
*/
public final Task createTask(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createTask");
/* Create new Task */
final Task task = new Task();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createTask, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createTask, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createTask, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createTask, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createTask, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set this contact info in task */
task.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createTask, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set company information in task */
task.setCompany(companyRef);
}
/* Check if object is support case */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.SupportCase.toString())) {
final RecordRef supportRef = new RecordRef();
logger.debug("----Inside createTask, support case is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
supportRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set support case information in task */
task.setSupportCase(supportRef);
}
/* Check if object is opportunity */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Opportunity.toString())) {
final RecordRef opportunityRef = new RecordRef();
logger.debug("----Inside createTask, opportunity is being processed");
/* Check if opportunity has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
opportunityRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set transaction information in task */
task.setTransaction(opportunityRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + "/" + NSCRMObjectType.SupportCase
+ " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createTask, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
task.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(task, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
}
}
} else {
logger.debug("----Inside createTask, no node name, skipped");
}
}
/* Dont set contact/case if company is not found */
if (task.getCompany() == null) {
logger.debug("----Inside createTask, company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
task.setContact(null);
/* Support case without company dont work at NS */
task.setSupportCase(null);
} else {
final RecordRef companyRef = task.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createTask, internal id of company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
task.setContact(null);
/* Support case without company dont work at NS */
task.setSupportCase(null);
/* Support case without company dont work at NS */
task.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
task.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createTask, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return task;
}
@SuppressWarnings("unused")
private final Object getNSCRMFieldObject(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue) {
logger.debug("----Inside getNSCRMFieldObject cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldType: "
+ cRMFieldType);
/* Trim the value */
if (cRMFieldValue != null) {
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG)) {
try {
/* Set value */
return Long.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'int/long'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING)) {
try {
/* Set value */
return String.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'string'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN)) {
try {
/* Set value */
return Boolean.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'boolean'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_CALANDER)) {
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
return calendar;
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DURATION)) {
try {
/* Create duration object */
final Duration duration = new Duration();
duration.setUnit(DurationUnit.hour);
/* Set value */
duration.setTimeSpan(Double.valueOf(cRMFieldValue.trim()));
return duration;
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE)) {
try {
/* Set value */
return Double.valueOf(cRMFieldValue.trim());
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_RECORD_REF)) {
final RecordRef recordRef = new RecordRef();
/* Check if record has an internal id */
if (cRMFieldValue != null) {
/* Set internal id of referenced contact */
recordRef.setInternalId(cRMFieldValue.trim().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
return recordRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_TASK_STATUS)) {
/* Check if record has an internal id */
if (cRMFieldValue != null && cRMFieldValue.equalsIgnoreCase("COMPLETED")) {
/* Set completed */
return TaskStatus._completed;
} else {
/* Set inprogress */
return TaskStatus._inProgress;
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_PHONE_CALL_STATUS)) {
/* Check if record has an internal id */
if (cRMFieldValue != null && cRMFieldValue.equalsIgnoreCase("COMPLETED")) {
/* Set completed */
return PhoneCallStatus._completed;
} else {
/* Set inprogress */
return PhoneCallStatus._scheduled;
}
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
} else {
return null;
}
}
private final Class<?> getNSCRMFieldParamType(final String cRMFieldType) {
logger.debug("----Inside getNSCRMFieldParamType cRMFieldType: " + cRMFieldType);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG)) {
return Long.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING)) {
return String.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN)) {
return Boolean.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_CALANDER)) {
return Calendar.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DURATION)) {
return Duration.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE)) {
return Double.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_RECORD_REF)) {
return RecordRef.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_TASK_STATUS)) {
return TaskStatus.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_PHONE_CALL_STATUS)) {
return PhoneCallStatus.class;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param cRMFieldName
* @param cRMFieldType
* @param cRMFieldValue
* @return
*/
private final CustomFieldRef getCustomFieldForCreateOperation(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue) {
logger.debug("----Inside getCustomFieldForCreateOperation cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldType: " + cRMFieldType);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING_CUSTOM_FIELD_REF)) {
/* Create new custom string field */
final StringCustomFieldRef stringCustomFieldRef = new StringCustomFieldRef();
/* Set internal id */
stringCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
stringCustomFieldRef.setValue(cRMFieldValue.trim());
}
return stringCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_MUTISELECT_CUSTOM_FIELD_REF)) {
/* Create new multi select field reference */
final MultiSelectCustomFieldRef multiSelectCustomFieldRef = new MultiSelectCustomFieldRef();
multiSelectCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
final ListOrRecordRef[] list = new ListOrRecordRef[1];
list[0] = new ListOrRecordRef();
list[0].setInternalId(cRMFieldValue.trim());
list[0].setTypeId(cRMFieldName);
multiSelectCustomFieldRef.setValue(list);
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Field value is is invalid: " + cRMFieldType);
}
return multiSelectCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN_CUSTOM_FIELD_REF)) {
/* Create new boolean field reference */
final BooleanCustomFieldRef booleanCustomFieldRef = new BooleanCustomFieldRef();
/* Set internal id */
booleanCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
booleanCustomFieldRef.setValue(Boolean.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
return booleanCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG_CUSTOM_FIELD_REF)) {
/* Create new long field reference */
final LongCustomFieldRef longCustomFieldRef = new LongCustomFieldRef();
/* Set internal id */
longCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
longCustomFieldRef.setValue(Long.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
return longCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE_CUSTOM_FIELD_REF)) {
/* Create new double field reference */
final DoubleCustomFieldRef doubleCustomFieldRef = new DoubleCustomFieldRef();
/* Set internal id */
doubleCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
doubleCustomFieldRef.setValue(Double.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double/float' format");
}
return doubleCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DATE_CUSTOM_FIELD_REF)) {
/* Create new date field reference */
final DateCustomFieldRef dateCustomFieldRef = new DateCustomFieldRef();
/* Set internal id */
dateCustomFieldRef.setInternalId(cRMFieldName);
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
/* Set value */
dateCustomFieldRef.setValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
return dateCustomFieldRef;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param cRMFieldName
* @param cRMFieldType
* @param cRMFieldValue
* @param cRMFieldOperator
* @return
*/
private final SearchCustomField getCustomCRMSearchObject(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue,
final String cRMFieldOperator) {
logger.debug("----Inside getCustomCRMSearchObject cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldType: "
+ cRMFieldType);
/* If field is string type */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_STRING_CUSTOM_FIELD)) {
/* Create new custom string field */
final SearchStringCustomField searchStringCustomField = new SearchStringCustomField();
/* Set internal id */
searchStringCustomField.setInternalId(cRMFieldName);
final SearchStringFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchStringFieldOperator.fromString(cRMFieldOperator);
searchStringCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchStringCustomField '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
/* Set value */
searchStringCustomField.setSearchValue(cRMFieldValue);
}
return searchStringCustomField;
} else
/* Check if type of custom field is long */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_LONG_CUSTOM_FIELD)) {
/* Create new custom string field */
final SearchLongCustomField searchLongCustomField = new SearchLongCustomField();
/* Set internal id */
searchLongCustomField.setInternalId(cRMFieldName);
final SearchLongFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchLongFieldOperator.fromString(cRMFieldOperator);
searchLongCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchLongCustomFields '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
try {
/* Set value */
searchLongCustomField.setSearchValue(Long.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in int/long format");
}
}
return searchLongCustomField;
} else
/* Check if type of custom field is date */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DATE_CUSTOM_FIELD)) {
/* Create new custom date field */
final SearchDateCustomField searchDateCustomField = new SearchDateCustomField();
/* Set internal id */
searchDateCustomField.setInternalId(cRMFieldName);
final SearchDateFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchDateFieldOperator.fromString(cRMFieldOperator);
searchDateCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchDateCustomField '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
/* Set value */
searchDateCustomField.setSearchValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
}
return searchDateCustomField;
} else
/* Check if type of custom field is boolean */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_BOOLEAN_CUSTOM_FIELD)) {
/* Create new custom boolean field */
final SearchBooleanCustomField searchBooleanCustomField = new SearchBooleanCustomField();
/* TODO how to set operator? */
/* Set internal id */
searchBooleanCustomField.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
try {
/* Set value */
searchBooleanCustomField.setSearchValue(Boolean.valueOf(cRMFieldValue));
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
}
return searchBooleanCustomField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_MULTI_SELECT_CUSTOM_FIELD)) {
logger.info("----Inside getCustomCRMSearchObject, found multiselect value: " + cRMFieldValue);
/* Create new Search Enum Multi Select Field field */
final SearchMultiSelectCustomField searchMultiSelectCustomField = new SearchMultiSelectCustomField();
final SearchMultiSelectFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchMultiSelectFieldOperator.fromString(cRMFieldOperator);
searchMultiSelectCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchMultiSelectCustomField '" + cRMFieldOperator + "'.");
}
/* Set value */
final SearchCustomFieldList searchCustomFieldList = new SearchCustomFieldList();
/* Split the value */
final String[] splitIdValue = this.splitCustomMutliSelectValue(cRMFieldValue);
final ListOrRecordRef listOrRecordRef = new ListOrRecordRef();
/* Set internal id */
listOrRecordRef.setInternalId(splitIdValue[1]);
/* Set type id */
listOrRecordRef.setTypeId(splitIdValue[0]);
/* Set internal id of the custom field name */
searchMultiSelectCustomField.setInternalId(cRMFieldName);
searchCustomFieldList.setCustomField(new SearchCustomField[] {searchMultiSelectCustomField});
searchMultiSelectCustomField.setSearchValue(new ListOrRecordRef[] {listOrRecordRef});
logger.info("----Inside getCustomCRMSearchObject, returning multi-select custom field reference. " + cRMFieldName);
return searchMultiSelectCustomField;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Following type: " + cRMFieldType + " is not supported");
}
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final SupportCase createSupportCase(final ScribeObject cADbject, final String crmFieldIntraSeparator) {
logger.debug("----Inside createSupportCase");
/* Create new support case */
final SupportCase supportCase = new SupportCase();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createSupportCase, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createSupportCase, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createSupportCase, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createSupportCase, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createSupportCase, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createSupportCase, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createSupportCase, regardingobjectid doesn't carry id");
}
/* Set this contact info in supportCase */
supportCase.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createSupportCase, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createSupportCase, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createSupportCase, regardingobjectid doesn't carry id");
}
/* Set company information in supportCase */
supportCase.setCompany(companyRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createSupportCase, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
supportCase.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(supportCase, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
}
}
} else {
logger.debug("----Inside createSupportCase, no node name, skipped");
}
}
/* Don't set contact if company is not found */
if (supportCase.getCompany() == null) {
logger.debug("----Inside createSupportCase, company is not found, hence removing contact");
/* Contact without company dont work at NS */
supportCase.setContact(null);
} else {
final RecordRef companyRef = supportCase.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createSupportCase, internal id of company is not found, hence removing contact");
/* Contact without company dont work at NS */
supportCase.setContact(null);
/* Contact without company dont work at NS */
supportCase.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
supportCase.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createSupportCase, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return supportCase;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final PhoneCall createPhoneCall(final ScribeObject cADbject, final String crmFieldIntraSeparator) {
logger.debug("----Inside createPhoneCall");
/* Create new Phone Call */
final PhoneCall phoneCall = new PhoneCall();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createPhoneCall, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createPhoneCall, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createPhoneCall, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createPhoneCall, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set this contact info in phoneCall */
phoneCall.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createPhoneCall, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set company information in task */
phoneCall.setCompany(companyRef);
}
/* Check if object is support case */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.SupportCase.toString())) {
final RecordRef supportRef = new RecordRef();
logger.debug("----Inside createPhoneCall, support case is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
supportRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set support case information in phoneCall */
phoneCall.setSupportCase(supportRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a custom field reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
} else {
/* Invoke the normal field setter method */
phoneCall.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(phoneCall, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
}
}
} else {
logger.debug("----Inside createPhoneCall, no node name, skipped");
}
}
/* Dont set contact/case if company is not found */
if (phoneCall.getCompany() == null) {
logger.debug("----Inside createPhoneCall, company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
phoneCall.setContact(null);
/* Support case without company dont work at NS */
phoneCall.setSupportCase(null);
} else {
final RecordRef companyRef = phoneCall.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createPhoneCall, internal id of company is not found, hence removing contact");
/* Contact without company dont work at NS */
phoneCall.setContact(null);
/* Support case without company dont work at NS */
phoneCall.setSupportCase(null);
/* Support case without company dont work at NS */
phoneCall.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
phoneCall.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createPhoneCall, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return phoneCall;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final ContactSearchBasic updateContactSearchBasic(final ContactSearchBasic contactSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat)
throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
logger.debug("----Inside updateContactSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + contactSearchBasic
+ " & cRMFieldOperator: " + cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = contactSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
contactSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the method */
contactSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(contactSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + " CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return contactSearchBasic;
}
private final SearchCustomField[] getCustomFieldForSearchOperation(final SearchCustomFieldList searchCustomFieldList, final String cRMFieldName,
final String cRMFieldType, final String cRMFieldValue, final String cRMFieldOperator) {
SearchCustomField[] searchCustomFieldUpdated = null;
/* Check if any list is already set */
if (searchCustomFieldList == null) {
/* Initialize it */
searchCustomFieldUpdated = new SearchCustomField[1];
/* Populate new array with additional values */
searchCustomFieldUpdated[0] = this.getCustomCRMSearchObject(cRMFieldName.trim(), cRMFieldType.trim(), cRMFieldValue, cRMFieldOperator);
} else {
searchCustomFieldUpdated = new SearchCustomField[searchCustomFieldList.getCustomField().length + 1];
/* Copy old array into new one */
System.arraycopy(searchCustomFieldList.getCustomField(), 0, searchCustomFieldUpdated, 0, searchCustomFieldList.getCustomField().length);
/* Populate new array with additional values */
searchCustomFieldUpdated[searchCustomFieldList.getCustomField().length] =
this.getCustomCRMSearchObject(cRMFieldName.trim(), cRMFieldType.trim(), cRMFieldValue, cRMFieldOperator);
}
return searchCustomFieldUpdated;
}
/**
*
* @param refArrayList
* @return
*/
private final CustomFieldRef[] getCustomFieldRefArray(List<CustomFieldRef> refArrayList) {
CustomFieldRef[] customFieldRefUpdated = null;
/* Check if any list is already set */
if (refArrayList == null || refArrayList.size() == 0) {
return null;
}
/* Initialize it */
customFieldRefUpdated = new CustomFieldRef[refArrayList.size()];
int counter = 0;
for (final CustomFieldRef ref : refArrayList) {
customFieldRefUpdated[counter] = ref;
counter++;
}
return customFieldRefUpdated;
}
/**
* Split the multiselect custom field value into 2 (format typeid__valueinternalid)
*
* @param value
* @return
* @throws ScribeException
*/
private final String[] splitCustomMutliSelectValue(final String value) throws ScribeException {
/* Verify value */
if (value == null) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of MultiSelect Custom CRM object field value '" + value + "' invalid format");
} else if (value != null && !value.matches("^..*__..*$")) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of MultiSelect Custom CRM object field value '" + value + "' invalid format");
}
final String[] splitResult = new String[2];
splitResult[0] = value.replaceAll("__.*$", "");
splitResult[1] = value.replaceAll("^.*__", "");
return splitResult;
}
/**
* Split a search string into a 3 element String array.
*
* @param searchString : search string using space and delimiter.
*
* @return a 3 element String array. element 0 => search key, element 1 => search operator and
* element 2 => search value.
*/
private final String[] splitSearchString(final String searchString) throws ScribeException {
final String[] finalResult = new String[3];
/* Split the search string from user */
final String[] splitResult = searchString.split("\\s+");
/* Check if length is less than 1 */
if (splitResult.length <= 1) {
logger.error("----Inside splitSearchString: invalid search string: " + searchString);
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid search string: '" + searchString
+ "' search string should contain at least 2 words for NS CRM");
}
/* Key */
finalResult[0] = splitResult[0];
/* Operator */
finalResult[1] = splitResult[1];
/* value, it will never null but can be empty string */
finalResult[2] = searchString.replaceAll("^[ ]*" + finalResult[0] + "[ ]*" + finalResult[1] + "[ ]*", "").trim();
logger.info("----Inside splitSearchString: split the search into [" + finalResult[0] + "],[" + finalResult[1] + "],[" + finalResult[2] + "]");
return finalResult;
}
}
| UTF-8 | Java | 121,524 | java | NSCRMV2K9Service.java | Java | [
{
"context": "/*\r\n * MIT License\r\n * \r\n * Copyright (c) 2016 Amit Dixit (github.com/inbravo)\r\n * \r\n * Permission is hereb",
"end": 57,
"score": 0.9998123049736023,
"start": 47,
"tag": "NAME",
"value": "Amit Dixit"
},
{
"context": " * \r\n * Copyright (c) 2016 Amit Dixit (github.com/inbravo)\r\n * \r\n * Permission is hereby granted, free of c",
"end": 77,
"score": 0.9990642666816711,
"start": 70,
"tag": "USERNAME",
"value": "inbravo"
},
{
"context": "s.sales.OpportunitySearch;\r\n\r\n/**\r\n * \r\n * @author amit.dixit\r\n * \r\n */\r\npublic final class NSCRMV2K9Service im",
"end": 5788,
"score": 0.8207533359527588,
"start": 5778,
"tag": "NAME",
"value": "amit.dixit"
}
]
| null | []
| /*
* MIT License
*
* Copyright (c) 2016 <NAME> (github.com/inbravo)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inbravo.scribe.rest.service.crm.ns.v2k9;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.inbravo.scribe.exception.ScribeException;
import com.inbravo.scribe.exception.ScribeResponseCodes;
import com.inbravo.scribe.rest.constants.HTTPConstants;
import com.inbravo.scribe.rest.constants.CRMConstants.NSCRMObjectType;
import com.inbravo.scribe.rest.resource.ScribeObject;
import com.inbravo.scribe.rest.service.crm.ns.NSCRMGenericService;
import com.inbravo.scribe.rest.service.crm.ns.NetSuiteMessageFormatUtils;
import com.inbravo.scribe.rest.service.crm.ns.type.NSCRMFieldTypes;
import com.netsuite.webservices.activities.scheduling.PhoneCall;
import com.netsuite.webservices.activities.scheduling.Task;
import com.netsuite.webservices.activities.scheduling.TaskSearch;
import com.netsuite.webservices.activities.scheduling.types.PhoneCallStatus;
import com.netsuite.webservices.activities.scheduling.types.TaskStatus;
import com.netsuite.webservices.lists.employees.EmployeeSearch;
import com.netsuite.webservices.lists.relationships.Contact;
import com.netsuite.webservices.lists.relationships.ContactSearch;
import com.netsuite.webservices.lists.relationships.Customer;
import com.netsuite.webservices.lists.relationships.CustomerSearch;
import com.netsuite.webservices.lists.support.SupportCase;
import com.netsuite.webservices.lists.support.SupportCaseSearch;
import com.netsuite.webservices.platform.common.ContactSearchBasic;
import com.netsuite.webservices.platform.common.CustomerSearchBasic;
import com.netsuite.webservices.platform.common.EmployeeSearchBasic;
import com.netsuite.webservices.platform.common.OpportunitySearchBasic;
import com.netsuite.webservices.platform.common.SupportCaseSearchBasic;
import com.netsuite.webservices.platform.common.TaskSearchBasic;
import com.netsuite.webservices.platform.core.BooleanCustomFieldRef;
import com.netsuite.webservices.platform.core.CustomFieldList;
import com.netsuite.webservices.platform.core.CustomFieldRef;
import com.netsuite.webservices.platform.core.DateCustomFieldRef;
import com.netsuite.webservices.platform.core.DoubleCustomFieldRef;
import com.netsuite.webservices.platform.core.Duration;
import com.netsuite.webservices.platform.core.ListOrRecordRef;
import com.netsuite.webservices.platform.core.LongCustomFieldRef;
import com.netsuite.webservices.platform.core.MultiSelectCustomFieldRef;
import com.netsuite.webservices.platform.core.RecordRef;
import com.netsuite.webservices.platform.core.SearchBooleanCustomField;
import com.netsuite.webservices.platform.core.SearchBooleanField;
import com.netsuite.webservices.platform.core.SearchCustomField;
import com.netsuite.webservices.platform.core.SearchCustomFieldList;
import com.netsuite.webservices.platform.core.SearchDateCustomField;
import com.netsuite.webservices.platform.core.SearchDateField;
import com.netsuite.webservices.platform.core.SearchDoubleField;
import com.netsuite.webservices.platform.core.SearchEnumMultiSelectField;
import com.netsuite.webservices.platform.core.SearchLongCustomField;
import com.netsuite.webservices.platform.core.SearchLongField;
import com.netsuite.webservices.platform.core.SearchMultiSelectCustomField;
import com.netsuite.webservices.platform.core.SearchRecord;
import com.netsuite.webservices.platform.core.SearchStringCustomField;
import com.netsuite.webservices.platform.core.SearchStringField;
import com.netsuite.webservices.platform.core.SearchTextNumberField;
import com.netsuite.webservices.platform.core.StringCustomFieldRef;
import com.netsuite.webservices.platform.core.types.DurationUnit;
import com.netsuite.webservices.platform.core.types.SearchDateFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchDoubleFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchEnumMultiSelectFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchLongFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchMultiSelectFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchStringFieldOperator;
import com.netsuite.webservices.platform.core.types.SearchTextNumberFieldOperator;
import com.netsuite.webservices.transactions.sales.Opportunity;
import com.netsuite.webservices.transactions.sales.OpportunitySearch;
/**
*
* @author amit.dixit
*
*/
public final class NSCRMV2K9Service implements NSCRMGenericService {
private static final Logger logger = Logger.getLogger(NSCRMV2K9Service.class.getName());
/**
*
* @param query
* @param order
* @param crmFieldsSeparator
* @param orderFieldsSeparator
* @return
* @throws Exception
*/
public final SearchRecord createCustomerSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create customer search */
final CustomerSearch customerSearch = new CustomerSearch();
/* Create customer search basic object to set search variable */
CustomerSearchBasic customerSearchBasic = new CustomerSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createCustomerSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/**
* Set the customerSearchBasic. We should not interpret NULL since we should support empty
* value itself. Let the client to decide what to do.
*/
customerSearchBasic =
this.updateCustomerSearchBasic(customerSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
customerSearch.setBasic(customerSearchBasic);
return customerSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createContactSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create contact search */
final ContactSearch contactSearch = new ContactSearch();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Create new contact search basic object */
ContactSearchBasic contactSearchBasic = new ContactSearchBasic();
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createContactSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update contact search object search */
contactSearchBasic =
this.updateContactSearchBasic(contactSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search basic in search object */
contactSearch.setBasic(contactSearchBasic);
return contactSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createSupportCaseSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create SupportCaseSearch */
final SupportCaseSearch supportCaseSearch = new SupportCaseSearch();
/* Create SupportCaseSearchBasic object to set search varialble */
SupportCaseSearchBasic supportCaseSearchBasic = new SupportCaseSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createSupportCaseSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update support case search object search */
supportCaseSearchBasic =
this.updateSupportCaseSearchBasic(supportCaseSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2],
splitSearchStringResult[1], crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
supportCaseSearch.setBasic(supportCaseSearchBasic);
return supportCaseSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createTaskSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create TaskSearch */
final TaskSearch taskSearch = new TaskSearch();
/* Create TaskSearchBasic object to set search varialble */
TaskSearchBasic taskSearchBasic = new TaskSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createTaskSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update task search object search */
taskSearchBasic =
this.updateTaskSearchBasic(taskSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
taskSearch.setBasic(taskSearchBasic);
return taskSearch;
} else {
return null;
}
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createOpportunitySearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + "Operator: '" + HTTPConstants.orClause + "' is not supported by Scribe");
}
/* Create OpportunitySearch */
final OpportunitySearch opportunitySearch = new OpportunitySearch();
/* Create OpportunitySearchBasic object to set search varialble */
OpportunitySearchBasic opportunitySearchBasic = new OpportunitySearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createOpportunitySearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update opportunity search object search */
opportunitySearchBasic =
this.updateOpportunitySearchBasic(opportunitySearchBasic, splitSearchStringResult[0], splitSearchStringResult[2],
splitSearchStringResult[1], crmFieldIntraSeparator, inputDateFormat);
}
/* Set search criteria */
opportunitySearch.setBasic(opportunitySearchBasic);
return opportunitySearch;
} else {
return null;
}
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final SupportCaseSearchBasic updateSupportCaseSearchBasic(final SupportCaseSearchBasic supportCaseSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateSupportCaseSearch cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = supportCaseSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
supportCaseSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
supportCaseSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(supportCaseSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'SupportCase'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return supportCaseSearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final OpportunitySearchBasic updateOpportunitySearchBasic(final OpportunitySearchBasic opportunitySearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateOpportunitySearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldOperator: " + cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = opportunitySearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
opportunitySearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
opportunitySearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(opportunitySearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Opportunity'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return opportunitySearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final TaskSearchBasic updateTaskSearchBasic(final TaskSearchBasic taskSearchBasic, final String cRMFieldName, final String cRMFieldValue,
final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateTaskSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = taskSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
taskSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
taskSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(taskSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName + " in CRM Object type 'Task'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return taskSearchBasic;
}
/**
*
* @param query
* @return
* @throws Exception
*/
public final SearchRecord createEmployeeSearch(final String query, final String crmFieldIntraSeparator, final String inputDateFormat)
throws Exception {
if (query != null) {
/* Inform user that 'OR' is not supported */
if (query.contains(HTTPConstants.orClause)) {
throw new ScribeException(ScribeResponseCodes._1003 + " Operator: '" + HTTPConstants.orClause + "' is not supported by NS CRM");
}
/* Create new employee search */
final EmployeeSearch employeeSearch = new EmployeeSearch();
/* Create new employee search basic */
EmployeeSearchBasic employeeSearchBasic = new EmployeeSearchBasic();
/* Tokenize the where clause */
final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause, false);
/* Iterate over tokenizer */
while (stringTokenizer.hasMoreElements()) {
/* Get next token */
final String tempElement = stringTokenizer.nextToken();
logger.debug("----Inside createEmployeeSearch: tempElement: " + tempElement);
/* Split the search string into key operator value */
final String[] splitSearchStringResult = this.splitSearchString(tempElement);
/* Update employee search object search */
employeeSearchBasic =
this.updateEmployeeSearchBasic(employeeSearchBasic, splitSearchStringResult[0], splitSearchStringResult[2], splitSearchStringResult[1],
crmFieldIntraSeparator, inputDateFormat);
}
/* Search this basis in employee search object */
employeeSearch.setBasic(employeeSearchBasic);
return employeeSearch;
} else {
return null;
}
}
/**
*
* @param customerSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final CustomerSearchBasic updateCustomerSearchBasic(final CustomerSearchBasic customerSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateCustomerSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
/* Split the cRMFieldName on the basis of seperator */
if (cRMFieldName != null && cRMFieldName.contains(crmFieldIntraSeparator)) {
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = customerSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
customerSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
customerSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(customerSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Customer'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return customerSearchBasic;
}
/**
*
* @param employeeSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final EmployeeSearchBasic updateEmployeeSearchBasic(final EmployeeSearchBasic employeeSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat) throws Exception {
logger.debug("----Inside updateEmployeeSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldOperator: "
+ cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = employeeSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
employeeSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the normal field setter method */
employeeSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(employeeSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Employee'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + "CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return employeeSearchBasic;
}
private final Object getNormalFieldForSearchOperation(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue,
final String cRMFieldOperator, final String inputDateFormat) {
logger.debug("----Inside getNormalFieldForSearchOperation cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldType: " + cRMFieldType);
/* Create date formatter */
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_LONG_FIELD)) {
/* Create new search long field */
final SearchLongField searchLongField = new SearchLongField();
final SearchLongFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchLongFieldOperator.fromString(cRMFieldOperator);
searchLongField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchLongFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchLongField.setSearchValue(Long.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'int/long' format");
}
return searchLongField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_STRING_FIELD)) {
logger.info("----Inside getNormalFieldForSearchOperation SearchStringField, with operator: " + cRMFieldOperator);
/* Create new search string field */
final SearchStringField searchStringField = new SearchStringField();
final SearchStringFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchStringFieldOperator.fromString(cRMFieldOperator);
searchStringField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchStringFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchStringField.setSearchValue(cRMFieldValue);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'string' format");
}
return searchStringField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_BOOLEAN_FIELD)) {
/* TODO how to add operator? */
/* Create new search boolean field */
final SearchBooleanField searchBooleanField = new SearchBooleanField();
try {
/* Set value */
searchBooleanField.setSearchValue(Boolean.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
return searchBooleanField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DATE_FIELD)) {
/* Create new date boolean field */
final SearchDateField searchDateField = new SearchDateField();
final SearchDateFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchDateFieldOperator.fromString(cRMFieldOperator);
searchDateField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchDateFieldOperator '" + cRMFieldOperator + "'.");
}
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTime(simpleDateFormat.parse(cRMFieldValue));
/* Set value */
searchDateField.setSearchValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be od format: '"
+ inputDateFormat + "'");
}
return searchDateField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_TEXT_NUMBER_FIELD)) {
/* Create new text string field */
final SearchTextNumberField searchTextNumberField = new SearchTextNumberField();
final SearchTextNumberFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchTextNumberFieldOperator.fromString(cRMFieldOperator);
searchTextNumberField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchTextNumberField '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchTextNumberField.setSearchValue(cRMFieldValue);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be of format 'text'");
}
return searchTextNumberField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DOUBLE_FIELD)) {
/* Create new double string field */
final SearchDoubleField searchDoubleField = new SearchDoubleField();
final SearchDoubleFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchDoubleFieldOperator.fromString(cRMFieldOperator);
searchDoubleField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchDoubleFieldOperator '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
searchDoubleField.setSearchValue(Double.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be of format 'double'");
}
return searchDoubleField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_ENUM_MULTI_SELECT_FIELD)) {
/* Create new Search Enum Multi Select Field field */
final SearchEnumMultiSelectField searchEnumMultiSelectField = new SearchEnumMultiSelectField();
final SearchEnumMultiSelectFieldOperator operator;
try {
/* Create search operator from user supplied operator */
operator = SearchEnumMultiSelectFieldOperator.fromString(cRMFieldOperator);
searchEnumMultiSelectField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchEnumMultiSelectField '" + cRMFieldOperator + "'.");
}
try {
/* Set value */
final String[] value = new String[1];
value[0] = cRMFieldValue;
searchEnumMultiSelectField.setSearchValue(value);
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Value of CRM object field '" + cRMFieldName + "' should be of type: 'Select'");
}
return searchEnumMultiSelectField;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Customer createCustomer(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createCustomer");
/* Create new Customer */
final Customer customer = new Customer();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createCustomer, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createCustomer, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createCustomer, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
customer.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(customer, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Customer'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in customer */
customer.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return customer;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Contact createContact(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createContact");
/* Create new contact */
final Contact contact = new Contact();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createContact, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createContact, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createContact, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
contact.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(contact, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Contact'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in customer */
contact.setCustomFieldList(newCustomFieldList);
}
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return contact;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final Opportunity createOpportunity(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createOpportunity");
/* Create new opportunity */
final Opportunity opportunity = new Opportunity();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createOpportunity, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createOpportunity, processing node " + nodeName + " of type: " + nodeType);
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef = this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createOpportunity, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
opportunity.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(opportunity, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'Opportunity'");
}
} else {
logger.debug("----Inside createCustomer, no node name, skipped");
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in opportunity */
opportunity.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createCustomer, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return opportunity;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws
* @throws Exception
*/
public final Task createTask(final ScribeObject cADbject, final String crmFieldIntraSeparator) throws Exception {
logger.debug("----Inside createTask");
/* Create new Task */
final Task task = new Task();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createTask, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createTask, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createTask, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createTask, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createTask, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set this contact info in task */
task.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createTask, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set company information in task */
task.setCompany(companyRef);
}
/* Check if object is support case */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.SupportCase.toString())) {
final RecordRef supportRef = new RecordRef();
logger.debug("----Inside createTask, support case is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
supportRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set support case information in task */
task.setSupportCase(supportRef);
}
/* Check if object is opportunity */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Opportunity.toString())) {
final RecordRef opportunityRef = new RecordRef();
logger.debug("----Inside createTask, opportunity is being processed");
/* Check if opportunity has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createTask, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
opportunityRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
/* Set transaction information in task */
task.setTransaction(opportunityRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + "/" + NSCRMObjectType.SupportCase
+ " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createTask, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
task.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(task, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName + " in CRM Object type 'Task'");
}
}
} else {
logger.debug("----Inside createTask, no node name, skipped");
}
}
/* Dont set contact/case if company is not found */
if (task.getCompany() == null) {
logger.debug("----Inside createTask, company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
task.setContact(null);
/* Support case without company dont work at NS */
task.setSupportCase(null);
} else {
final RecordRef companyRef = task.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createTask, internal id of company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
task.setContact(null);
/* Support case without company dont work at NS */
task.setSupportCase(null);
/* Support case without company dont work at NS */
task.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
task.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createTask, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return task;
}
@SuppressWarnings("unused")
private final Object getNSCRMFieldObject(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue) {
logger.debug("----Inside getNSCRMFieldObject cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldType: "
+ cRMFieldType);
/* Trim the value */
if (cRMFieldValue != null) {
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG)) {
try {
/* Set value */
return Long.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'int/long'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING)) {
try {
/* Set value */
return String.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'string'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN)) {
try {
/* Set value */
return Boolean.valueOf(cRMFieldValue.trim());
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be 'boolean'");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_CALANDER)) {
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
return calendar;
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DURATION)) {
try {
/* Create duration object */
final Duration duration = new Duration();
duration.setUnit(DurationUnit.hour);
/* Set value */
duration.setTimeSpan(Double.valueOf(cRMFieldValue.trim()));
return duration;
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE)) {
try {
/* Set value */
return Double.valueOf(cRMFieldValue.trim());
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double' format");
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_RECORD_REF)) {
final RecordRef recordRef = new RecordRef();
/* Check if record has an internal id */
if (cRMFieldValue != null) {
/* Set internal id of referenced contact */
recordRef.setInternalId(cRMFieldValue.trim().trim());
} else {
logger.debug("----Inside createTask, regardingobjectid doesn't carry id");
}
return recordRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_TASK_STATUS)) {
/* Check if record has an internal id */
if (cRMFieldValue != null && cRMFieldValue.equalsIgnoreCase("COMPLETED")) {
/* Set completed */
return TaskStatus._completed;
} else {
/* Set inprogress */
return TaskStatus._inProgress;
}
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_PHONE_CALL_STATUS)) {
/* Check if record has an internal id */
if (cRMFieldValue != null && cRMFieldValue.equalsIgnoreCase("COMPLETED")) {
/* Set completed */
return PhoneCallStatus._completed;
} else {
/* Set inprogress */
return PhoneCallStatus._scheduled;
}
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
} else {
return null;
}
}
private final Class<?> getNSCRMFieldParamType(final String cRMFieldType) {
logger.debug("----Inside getNSCRMFieldParamType cRMFieldType: " + cRMFieldType);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG)) {
return Long.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING)) {
return String.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN)) {
return Boolean.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_CALANDER)) {
return Calendar.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DURATION)) {
return Duration.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE)) {
return Double.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_RECORD_REF)) {
return RecordRef.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_TASK_STATUS)) {
return TaskStatus.class;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_PHONE_CALL_STATUS)) {
return PhoneCallStatus.class;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param cRMFieldName
* @param cRMFieldType
* @param cRMFieldValue
* @return
*/
private final CustomFieldRef getCustomFieldForCreateOperation(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue) {
logger.debug("----Inside getCustomFieldForCreateOperation cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue
+ " & cRMFieldType: " + cRMFieldType);
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_STRING_CUSTOM_FIELD_REF)) {
/* Create new custom string field */
final StringCustomFieldRef stringCustomFieldRef = new StringCustomFieldRef();
/* Set internal id */
stringCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
stringCustomFieldRef.setValue(cRMFieldValue.trim());
}
return stringCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_MUTISELECT_CUSTOM_FIELD_REF)) {
/* Create new multi select field reference */
final MultiSelectCustomFieldRef multiSelectCustomFieldRef = new MultiSelectCustomFieldRef();
multiSelectCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
final ListOrRecordRef[] list = new ListOrRecordRef[1];
list[0] = new ListOrRecordRef();
list[0].setInternalId(cRMFieldValue.trim());
list[0].setTypeId(cRMFieldName);
multiSelectCustomFieldRef.setValue(list);
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Field value is is invalid: " + cRMFieldType);
}
return multiSelectCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_BOOLEAN_CUSTOM_FIELD_REF)) {
/* Create new boolean field reference */
final BooleanCustomFieldRef booleanCustomFieldRef = new BooleanCustomFieldRef();
/* Set internal id */
booleanCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
booleanCustomFieldRef.setValue(Boolean.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
return booleanCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_LONG_CUSTOM_FIELD_REF)) {
/* Create new long field reference */
final LongCustomFieldRef longCustomFieldRef = new LongCustomFieldRef();
/* Set internal id */
longCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
longCustomFieldRef.setValue(Long.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
return longCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DOUBLE_CUSTOM_FIELD_REF)) {
/* Create new double field reference */
final DoubleCustomFieldRef doubleCustomFieldRef = new DoubleCustomFieldRef();
/* Set internal id */
doubleCustomFieldRef.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
/* Set value */
doubleCustomFieldRef.setValue(Double.valueOf((cRMFieldValue.trim())));
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'double/float' format");
}
return doubleCustomFieldRef;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.CREATE_DATE_CUSTOM_FIELD_REF)) {
/* Create new date field reference */
final DateCustomFieldRef dateCustomFieldRef = new DateCustomFieldRef();
/* Set internal id */
dateCustomFieldRef.setInternalId(cRMFieldName);
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
/* Set value */
dateCustomFieldRef.setValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
return dateCustomFieldRef;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field type: " + cRMFieldType);
}
}
/**
*
* @param cRMFieldName
* @param cRMFieldType
* @param cRMFieldValue
* @param cRMFieldOperator
* @return
*/
private final SearchCustomField getCustomCRMSearchObject(final String cRMFieldName, final String cRMFieldType, final String cRMFieldValue,
final String cRMFieldOperator) {
logger.debug("----Inside getCustomCRMSearchObject cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + cRMFieldValue + " & cRMFieldType: "
+ cRMFieldType);
/* If field is string type */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_STRING_CUSTOM_FIELD)) {
/* Create new custom string field */
final SearchStringCustomField searchStringCustomField = new SearchStringCustomField();
/* Set internal id */
searchStringCustomField.setInternalId(cRMFieldName);
final SearchStringFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchStringFieldOperator.fromString(cRMFieldOperator);
searchStringCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchStringCustomField '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
/* Set value */
searchStringCustomField.setSearchValue(cRMFieldValue);
}
return searchStringCustomField;
} else
/* Check if type of custom field is long */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_LONG_CUSTOM_FIELD)) {
/* Create new custom string field */
final SearchLongCustomField searchLongCustomField = new SearchLongCustomField();
/* Set internal id */
searchLongCustomField.setInternalId(cRMFieldName);
final SearchLongFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchLongFieldOperator.fromString(cRMFieldOperator);
searchLongCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchLongCustomFields '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
try {
/* Set value */
searchLongCustomField.setSearchValue(Long.valueOf(cRMFieldValue));
} catch (final NumberFormatException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in int/long format");
}
}
return searchLongCustomField;
} else
/* Check if type of custom field is date */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_DATE_CUSTOM_FIELD)) {
/* Create new custom date field */
final SearchDateCustomField searchDateCustomField = new SearchDateCustomField();
/* Set internal id */
searchDateCustomField.setInternalId(cRMFieldName);
final SearchDateFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchDateFieldOperator.fromString(cRMFieldOperator);
searchDateCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for type SearchDateCustomField '" + cRMFieldOperator + "'.");
}
if (cRMFieldValue != null) {
/* Create calander object */
final Calendar calendar = Calendar.getInstance();
try {
/* Set time */
calendar.setTimeInMillis(Long.parseLong(cRMFieldValue.trim()));
/* Set value */
searchDateCustomField.setSearchValue(calendar);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'long/int' format");
}
}
return searchDateCustomField;
} else
/* Check if type of custom field is boolean */
if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_BOOLEAN_CUSTOM_FIELD)) {
/* Create new custom boolean field */
final SearchBooleanCustomField searchBooleanCustomField = new SearchBooleanCustomField();
/* TODO how to set operator? */
/* Set internal id */
searchBooleanCustomField.setInternalId(cRMFieldName);
if (cRMFieldValue != null) {
try {
/* Set value */
searchBooleanCustomField.setSearchValue(Boolean.valueOf(cRMFieldValue));
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of CRM object field '" + cRMFieldName + "' should be in 'boolean' format");
}
}
return searchBooleanCustomField;
} else if (cRMFieldType.equalsIgnoreCase(NSCRMFieldTypes.SEARCH_MULTI_SELECT_CUSTOM_FIELD)) {
logger.info("----Inside getCustomCRMSearchObject, found multiselect value: " + cRMFieldValue);
/* Create new Search Enum Multi Select Field field */
final SearchMultiSelectCustomField searchMultiSelectCustomField = new SearchMultiSelectCustomField();
final SearchMultiSelectFieldOperator operator;
try {
/* Create search operator from user supplied value */
operator = SearchMultiSelectFieldOperator.fromString(cRMFieldOperator);
searchMultiSelectCustomField.setOperator(operator);
} catch (final Exception e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid operator for class SearchMultiSelectCustomField '" + cRMFieldOperator + "'.");
}
/* Set value */
final SearchCustomFieldList searchCustomFieldList = new SearchCustomFieldList();
/* Split the value */
final String[] splitIdValue = this.splitCustomMutliSelectValue(cRMFieldValue);
final ListOrRecordRef listOrRecordRef = new ListOrRecordRef();
/* Set internal id */
listOrRecordRef.setInternalId(splitIdValue[1]);
/* Set type id */
listOrRecordRef.setTypeId(splitIdValue[0]);
/* Set internal id of the custom field name */
searchMultiSelectCustomField.setInternalId(cRMFieldName);
searchCustomFieldList.setCustomField(new SearchCustomField[] {searchMultiSelectCustomField});
searchMultiSelectCustomField.setSearchValue(new ListOrRecordRef[] {listOrRecordRef});
logger.info("----Inside getCustomCRMSearchObject, returning multi-select custom field reference. " + cRMFieldName);
return searchMultiSelectCustomField;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1003 + "Following type: " + cRMFieldType + " is not supported");
}
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final SupportCase createSupportCase(final ScribeObject cADbject, final String crmFieldIntraSeparator) {
logger.debug("----Inside createSupportCase");
/* Create new support case */
final SupportCase supportCase = new SupportCase();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createSupportCase, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createSupportCase, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createSupportCase, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createSupportCase, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createSupportCase, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createSupportCase, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createSupportCase, regardingobjectid doesn't carry id");
}
/* Set this contact info in supportCase */
supportCase.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createSupportCase, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createSupportCase, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createSupportCase, regardingobjectid doesn't carry id");
}
/* Set company information in supportCase */
supportCase.setCompany(companyRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a customfield reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
logger.debug("----Inside createSupportCase, added custom field " + nodeName);
} else {
/* Invoke the normal field setter method */
supportCase.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(supportCase, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'SupportCase'");
}
}
} else {
logger.debug("----Inside createSupportCase, no node name, skipped");
}
}
/* Don't set contact if company is not found */
if (supportCase.getCompany() == null) {
logger.debug("----Inside createSupportCase, company is not found, hence removing contact");
/* Contact without company dont work at NS */
supportCase.setContact(null);
} else {
final RecordRef companyRef = supportCase.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createSupportCase, internal id of company is not found, hence removing contact");
/* Contact without company dont work at NS */
supportCase.setContact(null);
/* Contact without company dont work at NS */
supportCase.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
supportCase.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createSupportCase, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return supportCase;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public final PhoneCall createPhoneCall(final ScribeObject cADbject, final String crmFieldIntraSeparator) {
logger.debug("----Inside createPhoneCall");
/* Create new Phone Call */
final PhoneCall phoneCall = new PhoneCall();
/* Create list of element */
final List<Element> elementList = cADbject.getXmlContent();
/* An array list custom reference object */
final List<CustomFieldRef> customFieldRefArrayList = new ArrayList<CustomFieldRef>();
if (elementList != null) {
logger.debug("----Inside createPhoneCall, processing elementList with size " + elementList.size());
for (final Element element : elementList) {
/* Check if node name is not null */
if (element.getNodeName() != null) {
/* Break the element into name and type */
final String node = element.getNodeName();
String nodeName = null;
String nodeType = null;
/* Split the name on the basis of seperator */
if (node != null && node.contains(crmFieldIntraSeparator)) {
final int index = node.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = node.substring(0, index).trim();
/* Get node type */
nodeType = node.substring(index + crmFieldIntraSeparator.length(), node.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
} else if (node != null && node.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
/* Get node name */
nodeName = node;
/* Node type */
nodeType = NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID;
} else {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + " Field: '" + node + "' is not in correct format");
}
logger.debug("----Inside createPhoneCall, processing node " + nodeName + " of type: " + nodeType);
/* Check if regarding object id tag is found */
if (nodeName.trim().equalsIgnoreCase(NSCRMFieldTypes.CRM_FIELD_REGARDINGOBJECTID)) {
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null) {
logger.debug("----Inside createPhoneCall, node regardingobjectid is found with TYPE: "
+ element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE));
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid is found but no TYPE");
}
/* Check if its contact */
if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Contact.toString())) {
final RecordRef contactRef = new RecordRef();
logger.debug("----Inside createPhoneCall, contact is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
contactRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set this contact info in phoneCall */
phoneCall.setContact(contactRef);
} else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.Customer.toString())) {
final RecordRef companyRef = new RecordRef();
logger.debug("----Inside createPhoneCall, customer is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced contact */
companyRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set company information in task */
phoneCall.setCompany(companyRef);
}
/* Check if object is support case */
else if (element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE) != null
&& element.getAttribute(NSCRMFieldTypes.CRM_FIELD_ATTRIBUTE_TYPE).trim().equalsIgnoreCase(NSCRMObjectType.SupportCase.toString())) {
final RecordRef supportRef = new RecordRef();
logger.debug("----Inside createPhoneCall, support case is being processed");
/* Check if contact has an internal id */
if (element.getTextContent() != null) {
logger.debug("----Inside createPhoneCall, regardingobjectid is " + element.getTextContent().trim());
/* Set internal id of referenced support case */
supportRef.setInternalId(element.getTextContent().trim());
} else {
logger.debug("----Inside createPhoneCall, regardingobjectid doesn't carry id");
}
/* Set support case information in phoneCall */
phoneCall.setSupportCase(supportRef);
} else {
throw new ScribeException(ScribeResponseCodes._1008 + "Following 'TYPE' is not supported in 'REGARDINGOBJECTID' node. Please provide ."
+ NSCRMObjectType.Contact + "/" + NSCRMObjectType.SupportCase + "/" + NSCRMObjectType.Customer + " only");
}
} else {
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* build a custom field reference */
final CustomFieldRef customFieldRef =
this.getCustomFieldForCreateOperation(nodeName.trim(), nodeType.trim(), element.getTextContent());
/* Add reference in list */
customFieldRefArrayList.add(customFieldRef);
} else {
/* Invoke the normal field setter method */
phoneCall.getClass().getMethod("set" + nodeName, this.getNSCRMFieldParamType(nodeType))
.invoke(phoneCall, this.getNSCRMFieldObject(nodeName, nodeType, element.getTextContent()));
}
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + "Found problem in tracing CRM field: " + nodeName
+ " in CRM Object type 'PhoneCall'");
}
}
} else {
logger.debug("----Inside createPhoneCall, no node name, skipped");
}
}
/* Dont set contact/case if company is not found */
if (phoneCall.getCompany() == null) {
logger.debug("----Inside createPhoneCall, company is not found, hence removing contact/support case");
/* Contact without company dont work at NS */
phoneCall.setContact(null);
/* Support case without company dont work at NS */
phoneCall.setSupportCase(null);
} else {
final RecordRef companyRef = phoneCall.getCompany();
/* Check if internal id is found */
if (companyRef.getInternalId() != null && companyRef.getInternalId().trim().equalsIgnoreCase("")) {
logger.debug("----Inside createPhoneCall, internal id of company is not found, hence removing contact");
/* Contact without company dont work at NS */
phoneCall.setContact(null);
/* Support case without company dont work at NS */
phoneCall.setSupportCase(null);
/* Support case without company dont work at NS */
phoneCall.setCompany(null);
}
}
/* check if any custom field and set it to the task record */
final CustomFieldRef[] customFieldList = this.getCustomFieldRefArray(customFieldRefArrayList);
/* Set custom field list */
if (customFieldList != null) {
/* Create new custom field list */
final CustomFieldList newCustomFieldList = new CustomFieldList();
newCustomFieldList.setCustomField(customFieldList);
/* Add list in task */
phoneCall.setCustomFieldList(newCustomFieldList);
}
} else {
logger.warn("----Inside createPhoneCall, empty element list.");
throw new ScribeException(ScribeResponseCodes._1008 + " Request data is not found in request");
}
return phoneCall;
}
/**
*
* @param contactSearchBasic
* @param searchStringField
* @param cRMFieldName
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private final ContactSearchBasic updateContactSearchBasic(final ContactSearchBasic contactSearchBasic, final String cRMFieldName,
final String cRMFieldValue, final String cRMFieldOperator, final String crmFieldIntraSeparator, final String inputDateFormat)
throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
logger.debug("----Inside updateContactSearchBasic cRMFieldName: " + cRMFieldName + " & cRMFieldValue: " + contactSearchBasic
+ " & cRMFieldOperator: " + cRMFieldOperator);
if (cRMFieldName != null) {
/* Check if cRMFieldName contans crmFieldIntraSeparator */
if (cRMFieldName.contains(crmFieldIntraSeparator)) {
String nodeName = null;
String nodeType = null;
final int index = cRMFieldName.lastIndexOf(crmFieldIntraSeparator);
/* If found a positive index */
if (index > 0) {
/* Get node name */
nodeName = cRMFieldName.substring(0, index).trim();
/* Get node type */
nodeType = cRMFieldName.substring(index + crmFieldIntraSeparator.length(), cRMFieldName.length()).trim();
}
/* Validate node name/type */
if (nodeName == null & nodeType == null) {
/* Throw user error */
throw new ScribeException(ScribeResponseCodes._1008 + "Field: '" + cRMFieldName + "' is not in correct format");
}
try {
/* If a custom field */
if (nodeType.toUpperCase().contains("CUSTOM")) {
/* Invoke the normal field setter method */
SearchCustomFieldList searchCustomFieldList = contactSearchBasic.getCustomFieldList();
/* If already a list */
if (searchCustomFieldList != null) {
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(searchCustomFieldList, nodeName, nodeType, cRMFieldValue,
cRMFieldOperator));
} else {
/* Create a new list */
searchCustomFieldList = new SearchCustomFieldList();
/* Update the list */
searchCustomFieldList.setCustomField(this.getCustomFieldForSearchOperation(null, nodeName, nodeType, cRMFieldValue, cRMFieldOperator));
}
/* Set custom field list */
contactSearchBasic.setCustomFieldList(searchCustomFieldList);
} else {
/* Invoke the method */
contactSearchBasic
.getClass()
.getMethod("set" + nodeName.trim(), Class.forName(NetSuiteMessageFormatUtils.NS_WSDL_PACKAGE_NAME + nodeType.trim()))
.invoke(contactSearchBasic,
this.getNormalFieldForSearchOperation(nodeName.trim(), nodeType.trim(), cRMFieldValue, cRMFieldOperator, inputDateFormat));
}
} catch (final ClassNotFoundException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final NoSuchMethodException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final IllegalArgumentException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final IllegalAccessException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
} catch (final InvocationTargetException e) {
throw new ScribeException(ScribeResponseCodes._1003 + " Found problem in tracing CRM field: " + cRMFieldName
+ " in CRM Object type 'Contact'");
}
} else {
throw new ScribeException(ScribeResponseCodes._1003 + " CRM field format should be CRMFIELDNAME" + crmFieldIntraSeparator + "CRMFIELDTYPE");
}
}
return contactSearchBasic;
}
private final SearchCustomField[] getCustomFieldForSearchOperation(final SearchCustomFieldList searchCustomFieldList, final String cRMFieldName,
final String cRMFieldType, final String cRMFieldValue, final String cRMFieldOperator) {
SearchCustomField[] searchCustomFieldUpdated = null;
/* Check if any list is already set */
if (searchCustomFieldList == null) {
/* Initialize it */
searchCustomFieldUpdated = new SearchCustomField[1];
/* Populate new array with additional values */
searchCustomFieldUpdated[0] = this.getCustomCRMSearchObject(cRMFieldName.trim(), cRMFieldType.trim(), cRMFieldValue, cRMFieldOperator);
} else {
searchCustomFieldUpdated = new SearchCustomField[searchCustomFieldList.getCustomField().length + 1];
/* Copy old array into new one */
System.arraycopy(searchCustomFieldList.getCustomField(), 0, searchCustomFieldUpdated, 0, searchCustomFieldList.getCustomField().length);
/* Populate new array with additional values */
searchCustomFieldUpdated[searchCustomFieldList.getCustomField().length] =
this.getCustomCRMSearchObject(cRMFieldName.trim(), cRMFieldType.trim(), cRMFieldValue, cRMFieldOperator);
}
return searchCustomFieldUpdated;
}
/**
*
* @param refArrayList
* @return
*/
private final CustomFieldRef[] getCustomFieldRefArray(List<CustomFieldRef> refArrayList) {
CustomFieldRef[] customFieldRefUpdated = null;
/* Check if any list is already set */
if (refArrayList == null || refArrayList.size() == 0) {
return null;
}
/* Initialize it */
customFieldRefUpdated = new CustomFieldRef[refArrayList.size()];
int counter = 0;
for (final CustomFieldRef ref : refArrayList) {
customFieldRefUpdated[counter] = ref;
counter++;
}
return customFieldRefUpdated;
}
/**
* Split the multiselect custom field value into 2 (format typeid__valueinternalid)
*
* @param value
* @return
* @throws ScribeException
*/
private final String[] splitCustomMutliSelectValue(final String value) throws ScribeException {
/* Verify value */
if (value == null) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of MultiSelect Custom CRM object field value '" + value + "' invalid format");
} else if (value != null && !value.matches("^..*__..*$")) {
throw new ScribeException(ScribeResponseCodes._1003 + "Value of MultiSelect Custom CRM object field value '" + value + "' invalid format");
}
final String[] splitResult = new String[2];
splitResult[0] = value.replaceAll("__.*$", "");
splitResult[1] = value.replaceAll("^.*__", "");
return splitResult;
}
/**
* Split a search string into a 3 element String array.
*
* @param searchString : search string using space and delimiter.
*
* @return a 3 element String array. element 0 => search key, element 1 => search operator and
* element 2 => search value.
*/
private final String[] splitSearchString(final String searchString) throws ScribeException {
final String[] finalResult = new String[3];
/* Split the search string from user */
final String[] splitResult = searchString.split("\\s+");
/* Check if length is less than 1 */
if (splitResult.length <= 1) {
logger.error("----Inside splitSearchString: invalid search string: " + searchString);
throw new ScribeException(ScribeResponseCodes._1003 + "Invalid search string: '" + searchString
+ "' search string should contain at least 2 words for NS CRM");
}
/* Key */
finalResult[0] = splitResult[0];
/* Operator */
finalResult[1] = splitResult[1];
/* value, it will never null but can be empty string */
finalResult[2] = searchString.replaceAll("^[ ]*" + finalResult[0] + "[ ]*" + finalResult[1] + "[ ]*", "").trim();
logger.info("----Inside splitSearchString: split the search into [" + finalResult[0] + "],[" + finalResult[1] + "],[" + finalResult[2] + "]");
return finalResult;
}
}
| 121,520 | 0.635455 | 0.63032 | 2,909 | 39.775181 | 39.717327 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388106 | false | false | 9 |
ee398305016b6c61d523a75e30dbde566c7c4afb | 326,417,562,306 | 6717f8e8e481d47e6e2d5d862e4210571cbeefff | /src/main/java/cc/codingape/reflect/ClassDemo3.java | a6e345422445404e6c6196d6aaedd7f42280435b | []
| no_license | zitongchen/javase | https://github.com/zitongchen/javase | 7721f8da2d9a7c0194e2d3df9ceb806392c05dac | c3d496f1cc59826c614c6ca6db671886537a1198 | refs/heads/master | 2020-02-20T09:40:45.256000 | 2018-04-11T01:42:01 | 2018-04-11T01:42:01 | 99,230,869 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cc.codingape.reflect;
import java.lang.reflect.Field;
/**
* 通过ClassUtil工具类获取类信息
* @author Tony
*
*/
public class ClassDemo3 {
public static void main(String[] args) {
/*//打印对象的方法
ClassUtil.printClassMethodMessage("Tony");
//打印对象的成员变量
ClassUtil.printFiledMessage("Tony");
//打印对象的构造函数
ClassUtil.printConMessage("Tony");*/
printFiledMessage("Tony");
}
public static void printFiledMessage(Object obj) {
Class c = obj.getClass();
/*
* 成员变量也是对象
* java.lang.refilect.Filed
* Filed类封装了关于成员变量的操作
* getFields()方法获取的是所以的public的成员变量的信息
* getDeclaredFields获取的是该类自己声明的所以成员变量信息
*/
Field[] fs = c.getFields();
for(Field field : fs) {
Class fieldType = field.getType();
String typeName = fieldType.getSimpleName();
String fileName = field.getName();
System.out.println(typeName + " " + fileName);
}
}
}
| UTF-8 | Java | 1,084 | java | ClassDemo3.java | Java | [
{
"context": ".Field;\r\n\r\n/**\r\n * 通过ClassUtil工具类获取类信息\r\n * @author Tony\r\n *\r\n */\r\npublic class ClassDemo3 {\r\n\tpublic stat",
"end": 112,
"score": 0.9997168779373169,
"start": 108,
"tag": "NAME",
"value": "Tony"
},
{
"context": "/*//打印对象的方法\r\n\t\tClassUtil.printClassMethodMessage(\"Tony\");\r\n\t\t//打印对象的成员变量\r\n\t\tClassUtil.printFiledMessage(",
"end": 249,
"score": 0.9996165037155151,
"start": 245,
"tag": "NAME",
"value": "Tony"
},
{
"context": ");\r\n\t\t//打印对象的成员变量\r\n\t\tClassUtil.printFiledMessage(\"Tony\");\r\n\t\t//打印对象的构造函数\r\n\t\tClassUtil.printConMessage(\"T",
"end": 304,
"score": 0.9996322393417358,
"start": 300,
"tag": "NAME",
"value": "Tony"
},
{
"context": "y\");\r\n\t\t//打印对象的构造函数\r\n\t\tClassUtil.printConMessage(\"Tony\");*/\r\n\t\tprintFiledMessage(\"Tony\");\r\n\t}\r\n\tpublic s",
"end": 357,
"score": 0.999607264995575,
"start": 353,
"tag": "NAME",
"value": "Tony"
},
{
"context": ".printConMessage(\"Tony\");*/\r\n\t\tprintFiledMessage(\"Tony\");\r\n\t}\r\n\tpublic static void printFiledMessage(Obj",
"end": 389,
"score": 0.9996156692504883,
"start": 385,
"tag": "NAME",
"value": "Tony"
}
]
| null | []
| package cc.codingape.reflect;
import java.lang.reflect.Field;
/**
* 通过ClassUtil工具类获取类信息
* @author Tony
*
*/
public class ClassDemo3 {
public static void main(String[] args) {
/*//打印对象的方法
ClassUtil.printClassMethodMessage("Tony");
//打印对象的成员变量
ClassUtil.printFiledMessage("Tony");
//打印对象的构造函数
ClassUtil.printConMessage("Tony");*/
printFiledMessage("Tony");
}
public static void printFiledMessage(Object obj) {
Class c = obj.getClass();
/*
* 成员变量也是对象
* java.lang.refilect.Filed
* Filed类封装了关于成员变量的操作
* getFields()方法获取的是所以的public的成员变量的信息
* getDeclaredFields获取的是该类自己声明的所以成员变量信息
*/
Field[] fs = c.getFields();
for(Field field : fs) {
Class fieldType = field.getType();
String typeName = fieldType.getSimpleName();
String fileName = field.getName();
System.out.println(typeName + " " + fileName);
}
}
}
| 1,084 | 0.663333 | 0.662222 | 38 | 21.68421 | 16.249866 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.736842 | false | false | 9 |
5b288ccc88eb64012a7656e2a49558729a84010f | 23,184,233,503,853 | 78525153f4ea336a3d6afdfae858a2abe257f764 | /src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkParamsInfo.java | 7597d0ab8ca26b4ac902338b5727888812f96e46 | [
"Apache-2.0"
]
| permissive | slamdunking/bazel | https://github.com/slamdunking/bazel | 5195789e0aec657b80416ea2f13be86c96ecce62 | 98f10f46f33a06d848229f64d55fb28d846bcbfd | refs/heads/master | 2020-03-13T05:26:05.438000 | 2018-04-25T08:49:18 | 2018-04-25T08:50:58 | 130,983,928 | 1 | 0 | null | true | 2018-04-25T09:37:03 | 2018-04-25T09:37:03 | 2018-04-25T08:53:32 | 2018-04-25T08:51:38 | 462,720 | 0 | 0 | 0 | null | false | null | // Copyright 2014 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.rules.cpp;
import com.google.common.base.Function;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams.Builder;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore.CcLinkParamsStoreImpl;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
/** A target that provides C linker parameters. */
@Immutable
@AutoCodec
public final class CcLinkParamsInfo {
public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS =
input -> {
// ... then try Skylark.
CcLinkingInfo provider = input.get(CcLinkingInfo.PROVIDER);
CcLinkParamsInfo ccLinkParamsInfo =
provider == null ? null : provider.getCcLinkParamsInfo();
if (ccLinkParamsInfo != null) {
return ccLinkParamsInfo.getCcLinkParamsStore();
}
return null;
};
private final CcLinkParamsStoreImpl store;
@AutoCodec.Instantiator
public CcLinkParamsInfo(CcLinkParamsStore store) {
this.store = new CcLinkParamsStoreImpl(store);
}
@AutoCodec
@VisibleForSerialization
static class CcLinkParamsInfoCollection extends CcLinkParamsStore {
private final Iterable<CcLinkParamsInfo> providers;
CcLinkParamsInfoCollection(Iterable<CcLinkParamsInfo> providers) {
this.providers = providers;
}
@Override
protected void collect(Builder builder, boolean linkingStatically, boolean linkShared) {
for (CcLinkParamsInfo provider : providers) {
builder.add(provider.getCcLinkParamsStore());
}
}
}
public static CcLinkParamsInfo merge(final Iterable<CcLinkParamsInfo> providers) {
return new CcLinkParamsInfo(new CcLinkParamsInfoCollection(providers));
}
/** Returns the link params store. */
public CcLinkParamsStore getCcLinkParamsStore() {
return store;
}
/**
* Returns link parameters given static / shared linking settings.
*/
public CcLinkParams getCcLinkParams(boolean linkingStatically, boolean linkShared) {
return store.get(linkingStatically, linkShared);
}
}
| UTF-8 | Java | 2,969 | java | CcLinkParamsInfo.java | Java | []
| null | []
| // Copyright 2014 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.rules.cpp;
import com.google.common.base.Function;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams.Builder;
import com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore.CcLinkParamsStoreImpl;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
/** A target that provides C linker parameters. */
@Immutable
@AutoCodec
public final class CcLinkParamsInfo {
public static final Function<TransitiveInfoCollection, CcLinkParamsStore> TO_LINK_PARAMS =
input -> {
// ... then try Skylark.
CcLinkingInfo provider = input.get(CcLinkingInfo.PROVIDER);
CcLinkParamsInfo ccLinkParamsInfo =
provider == null ? null : provider.getCcLinkParamsInfo();
if (ccLinkParamsInfo != null) {
return ccLinkParamsInfo.getCcLinkParamsStore();
}
return null;
};
private final CcLinkParamsStoreImpl store;
@AutoCodec.Instantiator
public CcLinkParamsInfo(CcLinkParamsStore store) {
this.store = new CcLinkParamsStoreImpl(store);
}
@AutoCodec
@VisibleForSerialization
static class CcLinkParamsInfoCollection extends CcLinkParamsStore {
private final Iterable<CcLinkParamsInfo> providers;
CcLinkParamsInfoCollection(Iterable<CcLinkParamsInfo> providers) {
this.providers = providers;
}
@Override
protected void collect(Builder builder, boolean linkingStatically, boolean linkShared) {
for (CcLinkParamsInfo provider : providers) {
builder.add(provider.getCcLinkParamsStore());
}
}
}
public static CcLinkParamsInfo merge(final Iterable<CcLinkParamsInfo> providers) {
return new CcLinkParamsInfo(new CcLinkParamsInfoCollection(providers));
}
/** Returns the link params store. */
public CcLinkParamsStore getCcLinkParamsStore() {
return store;
}
/**
* Returns link parameters given static / shared linking settings.
*/
public CcLinkParams getCcLinkParams(boolean linkingStatically, boolean linkShared) {
return store.get(linkingStatically, linkShared);
}
}
| 2,969 | 0.753452 | 0.750758 | 80 | 36.112499 | 30.606369 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3875 | false | false | 9 |
5cc4b77ed935017438a067d2e6277e00bbb4f3e1 | 31,645,319,066,140 | 37b9cb3e42552a2f6561db3564856d74b2e1180f | /springboot-elasticsearch/src/test/java/com/example/elasticsearch/service/UserServiceTest.java | 010796fdde8ae7b93a525d014c88e4b6aa86c841 | [
"Apache-2.0"
]
| permissive | zzzzhhhhuuuu/springboot-action | https://github.com/zzzzhhhhuuuu/springboot-action | 3e4eb027d0b7f57bbabca202998f8b1094f862cb | 3fae256ce681ed9784db61c164696823662a3452 | refs/heads/master | 2023-06-19T18:18:24.610000 | 2021-07-18T09:28:14 | 2021-07-18T09:28:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.elasticsearch.service;
import com.example.elasticsearch.ElasticSearchApplication;
import com.example.elasticsearch.entity.User;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* UserServiceTest
*
* @author star
*/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class UserServiceTest {
@Autowired
private UserService userService;
private static final int ID = 1;
private static final String USER_NAME = "star";
private User mockUser() {
User user = new User();
user.setId(ID);
user.setName(USER_NAME);
user.setEmail("test@new.com");
user.setAge(24);
return user;
}
@Test
public void test1SaveUser() {
User user = this.mockUser();
// 保存数据
userService.saveUser(user);
User newUser = userService.getUser(user.getId().toString());
// 验证结果
Assert.assertEquals(user.getId(), newUser.getId());
Assert.assertEquals(user.getName(), newUser.getName());
Assert.assertEquals(user.getEmail(), newUser.getEmail());
Assert.assertEquals(user.getAge(), newUser.getAge());
}
@Test
public void test2SearchUserByName() {
List<User> users = userService.searchUserByName(USER_NAME);
// 验证结果
Assert.assertNotNull(users);
Assert.assertTrue(users.size() > 0);
}
@Test
public void test3DeleteUser() {
String id = String.valueOf(ID);
// 删除数据
userService.deleteUser(id);
User newUser = userService.getUser(id);
// 验证结果
Assert.assertNull(newUser);
}
}
| UTF-8 | Java | 2,070 | java | UserServiceTest.java | Java | [
{
"context": "a.util.List;\n\n/**\n * UserServiceTest\n *\n * @author star\n */\n@RunWith(SpringRunner.class)\n@FixMethodOrder(",
"end": 554,
"score": 0.9860230088233948,
"start": 550,
"tag": "USERNAME",
"value": "star"
},
{
"context": " 1;\n\n private static final String USER_NAME = \"star\";\n\n private User mockUser() {\n User use",
"end": 864,
"score": 0.9882506132125854,
"start": 860,
"tag": "USERNAME",
"value": "star"
},
{
"context": " user.setName(USER_NAME);\n user.setEmail(\"test@new.com\");\n user.setAge(24);\n\n return user;",
"end": 1022,
"score": 0.9999282956123352,
"start": 1010,
"tag": "EMAIL",
"value": "test@new.com"
}
]
| null | []
| package com.example.elasticsearch.service;
import com.example.elasticsearch.ElasticSearchApplication;
import com.example.elasticsearch.entity.User;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* UserServiceTest
*
* @author star
*/
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class UserServiceTest {
@Autowired
private UserService userService;
private static final int ID = 1;
private static final String USER_NAME = "star";
private User mockUser() {
User user = new User();
user.setId(ID);
user.setName(USER_NAME);
user.setEmail("<EMAIL>");
user.setAge(24);
return user;
}
@Test
public void test1SaveUser() {
User user = this.mockUser();
// 保存数据
userService.saveUser(user);
User newUser = userService.getUser(user.getId().toString());
// 验证结果
Assert.assertEquals(user.getId(), newUser.getId());
Assert.assertEquals(user.getName(), newUser.getName());
Assert.assertEquals(user.getEmail(), newUser.getEmail());
Assert.assertEquals(user.getAge(), newUser.getAge());
}
@Test
public void test2SearchUserByName() {
List<User> users = userService.searchUserByName(USER_NAME);
// 验证结果
Assert.assertNotNull(users);
Assert.assertTrue(users.size() > 0);
}
@Test
public void test3DeleteUser() {
String id = String.valueOf(ID);
// 删除数据
userService.deleteUser(id);
User newUser = userService.getUser(id);
// 验证结果
Assert.assertNull(newUser);
}
}
| 2,065 | 0.675862 | 0.671921 | 75 | 26.066668 | 20.959856 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 9 |
1b43667941da10bb2c602e5f753f07f27d6a257d | 13,245,679,146,276 | 4e90aa8bebea091947e459b4c92246f0f137b52d | /src/main/java/oopsPolymosphism/Vehicle.java | e63730d0a347312f3d51c5b7b9a09d2b2572b62f | []
| no_license | someone369/JenkinsTest | https://github.com/someone369/JenkinsTest | 6ceaf740b18802c0ff9384b6e53a1e7aac539482 | d8d763049cb1b96ec35295c771f4ac4b30610092 | refs/heads/master | 2023-05-25T06:37:17.731000 | 2020-04-26T17:16:53 | 2020-04-26T17:16:53 | 243,998,579 | 0 | 0 | null | false | 2023-05-09T18:22:57 | 2020-02-29T16:04:14 | 2020-04-26T17:17:15 | 2023-05-09T18:22:54 | 24,056 | 0 | 0 | 1 | Java | false | false | package oopsPolymosphism;
public class Vehicle {
public void engine(){
System.out.println("vehicle class engine");
}
}
| UTF-8 | Java | 126 | java | Vehicle.java | Java | []
| null | []
| package oopsPolymosphism;
public class Vehicle {
public void engine(){
System.out.println("vehicle class engine");
}
}
| 126 | 0.722222 | 0.722222 | 8 | 14.75 | 15.343973 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 9 |
0e74f08ccd1c9100795da8f7d6af446c86761717 | 22,462,679,000,444 | f1288a2cc9dfd3e9ea9d71108733c49d21ca8fce | /General.java | 906447985b146923566041ddd1ec20343d90e0fa | []
| no_license | BaekJae/Eternal | https://github.com/BaekJae/Eternal | 4a836add5eec2bb4a8535b0a065462f26596fa83 | 369394f5bfb3fcacfafd3ccb0a25f4458e857fde | refs/heads/master | 2021-01-23T16:28:14.728000 | 2017-08-21T14:58:45 | 2017-08-21T14:58:45 | 93,298,730 | 1 | 0 | null | false | 2017-07-15T08:59:30 | 2017-06-04T07:58:27 | 2017-07-15T08:16:32 | 2017-07-15T08:44:04 | 17 | 0 | 0 | 0 | Java | null | null | import java.util.*;
public class General {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
for(Object o : list)
System.out.println("list value = "+o);
}
}
| UTF-8 | Java | 255 | java | General.java | Java | []
| null | []
| import java.util.*;
public class General {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
for(Object o : list)
System.out.println("list value = "+o);
}
}
| 255 | 0.603922 | 0.603922 | 11 | 21.181818 | 15.176646 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.909091 | false | false | 9 |
d0c3d5825edddeae4431070dba3ff82909da1b5b | 25,598,005,126,655 | fe0419954769538df0766952d3db8b7288f4e81a | /solution/DeleteColumnsToMakeSorted.java | b6ed78ff9288d121d6fde7cc9133b6feb2d88210 | []
| no_license | Vamsicse/DailyCodingProblemSolutions | https://github.com/Vamsicse/DailyCodingProblemSolutions | 941e852332ff59e8c14b64a5c8849803c2e5f23f | 2b2cadcbe0c60c0cf52e0c61ccd387bfce60d598 | refs/heads/master | 2023-05-11T15:40:03.816000 | 2023-04-17T20:39:37 | 2023-04-17T20:39:37 | 243,082,578 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Problem: Find number of columns to delete to make it sorted
* Approach:
*
* Time Complexity: O(A)
* Space Complexity: O(1)
*
* @author Vamsi Krishna Myalapalli
* @version 1.0
* @since 2019-12-27
*/
public class DeleteColumnsToMakeSorted {
// Runtime: 7-8ms, Memory: 39.8MB
public int minDeletionSize(String[] A) {
if (A == null) return 0;
int count = 0;
int len = A[0].toCharArray().length;
for (int i = 0; i < len; i++) {
if(isNoSort(A, i)) count++;
}
return count;
}
public static boolean isNoSort(String[] A, int num) {
char c = A[0].charAt(num);
for (int i = 0; i < A.length;i++) {
if (A[i].charAt(num) < c) return true;
c = A[i].charAt(num);
}
return false;
}
public static void main(String[] args) {
DeleteColumnsToMakeSorted obj = new DeleteColumnsToMakeSorted();
String[] X = {"cba","daf","ghi"};
System.out.println(obj.minDeletionSize(X));
String[] Y = {"zyx","wvu","tsr"};
System.out.println(obj.minDeletionSize(Y));
String[] Z = {"abcdef"};
System.out.println(obj.minDeletionSize(Z));
}
}
/*
Output:
———————————————————
1
3
0
*/
| UTF-8 | Java | 1,303 | java | DeleteColumnsToMakeSorted.java | Java | [
{
"context": "xity: O(A)\n * Space Complexity: O(1)\n *\n * @author Vamsi Krishna Myalapalli\n * @version 1.0\n * @since 2019-12-27\n */\npublic c",
"end": 172,
"score": 0.9998888373374939,
"start": 148,
"tag": "NAME",
"value": "Vamsi Krishna Myalapalli"
}
]
| null | []
| /**
* Problem: Find number of columns to delete to make it sorted
* Approach:
*
* Time Complexity: O(A)
* Space Complexity: O(1)
*
* @author <NAME>
* @version 1.0
* @since 2019-12-27
*/
public class DeleteColumnsToMakeSorted {
// Runtime: 7-8ms, Memory: 39.8MB
public int minDeletionSize(String[] A) {
if (A == null) return 0;
int count = 0;
int len = A[0].toCharArray().length;
for (int i = 0; i < len; i++) {
if(isNoSort(A, i)) count++;
}
return count;
}
public static boolean isNoSort(String[] A, int num) {
char c = A[0].charAt(num);
for (int i = 0; i < A.length;i++) {
if (A[i].charAt(num) < c) return true;
c = A[i].charAt(num);
}
return false;
}
public static void main(String[] args) {
DeleteColumnsToMakeSorted obj = new DeleteColumnsToMakeSorted();
String[] X = {"cba","daf","ghi"};
System.out.println(obj.minDeletionSize(X));
String[] Y = {"zyx","wvu","tsr"};
System.out.println(obj.minDeletionSize(Y));
String[] Z = {"abcdef"};
System.out.println(obj.minDeletionSize(Z));
}
}
/*
Output:
———————————————————
1
3
0
*/
| 1,285 | 0.53913 | 0.519368 | 55 | 22 | 20.256536 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490909 | false | false | 9 |
438effdf6261cef29ee8bd7f2a45a5af3bb82a2e | 13,520,557,060,043 | 30b37cb0cabbf52c1a0110bb0f2b516cabd74f71 | /Updater.java | 7b065138673f7fa6adf04c46cd6be9f9073a1539 | [
"BSD-3-Clause"
]
| permissive | cubixguy77/Poker-Client | https://github.com/cubixguy77/Poker-Client | 2607ea977da52e2ae9ccb7034c377fcc8774f272 | f4f49b0f1c76b8df0995bffd7b1907f0cbfcb88e | refs/heads/master | 2021-01-11T09:40:51.510000 | 2016-12-28T03:00:30 | 2016-12-28T03:00:30 | 77,496,109 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Timer;
import java.util.TimerTask;
public class Updater extends TimerTask {
public void run() {
//updateTournamentInfo();
}
} | UTF-8 | Java | 175 | java | Updater.java | Java | []
| null | []
| import java.util.Timer;
import java.util.TimerTask;
public class Updater extends TimerTask {
public void run() {
//updateTournamentInfo();
}
} | 175 | 0.622857 | 0.622857 | 12 | 13.666667 | 13.966229 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
3ab949492a8afe11020b8f60f7e86de4334e1759 | 23,287,312,733,610 | 0ab8c30bc677e3c4a72a23ce98867b5c02e726a9 | /src/com/rc/rentcar/controller/uniquecar/UniqueCarAction.java | 51017ba57558aea00a048c8fb0f14b199ed8d496 | []
| no_license | bypain/RC | https://github.com/bypain/RC | 3198894d199d9494e113701ccf717ca0d005d318 | 82989d27b47013fda865ec03fdce9c70ef3822c3 | refs/heads/master | 2018-03-23T17:17:42.211000 | 2017-02-11T10:47:35 | 2017-02-11T10:47:35 | 66,042,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rc.rentcar.controller.uniquecar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import baidumapsdk.demo.LocationDemo;
import com.alibaba.fastjson.JSON;
import com.androidquery.AQuery;
import com.rc.rentcar.R;
import com.rc.rentcar.adapter.UniqueCarAdapter;
import com.rc.rentcar.base.BaseAction;
import com.rc.rentcar.base.BaseModel.NetResult;
import com.rc.rentcar.entities.AddressInfo;
import com.rc.rentcar.entities.ChooseTrainList;
import com.rc.rentcar.entities.ComInfo;
import com.rc.rentcar.model.mine.SettingModel;
import com.rc.rentcar.utils.ActJump;
import com.rc.rentcar.utils.DialogUtil;
import com.rc.rentcar.view.uniquecar.AroundTourActivity;
import com.rc.rentcar.view.uniquecar.CalendarActivity;
import com.rc.rentcar.view.uniquecar.ComCalendarActivity;
import com.rc.rentcar.view.uniquecar.CompanyCarActivity;
import com.rc.rentcar.view.uniquecar.LongRentActivity;
import com.rc.rentcar.view.uniquecar.PeopleCarActivity;
import com.util.baidu.APPLocation;
import com.util.utils.T;
import com.util.utils.TextUtil;
public class UniqueCarAction extends BaseAction implements OnClickListener {
private int flag;//1起始2目的地
private ComInfo ci;
private SettingModel model;
private UniqueCarAdapter trainAdapter;
private List<ChooseTrainList.StartsBean> carList;
public UniqueCarAction(AQuery aq) {
super(aq);
}
@Override
public void initModel() {
model = new SettingModel(this);
model.getModelConfig(4);
model.getComInfo(2);
APPLocation.init(act).start();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
model.getBc(3, APPLocation.getCity());
}
}, 2000);
}
@Override
public void initView() {
tm.setTitle("专车接送");
tm.addButtonBack(act);
ImageView iv = new ImageView(act);
iv.setImageResource(R.drawable.img_call);
tm.addButtonRight(iv, new OnClickListener() {
@Override
public void onClick(View v) {
model.getConfig(1, "contact.shuttle_bus");
}
});
aq.id(R.id.iv_change).clicked(this);
aq.id(R.id.btn_query).clicked(this);
aq.id(R.id.people_car).clicked(this);
aq.id(R.id.straight_car).clicked(this);
aq.id(R.id.around_tour).clicked(this);
aq.id(R.id.long_rent).clicked(this);
aq.id(R.id.et_start).clicked(this);
aq.id(R.id.et_end).clicked(this);
ci = (ComInfo) act.getIntent().getSerializableExtra("ci");
trainAdapter = new UniqueCarAdapter(act);
trainAdapter.setType(2);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
trainAdapter.setTime(df.format(new Date()));
aq.id(R.id.xlv).adapter(trainAdapter);
}
@Override
public void callback(NetResult result, int flag) {
switch (flag) {
case 1:
if (result.isSuccess()) {
final String phoneNum = result.getDataObject().getString("value");
DialogUtil.showDialog(act, "您确定要拨打客服热线吗?", new OnClickListener() {
@Override
public void onClick(View v) {
DialogUtil.cancel();
Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + phoneNum));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.startActivity(intent);
}
});
}
break;
case 2:
if (result.isSuccess()) {
ci = JSON.parseObject(result.getDataObject().toJSONString(), ComInfo.class);
}
break;
case 3:
if (result.isSuccess()) {
carList = model.getBcSuccess(result);
trainAdapter.setData(carList);
}
break;
case 4:
if (result.isSuccess()) {
String bmzc = result.getDataObject().getJSONObject("app.module_config.bmzc").getString("value");
String cz = result.getDataObject().getJSONObject("app.module_config.cz").getString("value");
String qybc = result.getDataObject().getJSONObject("app.module_config.qybc").getString("value");
String zby = result.getDataObject().getJSONObject("app.module_config.zby").getString("value");
if (bmzc.equals("show"))
aq.id(R.id.people_car).visible();
else
aq.id(R.id.people_car).gone();
if (cz.equals("show"))
aq.id(R.id.long_rent).visible();
else
aq.id(R.id.long_rent).gone();
if (qybc.equals("show"))
aq.id(R.id.straight_car).visible();
else
aq.id(R.id.straight_car).gone();
if (zby.equals("show"))
aq.id(R.id.around_tour).visible();
else
aq.id(R.id.around_tour).gone();
}
break;
default:
break;
}
}
private AddressInfo pi;
private String sAddress,eAddress;
@Override
public void update(Object obj) {
super.update(obj);
if (obj instanceof String) {
if (flag==1) {
aq.id(R.id.et_start).text((String)obj);
}else if (flag==2) {
aq.id(R.id.et_end).text((String)obj);
}
}else if (obj instanceof AddressInfo) {
pi = (AddressInfo) obj;
if (flag==8) {
// aq.id(R.id.et_start).text(pi.getAddress());
if ((pi.getCity()+"市辖区").equals(pi.getArea())) {
sAddress = pi.getCity();
}else{
sAddress = pi.getCity()+pi.getArea();
}
aq.id(R.id.et_start).text(pi.getAddress());
}else if (flag==9) {
// aq.id(R.id.et_end).text(pi.getAddress());
if ((pi.getCity()+"市辖区").equals(pi.getArea())) {
eAddress = pi.getCity();
}else{
eAddress = pi.getCity()+pi.getArea();
}
aq.id(R.id.et_end).text(pi.getAddress());
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_change:
String start = aq.id(R.id.et_end).getText().toString();
String end = aq.id(R.id.et_start).getText().toString();
aq.id(R.id.et_start).text(start);
aq.id(R.id.et_end).text(end);
break;
case R.id.btn_query:
// ActJump.load(act, CalendarActivity.class);
if (TextUtil.isEmpty(aq.id(R.id.et_start).getText().toString())) {
T.showShort(act, "请选择出发地");
return;
}
if (TextUtil.isEmpty(aq.id(R.id.et_end).getText().toString())) {
T.showShort(act, "请选择目的地");
return;
}
CalendarActivity.load(act, 2,sAddress, eAddress);
break;
case R.id.people_car:
ActJump.load(act, PeopleCarActivity.class);
break;
case R.id.straight_car:
// ActJump.load(act, StraightCarActivity.class);
if (ci!=null) {
if (ci.isState()) {
ActJump.load(act, ComCalendarActivity.class);
}else{
// ActJump.load(act, CompanyCarActivity.class);
CompanyCarActivity.load(act, ci);
}
}
break;
case R.id.around_tour:
ActJump.load(act, AroundTourActivity.class);
break;
case R.id.long_rent:
ActJump.load(act, LongRentActivity.class);
break;
case R.id.et_start:
flag = 8;
// ActJump.load(act, ProvinceActivity.class);
LocationDemo.load(act, 8);
break;
case R.id.et_end:
flag=9;
// ActJump.load(act, ProvinceActivity.class);
LocationDemo.load(act, 9);
break;
default:
break;
}
}
}
| GB18030 | Java | 7,252 | java | UniqueCarAction.java | Java | []
| null | []
| package com.rc.rentcar.controller.uniquecar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import baidumapsdk.demo.LocationDemo;
import com.alibaba.fastjson.JSON;
import com.androidquery.AQuery;
import com.rc.rentcar.R;
import com.rc.rentcar.adapter.UniqueCarAdapter;
import com.rc.rentcar.base.BaseAction;
import com.rc.rentcar.base.BaseModel.NetResult;
import com.rc.rentcar.entities.AddressInfo;
import com.rc.rentcar.entities.ChooseTrainList;
import com.rc.rentcar.entities.ComInfo;
import com.rc.rentcar.model.mine.SettingModel;
import com.rc.rentcar.utils.ActJump;
import com.rc.rentcar.utils.DialogUtil;
import com.rc.rentcar.view.uniquecar.AroundTourActivity;
import com.rc.rentcar.view.uniquecar.CalendarActivity;
import com.rc.rentcar.view.uniquecar.ComCalendarActivity;
import com.rc.rentcar.view.uniquecar.CompanyCarActivity;
import com.rc.rentcar.view.uniquecar.LongRentActivity;
import com.rc.rentcar.view.uniquecar.PeopleCarActivity;
import com.util.baidu.APPLocation;
import com.util.utils.T;
import com.util.utils.TextUtil;
public class UniqueCarAction extends BaseAction implements OnClickListener {
private int flag;//1起始2目的地
private ComInfo ci;
private SettingModel model;
private UniqueCarAdapter trainAdapter;
private List<ChooseTrainList.StartsBean> carList;
public UniqueCarAction(AQuery aq) {
super(aq);
}
@Override
public void initModel() {
model = new SettingModel(this);
model.getModelConfig(4);
model.getComInfo(2);
APPLocation.init(act).start();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
model.getBc(3, APPLocation.getCity());
}
}, 2000);
}
@Override
public void initView() {
tm.setTitle("专车接送");
tm.addButtonBack(act);
ImageView iv = new ImageView(act);
iv.setImageResource(R.drawable.img_call);
tm.addButtonRight(iv, new OnClickListener() {
@Override
public void onClick(View v) {
model.getConfig(1, "contact.shuttle_bus");
}
});
aq.id(R.id.iv_change).clicked(this);
aq.id(R.id.btn_query).clicked(this);
aq.id(R.id.people_car).clicked(this);
aq.id(R.id.straight_car).clicked(this);
aq.id(R.id.around_tour).clicked(this);
aq.id(R.id.long_rent).clicked(this);
aq.id(R.id.et_start).clicked(this);
aq.id(R.id.et_end).clicked(this);
ci = (ComInfo) act.getIntent().getSerializableExtra("ci");
trainAdapter = new UniqueCarAdapter(act);
trainAdapter.setType(2);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
trainAdapter.setTime(df.format(new Date()));
aq.id(R.id.xlv).adapter(trainAdapter);
}
@Override
public void callback(NetResult result, int flag) {
switch (flag) {
case 1:
if (result.isSuccess()) {
final String phoneNum = result.getDataObject().getString("value");
DialogUtil.showDialog(act, "您确定要拨打客服热线吗?", new OnClickListener() {
@Override
public void onClick(View v) {
DialogUtil.cancel();
Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + phoneNum));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.startActivity(intent);
}
});
}
break;
case 2:
if (result.isSuccess()) {
ci = JSON.parseObject(result.getDataObject().toJSONString(), ComInfo.class);
}
break;
case 3:
if (result.isSuccess()) {
carList = model.getBcSuccess(result);
trainAdapter.setData(carList);
}
break;
case 4:
if (result.isSuccess()) {
String bmzc = result.getDataObject().getJSONObject("app.module_config.bmzc").getString("value");
String cz = result.getDataObject().getJSONObject("app.module_config.cz").getString("value");
String qybc = result.getDataObject().getJSONObject("app.module_config.qybc").getString("value");
String zby = result.getDataObject().getJSONObject("app.module_config.zby").getString("value");
if (bmzc.equals("show"))
aq.id(R.id.people_car).visible();
else
aq.id(R.id.people_car).gone();
if (cz.equals("show"))
aq.id(R.id.long_rent).visible();
else
aq.id(R.id.long_rent).gone();
if (qybc.equals("show"))
aq.id(R.id.straight_car).visible();
else
aq.id(R.id.straight_car).gone();
if (zby.equals("show"))
aq.id(R.id.around_tour).visible();
else
aq.id(R.id.around_tour).gone();
}
break;
default:
break;
}
}
private AddressInfo pi;
private String sAddress,eAddress;
@Override
public void update(Object obj) {
super.update(obj);
if (obj instanceof String) {
if (flag==1) {
aq.id(R.id.et_start).text((String)obj);
}else if (flag==2) {
aq.id(R.id.et_end).text((String)obj);
}
}else if (obj instanceof AddressInfo) {
pi = (AddressInfo) obj;
if (flag==8) {
// aq.id(R.id.et_start).text(pi.getAddress());
if ((pi.getCity()+"市辖区").equals(pi.getArea())) {
sAddress = pi.getCity();
}else{
sAddress = pi.getCity()+pi.getArea();
}
aq.id(R.id.et_start).text(pi.getAddress());
}else if (flag==9) {
// aq.id(R.id.et_end).text(pi.getAddress());
if ((pi.getCity()+"市辖区").equals(pi.getArea())) {
eAddress = pi.getCity();
}else{
eAddress = pi.getCity()+pi.getArea();
}
aq.id(R.id.et_end).text(pi.getAddress());
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_change:
String start = aq.id(R.id.et_end).getText().toString();
String end = aq.id(R.id.et_start).getText().toString();
aq.id(R.id.et_start).text(start);
aq.id(R.id.et_end).text(end);
break;
case R.id.btn_query:
// ActJump.load(act, CalendarActivity.class);
if (TextUtil.isEmpty(aq.id(R.id.et_start).getText().toString())) {
T.showShort(act, "请选择出发地");
return;
}
if (TextUtil.isEmpty(aq.id(R.id.et_end).getText().toString())) {
T.showShort(act, "请选择目的地");
return;
}
CalendarActivity.load(act, 2,sAddress, eAddress);
break;
case R.id.people_car:
ActJump.load(act, PeopleCarActivity.class);
break;
case R.id.straight_car:
// ActJump.load(act, StraightCarActivity.class);
if (ci!=null) {
if (ci.isState()) {
ActJump.load(act, ComCalendarActivity.class);
}else{
// ActJump.load(act, CompanyCarActivity.class);
CompanyCarActivity.load(act, ci);
}
}
break;
case R.id.around_tour:
ActJump.load(act, AroundTourActivity.class);
break;
case R.id.long_rent:
ActJump.load(act, LongRentActivity.class);
break;
case R.id.et_start:
flag = 8;
// ActJump.load(act, ProvinceActivity.class);
LocationDemo.load(act, 8);
break;
case R.id.et_end:
flag=9;
// ActJump.load(act, ProvinceActivity.class);
LocationDemo.load(act, 9);
break;
default:
break;
}
}
}
| 7,252 | 0.6555 | 0.65215 | 238 | 28.10084 | 20.557726 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.063025 | false | false | 9 |
1cd9327dc530ced697816205ccf4cae7f83fa4e4 | 31,052,613,602,502 | cf5c1cca40dbe70ccd4d64ee31f04051ee566814 | /test-data-generator/src/main/java/com/hyena/big/data/generator/Generator.java | 217faa2fdcabb665ed5f993f0b011562c8226ab3 | []
| no_license | youngFF/big-data | https://github.com/youngFF/big-data | f66ceb48246b98a4a3fc8cb40e196306a3f9d430 | 0d88be813180bcf2f0aa3ebdfc25f315b8a921a4 | refs/heads/master | 2023-01-12T19:42:13.342000 | 2020-11-15T13:46:47 | 2020-11-15T13:46:47 | 312,780,690 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hyena.big.data.generator;
/**
* 生成big-data项目所需要的数据
*
*/
public interface Generator{
/**
* generate test-data for specific hadoop project
*/
void generatorData();
} | UTF-8 | Java | 218 | java | Generator.java | Java | []
| null | []
| package com.hyena.big.data.generator;
/**
* 生成big-data项目所需要的数据
*
*/
public interface Generator{
/**
* generate test-data for specific hadoop project
*/
void generatorData();
} | 218 | 0.651515 | 0.651515 | 13 | 14.307693 | 16.249897 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 9 |
1ef166cc7f5a580c3df07646b03bb36d213fe639 | 4,904,852,661,755 | 1ba14a05e7c8ac551fe6e60a77cad624121644a6 | /app/src/main/java/app/edwin/com/reportapetrabajador/presentation/activities/ReportesActivity.java | 4bfa79263db5210c2049ccc2600f144fc6ebc0c6 | []
| no_license | EdDeza/demo-practica | https://github.com/EdDeza/demo-practica | a3ff215bd321cd974b068c9d49c30c199628e29e | ca404b0e4f1c4da3682eae4c184e7e525203c75e | refs/heads/master | 2020-04-06T03:59:39.617000 | 2017-02-24T19:54:52 | 2017-02-24T19:54:52 | 83,077,526 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.edwin.com.reportapetrabajador.presentation.activities;
import android.os.Bundle;
import android.support.annotation.Nullable;
import app.edwin.com.reportapetrabajador.R;
import app.edwin.com.reportapetrabajador.core.BaseActivity;
import app.edwin.com.reportapetrabajador.presentation.fragments.VerReportesFragment;
import app.edwin.com.reportapetrabajador.presentation.presenters.VerReportesPresenter;
import app.edwin.com.reportapetrabajador.utils.ActivityUtils;
/**
* Created by linuxdesarrollo01 on 20/02/17.
*/
public class ReportesActivity extends BaseActivity {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("vista reportes creada");
setContentView(R.layout.activity_reportes);
VerReportesFragment fragment = (VerReportesFragment) getSupportFragmentManager().findFragmentById(R.id.body_reportes
);
if (fragment == null){
fragment = VerReportesFragment.newInstance();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),fragment,R.id.body_reportes);
}
new VerReportesPresenter(fragment , getApplicationContext());
}
@Override
protected void onDestroy() {
System.out.println("Vista reportes, destruida");
super.onDestroy();
}
}
| UTF-8 | Java | 1,363 | java | ReportesActivity.java | Java | [
{
"context": "trabajador.utils.ActivityUtils;\n\n/**\n * Created by linuxdesarrollo01 on 20/02/17.\n */\n\npublic class ReportesActivity e",
"end": 513,
"score": 0.9996051788330078,
"start": 496,
"tag": "USERNAME",
"value": "linuxdesarrollo01"
}
]
| null | []
| package app.edwin.com.reportapetrabajador.presentation.activities;
import android.os.Bundle;
import android.support.annotation.Nullable;
import app.edwin.com.reportapetrabajador.R;
import app.edwin.com.reportapetrabajador.core.BaseActivity;
import app.edwin.com.reportapetrabajador.presentation.fragments.VerReportesFragment;
import app.edwin.com.reportapetrabajador.presentation.presenters.VerReportesPresenter;
import app.edwin.com.reportapetrabajador.utils.ActivityUtils;
/**
* Created by linuxdesarrollo01 on 20/02/17.
*/
public class ReportesActivity extends BaseActivity {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("vista reportes creada");
setContentView(R.layout.activity_reportes);
VerReportesFragment fragment = (VerReportesFragment) getSupportFragmentManager().findFragmentById(R.id.body_reportes
);
if (fragment == null){
fragment = VerReportesFragment.newInstance();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),fragment,R.id.body_reportes);
}
new VerReportesPresenter(fragment , getApplicationContext());
}
@Override
protected void onDestroy() {
System.out.println("Vista reportes, destruida");
super.onDestroy();
}
}
| 1,363 | 0.749083 | 0.743213 | 40 | 33.075001 | 32.897861 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 9 |
a93078f1f6117c67559e4d7a267caa85636e687f | 22,024,592,349,451 | cb7a33aa2907a9d4400942f5307e08a0ae33a847 | /src/test/java/org/reformer/proxydebug/ProxyDebugApplicationTests.java | aa5ad59aa45b7734b0f05a5aef88bc9eb6ca3782 | [
"Apache-2.0"
]
| permissive | guyixn/proxy-debug | https://github.com/guyixn/proxy-debug | 875c5526ce610328360dfcdd10001cf9e2d76c34 | 3874d7a6fbac5fe58001067ce2d653e63b445db1 | refs/heads/main | 2023-06-24T01:56:30.302000 | 2021-07-26T14:08:11 | 2021-07-26T14:08:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.reformer.proxydebug;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProxyDebugApplicationTests {
@Test
void contextLoads() {
}
}
| UTF-8 | Java | 228 | java | ProxyDebugApplicationTests.java | Java | []
| null | []
| package org.reformer.proxydebug;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProxyDebugApplicationTests {
@Test
void contextLoads() {
}
}
| 228 | 0.763158 | 0.763158 | 13 | 16.538462 | 18.265627 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 9 |
b9ef610632894dd03ee3f725d4c8ad7f2dd65977 | 19,069,654,801,758 | b11a7336358784e2b4661e81601562927658e25b | /references/wps/src/main/java/net/opengis/ows/x11/ContentsBaseType.java | 6df8c315057bb917ce55a34a3d24cf4a9cb3210b | []
| no_license | Tartomas/geoengine | https://github.com/Tartomas/geoengine | b618ec33f69bf5e0c993b0035e0e47d67cdda5e7 | f9edf7ef3bb2bdff04ed3a2f93e8496d52885797 | refs/heads/master | 2016-09-06T01:35:24.298000 | 2010-08-05T16:55:48 | 2010-08-05T16:55:48 | 40,911,870 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* XML Type: ContentsBaseType
* Namespace: http://www.opengis.net/ows/1.1
* Java type: net.opengis.ows.x11.ContentsBaseType
*
* Automatically generated - do not modify.
*/
package net.opengis.ows.x11;
/**
* An XML ContentsBaseType(@http://www.opengis.net/ows/1.1).
*
* This is a complex type.
*/
public interface ContentsBaseType extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ContentsBaseType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sD8016F3398DC83C8008AC4516B9A9B98").resolveHandle("contentsbasetypea280type");
/**
* Gets array of all "DatasetDescriptionSummary" elements
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType[] getDatasetDescriptionSummaryArray();
/**
* Gets ith "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType getDatasetDescriptionSummaryArray(int i);
/**
* Returns number of "DatasetDescriptionSummary" element
*/
int sizeOfDatasetDescriptionSummaryArray();
/**
* Sets array of all "DatasetDescriptionSummary" element
*/
void setDatasetDescriptionSummaryArray(net.opengis.ows.x11.DatasetDescriptionSummaryBaseType[] datasetDescriptionSummaryArray);
/**
* Sets ith "DatasetDescriptionSummary" element
*/
void setDatasetDescriptionSummaryArray(int i, net.opengis.ows.x11.DatasetDescriptionSummaryBaseType datasetDescriptionSummary);
/**
* Inserts and returns a new empty value (as xml) as the ith "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType insertNewDatasetDescriptionSummary(int i);
/**
* Appends and returns a new empty value (as xml) as the last "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType addNewDatasetDescriptionSummary();
/**
* Removes the ith "DatasetDescriptionSummary" element
*/
void removeDatasetDescriptionSummary(int i);
/**
* Gets array of all "OtherSource" elements
*/
net.opengis.ows.x11.MetadataType[] getOtherSourceArray();
/**
* Gets ith "OtherSource" element
*/
net.opengis.ows.x11.MetadataType getOtherSourceArray(int i);
/**
* Returns number of "OtherSource" element
*/
int sizeOfOtherSourceArray();
/**
* Sets array of all "OtherSource" element
*/
void setOtherSourceArray(net.opengis.ows.x11.MetadataType[] otherSourceArray);
/**
* Sets ith "OtherSource" element
*/
void setOtherSourceArray(int i, net.opengis.ows.x11.MetadataType otherSource);
/**
* Inserts and returns a new empty value (as xml) as the ith "OtherSource" element
*/
net.opengis.ows.x11.MetadataType insertNewOtherSource(int i);
/**
* Appends and returns a new empty value (as xml) as the last "OtherSource" element
*/
net.opengis.ows.x11.MetadataType addNewOtherSource();
/**
* Removes the ith "OtherSource" element
*/
void removeOtherSource(int i);
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.ows.x11.ContentsBaseType newInstance() {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.ows.x11.ContentsBaseType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.ows.x11.ContentsBaseType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static net.opengis.ows.x11.ContentsBaseType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static net.opengis.ows.x11.ContentsBaseType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| UTF-8 | Java | 10,473 | java | ContentsBaseType.java | Java | []
| null | []
| /*
* XML Type: ContentsBaseType
* Namespace: http://www.opengis.net/ows/1.1
* Java type: net.opengis.ows.x11.ContentsBaseType
*
* Automatically generated - do not modify.
*/
package net.opengis.ows.x11;
/**
* An XML ContentsBaseType(@http://www.opengis.net/ows/1.1).
*
* This is a complex type.
*/
public interface ContentsBaseType extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ContentsBaseType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sD8016F3398DC83C8008AC4516B9A9B98").resolveHandle("contentsbasetypea280type");
/**
* Gets array of all "DatasetDescriptionSummary" elements
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType[] getDatasetDescriptionSummaryArray();
/**
* Gets ith "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType getDatasetDescriptionSummaryArray(int i);
/**
* Returns number of "DatasetDescriptionSummary" element
*/
int sizeOfDatasetDescriptionSummaryArray();
/**
* Sets array of all "DatasetDescriptionSummary" element
*/
void setDatasetDescriptionSummaryArray(net.opengis.ows.x11.DatasetDescriptionSummaryBaseType[] datasetDescriptionSummaryArray);
/**
* Sets ith "DatasetDescriptionSummary" element
*/
void setDatasetDescriptionSummaryArray(int i, net.opengis.ows.x11.DatasetDescriptionSummaryBaseType datasetDescriptionSummary);
/**
* Inserts and returns a new empty value (as xml) as the ith "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType insertNewDatasetDescriptionSummary(int i);
/**
* Appends and returns a new empty value (as xml) as the last "DatasetDescriptionSummary" element
*/
net.opengis.ows.x11.DatasetDescriptionSummaryBaseType addNewDatasetDescriptionSummary();
/**
* Removes the ith "DatasetDescriptionSummary" element
*/
void removeDatasetDescriptionSummary(int i);
/**
* Gets array of all "OtherSource" elements
*/
net.opengis.ows.x11.MetadataType[] getOtherSourceArray();
/**
* Gets ith "OtherSource" element
*/
net.opengis.ows.x11.MetadataType getOtherSourceArray(int i);
/**
* Returns number of "OtherSource" element
*/
int sizeOfOtherSourceArray();
/**
* Sets array of all "OtherSource" element
*/
void setOtherSourceArray(net.opengis.ows.x11.MetadataType[] otherSourceArray);
/**
* Sets ith "OtherSource" element
*/
void setOtherSourceArray(int i, net.opengis.ows.x11.MetadataType otherSource);
/**
* Inserts and returns a new empty value (as xml) as the ith "OtherSource" element
*/
net.opengis.ows.x11.MetadataType insertNewOtherSource(int i);
/**
* Appends and returns a new empty value (as xml) as the last "OtherSource" element
*/
net.opengis.ows.x11.MetadataType addNewOtherSource();
/**
* Removes the ith "OtherSource" element
*/
void removeOtherSource(int i);
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.ows.x11.ContentsBaseType newInstance() {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.ows.x11.ContentsBaseType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.ows.x11.ContentsBaseType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.ows.x11.ContentsBaseType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.ows.x11.ContentsBaseType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static net.opengis.ows.x11.ContentsBaseType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static net.opengis.ows.x11.ContentsBaseType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.ows.x11.ContentsBaseType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| 10,473 | 0.713549 | 0.701041 | 176 | 57.50568 | 63.454975 | 279 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568182 | false | false | 9 |
3b500981e9bade5a653cf60c663ca43918dc0fb0 | 28,784,870,862,911 | fa92b5e7dfa3c9a93cd399836fd5cc2b55bcec74 | /src/main/java/com/music/streaming/service/implementation/MusicServiceImpl.java | 9f40c2d2aca1ad6853cd1c3f901c5e05cf893093 | []
| no_license | AntonYastrebkov/MusicStreaming | https://github.com/AntonYastrebkov/MusicStreaming | 4ba2ae2b8368aa6a549bf98c1082b91569daa51d | ed1c7543e797371d9b72abeb8a7f40851d1227ac | refs/heads/master | 2022-12-05T14:19:30.633000 | 2019-12-23T11:25:34 | 2019-12-23T11:25:34 | 217,842,373 | 0 | 0 | null | false | 2022-11-16T09:58:30 | 2019-10-27T11:04:10 | 2019-12-23T11:25:38 | 2022-11-16T09:58:27 | 48 | 0 | 0 | 1 | Java | false | false | package com.music.streaming.service.implementation;
import com.music.streaming.model.Album;
import com.music.streaming.model.Artist;
import com.music.streaming.model.Genre;
import com.music.streaming.model.Song;
import com.music.streaming.repository.AlbumRepository;
import com.music.streaming.repository.ArtistRepository;
import com.music.streaming.repository.SongRepository;
import com.music.streaming.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
@Transactional
public class MusicServiceImpl implements MusicService {
@Autowired
private ArtistRepository artistRepository;
@Autowired
private AlbumRepository albumRepository;
@Autowired
private SongRepository songRepository;
@Value("${upload.path}")
private String uploadPath;
@Override
public boolean addArtist(String name, String description, String year, MultipartFile file) {
Artist artistFromDb = artistRepository.findByName(name);
if (artistFromDb != null) {
return false;
}
Artist artist = new Artist();
artist.setName(name);
artist.setDescription(description);
artist.setYear(year);
if (!file.isEmpty()) {
if (!saveArtistImage(artist, file)) {
return false;
}
}
artistRepository.save(artist);
return true;
}
@Override
public boolean addAlbum(String name, String artistName, MultipartFile cover, Genre genre) {
List<Album> albumByName = albumRepository.findByName(name);
Artist artist = artistRepository.findByName(artistName);
Optional<Album> optional = albumByName.stream()
.filter(a -> a.getArtist().getName().equals(artistName))
.findFirst();
if (artist == null || optional.isPresent()) {
return false;
}
System.out.println("Create");
Album album = new Album();
album.setName(name);
album.setArtist(artist);
album.setGenre(genre);
System.out.println("Saving file");
if (! saveCover(album, cover)) {
return false;
}
System.out.println("DB");
albumRepository.save(album);
return true;
}
@Override
public boolean updateAlbum(Album album, String name, String artistName, MultipartFile cover, Genre genre) {
album.setName(name);
Artist artist = artistRepository.findByName(artistName);
if (artist == null) {
return false;
}
album.setArtist(artist);
album.setGenre(genre);
if (!cover.isEmpty() && !saveCover(album, cover)) {
return false;
}
albumRepository.save(album);
return true;
}
@Override
public boolean updateArtist(Artist artist, String name, String description, String year, MultipartFile file) {
artist.setName(name);
artist.setDescription(description);
artist.setYear(year);
if (!file.isEmpty()) {
return saveArtistImage(artist, file);
}
artistRepository.save(artist);
return true;
}
@Override
public boolean addSong(Album album, String name) {
List<Song> songs = album.getSongs();
Song song = new Song();
song.setAlbum(album);
song.setName(name);
song.setNumber(songs.size() + 1);
songs.add(song);
songRepository.save(song);
return true;
}
@Override
public void deleteSong(Album album, Song song) {
songRepository.delete(song);
album.getSongs().remove(song);
}
private boolean saveArtistImage(Artist artist, MultipartFile image) {
String filename = saveImage(image);
if ("".equals(filename)) {
return false;
}
artist.setImagePath(filename);
return true;
}
private boolean saveCover(Album album, MultipartFile cover) {
String filename = saveImage(cover);
if ("".equals(filename)) {
return false;
}
album.setCoverPath(filename);
return true;
}
private String saveImage(MultipartFile file) {
if (file != null && !file.getOriginalFilename().isEmpty()) {
File destination = new File(uploadPath);
if (!destination.exists()) {
destination.mkdir();
}
String filename = UUID.randomUUID().toString() + "."
+ file.getOriginalFilename();
try {
file.transferTo(new File(uploadPath + "/" + filename));
} catch (IOException e) {
e.printStackTrace();
return "";
}
return filename;
} else {
return "";
}
}
}
| UTF-8 | Java | 5,198 | java | MusicServiceImpl.java | Java | []
| null | []
| package com.music.streaming.service.implementation;
import com.music.streaming.model.Album;
import com.music.streaming.model.Artist;
import com.music.streaming.model.Genre;
import com.music.streaming.model.Song;
import com.music.streaming.repository.AlbumRepository;
import com.music.streaming.repository.ArtistRepository;
import com.music.streaming.repository.SongRepository;
import com.music.streaming.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
@Transactional
public class MusicServiceImpl implements MusicService {
@Autowired
private ArtistRepository artistRepository;
@Autowired
private AlbumRepository albumRepository;
@Autowired
private SongRepository songRepository;
@Value("${upload.path}")
private String uploadPath;
@Override
public boolean addArtist(String name, String description, String year, MultipartFile file) {
Artist artistFromDb = artistRepository.findByName(name);
if (artistFromDb != null) {
return false;
}
Artist artist = new Artist();
artist.setName(name);
artist.setDescription(description);
artist.setYear(year);
if (!file.isEmpty()) {
if (!saveArtistImage(artist, file)) {
return false;
}
}
artistRepository.save(artist);
return true;
}
@Override
public boolean addAlbum(String name, String artistName, MultipartFile cover, Genre genre) {
List<Album> albumByName = albumRepository.findByName(name);
Artist artist = artistRepository.findByName(artistName);
Optional<Album> optional = albumByName.stream()
.filter(a -> a.getArtist().getName().equals(artistName))
.findFirst();
if (artist == null || optional.isPresent()) {
return false;
}
System.out.println("Create");
Album album = new Album();
album.setName(name);
album.setArtist(artist);
album.setGenre(genre);
System.out.println("Saving file");
if (! saveCover(album, cover)) {
return false;
}
System.out.println("DB");
albumRepository.save(album);
return true;
}
@Override
public boolean updateAlbum(Album album, String name, String artistName, MultipartFile cover, Genre genre) {
album.setName(name);
Artist artist = artistRepository.findByName(artistName);
if (artist == null) {
return false;
}
album.setArtist(artist);
album.setGenre(genre);
if (!cover.isEmpty() && !saveCover(album, cover)) {
return false;
}
albumRepository.save(album);
return true;
}
@Override
public boolean updateArtist(Artist artist, String name, String description, String year, MultipartFile file) {
artist.setName(name);
artist.setDescription(description);
artist.setYear(year);
if (!file.isEmpty()) {
return saveArtistImage(artist, file);
}
artistRepository.save(artist);
return true;
}
@Override
public boolean addSong(Album album, String name) {
List<Song> songs = album.getSongs();
Song song = new Song();
song.setAlbum(album);
song.setName(name);
song.setNumber(songs.size() + 1);
songs.add(song);
songRepository.save(song);
return true;
}
@Override
public void deleteSong(Album album, Song song) {
songRepository.delete(song);
album.getSongs().remove(song);
}
private boolean saveArtistImage(Artist artist, MultipartFile image) {
String filename = saveImage(image);
if ("".equals(filename)) {
return false;
}
artist.setImagePath(filename);
return true;
}
private boolean saveCover(Album album, MultipartFile cover) {
String filename = saveImage(cover);
if ("".equals(filename)) {
return false;
}
album.setCoverPath(filename);
return true;
}
private String saveImage(MultipartFile file) {
if (file != null && !file.getOriginalFilename().isEmpty()) {
File destination = new File(uploadPath);
if (!destination.exists()) {
destination.mkdir();
}
String filename = UUID.randomUUID().toString() + "."
+ file.getOriginalFilename();
try {
file.transferTo(new File(uploadPath + "/" + filename));
} catch (IOException e) {
e.printStackTrace();
return "";
}
return filename;
} else {
return "";
}
}
}
| 5,198 | 0.6212 | 0.621008 | 166 | 30.313253 | 22.367374 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662651 | false | false | 9 |
2f9fc5437e440a48284d9140108e3f9986be38e3 | 1,795,296,359,011 | 697b28c9b250ec2c505071f3cc968ee333c0adce | /src/main/java/com/hua/house/HouseCalc.java | b7a9a9f333a402d1d7a3f3a042c4e4f2f588639c | []
| no_license | javase/java-exlorer | https://github.com/javase/java-exlorer | 46a4cf06970047810cc0b70effd678d41a2039c7 | 9ef5f0305eb93fb801ab7d03199b6429b3bcff4c | refs/heads/master | 2018-03-22T08:38:53.435000 | 2017-09-20T08:35:18 | 2017-09-20T08:35:18 | 56,417,139 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hua.house;
/**
* Created by limenghua on 2016/8/18.
*
* @author limenghua
*/
public class HouseCalc {
public static void main(String[] args) {
int mi = 104; // 平米
int price = 8600;// 单价
double first = 0.25;
System.out.println(String.format("房屋面积:%s平米", mi));
System.out.println(String.format("%s元/平米", price));
System.out.println(String.format("总价:%s", (mi * price)));
System.out.println(String.format("首付:%s", (mi * price * first)));
}
}
| UTF-8 | Java | 560 | java | HouseCalc.java | Java | [
{
"context": "package com.hua.house;\n\n/**\n * Created by limenghua on 2016/8/18.\n *\n * @author limenghua\n */\npublic ",
"end": 51,
"score": 0.9902771711349487,
"start": 42,
"tag": "USERNAME",
"value": "limenghua"
},
{
"context": "* Created by limenghua on 2016/8/18.\n *\n * @author limenghua\n */\npublic class HouseCalc {\n public static vo",
"end": 89,
"score": 0.925400972366333,
"start": 80,
"tag": "USERNAME",
"value": "limenghua"
}
]
| null | []
| package com.hua.house;
/**
* Created by limenghua on 2016/8/18.
*
* @author limenghua
*/
public class HouseCalc {
public static void main(String[] args) {
int mi = 104; // 平米
int price = 8600;// 单价
double first = 0.25;
System.out.println(String.format("房屋面积:%s平米", mi));
System.out.println(String.format("%s元/平米", price));
System.out.println(String.format("总价:%s", (mi * price)));
System.out.println(String.format("首付:%s", (mi * price * first)));
}
}
| 560 | 0.582692 | 0.55 | 18 | 27.888889 | 23.263918 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
ea3451ecc3355ed835a4bedd55433c516bc97d26 | 26,886,495,328,044 | 48bfa74f740cd86866c6b4ecb16ee8b58d151f3c | /pgrk9340.java | 0e5750245f8bfb3a29509909d395c090f850cf64 | []
| no_license | rlt23/Implementation-of-Hashmap-and-Pagerank-Algorithm | https://github.com/rlt23/Implementation-of-Hashmap-and-Pagerank-Algorithm | d905fc12155ffcf57b8fef1392f1fbc1ed1a02a6 | 03407303c2f1727c8c4ac792927a91151a84e269 | refs/heads/main | 2023-08-06T08:05:54.040000 | 2020-12-22T06:26:01 | 2020-12-22T06:26:01 | 323,540,760 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //Name: Rohit Thole
//UCID: 31509340
import java.util.*;
import java.io.*;
import java.lang.*;
import static java.lang.Math.*;
public class pgrk9340 {
int iteration;
int initial_val;
String filename;
int n; // number of vertices in the graph
int m; // number of edges in the graph
int[][] Z; // adjacency matrix
final double d = 0.85;
final double errorrate = 0.00001;
double[] src_db;
int[] C;
pgrk9340() {} //default constructor
pgrk9340(int iteration, int initial_val, String filename) // 3 argument constructor to initialize class variables with provided command line arguments
{
this.iteration = iteration;
this.initial_val = initial_val;
this.filename = filename;
int p = 0;
int q = 0;
try {
Scanner scanner = new Scanner(new File(filename));
n = scanner.nextInt();
m = scanner.nextInt();
//Adjacency matrix representation of graph
Z = new int[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
Z[i][j] = 0;
while(scanner.hasNextInt())
{
p = scanner.nextInt();
q = scanner.nextInt();
Z[p][q] = 1;
}
C = new int[n];
for(int i = 0; i < n; i++) {
C[i] = 0;
for(int j = 0; j < n; j++) {
C[i] += Z[i][j];
}
}
src_db = new double[n];
switch(initial_val) {
case 0:
for(int i = 0; i < n; i++) {
src_db[i] = 0;
}
break;
case 1:
for(int i = 0; i < n; i++) {
src_db[i] = 1;
}
break;
case -1:
for(int i =0; i < n; i++) {
src_db[i] = 1.0/n;
}
break;
case -2:
for(int i =0; i < n; i++) {
src_db[i] = 1.0/Math.sqrt(n);
}
break;
}
}
catch(FileNotFoundException abc)
{
}
}
public static void main(String[] args)
{
if(args.length != 3) {
System.out.println("");
return;
}
//command line arguments
int iterations = Integer.parseInt(args[0]);
int initialvalue = Integer.parseInt(args[1]);
String filename = args[2];
if( !(initialvalue >= -2 && initialvalue <= 1) ) {
System.out.println("InitialValue should be -2,-1,0,1");
return;
}
pgrk9340 pr = new pgrk9340(iterations, initialvalue, filename);
pr.pgrk_Algo();
}
boolean is_Converged(double[] src, double[] target)
{
for(int i = 0; i < n; i++)
{
if ( abs(src[i] - target[i]) > errorrate )
return false;
}
return true;
}
void pgrk_Algo() {
double[] D = new double[n];
boolean flag = true;
if(n > 10) {
iteration = 0;
for(int i =0; i < n; i++) {
src_db[i] = 1.0/n;
}
int i = 0;
do {
if(flag == true)
{
flag = false;
}
else
{
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
//Compute and print pagerank of all pages
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
}
i++;
} while (is_Converged(src_db, D) != true);
// print pageranks at the stopping iteration
System.out.println("Iter: " + i);
for(int l = 0 ; l < n; l++) {
System.out.printf("P[" + l + "] = %.6f\n",Math.round(D[l]*1000000.0)/1000000.0);
}
return;
}
//Base Case
System.out.print("Base : 0 :");
for(int j = 0; j < n; j++) {
System.out.printf(" P[" + j + "]=%.6f",Math.round(src_db[j]*1000000.0)/1000000.0);
}
if (iteration != 0) {
for(int i = 0; i < iteration; i++)
{
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
System.out.println();
System.out.print("Iter : " + (i+1)+" : ");
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
System.out.printf(" P[" + l + "]=%.6f",Math.round(D[l]*1000000.0)/1000000.0);
}
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
System.out.println();
}
else
{
int i = 0;
do {
if(flag == true)
{
flag = false;
}
else
{
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
//Compute and print pagerank of all pages
System.out.println();
System.out.print("Iter : " + (i+1)+" : ");
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
System.out.printf(" P[" + l + "]=%.6f",Math.round(D[l]*1000000.0)/1000000.0);
}
i++;
} while (is_Converged(src_db, D) != true);
System.out.println();
}
}
}
| UTF-8 | Java | 7,003 | java | pgrk9340.java | Java | [
{
"context": "//Name: Rohit Thole\r\n//UCID: 31509340\r\n\r\nimport java.util.*;\r\nimport ",
"end": 19,
"score": 0.9998666048049927,
"start": 8,
"tag": "NAME",
"value": "Rohit Thole"
}
]
| null | []
| //Name: <NAME>
//UCID: 31509340
import java.util.*;
import java.io.*;
import java.lang.*;
import static java.lang.Math.*;
public class pgrk9340 {
int iteration;
int initial_val;
String filename;
int n; // number of vertices in the graph
int m; // number of edges in the graph
int[][] Z; // adjacency matrix
final double d = 0.85;
final double errorrate = 0.00001;
double[] src_db;
int[] C;
pgrk9340() {} //default constructor
pgrk9340(int iteration, int initial_val, String filename) // 3 argument constructor to initialize class variables with provided command line arguments
{
this.iteration = iteration;
this.initial_val = initial_val;
this.filename = filename;
int p = 0;
int q = 0;
try {
Scanner scanner = new Scanner(new File(filename));
n = scanner.nextInt();
m = scanner.nextInt();
//Adjacency matrix representation of graph
Z = new int[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
Z[i][j] = 0;
while(scanner.hasNextInt())
{
p = scanner.nextInt();
q = scanner.nextInt();
Z[p][q] = 1;
}
C = new int[n];
for(int i = 0; i < n; i++) {
C[i] = 0;
for(int j = 0; j < n; j++) {
C[i] += Z[i][j];
}
}
src_db = new double[n];
switch(initial_val) {
case 0:
for(int i = 0; i < n; i++) {
src_db[i] = 0;
}
break;
case 1:
for(int i = 0; i < n; i++) {
src_db[i] = 1;
}
break;
case -1:
for(int i =0; i < n; i++) {
src_db[i] = 1.0/n;
}
break;
case -2:
for(int i =0; i < n; i++) {
src_db[i] = 1.0/Math.sqrt(n);
}
break;
}
}
catch(FileNotFoundException abc)
{
}
}
public static void main(String[] args)
{
if(args.length != 3) {
System.out.println("");
return;
}
//command line arguments
int iterations = Integer.parseInt(args[0]);
int initialvalue = Integer.parseInt(args[1]);
String filename = args[2];
if( !(initialvalue >= -2 && initialvalue <= 1) ) {
System.out.println("InitialValue should be -2,-1,0,1");
return;
}
pgrk9340 pr = new pgrk9340(iterations, initialvalue, filename);
pr.pgrk_Algo();
}
boolean is_Converged(double[] src, double[] target)
{
for(int i = 0; i < n; i++)
{
if ( abs(src[i] - target[i]) > errorrate )
return false;
}
return true;
}
void pgrk_Algo() {
double[] D = new double[n];
boolean flag = true;
if(n > 10) {
iteration = 0;
for(int i =0; i < n; i++) {
src_db[i] = 1.0/n;
}
int i = 0;
do {
if(flag == true)
{
flag = false;
}
else
{
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
//Compute and print pagerank of all pages
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
}
i++;
} while (is_Converged(src_db, D) != true);
// print pageranks at the stopping iteration
System.out.println("Iter: " + i);
for(int l = 0 ; l < n; l++) {
System.out.printf("P[" + l + "] = %.6f\n",Math.round(D[l]*1000000.0)/1000000.0);
}
return;
}
//Base Case
System.out.print("Base : 0 :");
for(int j = 0; j < n; j++) {
System.out.printf(" P[" + j + "]=%.6f",Math.round(src_db[j]*1000000.0)/1000000.0);
}
if (iteration != 0) {
for(int i = 0; i < iteration; i++)
{
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
System.out.println();
System.out.print("Iter : " + (i+1)+" : ");
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
System.out.printf(" P[" + l + "]=%.6f",Math.round(D[l]*1000000.0)/1000000.0);
}
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
System.out.println();
}
else
{
int i = 0;
do {
if(flag == true)
{
flag = false;
}
else
{
for(int l = 0; l < n; l++) {
src_db[l] = D[l];
}
}
for(int l = 0; l < n; l++) {
D[l] = 0.0;
}
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++)
{
if(Z[k][j] == 1) {
D[j] += src_db[k]/C[k];
}
}
}
//Compute and print pagerank of all pages
System.out.println();
System.out.print("Iter : " + (i+1)+" : ");
for(int l = 0; l < n; l++) {
D[l] = d*D[l] + (1-d)/n;
System.out.printf(" P[" + l + "]=%.6f",Math.round(D[l]*1000000.0)/1000000.0);
}
i++;
} while (is_Converged(src_db, D) != true);
System.out.println();
}
}
}
| 6,998 | 0.328859 | 0.30287 | 241 | 27.058092 | 20.03474 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651452 | false | false | 9 |
4da301e605a777bc2f0521149467ff9eafe62e6b | 10,170,482,605,881 | 4d4bfba9521adfdb5225f4b17caac199801f34dc | /src/MyMainClass.java | 29c66c295fe50ae80d63dd88b15a3ba6e85e139b | []
| no_license | komura92/javaClasses | https://github.com/komura92/javaClasses | 35716ee68f71f0218e8ab090826de7389ec5b983 | adbc3e32c24fd496ac6f9df450777120dc307f2c | refs/heads/master | 2021-05-17T11:14:41.046000 | 2020-03-28T08:56:30 | 2020-03-28T08:56:30 | 250,751,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Outer {
//default access is package-private (public in package)
int outerField = 1;
private int outerPrivateField = 2; //no access from child objects | if needed -> protected
class Inner {
int innerField = 3;
}
static class StaticInner {
int staticInnerField = 4;
}
}
class Child extends Outer {
int childField = 5;
public Child() {
//this.outerPrivateField = 10; //NO ACCESS!!!
}
}
public class MyMainClass {
public static void main(String[] args) {
//Creating instance of inner class
Outer outer = new Outer();
//Creating instance of child class
Child child = new Child();
//Creating instance of inner class
Outer.Inner inner1 = new Outer().new Inner();
Outer.Inner inner2 = outer.new Inner();
Child.Inner inner3 = new Child().new Inner();
Child.Inner inner4 = child.new Inner();
//Creating instance of static inner class
Outer.StaticInner staticInner1 = new Outer.StaticInner();
Child.StaticInner staticInner2 = new Child.StaticInner();
System.out.println(outer.outerField);
System.out.println(child.outerField);
System.out.println(child.childField);
System.out.println(inner1.innerField);
System.out.println(staticInner1.staticInnerField);
}
} | UTF-8 | Java | 1,375 | java | MyMainClass.java | Java | []
| null | []
| class Outer {
//default access is package-private (public in package)
int outerField = 1;
private int outerPrivateField = 2; //no access from child objects | if needed -> protected
class Inner {
int innerField = 3;
}
static class StaticInner {
int staticInnerField = 4;
}
}
class Child extends Outer {
int childField = 5;
public Child() {
//this.outerPrivateField = 10; //NO ACCESS!!!
}
}
public class MyMainClass {
public static void main(String[] args) {
//Creating instance of inner class
Outer outer = new Outer();
//Creating instance of child class
Child child = new Child();
//Creating instance of inner class
Outer.Inner inner1 = new Outer().new Inner();
Outer.Inner inner2 = outer.new Inner();
Child.Inner inner3 = new Child().new Inner();
Child.Inner inner4 = child.new Inner();
//Creating instance of static inner class
Outer.StaticInner staticInner1 = new Outer.StaticInner();
Child.StaticInner staticInner2 = new Child.StaticInner();
System.out.println(outer.outerField);
System.out.println(child.outerField);
System.out.println(child.childField);
System.out.println(inner1.innerField);
System.out.println(staticInner1.staticInnerField);
}
} | 1,375 | 0.634182 | 0.623273 | 52 | 25.461538 | 23.833929 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 9 |
ae8ae04c0b2c7290600002a860ecb9fef3b88a40 | 9,380,208,595,355 | 1d0f4c25edfffb2928a2425ba635da6e584aaa1d | /ManejoComputadoras/src/emsamablajecomputadoras/creacional/AsusROGEBuilder.java | 7415e6b6967b7fb10a7de75e510ae351468409df | []
| no_license | HaroldYepez95/Builder5 | https://github.com/HaroldYepez95/Builder5 | 916e46ad590ef43bcbb61d8d5c8482a2d19e5e18 | 6e6a082b9071bfca8db4962d511b33cb47b22a9e | refs/heads/master | 2020-04-10T18:03:59.260000 | 2018-12-10T16:25:56 | 2018-12-10T16:25:56 | 161,192,894 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package emsamablajecomputadoras.creacional;
public class AsusROGEBuilder extends ComputerBuilder {
public void definircomputador() {
}
@Override
public void definirComputador() {
c = new Computador();
c.setMarca( "Asus") ;
c.setModelo("ROG") ;
c.setRam(32);
c.setAlmacenamiento(1000);
}
@Override
public void definirSistemaOperativo() {
c.setOs( new SistemaOperativo("Windows",64, "10 PRO"));
}
@Override
public void definirMainboard() {
c.setPlaca(new Mainboard ("Strix" , "x99"));
}
}
| UTF-8 | Java | 593 | java | AsusROGEBuilder.java | Java | []
| null | []
| package emsamablajecomputadoras.creacional;
public class AsusROGEBuilder extends ComputerBuilder {
public void definircomputador() {
}
@Override
public void definirComputador() {
c = new Computador();
c.setMarca( "Asus") ;
c.setModelo("ROG") ;
c.setRam(32);
c.setAlmacenamiento(1000);
}
@Override
public void definirSistemaOperativo() {
c.setOs( new SistemaOperativo("Windows",64, "10 PRO"));
}
@Override
public void definirMainboard() {
c.setPlaca(new Mainboard ("Strix" , "x99"));
}
}
| 593 | 0.613828 | 0.593592 | 40 | 12.825 | 16.974815 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.425 | false | false | 9 |
0e27a3c58e4ac1b4fdb522dde60c8991b3fb45e4 | 13,391,708,047,867 | a565137c1de4669226ad057cd336618fdf2481d4 | /src/main/java/com/moon/poi/excel/table/Parser.java | 09a30eebed8d6f33fad8636229efd8145745bd10 | [
"MIT"
]
| permissive | moon-util/moon-util | https://github.com/moon-util/moon-util | ec58aefa46c526ae11b1a55a946c1763ecb9c693 | 28c5cb418861da4d0a5a035a3de919b86b939c0e | refs/heads/master | 2022-12-25T23:01:28.564000 | 2020-12-17T15:55:52 | 2020-12-17T15:55:52 | 184,226,062 | 8 | 1 | MIT | false | 2022-12-16T15:29:24 | 2019-04-30T08:46:31 | 2022-09-05T10:58:36 | 2022-12-16T15:29:24 | 3,068 | 6 | 2 | 13 | Java | false | false | package com.moon.poi.excel.table;
import com.moon.poi.excel.annotation.value.DefaultNumber;
import com.moon.poi.excel.annotation.value.DefaultValue;
import org.apache.poi.ss.usermodel.Workbook;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* @author moonsky
*/
final class Parser<T extends Marked> {
private final Creator creator;
private final static Map<Class, TableRenderer> parsed = new WeakHashMap<>();
final static synchronized TableRenderer cache(Class type, TableRenderer renderer) {
parsed.putIfAbsent(type, renderer);
return renderer;
}
private final static TableRenderer getCached(Class type) { return parsed.get(type); }
Parser(Creator creator) { this.creator = creator; }
protected Creator getCreator() { return creator; }
// protected TableRenderer doParseConfiguration(Class type) {
// return doParseConfiguration(type, false);
// }
protected TableRenderer doParseConfiguration(Class type, boolean cacheDisabled) {
if (!cacheDisabled) {
TableRenderer renderer = getCached(type);
if (renderer != null) {
return renderer;
}
}
try {
Map<String, T> annotatedAtM = new LinkedHashMap<>();
Map<String, T> unAnnotatedAtM = new LinkedHashMap<>();
Map<String, T> annotatedAtF = new LinkedHashMap<>();
Map<String, T> unAnnotatedAtF = new LinkedHashMap<>();
parseDescriptors(type, annotatedAtM, unAnnotatedAtM);
parseFields(type, annotatedAtF, unAnnotatedAtF);
Map<String, Attribute> annotated = ParserUtil.merge2Attr(annotatedAtM,
annotatedAtF,
unAnnotatedAtM,
unAnnotatedAtF);
Map<String, Attribute> unAnnotated = ParserUtil.merge2Attr(unAnnotatedAtM, unAnnotatedAtF);
return toRendererResultAndCache(type, annotated, unAnnotated, cacheDisabled);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private TableRenderer toRendererResultAndCache(
Class type, Map<String, Attribute> annotated, Map<String, Attribute> unAnnotated, boolean cacheDisabled
) {
TableRenderer renderer;
if (annotated.isEmpty()) {
renderer = toResultByUnAnnotated(type, unAnnotated);
} else {
renderer = toResultByAnnotated(type, annotated, cacheDisabled);
}
return cache(type, renderer);
}
private TableRenderer toResultByAnnotated(
Class type, Map<String, Attribute> annotated, boolean cacheDisabled
) {
return ParserUtil.mapAttrs(type, annotated, config -> {
Attribute attr = config.getAttribute();
Class targetClass = attr.getPropertyType();
if (attr.isAnnotatedGroup()) {
Class cls = attr.getTableColumnGroup().targetClass();
TableRenderer renderer = doParseConfiguration(cls == Void.class ? targetClass : cls, cacheDisabled);
return new TableColGroup(config, renderer);
}
// TableColumnImage isImage = attr.getAnnotation(TableColumnImage.class);
// if (isImage != null) {
// Workbook.PICTURE_TYPE_DIB
// }
DefaultNumber atNumber = attr.getAnnotation(DefaultNumber.class);
if (atNumber != null && Assert.isNumberType(targetClass)) {
return TableDft.of(config, atNumber);
}
DefaultValue defaultVal = attr.getAnnotation(DefaultValue.class);
if (defaultVal != null) {
return TableDft.of(config, defaultVal);
}
return new TableCol(config);
});
}
private static TableRenderer toResultByUnAnnotated(Class type, Map<String, Attribute> unAnnotated) {
return ParserUtil.mapAttrsIfUnAnnotated(type, unAnnotated, TableCol::new);
}
private void parseDescriptors(Class type, Map annotated, Map unAnnotated) throws IntrospectionException {
Creator creator = getCreator();
BeanInfo beanInfo = Introspector.getBeanInfo(type, Object.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
Method method = creator.getMethod(descriptor);
if (method == null) {
continue;
}
Marked marked = Marked.of(descriptor, method);
ParserUtil.putMarked(marked, annotated, unAnnotated);
}
}
private static void parseFields(Class type, Map annotated, Map unAnnotated) {
while (type != null && type != Object.class) {
Field[] fields = type.getDeclaredFields();
for (Field field : fields) {
ParserUtil.putMarked(Marked.of(field), annotated, unAnnotated);
}
type = type.getSuperclass();
}
}
}
| UTF-8 | Java | 5,306 | java | Parser.java | Java | [
{
"context": "Map;\nimport java.util.WeakHashMap;\n\n/**\n * @author moonsky\n */\nfinal class Parser<T extends Marked> {\n\n p",
"end": 508,
"score": 0.9995366334915161,
"start": 501,
"tag": "USERNAME",
"value": "moonsky"
}
]
| null | []
| package com.moon.poi.excel.table;
import com.moon.poi.excel.annotation.value.DefaultNumber;
import com.moon.poi.excel.annotation.value.DefaultValue;
import org.apache.poi.ss.usermodel.Workbook;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* @author moonsky
*/
final class Parser<T extends Marked> {
private final Creator creator;
private final static Map<Class, TableRenderer> parsed = new WeakHashMap<>();
final static synchronized TableRenderer cache(Class type, TableRenderer renderer) {
parsed.putIfAbsent(type, renderer);
return renderer;
}
private final static TableRenderer getCached(Class type) { return parsed.get(type); }
Parser(Creator creator) { this.creator = creator; }
protected Creator getCreator() { return creator; }
// protected TableRenderer doParseConfiguration(Class type) {
// return doParseConfiguration(type, false);
// }
protected TableRenderer doParseConfiguration(Class type, boolean cacheDisabled) {
if (!cacheDisabled) {
TableRenderer renderer = getCached(type);
if (renderer != null) {
return renderer;
}
}
try {
Map<String, T> annotatedAtM = new LinkedHashMap<>();
Map<String, T> unAnnotatedAtM = new LinkedHashMap<>();
Map<String, T> annotatedAtF = new LinkedHashMap<>();
Map<String, T> unAnnotatedAtF = new LinkedHashMap<>();
parseDescriptors(type, annotatedAtM, unAnnotatedAtM);
parseFields(type, annotatedAtF, unAnnotatedAtF);
Map<String, Attribute> annotated = ParserUtil.merge2Attr(annotatedAtM,
annotatedAtF,
unAnnotatedAtM,
unAnnotatedAtF);
Map<String, Attribute> unAnnotated = ParserUtil.merge2Attr(unAnnotatedAtM, unAnnotatedAtF);
return toRendererResultAndCache(type, annotated, unAnnotated, cacheDisabled);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private TableRenderer toRendererResultAndCache(
Class type, Map<String, Attribute> annotated, Map<String, Attribute> unAnnotated, boolean cacheDisabled
) {
TableRenderer renderer;
if (annotated.isEmpty()) {
renderer = toResultByUnAnnotated(type, unAnnotated);
} else {
renderer = toResultByAnnotated(type, annotated, cacheDisabled);
}
return cache(type, renderer);
}
private TableRenderer toResultByAnnotated(
Class type, Map<String, Attribute> annotated, boolean cacheDisabled
) {
return ParserUtil.mapAttrs(type, annotated, config -> {
Attribute attr = config.getAttribute();
Class targetClass = attr.getPropertyType();
if (attr.isAnnotatedGroup()) {
Class cls = attr.getTableColumnGroup().targetClass();
TableRenderer renderer = doParseConfiguration(cls == Void.class ? targetClass : cls, cacheDisabled);
return new TableColGroup(config, renderer);
}
// TableColumnImage isImage = attr.getAnnotation(TableColumnImage.class);
// if (isImage != null) {
// Workbook.PICTURE_TYPE_DIB
// }
DefaultNumber atNumber = attr.getAnnotation(DefaultNumber.class);
if (atNumber != null && Assert.isNumberType(targetClass)) {
return TableDft.of(config, atNumber);
}
DefaultValue defaultVal = attr.getAnnotation(DefaultValue.class);
if (defaultVal != null) {
return TableDft.of(config, defaultVal);
}
return new TableCol(config);
});
}
private static TableRenderer toResultByUnAnnotated(Class type, Map<String, Attribute> unAnnotated) {
return ParserUtil.mapAttrsIfUnAnnotated(type, unAnnotated, TableCol::new);
}
private void parseDescriptors(Class type, Map annotated, Map unAnnotated) throws IntrospectionException {
Creator creator = getCreator();
BeanInfo beanInfo = Introspector.getBeanInfo(type, Object.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
Method method = creator.getMethod(descriptor);
if (method == null) {
continue;
}
Marked marked = Marked.of(descriptor, method);
ParserUtil.putMarked(marked, annotated, unAnnotated);
}
}
private static void parseFields(Class type, Map annotated, Map unAnnotated) {
while (type != null && type != Object.class) {
Field[] fields = type.getDeclaredFields();
for (Field field : fields) {
ParserUtil.putMarked(Marked.of(field), annotated, unAnnotated);
}
type = type.getSuperclass();
}
}
}
| 5,306 | 0.638711 | 0.638334 | 144 | 35.847221 | 30.343477 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.798611 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.