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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7ecc71127d5850c82942052079529eb0c60a5567
| 32,607,391,751,375 |
729cecd15f257fbde46fa3acd483670b7399a516
|
/guava/src/main/java/zh/guava/cache/GuavaCache9.java
|
7762079e10c253d330469f8b55027d85cbc5bec1
|
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
ksfzhaohui/blog
|
https://github.com/ksfzhaohui/blog
|
dcb0f573741edc159c45bbce057863078ac70255
|
9d6994f2d66f760c3dda507f08fcf2b2046814b8
|
refs/heads/master
| 2023-06-21T15:14:38.733000 | 2023-06-18T13:26:26 | 2023-06-18T13:26:26 | 140,855,650 | 107 | 47 |
BSD-2-Clause
| false | 2022-12-16T00:37:19 | 2018-07-13T14:18:27 | 2022-11-24T09:28:17 | 2022-12-16T00:37:16 | 20,142 | 92 | 45 | 35 |
Java
| false | false |
package zh.guava.cache;
import java.util.concurrent.ExecutionException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* LoadingCache是Cache的子接口,相比较于Cache,当从LoadingCache中读取一个指定key的记录时,
* 如果该记录不存在,则LoadingCache可以自动执行加载数据到缓存的操作
*
* @author hui.zhao.cfs
*
*/
public class GuavaCache9 {
public static void main(String[] args) throws ExecutionException {
CacheLoader<String, String> loader = new CacheLoader<String, String>() {
public String load(String key) throws Exception {
Thread.sleep(1000); // 休眠1s,模拟加载数据
System.out.println(key + " is loaded from a cacheLoader!");
return key + "'s value";
}
};
LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder().maximumSize(3).build(loader);// 在构建时指定自动加载器
loadingCache.get("key1");
loadingCache.get("key2");
loadingCache.get("key3");
}
}
|
UTF-8
|
Java
| 1,071 |
java
|
GuavaCache9.java
|
Java
|
[
{
"context": "记录不存在,则LoadingCache可以自动执行加载数据到缓存的操作\n * \n * @author hui.zhao.cfs\n *\n */\npublic class GuavaCache9 {\n\n\tpu",
"end": 337,
"score": 0.666533887386322,
"start": 336,
"tag": "USERNAME",
"value": "h"
},
{
"context": "不存在,则LoadingCache可以自动执行加载数据到缓存的操作\n * \n * @author hui.zhao.cfs\n *\n */\npublic class GuavaCache9 {\n\n\tpubl",
"end": 339,
"score": 0.5351628661155701,
"start": 337,
"tag": "NAME",
"value": "ui"
},
{
"context": "在,则LoadingCache可以自动执行加载数据到缓存的操作\n * \n * @author hui.zhao.cfs\n *\n */\npublic class GuavaCache9 {\n\n\tpubli",
"end": 339,
"score": 0.6694698333740234,
"start": 339,
"tag": "USERNAME",
"value": ""
},
{
"context": ",则LoadingCache可以自动执行加载数据到缓存的操作\n * \n * @author hui.zhao.cfs\n *\n */\npublic class GuavaCache9 {\n\n\tpublic st",
"end": 344,
"score": 0.6098870038986206,
"start": 340,
"tag": "NAME",
"value": "zhao"
},
{
"context": "adingCache可以自动执行加载数据到缓存的操作\n * \n * @author hui.zhao.cfs\n *\n */\npublic class GuavaCache9 {\n\n\tpublic static",
"end": 348,
"score": 0.7634629011154175,
"start": 345,
"tag": "USERNAME",
"value": "cfs"
}
] | null |
[] |
package zh.guava.cache;
import java.util.concurrent.ExecutionException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* LoadingCache是Cache的子接口,相比较于Cache,当从LoadingCache中读取一个指定key的记录时,
* 如果该记录不存在,则LoadingCache可以自动执行加载数据到缓存的操作
*
* @author hui.zhao.cfs
*
*/
public class GuavaCache9 {
public static void main(String[] args) throws ExecutionException {
CacheLoader<String, String> loader = new CacheLoader<String, String>() {
public String load(String key) throws Exception {
Thread.sleep(1000); // 休眠1s,模拟加载数据
System.out.println(key + " is loaded from a cacheLoader!");
return key + "'s value";
}
};
LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder().maximumSize(3).build(loader);// 在构建时指定自动加载器
loadingCache.get("key1");
loadingCache.get("key2");
loadingCache.get("key3");
}
}
| 1,071 | 0.741658 | 0.730893 | 33 | 27.151516 | 27.846027 | 115 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.454545 | false | false |
7
|
1d08e1d233b70bcb978f2c9264159b8b22c33946
| 18,932,215,893,122 |
54bf327e6d95e269f2bd1aadf4279b7da389d9a2
|
/subciber-configuracion-entity/src/main/java/com/subciber/configuracion/entity/CnfAplicacion.java
|
4fe770fd5cd1b02b8848443cd7f2e69cc0631973
|
[] |
no_license
|
jodavivi/subciber-configuracion
|
https://github.com/jodavivi/subciber-configuracion
|
c0a80711c8e141af394ae66e7579ce90fd1f5ece
|
364dda7ea60de0740cf75f996c3c8272c7f45374
|
refs/heads/master
| 2022-12-06T08:01:01.654000 | 2020-03-03T06:21:42 | 2020-03-03T06:21:42 | 170,629,467 | 0 | 0 | null | false | 2022-11-24T04:25:09 | 2019-02-14T04:55:39 | 2020-03-03T06:21:52 | 2022-11-24T04:25:06 | 159 | 0 | 0 | 4 |
Java
| false | false |
/**
*
*/
package com.subciber.configuracion.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* @author josep
*
*/
@Entity
@Table( schema="\"Configuracion\"",name="\"Aplicacion\"")
public class CnfAplicacion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "seq_gen",schema="\"Configuracion\"", sequenceName = "\"Aplicacion_Id_seq\"", allocationSize = 1)
@GeneratedValue(generator = "seq_gen")
@Column(name="\"Id\"")
private Integer id;
@Column(name="\"EstadoId\"")
private Integer estadoId;
@Column(name="\"UsuarioCreador\"")
private String usuarioCreador;
@Column(name="\"FechaCreacion\"")
private LocalDateTime fechaCreacion;
@Column(name="\"TerminalCreacion\"")
private String terminalCreacion;
@Column(name="\"UsuarioModificador\"")
private String usuarioModificador;
@Column(name="\"FechaModificacion\"")
private LocalDateTime fechaModificacion;
@Column(name="\"TerminalModificador\"")
private String terminalModificador;
@Column(name="\"TransaccionId\"")
private String transaccionId;
@Column(name="\"Codigo\"")
private String codigo;
@Column(name="\"RazonSocial\"")
private String razonSocial;
@Column(name="\"NumeroIdentificacion\"")
private String numeroIdentificacion;
@Column(name="\"EmailNotificacion\"")
private String emailNotificacion;
@Column(name="\"Logo\"")
private String logo;
@Column(name="\"Url\"")
private String url;
@Column(name="\"Path\"")
private String path;
public CnfAplicacion() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getEstadoId() {
return estadoId;
}
public void setEstadoId(Integer estadoId) {
this.estadoId = estadoId;
}
public String getUsuarioCreador() {
return usuarioCreador;
}
public void setUsuarioCreador(String usuarioCreador) {
this.usuarioCreador = usuarioCreador;
}
public LocalDateTime getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(LocalDateTime fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getTerminalCreacion() {
return terminalCreacion;
}
public void setTerminalCreacion(String terminalCreacion) {
this.terminalCreacion = terminalCreacion;
}
public String getUsuarioModificador() {
return usuarioModificador;
}
public void setUsuarioModificador(String usuarioModificador) {
this.usuarioModificador = usuarioModificador;
}
public LocalDateTime getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(LocalDateTime fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getTerminalModificador() {
return terminalModificador;
}
public void setTerminalModificador(String terminalModificador) {
this.terminalModificador = terminalModificador;
}
public String getTransaccionId() {
return transaccionId;
}
public void setTransaccionId(String transaccionId) {
this.transaccionId = transaccionId;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getNumeroIdentificacion() {
return numeroIdentificacion;
}
public void setNumeroIdentificacion(String numeroIdentificacion) {
this.numeroIdentificacion = numeroIdentificacion;
}
public String getEmailNotificacion() {
return emailNotificacion;
}
public void setEmailNotificacion(String emailNotificacion) {
this.emailNotificacion = emailNotificacion;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
|
UTF-8
|
Java
| 4,446 |
java
|
CnfAplicacion.java
|
Java
|
[
{
"context": "import javax.persistence.Table;\r\n\r\n/**\r\n * @author josep\r\n *\r\n */\r\n@Entity\r\n@Table( schema=\"\\\"Configuracio",
"end": 367,
"score": 0.9996086955070496,
"start": 362,
"tag": "USERNAME",
"value": "josep"
}
] | null |
[] |
/**
*
*/
package com.subciber.configuracion.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* @author josep
*
*/
@Entity
@Table( schema="\"Configuracion\"",name="\"Aplicacion\"")
public class CnfAplicacion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "seq_gen",schema="\"Configuracion\"", sequenceName = "\"Aplicacion_Id_seq\"", allocationSize = 1)
@GeneratedValue(generator = "seq_gen")
@Column(name="\"Id\"")
private Integer id;
@Column(name="\"EstadoId\"")
private Integer estadoId;
@Column(name="\"UsuarioCreador\"")
private String usuarioCreador;
@Column(name="\"FechaCreacion\"")
private LocalDateTime fechaCreacion;
@Column(name="\"TerminalCreacion\"")
private String terminalCreacion;
@Column(name="\"UsuarioModificador\"")
private String usuarioModificador;
@Column(name="\"FechaModificacion\"")
private LocalDateTime fechaModificacion;
@Column(name="\"TerminalModificador\"")
private String terminalModificador;
@Column(name="\"TransaccionId\"")
private String transaccionId;
@Column(name="\"Codigo\"")
private String codigo;
@Column(name="\"RazonSocial\"")
private String razonSocial;
@Column(name="\"NumeroIdentificacion\"")
private String numeroIdentificacion;
@Column(name="\"EmailNotificacion\"")
private String emailNotificacion;
@Column(name="\"Logo\"")
private String logo;
@Column(name="\"Url\"")
private String url;
@Column(name="\"Path\"")
private String path;
public CnfAplicacion() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getEstadoId() {
return estadoId;
}
public void setEstadoId(Integer estadoId) {
this.estadoId = estadoId;
}
public String getUsuarioCreador() {
return usuarioCreador;
}
public void setUsuarioCreador(String usuarioCreador) {
this.usuarioCreador = usuarioCreador;
}
public LocalDateTime getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(LocalDateTime fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getTerminalCreacion() {
return terminalCreacion;
}
public void setTerminalCreacion(String terminalCreacion) {
this.terminalCreacion = terminalCreacion;
}
public String getUsuarioModificador() {
return usuarioModificador;
}
public void setUsuarioModificador(String usuarioModificador) {
this.usuarioModificador = usuarioModificador;
}
public LocalDateTime getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(LocalDateTime fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getTerminalModificador() {
return terminalModificador;
}
public void setTerminalModificador(String terminalModificador) {
this.terminalModificador = terminalModificador;
}
public String getTransaccionId() {
return transaccionId;
}
public void setTransaccionId(String transaccionId) {
this.transaccionId = transaccionId;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getNumeroIdentificacion() {
return numeroIdentificacion;
}
public void setNumeroIdentificacion(String numeroIdentificacion) {
this.numeroIdentificacion = numeroIdentificacion;
}
public String getEmailNotificacion() {
return emailNotificacion;
}
public void setEmailNotificacion(String emailNotificacion) {
this.emailNotificacion = emailNotificacion;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
| 4,446 | 0.708277 | 0.707827 | 208 | 19.375 | 20.155972 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.144231 | false | false |
7
|
5f5a811adb3fdffe4fb325af438b418bc839ec14
| 28,174,985,499,948 |
5e8516a09a2913a1848dacab69b265de99279cc9
|
/web/src/main/java/net/daergoth/homewire/BaseUI.java
|
a67c3de878de821202d3937d01c789e6efc47c6e
|
[
"Apache-2.0"
] |
permissive
|
daergoth/HomeWire-Server
|
https://github.com/daergoth/HomeWire-Server
|
a8de7b8316d748ef852934c2b75634bf5b9a93ba
|
0fd1896b899c8abb69db8c928f5a80a8e998cc96
|
refs/heads/master
| 2021-05-01T19:44:51.264000 | 2017-04-02T20:38:53 | 2017-04-02T20:38:53 | 70,842,802 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.daergoth.homewire;
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.annotation.SpringViewDisplay;
import com.vaadin.ui.Component;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import net.daergoth.homewire.controlpanel.ControlPanelView;
import net.daergoth.homewire.flow.FlowView;
import net.daergoth.homewire.home.HomeView;
import net.daergoth.homewire.setup.SetupView;
import net.daergoth.homewire.statistic.StatisticView;
import org.vaadin.teemusa.sidemenu.SideMenu;
import org.vaadin.teemusa.sidemenu.SideMenuUI;
@Theme("homewire")
@SpringUI
@SideMenuUI
@SpringViewDisplay
public class BaseUI extends UI implements ViewDisplay {
private VerticalLayout springViewDisplay;
@Override
protected void init(VaadinRequest request) {
SideMenu menu = new SideMenu();
menu.setMenuCaption("HomeWire");
menu.addMenuItem("Home", () -> {
getUI().getNavigator().navigateTo(HomeView.VIEW_NAME);
});
menu.addMenuItem("Control Panel", () -> {
getUI().getNavigator().navigateTo(ControlPanelView.VIEW_NAME);
});
menu.addMenuItem("Flows", () -> {
getUI().getNavigator().navigateTo(FlowView.VIEW_NAME);
});
menu.addMenuItem("Statistics", () -> {
getUI().getNavigator().navigateTo(StatisticView.VIEW_NAME);
});
menu.addMenuItem("Setup", () -> {
getUI().getNavigator().navigateTo(SetupView.VIEW_NAME);
});
setContent(menu);
springViewDisplay = new VerticalLayout();
springViewDisplay.setSizeFull();
springViewDisplay.setMargin(true);
springViewDisplay.setSpacing(true);
menu.setContent(springViewDisplay);
}
@Override
public void showView(View view) {
springViewDisplay.removeAllComponents();
springViewDisplay.addComponent((Component) view);
}
}
|
UTF-8
|
Java
| 1,960 |
java
|
BaseUI.java
|
Java
|
[] | null |
[] |
package net.daergoth.homewire;
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.annotation.SpringViewDisplay;
import com.vaadin.ui.Component;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import net.daergoth.homewire.controlpanel.ControlPanelView;
import net.daergoth.homewire.flow.FlowView;
import net.daergoth.homewire.home.HomeView;
import net.daergoth.homewire.setup.SetupView;
import net.daergoth.homewire.statistic.StatisticView;
import org.vaadin.teemusa.sidemenu.SideMenu;
import org.vaadin.teemusa.sidemenu.SideMenuUI;
@Theme("homewire")
@SpringUI
@SideMenuUI
@SpringViewDisplay
public class BaseUI extends UI implements ViewDisplay {
private VerticalLayout springViewDisplay;
@Override
protected void init(VaadinRequest request) {
SideMenu menu = new SideMenu();
menu.setMenuCaption("HomeWire");
menu.addMenuItem("Home", () -> {
getUI().getNavigator().navigateTo(HomeView.VIEW_NAME);
});
menu.addMenuItem("Control Panel", () -> {
getUI().getNavigator().navigateTo(ControlPanelView.VIEW_NAME);
});
menu.addMenuItem("Flows", () -> {
getUI().getNavigator().navigateTo(FlowView.VIEW_NAME);
});
menu.addMenuItem("Statistics", () -> {
getUI().getNavigator().navigateTo(StatisticView.VIEW_NAME);
});
menu.addMenuItem("Setup", () -> {
getUI().getNavigator().navigateTo(SetupView.VIEW_NAME);
});
setContent(menu);
springViewDisplay = new VerticalLayout();
springViewDisplay.setSizeFull();
springViewDisplay.setMargin(true);
springViewDisplay.setSpacing(true);
menu.setContent(springViewDisplay);
}
@Override
public void showView(View view) {
springViewDisplay.removeAllComponents();
springViewDisplay.addComponent((Component) view);
}
}
| 1,960 | 0.742347 | 0.742347 | 64 | 29.640625 | 20.423155 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671875 | false | false |
7
|
344eb5ab80350ed52ace56e4f79344c9ec4b3e73
| 13,984,413,578,314 |
9e3aa1603c8ad767b65aa8804c2f019017b94d9d
|
/ppl/src/main/java/com/jm/ppl/actor/service/ActorService.java
|
20da6644027b831062d297664776d5598aded681
|
[] |
no_license
|
linaling/SulAndLina
|
https://github.com/linaling/SulAndLina
|
87358b04e04a20124fae8d6b505d88ee42f57fd4
|
7a6fc0c0e2a093e98e1284bbb4b581067e9023d7
|
refs/heads/master
| 2019-07-26T00:27:40.139000 | 2017-03-27T07:46:05 | 2017-03-27T07:46:05 | 85,766,251 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jm.ppl.actor.service;
public interface ActorService {
}
|
UTF-8
|
Java
| 70 |
java
|
ActorService.java
|
Java
|
[] | null |
[] |
package com.jm.ppl.actor.service;
public interface ActorService {
}
| 70 | 0.771429 | 0.771429 | 5 | 13 | 15.530615 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
7
|
4e940bab24334c6a6d901046d2e6c18dffacabc9
| 19,894,288,538,013 |
0d48af5cb8012a79b3327a1d3e7ff0e65af54ea8
|
/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/TestComponentVersionInvariants.java
|
d5524688a64f3a3674e9c0e2f1503390baab56f7
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown"
] |
permissive
|
apache/ozone
|
https://github.com/apache/ozone
|
4426dd1ae18716d0585f1e846f7881970e3c4279
|
a3b89e73185894f905b4ad96cd6d78429497d0c9
|
refs/heads/master
| 2023-09-04T05:26:08.656000 | 2023-09-02T15:16:12 | 2023-09-02T15:16:12 | 212,382,406 | 509 | 386 |
Apache-2.0
| false | 2023-09-14T19:54:21 | 2019-10-02T15:56:19 | 2023-09-07T07:28:25 | 2023-09-14T19:54:20 | 70,251 | 685 | 437 | 88 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdds;
import org.apache.hadoop.ozone.ClientVersion;
import org.apache.hadoop.ozone.OzoneManagerVersion;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.arguments;
/**
* Test to ensure Component version instances conform with invariants relied
* upon in other parts of the codebase.
*/
public class TestComponentVersionInvariants {
public static Stream<Arguments> values() {
return Stream.of(
arguments(
DatanodeVersion.values(),
DatanodeVersion.DEFAULT_VERSION,
DatanodeVersion.FUTURE_VERSION),
arguments(
ClientVersion.values(),
ClientVersion.DEFAULT_VERSION,
ClientVersion.FUTURE_VERSION),
arguments(
OzoneManagerVersion.values(),
OzoneManagerVersion.DEFAULT_VERSION,
OzoneManagerVersion.FUTURE_VERSION)
);
}
// FUTURE_VERSION is the latest
@ParameterizedTest
@MethodSource("values")
public void testFutureVersionHasTheHighestOrdinal(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(values[values.length - 1], futureValue);
}
// FUTURE_VERSION's internal version id is -1
@ParameterizedTest
@MethodSource("values")
public void testFuturVersionHasMinusOneAsProtoRepresentation(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(-1, futureValue.toProtoValue());
}
// DEFAULT_VERSION's internal version id is 0
@ParameterizedTest
@MethodSource("values")
public void testDefaultVersionHasZeroAsProtoRepresentation(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(0, defaultValue.toProtoValue());
}
// versions are increasing monotonically by one
@ParameterizedTest
@MethodSource("values")
public void testAssignedProtoRepresentations(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
int startValue = defaultValue.toProtoValue();
// we skip the future version at the last position
for (int i = 0; i < values.length - 1; i++) {
assertEquals(values[i].toProtoValue(), startValue++);
}
assertEquals(values.length, ++startValue);
}
}
|
UTF-8
|
Java
| 3,413 |
java
|
TestComponentVersionInvariants.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdds;
import org.apache.hadoop.ozone.ClientVersion;
import org.apache.hadoop.ozone.OzoneManagerVersion;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.arguments;
/**
* Test to ensure Component version instances conform with invariants relied
* upon in other parts of the codebase.
*/
public class TestComponentVersionInvariants {
public static Stream<Arguments> values() {
return Stream.of(
arguments(
DatanodeVersion.values(),
DatanodeVersion.DEFAULT_VERSION,
DatanodeVersion.FUTURE_VERSION),
arguments(
ClientVersion.values(),
ClientVersion.DEFAULT_VERSION,
ClientVersion.FUTURE_VERSION),
arguments(
OzoneManagerVersion.values(),
OzoneManagerVersion.DEFAULT_VERSION,
OzoneManagerVersion.FUTURE_VERSION)
);
}
// FUTURE_VERSION is the latest
@ParameterizedTest
@MethodSource("values")
public void testFutureVersionHasTheHighestOrdinal(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(values[values.length - 1], futureValue);
}
// FUTURE_VERSION's internal version id is -1
@ParameterizedTest
@MethodSource("values")
public void testFuturVersionHasMinusOneAsProtoRepresentation(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(-1, futureValue.toProtoValue());
}
// DEFAULT_VERSION's internal version id is 0
@ParameterizedTest
@MethodSource("values")
public void testDefaultVersionHasZeroAsProtoRepresentation(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
assertEquals(0, defaultValue.toProtoValue());
}
// versions are increasing monotonically by one
@ParameterizedTest
@MethodSource("values")
public void testAssignedProtoRepresentations(
ComponentVersion[] values, ComponentVersion defaultValue,
ComponentVersion futureValue) {
int startValue = defaultValue.toProtoValue();
// we skip the future version at the last position
for (int i = 0; i < values.length - 1; i++) {
assertEquals(values[i].toProtoValue(), startValue++);
}
assertEquals(values.length, ++startValue);
}
}
| 3,413 | 0.735716 | 0.732493 | 96 | 34.552082 | 23.370596 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
7
|
515156390d0f71ad1bcd009ae2409ffcc26cbc00
| 28,810,640,665,772 |
7be91274d20aa36fe5071b530c7a5200c7528f66
|
/app/src/main/java/com/littleheap/webcoursedesign/ui/InfoAdd.java
|
1eacbefd47e4846938032119a59ccd567862e0c8
|
[] |
no_license
|
littleheap/ContactAPP
|
https://github.com/littleheap/ContactAPP
|
88254bd6eab865d57a8095b8c54dd888bdeea226
|
0b1e3e55989c49d8cfa5652170be0025f96412a4
|
refs/heads/master
| 2022-09-27T02:03:59.352000 | 2018-01-18T10:14:51 | 2018-01-18T10:14:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.littleheap.webcoursedesign.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.littleheap.webcoursedesign.MainActivity;
import com.littleheap.webcoursedesign.R;
import com.littleheap.webcoursedesign.fragment.ContactFragment;
import com.littleheap.webcoursedesign.utils.DataBase;
import com.littleheap.webcoursedesign.utils.MyDatabaseHelper;
import com.littleheap.webcoursedesign.utils.ShareUtils;
import com.littleheap.webcoursedesign.utils.StaticClass;
public class InfoAdd extends AppCompatActivity implements View.OnClickListener {
private EditText add_person, add_number;
private Button btn_add;
//数据库操作
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_add);
initView();
}
private void initView() {
//获取数据库操作
dbHelper = MainActivity.dbHelper;
//新联系人姓名
add_person = (EditText) findViewById(R.id.add_person);
//新联系人号码
add_number = (EditText) findViewById(R.id.add_number);
//添加按钮
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_add://添加按钮
//将新联系人数据插入后台数据库
DataBase.insertDataBase(dbHelper, "Contact_" + ShareUtils.getString(this, "user", ""), add_person.getText().toString(), add_number.getText().toString());
//更新联系人数据字符串
StaticClass.CONTACT = DataBase.selectDataBase(dbHelper, "Contact_" + ShareUtils.getString(this, "user", ""));
//更新通讯录UI
ContactFragment.updateList();
Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show();
finish();
break;
}
}
}
|
UTF-8
|
Java
| 2,140 |
java
|
InfoAdd.java
|
Java
|
[] | null |
[] |
package com.littleheap.webcoursedesign.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.littleheap.webcoursedesign.MainActivity;
import com.littleheap.webcoursedesign.R;
import com.littleheap.webcoursedesign.fragment.ContactFragment;
import com.littleheap.webcoursedesign.utils.DataBase;
import com.littleheap.webcoursedesign.utils.MyDatabaseHelper;
import com.littleheap.webcoursedesign.utils.ShareUtils;
import com.littleheap.webcoursedesign.utils.StaticClass;
public class InfoAdd extends AppCompatActivity implements View.OnClickListener {
private EditText add_person, add_number;
private Button btn_add;
//数据库操作
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_add);
initView();
}
private void initView() {
//获取数据库操作
dbHelper = MainActivity.dbHelper;
//新联系人姓名
add_person = (EditText) findViewById(R.id.add_person);
//新联系人号码
add_number = (EditText) findViewById(R.id.add_number);
//添加按钮
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_add://添加按钮
//将新联系人数据插入后台数据库
DataBase.insertDataBase(dbHelper, "Contact_" + ShareUtils.getString(this, "user", ""), add_person.getText().toString(), add_number.getText().toString());
//更新联系人数据字符串
StaticClass.CONTACT = DataBase.selectDataBase(dbHelper, "Contact_" + ShareUtils.getString(this, "user", ""));
//更新通讯录UI
ContactFragment.updateList();
Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show();
finish();
break;
}
}
}
| 2,140 | 0.666501 | 0.666006 | 58 | 33.793102 | 30.440308 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false |
7
|
e9744629b324ae60c40e11be65b9620a442fdb50
| 31,525,059,985,808 |
c9cfc6279726394475f59800259f194d349ea8da
|
/src/com/scholastic/sbam/client/services/TerminateExportService.java
|
2904fe4cf29482a47418e3938d235e56326b0302
|
[] |
no_license
|
VijayEluri/SBAM-Dev
|
https://github.com/VijayEluri/SBAM-Dev
|
ce15f813da784fa764c42f8711bc565be6251580
|
1ba017f990e633112d2bbc94e20ac190f799dee4
|
refs/heads/master
| 2020-05-20T11:15:01.750000 | 2012-02-25T03:19:55 | 2012-02-25T03:19:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.scholastic.sbam.client.services;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.scholastic.sbam.shared.objects.ExportProcessReport;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("terminateExport")
public interface TerminateExportService extends RemoteService {
ExportProcessReport terminateExport(String terminationReason) throws IllegalArgumentException;
}
|
UTF-8
|
Java
| 489 |
java
|
TerminateExportService.java
|
Java
|
[] | null |
[] |
package com.scholastic.sbam.client.services;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.scholastic.sbam.shared.objects.ExportProcessReport;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("terminateExport")
public interface TerminateExportService extends RemoteService {
ExportProcessReport terminateExport(String terminationReason) throws IllegalArgumentException;
}
| 489 | 0.838446 | 0.838446 | 13 | 36.615383 | 30.540108 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
7
|
6b240bf5bdace0319cd4df131cebcf6aeb47284f
| 28,509,992,952,232 |
3a8da79d29a7a9603063e4a1b1394081f08df8ad
|
/src/fal/contract/Contract.java
|
d57dc9be49c6c874094975aea0bae618f5764eb7
|
[] |
no_license
|
Falynsky/prezentacjaGitFlow
|
https://github.com/Falynsky/prezentacjaGitFlow
|
3ba052631c532bb3358c465878c24440551c3d33
|
e13468cd58ba5dbeeae4081a16dd2231c836c080
|
refs/heads/master
| 2021-02-07T17:12:41.452000 | 2020-02-29T23:07:03 | 2020-02-29T23:07:03 | 244,055,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fal.contract;
public class Contract {
private String idn;
private ContractType contractType;
private Job jobType;
private double salary;
public Contract(String idn, ContractType contractType, Job jobType, double salary) {
this.idn = idn;
this.contractType = contractType;
this.jobType = jobType;
this.salary = salary;
}
public String getIdn() {
return idn;
}
public void setIdn(String idn) {
this.idn = idn;
}
public ContractType getContractType() {
return contractType;
}
public void setContractType(ContractType contractType) {
this.contractType = contractType;
}
public Job getJobType() {
return jobType;
}
public void setJobType(Job jobType) {
this.jobType = jobType;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Contract{" +
"idn='" + idn + '\'' +
", contractType=" + contractType +
", jobType=" + jobType +
", salary=" + salary +
'}';
}
}
|
UTF-8
|
Java
| 1,259 |
java
|
Contract.java
|
Java
|
[] | null |
[] |
package fal.contract;
public class Contract {
private String idn;
private ContractType contractType;
private Job jobType;
private double salary;
public Contract(String idn, ContractType contractType, Job jobType, double salary) {
this.idn = idn;
this.contractType = contractType;
this.jobType = jobType;
this.salary = salary;
}
public String getIdn() {
return idn;
}
public void setIdn(String idn) {
this.idn = idn;
}
public ContractType getContractType() {
return contractType;
}
public void setContractType(ContractType contractType) {
this.contractType = contractType;
}
public Job getJobType() {
return jobType;
}
public void setJobType(Job jobType) {
this.jobType = jobType;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Contract{" +
"idn='" + idn + '\'' +
", contractType=" + contractType +
", jobType=" + jobType +
", salary=" + salary +
'}';
}
}
| 1,259 | 0.563145 | 0.563145 | 58 | 20.706896 | 18.345354 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413793 | false | false |
7
|
bece84af59adce0bcc5988ed5643a5e320e26e79
| 29,807,073,061,352 |
b894e7feec5ef4711e9d5f00bffc3effc1294143
|
/src/by/it/makarenko/jd01_05/TaskA.java
|
a48f049b8c2cb894b11371a74a8aba2721ff0492
|
[] |
no_license
|
Vladislav7776/JD2020-01-20
|
https://github.com/Vladislav7776/JD2020-01-20
|
877e311bfa2be42152424f5f4963deb1b718e7e3
|
2f977ee26b79a97fa37bd1053756c91f344c5757
|
refs/heads/master
| 2020-12-22T21:37:24.187000 | 2020-03-12T20:22:51 | 2020-03-12T20:22:51 | 236,938,743 | 6 | 0 | null | true | 2020-01-29T08:46:59 | 2020-01-29T08:46:58 | 2020-01-28T20:24:12 | 2020-01-28T20:24:10 | 326 | 0 | 0 | 0 | null | false | false |
package by.it.makarenko.jd01_05;
public class TaskA {
public static void main(String[] args) {
TaskA2();
TaskA3();
double a = 756.13;
double x = 0.3;
double z = Math.cos(Math.pow(x*x+Math.PI/6,5))-Math.sqrt(x*Math.pow(a,3)) - Math.log((a-1.12*x)/4);
System.out.println(z);
}
static void TaskA2(){
double a = 1.21;
double b = 0.371;
double y = Math.tan(Math.pow(a+b,2)) - Math.cbrt(a+1.5) + a*Math.pow(b,5)- b/Math.log(Math.pow(a,2));
System.out.println(y);
}
static void TaskA3(){
double x =12.1;
for (double a = -5; a <12 ; a = a+3.75) {
double f = Math.pow(Math.E,a*x) - 3.45*a;
System.out.println("При a= "+a+ " " +"f= "+f);
}
}
}
|
UTF-8
|
Java
| 791 |
java
|
TaskA.java
|
Java
|
[] | null |
[] |
package by.it.makarenko.jd01_05;
public class TaskA {
public static void main(String[] args) {
TaskA2();
TaskA3();
double a = 756.13;
double x = 0.3;
double z = Math.cos(Math.pow(x*x+Math.PI/6,5))-Math.sqrt(x*Math.pow(a,3)) - Math.log((a-1.12*x)/4);
System.out.println(z);
}
static void TaskA2(){
double a = 1.21;
double b = 0.371;
double y = Math.tan(Math.pow(a+b,2)) - Math.cbrt(a+1.5) + a*Math.pow(b,5)- b/Math.log(Math.pow(a,2));
System.out.println(y);
}
static void TaskA3(){
double x =12.1;
for (double a = -5; a <12 ; a = a+3.75) {
double f = Math.pow(Math.E,a*x) - 3.45*a;
System.out.println("При a= "+a+ " " +"f= "+f);
}
}
}
| 791 | 0.498731 | 0.440355 | 26 | 29.307692 | 27.492334 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false |
7
|
5037cf18370fbcaf500edd3cff998c67ebd71c36
| 6,897,717,493,681 |
29f0e48c96ccf1b8b1d2bddc22b24a209acbb9f0
|
/src/com/snake/common/Constant.java
|
69983d0d7440272072bbacb1612ab4d1807aa7c4
|
[] |
no_license
|
zongjunhao/SnakeServer
|
https://github.com/zongjunhao/SnakeServer
|
01cc0220c894a1526c8a262a9fba38c3ba9dbbc1
|
cc2818254b76efa084bb1bdf5be4f8e9d199af26
|
refs/heads/master
| 2020-09-13T03:54:24.845000 | 2019-11-19T08:41:54 | 2019-11-19T08:41:54 | 222,648,636 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.snake.common;
public class Constant {
public static String idAddress = "10.174.41.107";
//用于区分信息显示区域
public final static int GAME_VIEW_MARGIN = 1;
public final static int SNAKE_LEN = 2;
public final static int SNAKE_RANK = 3;
public final static int PLAYER_ALIVE = 4;
//用于标志玩家是否存活
public static int playerAlive = 1;
//屏幕的长和宽,初始设为0,将在应用初始化时进行重新设置
public static int screenWidth = 1920;
public static int screenHeight = 1080;
//游戏的可视范围
public static int viewWidth = 3840;
public static int viewHeight = 2160;
//游戏边框宽度
public static int nullWidth = 100;
//网格线间距
public static int gridWidth = 25;
//按钮边界
public static int buttonMargin = 54;
//蛇的每节身体的直径
public static int snake_d = 54;
//蛇前进的长度
public static int snake_len = 25;
//AI的数量
public static int snake_num = 30;
//食物的数量
public static int food_num = 200;
//蛇一节身体所代表的分数
public static int snake_score = 75;
}
|
UTF-8
|
Java
| 1,200 |
java
|
Constant.java
|
Java
|
[
{
"context": " Constant {\n public static String idAddress = \"10.174.41.107\";\n\n //用于区分信息显示区域\n public final static int G",
"end": 102,
"score": 0.9997373819351196,
"start": 89,
"tag": "IP_ADDRESS",
"value": "10.174.41.107"
}
] | null |
[] |
package com.snake.common;
public class Constant {
public static String idAddress = "10.174.41.107";
//用于区分信息显示区域
public final static int GAME_VIEW_MARGIN = 1;
public final static int SNAKE_LEN = 2;
public final static int SNAKE_RANK = 3;
public final static int PLAYER_ALIVE = 4;
//用于标志玩家是否存活
public static int playerAlive = 1;
//屏幕的长和宽,初始设为0,将在应用初始化时进行重新设置
public static int screenWidth = 1920;
public static int screenHeight = 1080;
//游戏的可视范围
public static int viewWidth = 3840;
public static int viewHeight = 2160;
//游戏边框宽度
public static int nullWidth = 100;
//网格线间距
public static int gridWidth = 25;
//按钮边界
public static int buttonMargin = 54;
//蛇的每节身体的直径
public static int snake_d = 54;
//蛇前进的长度
public static int snake_len = 25;
//AI的数量
public static int snake_num = 30;
//食物的数量
public static int food_num = 200;
//蛇一节身体所代表的分数
public static int snake_score = 75;
}
| 1,200 | 0.660643 | 0.610442 | 38 | 25.210526 | 16.353268 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
7
|
54b66546b3d86ebbfae5293d6102eee1483c73d7
| 11,312,943,924,895 |
c5159298809ed14b8a6be14a727705089493c1dd
|
/src/test/java/com/google/enterprise/secmgr/http/SlowHostTrackerTest.java
|
b8d784dc15460894dd44e0ba13d0d21680a0e60a
|
[
"Apache-2.0"
] |
permissive
|
googlegsa/secmgr
|
https://github.com/googlegsa/secmgr
|
42966000b1558a54fdeade28ec4d54f1e1700536
|
2bddd2a8564973a4bf14e99e950d58a692159765
|
refs/heads/master
| 2023-09-03T19:42:47.389000 | 2019-07-26T01:24:52 | 2019-07-26T01:24:52 | 133,093,317 | 2 | 3 |
Apache-2.0
| false | 2023-08-18T17:08:31 | 2018-05-11T22:13:05 | 2023-05-21T15:42:29 | 2023-08-18T17:08:27 | 1,813 | 2 | 7 | 10 |
Java
| false | false |
// Copyright 2018 Google Inc.
//
// 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.enterprise.secmgr.http;
import com.google.common.base.Ticker;
import com.google.enterprise.secmgr.config.ConfigParams;
import com.google.enterprise.secmgr.config.ParamName;
import com.google.enterprise.secmgr.http.SlowHostTracker.UnresponsiveHostException;
import com.google.enterprise.secmgr.mock.MockHttpClient;
import com.google.enterprise.secmgr.mock.MockHttpServer;
import com.google.enterprise.secmgr.mock.MockHttpTransport;
import com.google.enterprise.secmgr.mock.MockSlowServer;
import com.google.enterprise.secmgr.testing.SecurityManagerTestCase;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URL;
import javax.servlet.ServletException;
/**
* Tests for the {@link SlowHostTracker} class.
*
*/
public class SlowHostTrackerTest extends SecurityManagerTestCase {
private static final String GOOD_HOST = "goodHost";
private static final String GOOD_URL = "http://goodHost/good";
private static final String SLOW_HOST = "slowHost";
private static final String SLOW_URL = "http://slowHost/slow";
private final TestTicker ticker;
private final SlowHostTracker tracker;
private final HttpRequester requester;
public SlowHostTrackerTest()
throws ServletException {
ticker = new TestTicker();
tracker = SlowHostTracker.getInstanceForTesting(ticker);
MockHttpTransport transport = new MockHttpTransport();
transport.registerServlet(GOOD_URL, new MockHttpServer());
transport.registerServlet(SLOW_URL, new MockSlowServer());
HttpClientUtil.setHttpClient(new MockHttpClient(transport));
requester = HttpRequester.builder()
.setPageFetcher(PageFetcher.getInstanceForTesting(tracker))
.build();
}
@Override
public void setUp()
throws Exception {
super.setUp();
ticker.reset();
updateConfigParams(
new ConfigParamsUpdater() {
@Override
public void apply(ConfigParams.Builder builder) {
builder.put(ParamName.SLOW_HOST_TRACKER_ENABLED, true);
}
});
}
/**
* A simple ticker that we can manipulate.
*/
private static final class TestTicker extends Ticker {
long value;
void reset() {
value = Ticker.systemTicker().read();
}
void advance(long n) {
value += n * 1000000000;
}
@Override
public long read() {
return value;
}
}
// Test that a normal fetch works without generating a time-out record.
public void testFetchSuccess()
throws IOException {
assertEquals(0, tracker.getNumberOfTimeouts(GOOD_HOST));
requester.runExchange(new URL(GOOD_URL), null);
assertEquals(0, tracker.getNumberOfTimeouts(GOOD_HOST));
}
// Confirm that a time-out is properly recorded.
public void testFetchTimeout() {
assertEquals(0, tracker.getNumberOfTimeouts(SLOW_HOST));
slowFetch(requester);
assertEquals(1, tracker.getNumberOfTimeouts(SLOW_HOST));
}
// Confirm that the number of time-outs increases up to the limit but does not
// exceed it.
public void testFetchSlowHost() {
tracker.markAsUnresponsive(SLOW_HOST);
try {
requester.runExchange(new URL(SLOW_URL), null);
fail("Timeout exception should have been thrown");
} catch (UnresponsiveHostException e) {
// expected.
} catch (IOException e) {
e.printStackTrace();
fail("I/O exception was thrown: " + e.getMessage());
}
}
public void testNumberOfTimeouts() {
tryNumberOfTimeouts(5);
tryNumberOfTimeouts(10);
tryNumberOfTimeouts(20);
tryNumberOfTimeouts(50);
tryNumberOfTimeouts(100);
tryNumberOfTimeouts(200);
tryNumberOfTimeouts(500);
tryNumberOfTimeouts(1000);
tryNumberOfTimeouts(2000);
tryNumberOfTimeouts(5000);
}
private void tryNumberOfTimeouts(int numberOfTimeouts) {
setNumberOfTimeouts(numberOfTimeouts);
double increment = (double) numberOfTimeouts / (double) getConfig().getSlowHostSamplePeriod();
double sum = 0;
int n = 0;
while (!tracker.isUnresponsive(SLOW_HOST)) {
sum += increment;
while (n <= (sum - 1)) {
tracker.recordHostTimeout(SLOW_HOST);
n += 1;
}
ticker.advance(1);
}
assertTrue("number of timeouts too small; limit: " + numberOfTimeouts + ", actual: " + n,
n >= numberOfTimeouts);
double upperLimit = numberOfTimeouts * 1.01d;
assertTrue("number of timeouts too large; limit: " + upperLimit + ", actual: " + n,
n <= upperLimit);
}
private void setNumberOfTimeouts(final int numberOfTimeouts) {
updateConfigParams(
new ConfigParamsUpdater() {
@Override
public void apply(ConfigParams.Builder builder) {
builder.put(ParamName.SLOW_HOST_NUMBER_OF_TIMEOUTS, numberOfTimeouts);
}
});
}
public void testEmbargoPeriod() {
tracker.markAsUnresponsive(SLOW_HOST);
int i = 1;
while (tracker.isUnresponsive(SLOW_HOST)) {
ticker.advance(1);
i += 1;
}
assertEquals(getConfig().getSlowHostEmbargoPeriod(), i);
}
// Do a fetch that times out.
private static void slowFetch(HttpRequester requester) {
try {
requester.runExchange(new URL(SLOW_URL), null);
fail("Timeout exception should have been thrown");
} catch (InterruptedIOException e) {
// expected.
} catch (IOException e) {
e.printStackTrace();
fail("I/O exception was thrown: " + e.getMessage());
}
}
}
|
UTF-8
|
Java
| 6,076 |
java
|
SlowHostTrackerTest.java
|
Java
|
[] | null |
[] |
// Copyright 2018 Google Inc.
//
// 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.enterprise.secmgr.http;
import com.google.common.base.Ticker;
import com.google.enterprise.secmgr.config.ConfigParams;
import com.google.enterprise.secmgr.config.ParamName;
import com.google.enterprise.secmgr.http.SlowHostTracker.UnresponsiveHostException;
import com.google.enterprise.secmgr.mock.MockHttpClient;
import com.google.enterprise.secmgr.mock.MockHttpServer;
import com.google.enterprise.secmgr.mock.MockHttpTransport;
import com.google.enterprise.secmgr.mock.MockSlowServer;
import com.google.enterprise.secmgr.testing.SecurityManagerTestCase;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URL;
import javax.servlet.ServletException;
/**
* Tests for the {@link SlowHostTracker} class.
*
*/
public class SlowHostTrackerTest extends SecurityManagerTestCase {
private static final String GOOD_HOST = "goodHost";
private static final String GOOD_URL = "http://goodHost/good";
private static final String SLOW_HOST = "slowHost";
private static final String SLOW_URL = "http://slowHost/slow";
private final TestTicker ticker;
private final SlowHostTracker tracker;
private final HttpRequester requester;
public SlowHostTrackerTest()
throws ServletException {
ticker = new TestTicker();
tracker = SlowHostTracker.getInstanceForTesting(ticker);
MockHttpTransport transport = new MockHttpTransport();
transport.registerServlet(GOOD_URL, new MockHttpServer());
transport.registerServlet(SLOW_URL, new MockSlowServer());
HttpClientUtil.setHttpClient(new MockHttpClient(transport));
requester = HttpRequester.builder()
.setPageFetcher(PageFetcher.getInstanceForTesting(tracker))
.build();
}
@Override
public void setUp()
throws Exception {
super.setUp();
ticker.reset();
updateConfigParams(
new ConfigParamsUpdater() {
@Override
public void apply(ConfigParams.Builder builder) {
builder.put(ParamName.SLOW_HOST_TRACKER_ENABLED, true);
}
});
}
/**
* A simple ticker that we can manipulate.
*/
private static final class TestTicker extends Ticker {
long value;
void reset() {
value = Ticker.systemTicker().read();
}
void advance(long n) {
value += n * 1000000000;
}
@Override
public long read() {
return value;
}
}
// Test that a normal fetch works without generating a time-out record.
public void testFetchSuccess()
throws IOException {
assertEquals(0, tracker.getNumberOfTimeouts(GOOD_HOST));
requester.runExchange(new URL(GOOD_URL), null);
assertEquals(0, tracker.getNumberOfTimeouts(GOOD_HOST));
}
// Confirm that a time-out is properly recorded.
public void testFetchTimeout() {
assertEquals(0, tracker.getNumberOfTimeouts(SLOW_HOST));
slowFetch(requester);
assertEquals(1, tracker.getNumberOfTimeouts(SLOW_HOST));
}
// Confirm that the number of time-outs increases up to the limit but does not
// exceed it.
public void testFetchSlowHost() {
tracker.markAsUnresponsive(SLOW_HOST);
try {
requester.runExchange(new URL(SLOW_URL), null);
fail("Timeout exception should have been thrown");
} catch (UnresponsiveHostException e) {
// expected.
} catch (IOException e) {
e.printStackTrace();
fail("I/O exception was thrown: " + e.getMessage());
}
}
public void testNumberOfTimeouts() {
tryNumberOfTimeouts(5);
tryNumberOfTimeouts(10);
tryNumberOfTimeouts(20);
tryNumberOfTimeouts(50);
tryNumberOfTimeouts(100);
tryNumberOfTimeouts(200);
tryNumberOfTimeouts(500);
tryNumberOfTimeouts(1000);
tryNumberOfTimeouts(2000);
tryNumberOfTimeouts(5000);
}
private void tryNumberOfTimeouts(int numberOfTimeouts) {
setNumberOfTimeouts(numberOfTimeouts);
double increment = (double) numberOfTimeouts / (double) getConfig().getSlowHostSamplePeriod();
double sum = 0;
int n = 0;
while (!tracker.isUnresponsive(SLOW_HOST)) {
sum += increment;
while (n <= (sum - 1)) {
tracker.recordHostTimeout(SLOW_HOST);
n += 1;
}
ticker.advance(1);
}
assertTrue("number of timeouts too small; limit: " + numberOfTimeouts + ", actual: " + n,
n >= numberOfTimeouts);
double upperLimit = numberOfTimeouts * 1.01d;
assertTrue("number of timeouts too large; limit: " + upperLimit + ", actual: " + n,
n <= upperLimit);
}
private void setNumberOfTimeouts(final int numberOfTimeouts) {
updateConfigParams(
new ConfigParamsUpdater() {
@Override
public void apply(ConfigParams.Builder builder) {
builder.put(ParamName.SLOW_HOST_NUMBER_OF_TIMEOUTS, numberOfTimeouts);
}
});
}
public void testEmbargoPeriod() {
tracker.markAsUnresponsive(SLOW_HOST);
int i = 1;
while (tracker.isUnresponsive(SLOW_HOST)) {
ticker.advance(1);
i += 1;
}
assertEquals(getConfig().getSlowHostEmbargoPeriod(), i);
}
// Do a fetch that times out.
private static void slowFetch(HttpRequester requester) {
try {
requester.runExchange(new URL(SLOW_URL), null);
fail("Timeout exception should have been thrown");
} catch (InterruptedIOException e) {
// expected.
} catch (IOException e) {
e.printStackTrace();
fail("I/O exception was thrown: " + e.getMessage());
}
}
}
| 6,076 | 0.696017 | 0.685978 | 191 | 30.811518 | 24.309008 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534031 | false | false |
7
|
95feffb2ec79c7c07efb30738e4410c0a5f14680
| 5,179,730,624,381 |
2d2d83e5f9dc3f00975ab991d0bf69a177c47de6
|
/src/test/java/uk/co/hmtt/gym/app/service/ActivityServiceTest.java
|
febe77ed59a80eb729b86bef231d05aa9690d007
|
[
"Apache-2.0"
] |
permissive
|
hmtt/gym
|
https://github.com/hmtt/gym
|
19a97082c392d2a32eb0436ca5173bd4afed0393
|
92d090c7993dbfe7b7a54396ad503753b466e73c
|
refs/heads/master
| 2021-01-10T10:06:37.749000 | 2017-04-01T09:56:27 | 2017-04-01T09:56:27 | 50,620,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uk.co.hmtt.gym.app.service;
import liquibase.integration.spring.SpringLiquibase;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCountCallbackHandler;
import org.springframework.test.context.ContextConfiguration;
import uk.co.hmtt.gym.app.service.impl.GymActivityService;
import uk.co.hmtt.gym.repository.impl.GymActivityDao;
import uk.co.hmtt.gym.repository.RepositoryTestConfig;
import javax.sql.DataSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.Is.is;
@ContextConfiguration(classes = {GymActivityService.class, GymActivityDao.class, ActivityServiceTest.DataLoad.class})
public class ActivityServiceTest extends RepositoryTestConfig {
@Autowired
private ActivityService activityService;
@Autowired
private JdbcTemplate jdbcTemplate;
private String siteName = "booker";
@Test
@Ignore
public void shouldAddAnActivity() {
final Integer countBeforeAddition = getRowCount();
activityService.addActivity("The Peak - Velocity Spin", "Velocity Blast Fri 07:15");
final Integer countAfterAddition = getRowCount();
assertThat(countAfterAddition, is(equalTo(countBeforeAddition + 1)));
}
private Integer getRowCount() {
RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler();
jdbcTemplate.query("select * from " + siteName + ".Activity", countCallbackHandler);
return countCallbackHandler.getRowCount();
}
@Configuration
public static class DataLoad {
@Autowired
private DataSource dataSource;
@Bean
public SpringLiquibase liquibase() {
final SpringLiquibase springLiquibase = new SpringLiquibase();
springLiquibase.setDataSource(dataSource);
springLiquibase.setChangeLog("classpath:changeset/changeset_activity_single.xml");
springLiquibase.setContexts("test, production");
return springLiquibase;
}
}
}
|
UTF-8
|
Java
| 2,311 |
java
|
ActivityServiceTest.java
|
Java
|
[] | null |
[] |
package uk.co.hmtt.gym.app.service;
import liquibase.integration.spring.SpringLiquibase;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCountCallbackHandler;
import org.springframework.test.context.ContextConfiguration;
import uk.co.hmtt.gym.app.service.impl.GymActivityService;
import uk.co.hmtt.gym.repository.impl.GymActivityDao;
import uk.co.hmtt.gym.repository.RepositoryTestConfig;
import javax.sql.DataSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.Is.is;
@ContextConfiguration(classes = {GymActivityService.class, GymActivityDao.class, ActivityServiceTest.DataLoad.class})
public class ActivityServiceTest extends RepositoryTestConfig {
@Autowired
private ActivityService activityService;
@Autowired
private JdbcTemplate jdbcTemplate;
private String siteName = "booker";
@Test
@Ignore
public void shouldAddAnActivity() {
final Integer countBeforeAddition = getRowCount();
activityService.addActivity("The Peak - Velocity Spin", "Velocity Blast Fri 07:15");
final Integer countAfterAddition = getRowCount();
assertThat(countAfterAddition, is(equalTo(countBeforeAddition + 1)));
}
private Integer getRowCount() {
RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler();
jdbcTemplate.query("select * from " + siteName + ".Activity", countCallbackHandler);
return countCallbackHandler.getRowCount();
}
@Configuration
public static class DataLoad {
@Autowired
private DataSource dataSource;
@Bean
public SpringLiquibase liquibase() {
final SpringLiquibase springLiquibase = new SpringLiquibase();
springLiquibase.setDataSource(dataSource);
springLiquibase.setChangeLog("classpath:changeset/changeset_activity_single.xml");
springLiquibase.setContexts("test, production");
return springLiquibase;
}
}
}
| 2,311 | 0.753354 | 0.75119 | 65 | 34.553844 | 29.347275 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
7
|
9c353b79d8400d7ca12eca2189a41434891a5c80
| 24,094,766,557,598 |
2ecd69120d070b28b8e032c5b696234e8bb5c42b
|
/An2/Sem1/Graphs/Graphs/src/Lab5_P1/MaximumCliqueFinder.java
|
7288c1066be9fa17d600b455fb05b1437e3d2e1f
|
[] |
no_license
|
csergiu/Labs
|
https://github.com/csergiu/Labs
|
61a5ba75405805f932a1635ea14d3434def4ffda
|
4a2be207cfb58e74e8ee426835f84315ee7d8880
|
refs/heads/master
| 2021-01-15T11:38:36.182000 | 2015-01-29T07:58:54 | 2015-01-29T07:58:54 | 49,513,568 | 1 | 0 | null | true | 2016-01-12T16:34:20 | 2016-01-12T16:34:20 | 2015-01-29T08:03:49 | 2015-01-29T08:03:43 | 103,949 | 0 | 0 | 0 | null | null | null |
package Lab5_P1;
import Model.GraphException;
import Model.GraphInterface;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created by mihai on 1/16/14.
*/
public class MaximumCliqueFinder<V, C> {
private Set<V> maximumSizeClique;
private Set<V> currentClique;
private GraphInterface<C, V> graph;
public MaximumCliqueFinder() {
maximumSizeClique = new HashSet<V>();
currentClique = new HashSet<V>();
}
public Set<V> find(GraphInterface<C, V> graph) throws GraphException {
maximumSizeClique = new HashSet<V>();
currentClique = new HashSet<V>();
this.graph = graph;
clique(this.graph.getVertices());
return maximumSizeClique;
}
private void clique(Set<V> candidateVertices) throws GraphException {
if (candidateVertices.isEmpty()) {
if (currentClique.size() > maximumSizeClique.size()) {
maximumSizeClique.clear();
maximumSizeClique.addAll(currentClique);
}
return;
}
while (!candidateVertices.isEmpty()) {
if (currentClique.size() + candidateVertices.size() <= maximumSizeClique
.size()) {
return;
}
Iterator<V> verticesIterator = candidateVertices.iterator();
V pickedVertex = verticesIterator.next();
candidateVertices.remove(pickedVertex);
Set<V> newCandidateVertices = new HashSet<V>();
newCandidateVertices.addAll(candidateVertices);
newCandidateVertices.retainAll(graph.getAdjacentVertices(pickedVertex));
currentClique.add(pickedVertex);
clique(newCandidateVertices);
currentClique.remove(pickedVertex);
}
return;
}
}
|
UTF-8
|
Java
| 1,832 |
java
|
MaximumCliqueFinder.java
|
Java
|
[
{
"context": "Iterator;\nimport java.util.Set;\n\n/**\n * Created by mihai on 1/16/14.\n */\npublic class MaximumCliqueFinder<",
"end": 176,
"score": 0.9989531636238098,
"start": 171,
"tag": "USERNAME",
"value": "mihai"
}
] | null |
[] |
package Lab5_P1;
import Model.GraphException;
import Model.GraphInterface;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created by mihai on 1/16/14.
*/
public class MaximumCliqueFinder<V, C> {
private Set<V> maximumSizeClique;
private Set<V> currentClique;
private GraphInterface<C, V> graph;
public MaximumCliqueFinder() {
maximumSizeClique = new HashSet<V>();
currentClique = new HashSet<V>();
}
public Set<V> find(GraphInterface<C, V> graph) throws GraphException {
maximumSizeClique = new HashSet<V>();
currentClique = new HashSet<V>();
this.graph = graph;
clique(this.graph.getVertices());
return maximumSizeClique;
}
private void clique(Set<V> candidateVertices) throws GraphException {
if (candidateVertices.isEmpty()) {
if (currentClique.size() > maximumSizeClique.size()) {
maximumSizeClique.clear();
maximumSizeClique.addAll(currentClique);
}
return;
}
while (!candidateVertices.isEmpty()) {
if (currentClique.size() + candidateVertices.size() <= maximumSizeClique
.size()) {
return;
}
Iterator<V> verticesIterator = candidateVertices.iterator();
V pickedVertex = verticesIterator.next();
candidateVertices.remove(pickedVertex);
Set<V> newCandidateVertices = new HashSet<V>();
newCandidateVertices.addAll(candidateVertices);
newCandidateVertices.retainAll(graph.getAdjacentVertices(pickedVertex));
currentClique.add(pickedVertex);
clique(newCandidateVertices);
currentClique.remove(pickedVertex);
}
return;
}
}
| 1,832 | 0.621725 | 0.617904 | 56 | 31.732143 | 23.079437 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.589286 | false | false |
7
|
dac537d91c7ae49e8a9348706d7631cdb90dfe0f
| 29,308,856,846,465 |
e5968df96fe0e4252ecc034c25cf4390338ab71f
|
/netty-study-05-bytebuffer/src/main/java/co/kr/hjt/netty/bytebuffer/ByteBufferPoolHandler.java
|
edce39c3421513361b270b45716abd20a2242164
|
[] |
no_license
|
kiosk123/netty-study
|
https://github.com/kiosk123/netty-study
|
8508cdf807bc88803b53981d465f8c136961c9eb
|
20ad087ab6144743ee5e7f4d7ee2586c88f5b35a
|
refs/heads/master
| 2022-12-30T05:28:21.475000 | 2020-10-22T17:11:52 | 2020-10-22T17:11:52 | 291,081,919 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package co.kr.hjt.netty.bytebuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.Charset;
/**
* 네티 바이트 버퍼 풀은 네트 애플리케이션의 서버 소켓 채널이
* 초기화될 때 같이 초기화되며 ChannelHandlerContext의 alloc메서드로
* 생성된 바이트 버퍼 풀을 참조할 수 있다.
*/
public class ByteBufferPoolHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf readMessage = (ByteBuf) msg;
System.out.println("channelRead : " + readMessage.toString(Charset.defaultCharset()));
/**
* ByteBufAllocator는 버퍼풀을 관리하는 인터페이스이며
* 플랫폼의 지원 여부에 따라 다이렉트 버퍼와 힙 버퍼 풀을 생성한다.
* 기본적으로 다이렉트 버퍼 풀을 새성하며 애플리케이션 개발자의
* 필요에 따라 힙 버퍼 풀을 생성할 수도 있다.
*/
ByteBufAllocator byteBufAllocator = ctx.alloc();
/**
* ByteBufAllocator의 buffer메서드로 생성된 버퍼는
* ByteBufAllocator의 풀에서 관리되며
* 바이트 버퍼를 채널에 기록하거나 명시적으로 release메서드를 호출하면
* 바이트 버퍼 풀로 돌아간다.
*/
ByteBuf newBuffer = byteBufAllocator.buffer();
// newBuffer 사용.
/**
* write 메서드의 인수로 바이트 버퍼가 입력되면
* 데이터를 채널에 기록하고 난뒤에
* 버퍼풀로 돌아간다.
*/
ctx.write(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
UTF-8
|
Java
| 2,002 |
java
|
ByteBufferPoolHandler.java
|
Java
|
[] | null |
[] |
package co.kr.hjt.netty.bytebuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.Charset;
/**
* 네티 바이트 버퍼 풀은 네트 애플리케이션의 서버 소켓 채널이
* 초기화될 때 같이 초기화되며 ChannelHandlerContext의 alloc메서드로
* 생성된 바이트 버퍼 풀을 참조할 수 있다.
*/
public class ByteBufferPoolHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf readMessage = (ByteBuf) msg;
System.out.println("channelRead : " + readMessage.toString(Charset.defaultCharset()));
/**
* ByteBufAllocator는 버퍼풀을 관리하는 인터페이스이며
* 플랫폼의 지원 여부에 따라 다이렉트 버퍼와 힙 버퍼 풀을 생성한다.
* 기본적으로 다이렉트 버퍼 풀을 새성하며 애플리케이션 개발자의
* 필요에 따라 힙 버퍼 풀을 생성할 수도 있다.
*/
ByteBufAllocator byteBufAllocator = ctx.alloc();
/**
* ByteBufAllocator의 buffer메서드로 생성된 버퍼는
* ByteBufAllocator의 풀에서 관리되며
* 바이트 버퍼를 채널에 기록하거나 명시적으로 release메서드를 호출하면
* 바이트 버퍼 풀로 돌아간다.
*/
ByteBuf newBuffer = byteBufAllocator.buffer();
// newBuffer 사용.
/**
* write 메서드의 인수로 바이트 버퍼가 입력되면
* 데이터를 채널에 기록하고 난뒤에
* 버퍼풀로 돌아간다.
*/
ctx.write(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
| 2,002 | 0.634565 | 0.634565 | 51 | 28.725491 | 22.624886 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
7
|
f22c06cdfd3a4d8a540a923f20dc71b2bf3f3982
| 17,239,998,753,811 |
d968e22f1757576dc82c16a5a920e7657b78c6bb
|
/src/experiment/runner/ExperimentRunner.java
|
e7be3fdda9d1d37187f10046160c9eba8ebc37be
|
[
"BSD-2-Clause"
] |
permissive
|
alibov/StreamAid
|
https://github.com/alibov/StreamAid
|
1723b57eca34e54d0c6da3dfe9d5bb8163ce297a
|
169d9be831b274ac2e5932f380fbf6b27a28df03
|
refs/heads/master
| 2021-01-23T12:22:35.552000 | 2015-11-19T16:07:26 | 2015-11-19T16:07:26 | 41,051,257 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package experiment.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import utils.Common;
import experiment.ExperimentConfiguration;
public class ExperimentRunner {
public static void main(final String[] args) throws Exception {
System.err.println("Exp runner running ver 14/12/14 02:33");
if (args.length != 3 && args.length != 4) {
throw new IllegalStateException("usage: program <xml-list file name> <exp-jar file name> <num-processes> (<java flags>)");
}
String flags = "";
if (args.length == 4) {
flags = args[3];
}
final int numProcs = Integer.valueOf(args[2]);
final BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line = null;
final ArrayList<ProcessStreams> processList = new ArrayList<ProcessStreams>();
final RunManager rm = new LocalRunManager();
while ((line = br.readLine()) != null) {
Thread.sleep(1000 * 1);
final ExperimentConfiguration expc = new ExperimentConfiguration(new File(line));
Common.currentConfiguration = expc;
rm.initFiles();
while (processList.size() == numProcs) {
Thread.sleep(1000 * 1);
for (int i = 0; i < processList.size(); i++) {
final ProcessStreams ps = processList.get(i);
try {
final int exVal = ps.proc.exitValue();
if (ps.err != null) {
ps.err.close();
}
if (ps.out != null) {
ps.out.close();
}
if (exVal != 0) {
System.err.println("exit value: " + exVal);
}
processList.remove(i);
i--;
} catch (final IllegalThreadStateException itx) {
// itx.printStackTrace();
}
}
}
final String commandLine = "java " + flags + " -jar " + args[1] + " " + line;
System.out.println("running: " + commandLine);
final ProcessStreams ps = new ProcessStreams();
ps.proc = Runtime.getRuntime().exec(commandLine);
ps.err = new FileOutputStream(line + ".errorLog");
ps.out = new FileOutputStream(line + ".outputLog");
final StreamGobbler errorGobbler = new StreamGobbler(ps.proc.getErrorStream(), "", ps.err);
// any output?
final StreamGobbler outputGobbler = new StreamGobbler(ps.proc.getInputStream(), "", ps.out);
// kick them off
errorGobbler.start();
outputGobbler.start();
processList.add(ps);
}
br.close();
}
}
class ProcessStreams {
Process proc;
FileOutputStream out = null;
FileOutputStream err = null;
}
class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(final InputStream is, final String type) {
this(is, type, null);
}
StreamGobbler(final InputStream is, final String type, final OutputStream redirect) {
this.is = is;
this.type = type;
os = redirect;
}
@Override public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os);
}
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
pw.flush();
}
// System.out.println(type + ">" + line);
}
if (pw != null) {
pw.flush();
}
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 3,768 |
java
|
ExperimentRunner.java
|
Java
|
[] | null |
[] |
package experiment.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import utils.Common;
import experiment.ExperimentConfiguration;
public class ExperimentRunner {
public static void main(final String[] args) throws Exception {
System.err.println("Exp runner running ver 14/12/14 02:33");
if (args.length != 3 && args.length != 4) {
throw new IllegalStateException("usage: program <xml-list file name> <exp-jar file name> <num-processes> (<java flags>)");
}
String flags = "";
if (args.length == 4) {
flags = args[3];
}
final int numProcs = Integer.valueOf(args[2]);
final BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line = null;
final ArrayList<ProcessStreams> processList = new ArrayList<ProcessStreams>();
final RunManager rm = new LocalRunManager();
while ((line = br.readLine()) != null) {
Thread.sleep(1000 * 1);
final ExperimentConfiguration expc = new ExperimentConfiguration(new File(line));
Common.currentConfiguration = expc;
rm.initFiles();
while (processList.size() == numProcs) {
Thread.sleep(1000 * 1);
for (int i = 0; i < processList.size(); i++) {
final ProcessStreams ps = processList.get(i);
try {
final int exVal = ps.proc.exitValue();
if (ps.err != null) {
ps.err.close();
}
if (ps.out != null) {
ps.out.close();
}
if (exVal != 0) {
System.err.println("exit value: " + exVal);
}
processList.remove(i);
i--;
} catch (final IllegalThreadStateException itx) {
// itx.printStackTrace();
}
}
}
final String commandLine = "java " + flags + " -jar " + args[1] + " " + line;
System.out.println("running: " + commandLine);
final ProcessStreams ps = new ProcessStreams();
ps.proc = Runtime.getRuntime().exec(commandLine);
ps.err = new FileOutputStream(line + ".errorLog");
ps.out = new FileOutputStream(line + ".outputLog");
final StreamGobbler errorGobbler = new StreamGobbler(ps.proc.getErrorStream(), "", ps.err);
// any output?
final StreamGobbler outputGobbler = new StreamGobbler(ps.proc.getInputStream(), "", ps.out);
// kick them off
errorGobbler.start();
outputGobbler.start();
processList.add(ps);
}
br.close();
}
}
class ProcessStreams {
Process proc;
FileOutputStream out = null;
FileOutputStream err = null;
}
class StreamGobbler extends Thread {
InputStream is;
String type;
OutputStream os;
StreamGobbler(final InputStream is, final String type) {
this(is, type, null);
}
StreamGobbler(final InputStream is, final String type, final OutputStream redirect) {
this.is = is;
this.type = type;
os = redirect;
}
@Override public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os);
}
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
pw.flush();
}
// System.out.println(type + ">" + line);
}
if (pw != null) {
pw.flush();
}
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
}
| 3,768 | 0.606953 | 0.599257 | 121 | 30.140495 | 23.899343 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.644628 | false | false |
7
|
d4a8d3796a1ed1ed702a4fbd29c6231074f82759
| 14,104,672,627,378 |
a3f9d4cb7a186d5fac37b310b78ed5b69ef715be
|
/Java Problems/Armstrong/src/Number.java
|
125206b486e2ac7d728ac52c6666cf3b8f37e4a9
|
[] |
no_license
|
abhishek03011/Codes
|
https://github.com/abhishek03011/Codes
|
855a0a73012b7be1cdc577271038439c16d479f7
|
87a71160844d209712ff9a71079989f23d850822
|
refs/heads/master
| 2021-01-12T12:52:23.275000 | 2016-09-27T19:11:44 | 2016-09-27T19:11:44 | 69,389,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Number {
static boolean number(int number)
{
int copy = number;
int digits = String.valueOf(copy).length();
//System.out.println(digits);
int sum = 0;
while(copy!=0)
{
int last = copy%10;
int temp = 1;
for(int i = 0 ;i<digits;i++)
{
temp = temp * last;
}
sum = sum + temp;
copy = copy / 10;
}
if(sum == number)
return true;
else
return false;
}
public static void main(String[] args)
{
System.out.println(Number.number(153));
}
}
|
UTF-8
|
Java
| 511 |
java
|
Number.java
|
Java
|
[] | null |
[] |
public class Number {
static boolean number(int number)
{
int copy = number;
int digits = String.valueOf(copy).length();
//System.out.println(digits);
int sum = 0;
while(copy!=0)
{
int last = copy%10;
int temp = 1;
for(int i = 0 ;i<digits;i++)
{
temp = temp * last;
}
sum = sum + temp;
copy = copy / 10;
}
if(sum == number)
return true;
else
return false;
}
public static void main(String[] args)
{
System.out.println(Number.number(153));
}
}
| 511 | 0.577299 | 0.555773 | 33 | 14.454545 | 13.170424 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.242424 | false | false |
7
|
2f1e69db49e249147ca887328baae10a9ae8478e
| 14,104,672,624,393 |
e0a01027ead6aaf1a4bcface5eeebc27ad942d10
|
/osc-server/src/main/java/org/osc/core/broker/service/DeleteDeploymentSpecService.java
|
203843b676209bcd7eba012692091d19868dc86b
|
[
"Apache-2.0"
] |
permissive
|
arvindn05/osc-core
|
https://github.com/arvindn05/osc-core
|
238db6997aba0d47fd0147ac885fadcede82bfc1
|
fe6a145623066c030008a753f618eca6a7c919ac
|
refs/heads/master
| 2021-07-01T19:48:49.926000 | 2018-07-12T23:53:14 | 2018-07-12T23:54:48 | 95,853,862 | 0 | 0 |
Apache-2.0
| true | 2018-02-07T03:06:31 | 2017-06-30T05:56:20 | 2017-06-30T05:56:25 | 2018-02-07T03:05:50 | 10,774 | 0 | 0 | 0 |
Java
| false | null |
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.osc.core.broker.service;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import org.osc.core.broker.job.Job;
import org.osc.core.broker.job.JobEngine;
import org.osc.core.broker.job.TaskGraph;
import org.osc.core.broker.job.lock.LockObjectReference;
import org.osc.core.broker.model.entities.appliance.DistributedAppliance;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.virtualization.SecurityGroup;
import org.osc.core.broker.model.entities.virtualization.ServiceFunctionChain;
import org.osc.core.broker.model.entities.virtualization.openstack.DeploymentSpec;
import org.osc.core.broker.service.api.DeleteDeploymentSpecServiceApi;
import org.osc.core.broker.service.exceptions.VmidcBrokerValidationException;
import org.osc.core.broker.service.persistence.DeploymentSpecEntityMgr;
import org.osc.core.broker.service.persistence.OSCEntityManager;
import org.osc.core.broker.service.persistence.SecurityGroupEntityMgr;
import org.osc.core.broker.service.persistence.VirtualSystemEntityMgr;
import org.osc.core.broker.service.request.BaseDeleteRequest;
import org.osc.core.broker.service.response.BaseJobResponse;
import org.osc.core.broker.service.tasks.conformance.UnlockObjectMetaTask;
import org.osc.core.broker.service.tasks.conformance.openstack.deploymentspec.ForceDeleteDSTask;
import org.osc.core.broker.service.validator.BaseIdRequestValidator;
import org.osc.core.common.job.TaskGuard;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component
public class DeleteDeploymentSpecService extends ServiceDispatcher<BaseDeleteRequest, BaseJobResponse>
implements DeleteDeploymentSpecServiceApi {
@Reference
private DeploymentSpecConformJobFactory dsConformJobFactory;
@Reference
private ForceDeleteDSTask forceDeleteDSTask;
private DeploymentSpec ds;
@Override
public BaseJobResponse exec(BaseDeleteRequest request, EntityManager em) throws Exception {
BaseJobResponse response = new BaseJobResponse();
validateAndLoad(em, request);
UnlockObjectMetaTask dsUnlock = null;
try {
DistributedAppliance da = this.ds.getVirtualSystem().getDistributedAppliance();
dsUnlock = LockUtil.tryLockDS(this.ds, da, da.getApplianceManagerConnector(), this.ds.getVirtualSystem()
.getVirtualizationConnector());
if (request.isForceDelete()) {
TaskGraph tg = new TaskGraph();
tg.addTask(this.forceDeleteDSTask.create(this.ds));
tg.appendTask(dsUnlock, TaskGuard.ALL_PREDECESSORS_COMPLETED);
Job job = JobEngine.getEngine().submit("Force Delete Deployment Spec '" + this.ds.getName() + "'", tg,
LockObjectReference.getObjectReferences(this.ds));
response.setJobId(job.getId());
} else {
OSCEntityManager.markDeleted(em, this.ds, this.txBroadcastUtil);
UnlockObjectMetaTask forLambda = dsUnlock;
chain(() -> {
try {
Job job = this.dsConformJobFactory.startDsConformanceJob(em, this.ds, forLambda);
response.setJobId(job.getId());
return response;
} catch (Exception e) {
LockUtil.releaseLocks(forLambda);
throw e;
}
});
}
} catch (Exception e) {
LockUtil.releaseLocks(dsUnlock);
throw e;
}
return response;
}
private void validateAndLoad(EntityManager em, BaseDeleteRequest request) throws Exception {
BaseIdRequestValidator.checkForNullIdAndParentNullId(request);
VirtualSystem vs = VirtualSystemEntityMgr.findById(em, request.getParentId());
if (vs == null) {
throw new VmidcBrokerValidationException("Virtual System with Id: " + request.getParentId()
+ " is not found.");
}
this.ds = em.find(DeploymentSpec.class, request.getId());
// entry must pre-exist in db
if (this.ds == null) { // note: we cannot use name here in error msg since
// del req does not have name, only ID
throw new VmidcBrokerValidationException("Deployment Specification entry with ID " + request.getId()
+ " is not found.");
}
if (DeploymentSpecEntityMgr.isProtectingWorkload(this.ds)) {
throw new VmidcBrokerValidationException(
String.format("The deployment spec with name '%s' is currently protecting a workload",
this.ds.getName()));
}
//check if virtual system of this DS is attached to a SFC and only allow deletion of DS if no SG is binding
// to this virtual systems SFC.
validateDSReferenceToSfcAndSecurityGroup(em, vs);
if (!this.ds.getMarkedForDeletion() && request.isForceDelete()) {
throw new VmidcBrokerValidationException(
"Deployment Spec '"
+ this.ds.getName()
+ "' is not marked for deletion and force delete operation is applicable only for entries marked for deletion.");
}
}
private void validateDSReferenceToSfcAndSecurityGroup(EntityManager em, VirtualSystem vs) throws Exception {
if (!vs.getServiceFunctionChains().isEmpty()) {
//Look if these SFCs are binded to any of the SG of same tenant as of DS
for (ServiceFunctionChain sfc : vs.getServiceFunctionChains()) {
List<SecurityGroup> sgList = SecurityGroupEntityMgr.listSecurityGroupsBySfcIdAndProjectId(em,
sfc.getId(), this.ds.getProjectId());
String sgNames = sgList.stream().filter(sg -> !sg.getMarkedForDeletion()).map(sg -> sg.getName()).collect(Collectors.joining(", "));
if (!sgNames.isEmpty()) {
throw new VmidcBrokerValidationException(String.format(
"Cannot delete deployment spec with name '%s' which is currently referencing Service Function Chain '%s' and binded to a SecurityGroup(s) '%s'",
this.ds.getName(), sfc.getName(), sgNames));
}
}
}
}
}
|
UTF-8
|
Java
| 7,292 |
java
|
DeleteDeploymentSpecService.java
|
Java
|
[] | null |
[] |
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.osc.core.broker.service;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import org.osc.core.broker.job.Job;
import org.osc.core.broker.job.JobEngine;
import org.osc.core.broker.job.TaskGraph;
import org.osc.core.broker.job.lock.LockObjectReference;
import org.osc.core.broker.model.entities.appliance.DistributedAppliance;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.virtualization.SecurityGroup;
import org.osc.core.broker.model.entities.virtualization.ServiceFunctionChain;
import org.osc.core.broker.model.entities.virtualization.openstack.DeploymentSpec;
import org.osc.core.broker.service.api.DeleteDeploymentSpecServiceApi;
import org.osc.core.broker.service.exceptions.VmidcBrokerValidationException;
import org.osc.core.broker.service.persistence.DeploymentSpecEntityMgr;
import org.osc.core.broker.service.persistence.OSCEntityManager;
import org.osc.core.broker.service.persistence.SecurityGroupEntityMgr;
import org.osc.core.broker.service.persistence.VirtualSystemEntityMgr;
import org.osc.core.broker.service.request.BaseDeleteRequest;
import org.osc.core.broker.service.response.BaseJobResponse;
import org.osc.core.broker.service.tasks.conformance.UnlockObjectMetaTask;
import org.osc.core.broker.service.tasks.conformance.openstack.deploymentspec.ForceDeleteDSTask;
import org.osc.core.broker.service.validator.BaseIdRequestValidator;
import org.osc.core.common.job.TaskGuard;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component
public class DeleteDeploymentSpecService extends ServiceDispatcher<BaseDeleteRequest, BaseJobResponse>
implements DeleteDeploymentSpecServiceApi {
@Reference
private DeploymentSpecConformJobFactory dsConformJobFactory;
@Reference
private ForceDeleteDSTask forceDeleteDSTask;
private DeploymentSpec ds;
@Override
public BaseJobResponse exec(BaseDeleteRequest request, EntityManager em) throws Exception {
BaseJobResponse response = new BaseJobResponse();
validateAndLoad(em, request);
UnlockObjectMetaTask dsUnlock = null;
try {
DistributedAppliance da = this.ds.getVirtualSystem().getDistributedAppliance();
dsUnlock = LockUtil.tryLockDS(this.ds, da, da.getApplianceManagerConnector(), this.ds.getVirtualSystem()
.getVirtualizationConnector());
if (request.isForceDelete()) {
TaskGraph tg = new TaskGraph();
tg.addTask(this.forceDeleteDSTask.create(this.ds));
tg.appendTask(dsUnlock, TaskGuard.ALL_PREDECESSORS_COMPLETED);
Job job = JobEngine.getEngine().submit("Force Delete Deployment Spec '" + this.ds.getName() + "'", tg,
LockObjectReference.getObjectReferences(this.ds));
response.setJobId(job.getId());
} else {
OSCEntityManager.markDeleted(em, this.ds, this.txBroadcastUtil);
UnlockObjectMetaTask forLambda = dsUnlock;
chain(() -> {
try {
Job job = this.dsConformJobFactory.startDsConformanceJob(em, this.ds, forLambda);
response.setJobId(job.getId());
return response;
} catch (Exception e) {
LockUtil.releaseLocks(forLambda);
throw e;
}
});
}
} catch (Exception e) {
LockUtil.releaseLocks(dsUnlock);
throw e;
}
return response;
}
private void validateAndLoad(EntityManager em, BaseDeleteRequest request) throws Exception {
BaseIdRequestValidator.checkForNullIdAndParentNullId(request);
VirtualSystem vs = VirtualSystemEntityMgr.findById(em, request.getParentId());
if (vs == null) {
throw new VmidcBrokerValidationException("Virtual System with Id: " + request.getParentId()
+ " is not found.");
}
this.ds = em.find(DeploymentSpec.class, request.getId());
// entry must pre-exist in db
if (this.ds == null) { // note: we cannot use name here in error msg since
// del req does not have name, only ID
throw new VmidcBrokerValidationException("Deployment Specification entry with ID " + request.getId()
+ " is not found.");
}
if (DeploymentSpecEntityMgr.isProtectingWorkload(this.ds)) {
throw new VmidcBrokerValidationException(
String.format("The deployment spec with name '%s' is currently protecting a workload",
this.ds.getName()));
}
//check if virtual system of this DS is attached to a SFC and only allow deletion of DS if no SG is binding
// to this virtual systems SFC.
validateDSReferenceToSfcAndSecurityGroup(em, vs);
if (!this.ds.getMarkedForDeletion() && request.isForceDelete()) {
throw new VmidcBrokerValidationException(
"Deployment Spec '"
+ this.ds.getName()
+ "' is not marked for deletion and force delete operation is applicable only for entries marked for deletion.");
}
}
private void validateDSReferenceToSfcAndSecurityGroup(EntityManager em, VirtualSystem vs) throws Exception {
if (!vs.getServiceFunctionChains().isEmpty()) {
//Look if these SFCs are binded to any of the SG of same tenant as of DS
for (ServiceFunctionChain sfc : vs.getServiceFunctionChains()) {
List<SecurityGroup> sgList = SecurityGroupEntityMgr.listSecurityGroupsBySfcIdAndProjectId(em,
sfc.getId(), this.ds.getProjectId());
String sgNames = sgList.stream().filter(sg -> !sg.getMarkedForDeletion()).map(sg -> sg.getName()).collect(Collectors.joining(", "));
if (!sgNames.isEmpty()) {
throw new VmidcBrokerValidationException(String.format(
"Cannot delete deployment spec with name '%s' which is currently referencing Service Function Chain '%s' and binded to a SecurityGroup(s) '%s'",
this.ds.getName(), sfc.getName(), sgNames));
}
}
}
}
}
| 7,292 | 0.65853 | 0.657433 | 155 | 46.045162 | 35.998627 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
7
|
bc4d3809113f96e5f79b3fa100ed9eaf150d56b3
| 27,728,308,876,674 |
ffdc9c7904c4f4dbc01a8b6d4c3b7b7f6bf6373c
|
/TheNewBostonJavaBeginner/src/basic_calculator.java
|
c2deeaa553b2afe208c0684f5120d7c8bd666dee
|
[] |
no_license
|
Phedri/javaTraining
|
https://github.com/Phedri/javaTraining
|
82dac1b203c36e2ae53a0134973bebac1ae29c7a
|
f9e5b8478a120231f4c869c852198cef2b0dde93
|
refs/heads/master
| 2021-10-26T14:11:10.885000 | 2019-04-13T04:28:00 | 2019-04-13T04:28:00 | 181,120,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class basic_calculator {
public static void main(String[] args) {
Scanner stock = new Scanner(System.in);
float fnum, snum;
System.out.println("Inserez le premier numero: ");
fnum = stock.nextFloat();
System.out.println("Inserez le deuxieme numero: ");
snum = stock.nextFloat();
System.out.println("Please choose an operation by tiping the number associated: \n 1 + \n 2- \n 3 x \n 4 /");
int op;
op = stock.nextInt();
if (op == (int) op) {
switch (op) {
case 1:
System.out.println(fnum + snum);
break;
case 2:
System.out.println(fnum - snum);
break;
case 3:
System.out.println(fnum * snum);
break;
case 4:
System.out.println(fnum / snum);
System.out.println("And the rest is: " + fnum % snum);
break;
default:
System.out.println("Please choose a number from 1 to 4.");
}
} else {
System.out.println("Please choose a number from 1 to 4.");
}
}
}
|
UTF-8
|
Java
| 972 |
java
|
basic_calculator.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class basic_calculator {
public static void main(String[] args) {
Scanner stock = new Scanner(System.in);
float fnum, snum;
System.out.println("Inserez le premier numero: ");
fnum = stock.nextFloat();
System.out.println("Inserez le deuxieme numero: ");
snum = stock.nextFloat();
System.out.println("Please choose an operation by tiping the number associated: \n 1 + \n 2- \n 3 x \n 4 /");
int op;
op = stock.nextInt();
if (op == (int) op) {
switch (op) {
case 1:
System.out.println(fnum + snum);
break;
case 2:
System.out.println(fnum - snum);
break;
case 3:
System.out.println(fnum * snum);
break;
case 4:
System.out.println(fnum / snum);
System.out.println("And the rest is: " + fnum % snum);
break;
default:
System.out.println("Please choose a number from 1 to 4.");
}
} else {
System.out.println("Please choose a number from 1 to 4.");
}
}
}
| 972 | 0.630658 | 0.618313 | 39 | 23.948717 | 23.089512 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.871795 | false | false |
4
|
e986aa364ab1400511461a57278fd435a84b3780
| 30,477,087,947,065 |
f8bda8b24fe86132aa7424216dbd78b23ae94834
|
/DemoEjbPrj/ejbModule/org/demo/example/cdi/alternates/VisaCardPayment.java
|
ed248edbc23dcd06bd6ee129da642341b9a5fbc5
|
[] |
no_license
|
SunRavD/CDI-Eamples
|
https://github.com/SunRavD/CDI-Eamples
|
89b7fc385937f6f7258ff7aab2b65d6e47cf1e2f
|
232990ef7a8f55b2ddb3dbce23fd256c5514b22c
|
refs/heads/master
| 2020-04-06T06:21:14.293000 | 2014-07-02T02:33:44 | 2014-07-02T02:48:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.demo.example.cdi.alternates;
@Card(cardType={CardType.VISA_CARD})
public class VisaCardPayment implements PaymentBy {
private double charges = 0.23;
@Override
public void paymentChargeAmount(Double aDouble) {
System.out.println(" VisaCardPayment charge amount : "+(aDouble*charges));
}
}
|
UTF-8
|
Java
| 328 |
java
|
VisaCardPayment.java
|
Java
|
[] | null |
[] |
package org.demo.example.cdi.alternates;
@Card(cardType={CardType.VISA_CARD})
public class VisaCardPayment implements PaymentBy {
private double charges = 0.23;
@Override
public void paymentChargeAmount(Double aDouble) {
System.out.println(" VisaCardPayment charge amount : "+(aDouble*charges));
}
}
| 328 | 0.722561 | 0.713415 | 14 | 21.428572 | 24.517382 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false |
4
|
a470b802f03a986ec1a2a47ec6368fc572203f77
| 29,420,526,033,449 |
f7a0e43833163459c5441203e8099e07f5c256ab
|
/testgit/src/main/java/cn/enjoy/App.java
|
fbee3cefb7c0c6306f4749af6ebed806782a7cce
|
[] |
no_license
|
sanwu-7/testgit
|
https://github.com/sanwu-7/testgit
|
e907085c75190923c8e71a31cf6854d2ae506e63
|
5b2feb04102a6d113f6560aad7f8ffa60dd663ed
|
refs/heads/master
| 2020-08-22T19:03:43.356000 | 2019-10-21T03:12:48 | 2019-10-21T03:12:48 | 216,462,166 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.enjoy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
//@SpringBootApplication
@EnableAutoConfiguration
public class App{
@RequestMapping("/hello")
public Object sayHello() {
return "hello";
}
public static void main(String[] args) {
//启动类
//定制化
SpringApplication.run(App.class, args);
}
}
|
UTF-8
|
Java
| 687 |
java
|
App.java
|
Java
|
[] | null |
[] |
package cn.enjoy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
//@SpringBootApplication
@EnableAutoConfiguration
public class App{
@RequestMapping("/hello")
public Object sayHello() {
return "hello";
}
public static void main(String[] args) {
//启动类
//定制化
SpringApplication.run(App.class, args);
}
}
| 687 | 0.718518 | 0.718518 | 28 | 22.107143 | 22.854101 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false |
4
|
e50e6c513f4a34b0a51ae8500e01e2f64d53c2c5
| 21,466,246,570,498 |
9e7e2533f47e1acce766ce67fb76c739a0600058
|
/response_result/src/main/java/com/tpy/response_result/advice/GlobalExceptionHandler.java
|
db87c93b8427080dabf97f2c319d931d467e3009
|
[] |
no_license
|
tangpengyi/SpringBoot
|
https://github.com/tangpengyi/SpringBoot
|
32fad2eb45aae65971479adc9e97604cd1e587a7
|
977c574300a25ec61edb8d40124b20c63c3da736
|
refs/heads/master
| 2023-01-20T02:45:02.498000 | 2020-11-19T06:50:14 | 2020-11-19T06:50:14 | 292,777,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tpy.response_result.advice;
import com.tpy.response_result.api.ErrorResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult validationError(MethodArgumentNotValidException ex) {
ErrorResult errorResult = new ErrorResult();
FieldError fieldError = ex.getBindingResult().getFieldError();
errorResult.setMsg(fieldError.getField() + fieldError.getDefaultMessage());
return errorResult;
}
}
|
UTF-8
|
Java
| 939 |
java
|
GlobalExceptionHandler.java
|
Java
|
[] | null |
[] |
package com.tpy.response_result.advice;
import com.tpy.response_result.api.ErrorResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult validationError(MethodArgumentNotValidException ex) {
ErrorResult errorResult = new ErrorResult();
FieldError fieldError = ex.getBindingResult().getFieldError();
errorResult.setMsg(fieldError.getField() + fieldError.getDefaultMessage());
return errorResult;
}
}
| 939 | 0.809372 | 0.809372 | 23 | 39.782608 | 27.226835 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
4
|
41ef5dcb63063cd312390044786191a8a34da7fe
| 2,456,721,364,860 |
72db4785dbab9df123ac951ab98fcc61ba28949b
|
/OOSD3_DannyBrassil/src/bankAccount/BankAccountGUI.java
|
c26a1979393cb08c6792a48154de848f7a3187fa
|
[] |
no_license
|
DannyBrassil/College
|
https://github.com/DannyBrassil/College
|
8bd4ef58eec3c46bac8e433c3930e9fcf4382419
|
a9c72ec58961705aa116b740414a35c8bf415d72
|
refs/heads/master
| 2020-07-29T00:48:52.360000 | 2019-09-30T19:26:38 | 2019-09-30T19:26:38 | 209,603,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bankAccount;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class BankAccountGUI extends JFrame{
// Menu structure
private JMenuBar myBar;
private JMenu fileMenu, recordMenu;
private JMenuItem fileLoad, fileSaveAs, removeAccount;
//Arraylist of account objects
private ArrayList <Account> arrData;
//Table components
private JTable myTable;
private MyTableModel tm;
private JScrollPane myPane;
//Form panel components
private JLabel nameLabel = new JLabel("Name");
private JTextField nameField = new JTextField(10);
private JLabel accountNoLabel = new JLabel("Account Number");
private JTextField accountNoField= new JTextField(10);
private JLabel balanceLabel = new JLabel("Balance");
private JTextField balanceField= new JTextField(10);
private JButton addButton = new JButton("Add Account");
private JPanel formPnl = new JPanel();
private JPanel tblPnl = new JPanel();
//Thread panel
private JPanel threadPnl = new JPanel();
private JTextArea threadOutput = new JTextArea();
private JButton threadButton = new JButton("Thread simulation");
//File variables
private File file = new File("accounts.dat");
private String currentDirectory;
public BankAccountGUI(){
// Setting up menu
setUpMenu();
//create array of account objects and pass to custom TableModel
arrData = new ArrayList<Account>();
tm = new MyTableModel(arrData);
myTable = new JTable(tm);
myPane = new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myTable.setSelectionForeground(Color.white);
myTable.setSelectionBackground(Color.red);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//create form panel
createFormPanel();
//Event Listeners
//Add Account Event
addButton.addActionListener(new ActionListener() {
Account acc;
@Override
public void actionPerformed(ActionEvent evt) {
try {
if (nameField.getText().isEmpty() || accountNoField.getText().isEmpty() || balanceField.getText().isEmpty() )
JOptionPane.showMessageDialog(BankAccountGUI.this, "All textfields must have a value");
else {
String name = nameField.getText();
int accNum = Integer.parseInt(accountNoField.getText());
int bal = Integer.parseInt(balanceField.getText());
acc = new Account(name, accNum, bal);
arrData.add(acc);
tm.fireTableDataChanged();
nameField.setText("");
accountNoField.setText("");
balanceField.setText("");
}
}
catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "account number and balance must be a number");
}
}
});
// Save the data to a file (save event handler)
// Use provided function: writeDataFile() to save the data into the file
fileSaveAs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if(arrData.size()<=0) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "You must add customer records before saving");
}
else {
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(file);
int retVal = jfc.showSaveDialog(BankAccountGUI.this);
if(retVal == JFileChooser.APPROVE_OPTION) {
file = jfc.getSelectedFile();
if(file.exists()) {//check to see if file exists
JOptionPane.showMessageDialog(BankAccountGUI.this, "This file already exists", "Warning",
JOptionPane.INFORMATION_MESSAGE);
}
else {//if file doesnt exist
System.out.println(file.getAbsolutePath());
try {
writeDataFile(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}//end else
}
arrData.clear();
tm.fireTableDataChanged();
}
}
});
// Loading the contents of a file into the table (load event handler)
// Use provided function: readDataFile() to save the data into the file
fileLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JFileChooser jfc = new JFileChooser();
int openVal = jfc.showOpenDialog(BankAccountGUI.this);
if(openVal == JFileChooser.APPROVE_OPTION) {
file = jfc.getSelectedFile();
try {
readDataFile(file);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
// 4 Remove Selected Account Event
removeAccount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
//get selected item
int row = myTable.getSelectedRow();
if(row == -1) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "you must select a row to delete first");
}
else {
arrData.remove(row);
tm.fireTableRowsDeleted(arrData.size(), arrData.size());
}
}
});
// 5 Thread Button simulation Event
threadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
Scanner scan = new Scanner(System.in);
int x;//amount to deposit/withdraw
int r;// num of repetitions
//check to see if row is selected
if (myTable.getSelectionModel().isSelectionEmpty()) {
System.out.println("You must select a row in the table first");
}
else {
Account ac = arrData.get(myTable.getSelectedRow());
do {
System.out.println("How many repitions do you want?");
r = scan.nextInt();
if(r<=0) {
System.out.println("repetions must be greater than 0");
}
}while(r<=0);
// check to see if funds are available
do {
System.out.println("How much do you wish to redraw?");
x = scan.nextInt();
if(x>ac.getBalance()) {
System.out.println("You do not have enough funds to withdraw this amount");
}
if(x<=0) {
System.out.println("you cannot withdraw this amount");
}
}while(x>ac.getBalance()|| x<=0);
DepositRunnable dr = new DepositRunnable(ac, x, r);
WithdrawalRunnable wr = new WithdrawalRunnable(ac, x, r);
//start threads
dr.start();
wr.start();
}
}
});
// Adding menu bar
setJMenuBar(myBar);
//add scrollpane with table
tblPnl.add(myPane);
//add thread button to thread panel
threadPnl.add(threadButton);
threadPnl.add(threadOutput);
//add panel for form
add(formPnl, BorderLayout.NORTH);
TitledBorder title = BorderFactory.createTitledBorder("Account Summary");
tblPnl.setBorder(title);
add(tblPnl, BorderLayout.CENTER);
add(threadPnl, BorderLayout.SOUTH);
this.setTitle("Bank Account Details");
this.setVisible(true);
this.pack();
} // constructor
private void setUpMenu() {
fileLoad = new JMenuItem("Open");
fileSaveAs = new JMenuItem("Save As");
fileMenu = new JMenu("File");
fileMenu.add(fileLoad);
fileMenu.add(fileSaveAs);
removeAccount = new JMenuItem("Remove Account");
recordMenu = new JMenu("Account");
recordMenu.add(removeAccount);
myBar = new JMenuBar();
myBar.add(fileMenu);
myBar.add(recordMenu);
}
public void writeDataFile(File f) throws IOException, FileNotFoundException {
FileOutputStream fo = null;
ObjectOutputStream os = null;
try {
fo = new FileOutputStream(f);
os = new ObjectOutputStream(fo);
os.writeObject(arrData);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void readDataFile(File f) throws IOException, ClassNotFoundException {
FileInputStream fi = null;
ObjectInputStream in = null;
ArrayList<Account>arr = null;
try {
fi = new FileInputStream(f);
in = new ObjectInputStream(fi);
arr = (ArrayList<Account>)in.readObject();
arrData.clear();
arrData.addAll(arr);
//update table model
tm.fireTableDataChanged();
} catch(EOFException ex) {}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void closeDown() {
System.exit(0);
}
public void createFormPanel() {
formPnl.setLayout(new GridBagLayout());
TitledBorder title = BorderFactory.createTitledBorder("Add Account");
formPnl.setBorder(title);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(10,0,0,0);
formPnl.add(nameLabel, c);
c.gridx = 1;
formPnl.add(nameField, c);
c.gridx = 0;
c.gridy = 1;
formPnl.add(accountNoLabel, c);
c.gridx = 1;
formPnl.add(accountNoField,c);
c.gridx = 0;
c.gridy = 2;
formPnl.add(balanceLabel,c);
c.gridx = 1;
formPnl.add(balanceField,c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
formPnl.add(addButton, c);
}
public static void main (String args[]){
new BankAccountGUI();
} // main
} //class
|
UTF-8
|
Java
| 10,776 |
java
|
BankAccountGUI.java
|
Java
|
[] | null |
[] |
package bankAccount;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class BankAccountGUI extends JFrame{
// Menu structure
private JMenuBar myBar;
private JMenu fileMenu, recordMenu;
private JMenuItem fileLoad, fileSaveAs, removeAccount;
//Arraylist of account objects
private ArrayList <Account> arrData;
//Table components
private JTable myTable;
private MyTableModel tm;
private JScrollPane myPane;
//Form panel components
private JLabel nameLabel = new JLabel("Name");
private JTextField nameField = new JTextField(10);
private JLabel accountNoLabel = new JLabel("Account Number");
private JTextField accountNoField= new JTextField(10);
private JLabel balanceLabel = new JLabel("Balance");
private JTextField balanceField= new JTextField(10);
private JButton addButton = new JButton("Add Account");
private JPanel formPnl = new JPanel();
private JPanel tblPnl = new JPanel();
//Thread panel
private JPanel threadPnl = new JPanel();
private JTextArea threadOutput = new JTextArea();
private JButton threadButton = new JButton("Thread simulation");
//File variables
private File file = new File("accounts.dat");
private String currentDirectory;
public BankAccountGUI(){
// Setting up menu
setUpMenu();
//create array of account objects and pass to custom TableModel
arrData = new ArrayList<Account>();
tm = new MyTableModel(arrData);
myTable = new JTable(tm);
myPane = new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myTable.setSelectionForeground(Color.white);
myTable.setSelectionBackground(Color.red);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//create form panel
createFormPanel();
//Event Listeners
//Add Account Event
addButton.addActionListener(new ActionListener() {
Account acc;
@Override
public void actionPerformed(ActionEvent evt) {
try {
if (nameField.getText().isEmpty() || accountNoField.getText().isEmpty() || balanceField.getText().isEmpty() )
JOptionPane.showMessageDialog(BankAccountGUI.this, "All textfields must have a value");
else {
String name = nameField.getText();
int accNum = Integer.parseInt(accountNoField.getText());
int bal = Integer.parseInt(balanceField.getText());
acc = new Account(name, accNum, bal);
arrData.add(acc);
tm.fireTableDataChanged();
nameField.setText("");
accountNoField.setText("");
balanceField.setText("");
}
}
catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "account number and balance must be a number");
}
}
});
// Save the data to a file (save event handler)
// Use provided function: writeDataFile() to save the data into the file
fileSaveAs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if(arrData.size()<=0) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "You must add customer records before saving");
}
else {
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(file);
int retVal = jfc.showSaveDialog(BankAccountGUI.this);
if(retVal == JFileChooser.APPROVE_OPTION) {
file = jfc.getSelectedFile();
if(file.exists()) {//check to see if file exists
JOptionPane.showMessageDialog(BankAccountGUI.this, "This file already exists", "Warning",
JOptionPane.INFORMATION_MESSAGE);
}
else {//if file doesnt exist
System.out.println(file.getAbsolutePath());
try {
writeDataFile(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}//end else
}
arrData.clear();
tm.fireTableDataChanged();
}
}
});
// Loading the contents of a file into the table (load event handler)
// Use provided function: readDataFile() to save the data into the file
fileLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JFileChooser jfc = new JFileChooser();
int openVal = jfc.showOpenDialog(BankAccountGUI.this);
if(openVal == JFileChooser.APPROVE_OPTION) {
file = jfc.getSelectedFile();
try {
readDataFile(file);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
// 4 Remove Selected Account Event
removeAccount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
//get selected item
int row = myTable.getSelectedRow();
if(row == -1) {
JOptionPane.showMessageDialog(BankAccountGUI.this, "you must select a row to delete first");
}
else {
arrData.remove(row);
tm.fireTableRowsDeleted(arrData.size(), arrData.size());
}
}
});
// 5 Thread Button simulation Event
threadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
Scanner scan = new Scanner(System.in);
int x;//amount to deposit/withdraw
int r;// num of repetitions
//check to see if row is selected
if (myTable.getSelectionModel().isSelectionEmpty()) {
System.out.println("You must select a row in the table first");
}
else {
Account ac = arrData.get(myTable.getSelectedRow());
do {
System.out.println("How many repitions do you want?");
r = scan.nextInt();
if(r<=0) {
System.out.println("repetions must be greater than 0");
}
}while(r<=0);
// check to see if funds are available
do {
System.out.println("How much do you wish to redraw?");
x = scan.nextInt();
if(x>ac.getBalance()) {
System.out.println("You do not have enough funds to withdraw this amount");
}
if(x<=0) {
System.out.println("you cannot withdraw this amount");
}
}while(x>ac.getBalance()|| x<=0);
DepositRunnable dr = new DepositRunnable(ac, x, r);
WithdrawalRunnable wr = new WithdrawalRunnable(ac, x, r);
//start threads
dr.start();
wr.start();
}
}
});
// Adding menu bar
setJMenuBar(myBar);
//add scrollpane with table
tblPnl.add(myPane);
//add thread button to thread panel
threadPnl.add(threadButton);
threadPnl.add(threadOutput);
//add panel for form
add(formPnl, BorderLayout.NORTH);
TitledBorder title = BorderFactory.createTitledBorder("Account Summary");
tblPnl.setBorder(title);
add(tblPnl, BorderLayout.CENTER);
add(threadPnl, BorderLayout.SOUTH);
this.setTitle("Bank Account Details");
this.setVisible(true);
this.pack();
} // constructor
private void setUpMenu() {
fileLoad = new JMenuItem("Open");
fileSaveAs = new JMenuItem("Save As");
fileMenu = new JMenu("File");
fileMenu.add(fileLoad);
fileMenu.add(fileSaveAs);
removeAccount = new JMenuItem("Remove Account");
recordMenu = new JMenu("Account");
recordMenu.add(removeAccount);
myBar = new JMenuBar();
myBar.add(fileMenu);
myBar.add(recordMenu);
}
public void writeDataFile(File f) throws IOException, FileNotFoundException {
FileOutputStream fo = null;
ObjectOutputStream os = null;
try {
fo = new FileOutputStream(f);
os = new ObjectOutputStream(fo);
os.writeObject(arrData);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void readDataFile(File f) throws IOException, ClassNotFoundException {
FileInputStream fi = null;
ObjectInputStream in = null;
ArrayList<Account>arr = null;
try {
fi = new FileInputStream(f);
in = new ObjectInputStream(fi);
arr = (ArrayList<Account>)in.readObject();
arrData.clear();
arrData.addAll(arr);
//update table model
tm.fireTableDataChanged();
} catch(EOFException ex) {}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void closeDown() {
System.exit(0);
}
public void createFormPanel() {
formPnl.setLayout(new GridBagLayout());
TitledBorder title = BorderFactory.createTitledBorder("Add Account");
formPnl.setBorder(title);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(10,0,0,0);
formPnl.add(nameLabel, c);
c.gridx = 1;
formPnl.add(nameField, c);
c.gridx = 0;
c.gridy = 1;
formPnl.add(accountNoLabel, c);
c.gridx = 1;
formPnl.add(accountNoField,c);
c.gridx = 0;
c.gridy = 2;
formPnl.add(balanceLabel,c);
c.gridx = 1;
formPnl.add(balanceField,c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
formPnl.add(addButton, c);
}
public static void main (String args[]){
new BankAccountGUI();
} // main
} //class
| 10,776 | 0.627227 | 0.623794 | 399 | 25.012531 | 21.919134 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.711779 | false | false |
4
|
219afc9675cb1a5a9ef36400fdf35617603bfc97
| 3,547,643,024,793 |
d0783bc2170f3f1115a2747e53881e6bdebaa74d
|
/src/main/java/com/uuola/app/sitecrawler/action/OuterSiteInfoHandlerAction.java
|
eea73f4e5509b4c5e5db478894e98b381bca17fe
|
[] |
no_license
|
TonyDon/site-crawler
|
https://github.com/TonyDon/site-crawler
|
0a5e1902c3af3e549d6eea90db3712d11fbe1722
|
446840e454765acb8f7968240cff53bca932b01f
|
refs/heads/master
| 2021-01-21T04:40:42.729000 | 2018-08-08T03:04:01 | 2018-08-08T03:04:01 | 55,339,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* @(#)OuterSiteInfoHandlerAction.java 2016年4月3日
*
* Copy Right@ uuola
*/
package com.uuola.app.sitecrawler.action;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.uuola.app.sitecrawler.component.RecordQueueManager;
import com.uuola.app.sitecrawler.component.RecordRepeaterCrawlManager;
import com.uuola.app.sitecrawler.dto.ClientPostEntity;
import com.uuola.app.sitecrawler.dto.InfoRecord;
import com.uuola.commons.CollectionUtil;
import com.uuola.txweb.framework.action.BaseAction;
/**
* <pre>
* 接受来自phantomjs客户端抓取后的结果处理
* @author tangxiaodong
* 创建日期: 2016年4月3日
* </pre>
*/
@Controller
@RequestMapping("/outerSiteInfoHandler")
public class OuterSiteInfoHandlerAction extends BaseAction {
@RequestMapping(value="/resovle", method = RequestMethod.POST)
@ResponseBody
public String resovle(@RequestBody ClientPostEntity clientPost){
log.info("requestId:"+clientPost.getRequestId());
InfoRecord rec = clientPost.getSingleRecord();
checkAndPushQueue(rec);
List<InfoRecord> records = clientPost.getRecords();
if(CollectionUtil.isNotEmpty(records)){
for(InfoRecord record : records){
checkAndPushQueue(record);
}
}
return "ok";
}
private void checkAndPushQueue(InfoRecord rec) {
if(null != rec && !RecordRepeaterCrawlManager.exist(rec.getRecordMd5Value())){
RecordQueueManager.push(rec);
}
}
@RequestMapping(value="/queueInfo", method = RequestMethod.GET)
@ResponseBody
public String queueInfo(){
return "curr queue count: " + RecordQueueManager.getCurrCount();
}
}
|
UTF-8
|
Java
| 2,060 |
java
|
OuterSiteInfoHandlerAction.java
|
Java
|
[
{
"context": "\n * <pre>\r\n * 接受来自phantomjs客户端抓取后的结果处理\r\n * @author tangxiaodong\r\n * 创建日期: 2016年4月3日\r\n * </pre>\r\n */\r\n@Controller\r",
"end": 871,
"score": 0.9996789693832397,
"start": 859,
"tag": "USERNAME",
"value": "tangxiaodong"
}
] | null |
[] |
/*
* @(#)OuterSiteInfoHandlerAction.java 2016年4月3日
*
* Copy Right@ uuola
*/
package com.uuola.app.sitecrawler.action;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.uuola.app.sitecrawler.component.RecordQueueManager;
import com.uuola.app.sitecrawler.component.RecordRepeaterCrawlManager;
import com.uuola.app.sitecrawler.dto.ClientPostEntity;
import com.uuola.app.sitecrawler.dto.InfoRecord;
import com.uuola.commons.CollectionUtil;
import com.uuola.txweb.framework.action.BaseAction;
/**
* <pre>
* 接受来自phantomjs客户端抓取后的结果处理
* @author tangxiaodong
* 创建日期: 2016年4月3日
* </pre>
*/
@Controller
@RequestMapping("/outerSiteInfoHandler")
public class OuterSiteInfoHandlerAction extends BaseAction {
@RequestMapping(value="/resovle", method = RequestMethod.POST)
@ResponseBody
public String resovle(@RequestBody ClientPostEntity clientPost){
log.info("requestId:"+clientPost.getRequestId());
InfoRecord rec = clientPost.getSingleRecord();
checkAndPushQueue(rec);
List<InfoRecord> records = clientPost.getRecords();
if(CollectionUtil.isNotEmpty(records)){
for(InfoRecord record : records){
checkAndPushQueue(record);
}
}
return "ok";
}
private void checkAndPushQueue(InfoRecord rec) {
if(null != rec && !RecordRepeaterCrawlManager.exist(rec.getRecordMd5Value())){
RecordQueueManager.push(rec);
}
}
@RequestMapping(value="/queueInfo", method = RequestMethod.GET)
@ResponseBody
public String queueInfo(){
return "curr queue count: " + RecordQueueManager.getCurrCount();
}
}
| 2,060 | 0.70199 | 0.695522 | 63 | 29.904762 | 25.257854 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365079 | false | false |
4
|
303f98e74db0f7d73050d78c0fff3c49e007afca
| 7,069,516,193,689 |
616171b04ee6ade24cf65b64253fa7ee534599a2
|
/produtor-service/src/main/java/br/com/loja/produtor/amq/source/VendaCodSource.java
|
4063ff78da602bd33f8fbc7291505e88ceb421c4
|
[] |
no_license
|
murilofidelis/mensageria-exemplo
|
https://github.com/murilofidelis/mensageria-exemplo
|
14b157de698e2602900a32a663d85e03aa2647ff
|
a677cd5aaa6346dd62a2d764e314103f80627273
|
refs/heads/master
| 2023-01-09T12:12:20.789000 | 2020-04-12T00:14:58 | 2020-04-12T00:14:58 | 242,423,740 | 0 | 0 | null | false | 2023-01-07T15:31:34 | 2020-02-22T22:58:28 | 2020-04-12T00:18:22 | 2023-01-07T15:31:34 | 645 | 0 | 0 | 10 |
Java
| false | false |
package br.com.loja.produtor.amq.source;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface VendaCodSource {
@Input(Channels.VENDA_COD_CHANNEL)
SubscribableChannel inputChannel();
}
|
UTF-8
|
Java
| 275 |
java
|
VendaCodSource.java
|
Java
|
[] | null |
[] |
package br.com.loja.produtor.amq.source;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface VendaCodSource {
@Input(Channels.VENDA_COD_CHANNEL)
SubscribableChannel inputChannel();
}
| 275 | 0.810909 | 0.810909 | 10 | 26.5 | 22.650606 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
4
|
bb0a0874a821346a782aa8bc28adf24dd16404d4
| 28,948,079,597,227 |
3635f6d9bd4e39a2e33e1554c2b03139ccb016de
|
/app/src/main/java/com/kzbandai/beginner/android/MainActivity.java
|
c047dcd2d7a680a8527c92f63ce2c2c458b81a25
|
[] |
no_license
|
kzbandai/android_pi
|
https://github.com/kzbandai/android_pi
|
b795aad96efebcf1449f272eb2288882e06b9d50
|
6198ec9d7775d295eaa93a9837e978ce11165448
|
refs/heads/master
| 2020-12-31T07:09:37.963000 | 2017-06-04T16:42:49 | 2017-06-04T16:42:49 | 86,571,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kzbandai.beginner.android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
static String extraWithResultActivity = "result";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button login_button = (Button) findViewById(R.id.submit);
login_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
EditText resultEditText = (EditText) findViewById(R.id.targetNumber);
String targetNumber = resultEditText.getText().toString();
intent.putExtra(extraWithResultActivity, searchResult(targetNumber));
startActivity(intent);
}
});
}
private String searchResult(String targetNumber) {
String searchResult = String.valueOf(String.valueOf(Math.PI).substring(2).indexOf(targetNumber) + 1);
if (searchResult.equals("0")) {
return "ないです";
}
return searchResult;
}
}
|
UTF-8
|
Java
| 1,416 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.kzbandai.beginner.android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
static String extraWithResultActivity = "result";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button login_button = (Button) findViewById(R.id.submit);
login_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
EditText resultEditText = (EditText) findViewById(R.id.targetNumber);
String targetNumber = resultEditText.getText().toString();
intent.putExtra(extraWithResultActivity, searchResult(targetNumber));
startActivity(intent);
}
});
}
private String searchResult(String targetNumber) {
String searchResult = String.valueOf(String.valueOf(Math.PI).substring(2).indexOf(targetNumber) + 1);
if (searchResult.equals("0")) {
return "ないです";
}
return searchResult;
}
}
| 1,416 | 0.682528 | 0.679688 | 41 | 33.341465 | 28.492712 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560976 | false | false |
4
|
f3718bd3c353f673ac97776c1838f8c1a89c6945
| 8,383,776,189,755 |
68ebbc7b1d18b0093ebf07c3cd646e21b09a7edf
|
/WEB-INF/classes/adminShop/PasswordReminderServlet.java
|
07177abc092a686118994953f16ec09e5da2def1
|
[] |
no_license
|
shobc/legame
|
https://github.com/shobc/legame
|
ae9ab4c13d598fc1d44a908363a6b342cbb0691f
|
acc9f1820db3be7e3f69b20f705150f89ef1ef92
|
refs/heads/master
| 2020-09-01T06:33:46.813000 | 2020-03-03T13:10:43 | 2020-03-03T13:10:43 | 218,897,970 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package adminShop;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import function.EscapeString;
import adminShop.dao.ShopAdminAbstractDaoFactory;
import adminShop.dao.ShopAdminUserDao;
import adminShop.bean.ShopAdminUserBean;
import adminShop.exception.RegisterAccountException;
import function.SendMail;
import function.RandomString;
@WebServlet("/shopAdmin/PasswordReminderServlet")
public class PasswordReminderServlet extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
req.setCharacterEncoding("Windows-31J");
ServletContext sc = getServletContext();
String mail = EscapeString.escape(req.getParameter("mail"));
ShopAdminAbstractDaoFactory factory = ShopAdminAbstractDaoFactory.getFactory();
ShopAdminUserDao dao = factory.getShopAdminUserDao();
if(dao.emailJudge(mail)){
throw new RegisterAccountException("メールアドレスが登録されていません");
}
String RString = RandomString.getString();
ShopAdminUserBean saub = new ShopAdminUserBean();
saub.setMail(mail);
saub.setRandom(RString);
String url = "http://localhost:8080/legame/shopAdmin/AuthAccountServlet?RandomCode="+RString;
SendMail sm = new SendMail();
String message = "URLにアクセスしてパスワード変更してください";
sm.send(mail,message,url);
sc.setAttribute(RString,saub);
req.setAttribute("message","メールを送信しました");
RequestDispatcher dis = req.getRequestDispatcher("/WEB-INF/jsp/adminShop/confirm.jsp");
dis.forward(req,res);
}
}
|
SHIFT_JIS
|
Java
| 2,037 |
java
|
PasswordReminderServlet.java
|
Java
|
[] | null |
[] |
package adminShop;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import function.EscapeString;
import adminShop.dao.ShopAdminAbstractDaoFactory;
import adminShop.dao.ShopAdminUserDao;
import adminShop.bean.ShopAdminUserBean;
import adminShop.exception.RegisterAccountException;
import function.SendMail;
import function.RandomString;
@WebServlet("/shopAdmin/PasswordReminderServlet")
public class PasswordReminderServlet extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
req.setCharacterEncoding("Windows-31J");
ServletContext sc = getServletContext();
String mail = EscapeString.escape(req.getParameter("mail"));
ShopAdminAbstractDaoFactory factory = ShopAdminAbstractDaoFactory.getFactory();
ShopAdminUserDao dao = factory.getShopAdminUserDao();
if(dao.emailJudge(mail)){
throw new RegisterAccountException("メールアドレスが登録されていません");
}
String RString = RandomString.getString();
ShopAdminUserBean saub = new ShopAdminUserBean();
saub.setMail(mail);
saub.setRandom(RString);
String url = "http://localhost:8080/legame/shopAdmin/AuthAccountServlet?RandomCode="+RString;
SendMail sm = new SendMail();
String message = "URLにアクセスしてパスワード変更してください";
sm.send(mail,message,url);
sc.setAttribute(RString,saub);
req.setAttribute("message","メールを送信しました");
RequestDispatcher dis = req.getRequestDispatcher("/WEB-INF/jsp/adminShop/confirm.jsp");
dis.forward(req,res);
}
}
| 2,037 | 0.759135 | 0.756047 | 46 | 41.260868 | 24.195251 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.934783 | false | false |
4
|
f7d6f798b1717ec2da5b6dc1a49800c58c7ca8b3
| 4,209,067,983,002 |
29d4877ddcdca30469e450d07331daabf6762974
|
/app/src/main/java/com/chuizi/wensente/widget/GsonUtil.java
|
9ad0677986288268b14c8c26fcc630ccd1854602
|
[] |
no_license
|
willow2/Wensente
|
https://github.com/willow2/Wensente
|
2bba14bf7a2f9dfc57a3dafa4104ab21cc4bc56a
|
2b39af148bf3ef23df2b746a5843423c1b002730
|
refs/heads/master
| 2021-01-23T04:44:34.064000 | 2017-05-31T11:18:21 | 2017-05-31T11:18:21 | 92,938,798 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chuizi.wensente.widget;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class GsonUtil {
private static Gson gson = new Gson();
public static Gson getGson() {
return new Gson();
}
/**
* json转换为map
*
* @param json
* @return
*/
public static Map getMap(String json) {
return new Gson().fromJson(json, Map.class);
}
public static String getJson(Object src) {
return new Gson().toJson(src);
}
/**
* 获取轮播图列表
* @param json
* @return
*/
// public static List getScrollAdBeanList(String json) {
// // gson.fromJson(json,new TypeToken<List<RegionBean>>() { }.getType());
//
// return new Gson().fromJson(json, new TypeToken<List<ScrollAdBean>>() {
// }.getType());
//
// }
// /**
// * json转换为list
// *
// * @param json
// * @return
// */
// public static List getList(String json) {
// return new Gson().fromJson(json, List.class);
// }
// public static ResultMapBean getMapString(String json) {
//
// ResultMapBean bean = null;
// try {
// JSONObject jsonObject = new JSONObject(json);
// bean = new ResultMapBean();
//
// bean.setResultcode(jsonObject.has("resultcode")?jsonObject.getString("resultcode"):"");
// bean.setReason(jsonObject.has("reason")?jsonObject.getString("reason"):"");
// bean.setResult(jsonObject.has("result")?jsonObject.getString("result"):"");
// bean.setError_code(jsonObject.has("error_code")?jsonObject.getInt("error_code"):0);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return bean;
// }
}
|
UTF-8
|
Java
| 1,681 |
java
|
GsonUtil.java
|
Java
|
[] | null |
[] |
package com.chuizi.wensente.widget;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class GsonUtil {
private static Gson gson = new Gson();
public static Gson getGson() {
return new Gson();
}
/**
* json转换为map
*
* @param json
* @return
*/
public static Map getMap(String json) {
return new Gson().fromJson(json, Map.class);
}
public static String getJson(Object src) {
return new Gson().toJson(src);
}
/**
* 获取轮播图列表
* @param json
* @return
*/
// public static List getScrollAdBeanList(String json) {
// // gson.fromJson(json,new TypeToken<List<RegionBean>>() { }.getType());
//
// return new Gson().fromJson(json, new TypeToken<List<ScrollAdBean>>() {
// }.getType());
//
// }
// /**
// * json转换为list
// *
// * @param json
// * @return
// */
// public static List getList(String json) {
// return new Gson().fromJson(json, List.class);
// }
// public static ResultMapBean getMapString(String json) {
//
// ResultMapBean bean = null;
// try {
// JSONObject jsonObject = new JSONObject(json);
// bean = new ResultMapBean();
//
// bean.setResultcode(jsonObject.has("resultcode")?jsonObject.getString("resultcode"):"");
// bean.setReason(jsonObject.has("reason")?jsonObject.getString("reason"):"");
// bean.setResult(jsonObject.has("result")?jsonObject.getString("result"):"");
// bean.setError_code(jsonObject.has("error_code")?jsonObject.getInt("error_code"):0);
//
// } catch (JSONException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// return bean;
// }
}
| 1,681 | 0.644713 | 0.644109 | 89 | 17.595505 | 23.27931 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.191011 | false | false |
4
|
b0b94e2dbdfedeab044565bd81ce30e9bb857f65
| 33,105,607,949,316 |
c474b03758be154e43758220e47b3403eb7fc1fc
|
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/recsads/analytics/C16432d.java
|
b847a731078b020a721514b49aef8a4442bc011f
|
[] |
no_license
|
EstebanDalelR/tinderAnalysis
|
https://github.com/EstebanDalelR/tinderAnalysis
|
f80fe1f43b3b9dba283b5db1781189a0dd592c24
|
941e2c634c40e5dbf5585c6876ef33f2a578b65c
|
refs/heads/master
| 2020-04-04T09:03:32.659000 | 2018-11-23T20:41:28 | 2018-11-23T20:41:28 | 155,805,042 | 0 | 0 | null | false | 2018-11-18T16:02:45 | 2018-11-02T02:44:34 | 2018-11-18T15:58:25 | 2018-11-18T16:02:44 | 353,670 | 0 | 0 | 0 | null | false | null |
package com.tinder.recsads.analytics;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.tinder.analytics.fireworks.C2630h;
import com.tinder.etl.event.C11530v;
import com.tinder.etl.event.EtlEvent;
import com.tinder.recsads.analytics.AdEventFields.C14729c;
import com.tinder.recsads.analytics.C16444w.C16443a;
import javax.inject.Inject;
/* renamed from: com.tinder.recsads.analytics.d */
public class C16432d extends C14737g<C14735a> {
/* renamed from: com.tinder.recsads.analytics.d$a */
public static abstract class C14735a {
/* renamed from: com.tinder.recsads.analytics.d$a$a */
public static abstract class C14734a {
/* renamed from: a */
public abstract C14735a mo12169a();
}
@Nullable
/* renamed from: a */
public abstract Number mo12170a();
@Nullable
/* renamed from: b */
public abstract String mo12171b();
/* renamed from: c */
public static C14734a m55997c() {
return new C16443a();
}
}
@Inject
C16432d(C2630h c2630h, C14729c c14729c) {
super(c2630h, c14729c);
}
/* renamed from: a */
protected EtlEvent m61819a(@NonNull C14735a c14735a, AdEventFields adEventFields) {
return C11530v.a().a(adEventFields.mo12162a()).a(adEventFields.mo12164c()).e(c14735a.mo12170a()).b(adEventFields.mo12163b()).b(adEventFields.mo12167f().key()).a(adEventFields.mo12168g()).c(adEventFields.mo12165d().key()).d(Integer.valueOf(adEventFields.mo12166e().key())).a();
}
}
|
UTF-8
|
Java
| 1,603 |
java
|
C16432d.java
|
Java
|
[] | null |
[] |
package com.tinder.recsads.analytics;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.tinder.analytics.fireworks.C2630h;
import com.tinder.etl.event.C11530v;
import com.tinder.etl.event.EtlEvent;
import com.tinder.recsads.analytics.AdEventFields.C14729c;
import com.tinder.recsads.analytics.C16444w.C16443a;
import javax.inject.Inject;
/* renamed from: com.tinder.recsads.analytics.d */
public class C16432d extends C14737g<C14735a> {
/* renamed from: com.tinder.recsads.analytics.d$a */
public static abstract class C14735a {
/* renamed from: com.tinder.recsads.analytics.d$a$a */
public static abstract class C14734a {
/* renamed from: a */
public abstract C14735a mo12169a();
}
@Nullable
/* renamed from: a */
public abstract Number mo12170a();
@Nullable
/* renamed from: b */
public abstract String mo12171b();
/* renamed from: c */
public static C14734a m55997c() {
return new C16443a();
}
}
@Inject
C16432d(C2630h c2630h, C14729c c14729c) {
super(c2630h, c14729c);
}
/* renamed from: a */
protected EtlEvent m61819a(@NonNull C14735a c14735a, AdEventFields adEventFields) {
return C11530v.a().a(adEventFields.mo12162a()).a(adEventFields.mo12164c()).e(c14735a.mo12170a()).b(adEventFields.mo12163b()).b(adEventFields.mo12167f().key()).a(adEventFields.mo12168g()).c(adEventFields.mo12165d().key()).d(Integer.valueOf(adEventFields.mo12166e().key())).a();
}
}
| 1,603 | 0.674984 | 0.562071 | 47 | 33.106384 | 42.630642 | 284 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382979 | false | false |
4
|
967c67f64baa6954bdc5e5d2791c155b370c02da
| 15,367,393,011,527 |
72227a9558c6031da6d70f50fff78b542a0af352
|
/M48-Rotate-Image.java
|
5142c1de62837a3c325e1f82fb203887f1d809b2
|
[] |
no_license
|
YoungYang0820/LeetcodeForFall
|
https://github.com/YoungYang0820/LeetcodeForFall
|
74f67b39bfc606a04fa38b8260f15aed8f3cf48a
|
0eb6305ff4bf6379fed0913e0cdfecaa5a26b035
|
refs/heads/master
| 2020-03-17T04:42:59.063000 | 2018-08-08T01:34:25 | 2018-08-08T01:34:25 | 133,286,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix[0] == null || matrix.length == 0) return;
int n = matrix.length;
int axis = n % 2 == 0 ? n/2 : n/2 + 1;
for (int i = 0; i < n/2; i++) {
for (int j = 0; j < axis; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = tmp;
}
}
}
}
|
UTF-8
|
Java
| 575 |
java
|
M48-Rotate-Image.java
|
Java
|
[] | null |
[] |
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix[0] == null || matrix.length == 0) return;
int n = matrix.length;
int axis = n % 2 == 0 ? n/2 : n/2 + 1;
for (int i = 0; i < n/2; i++) {
for (int j = 0; j < axis; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = tmp;
}
}
}
}
| 575 | 0.393043 | 0.361739 | 16 | 34.9375 | 20.58054 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
4
|
7d3e0ec8ff6c6f1978d6492e7c40956ae0e775d2
| 6,064,493,857,412 |
f7c1e2b0425755ec281b58cc81d269f9acfe0516
|
/payeemanagement/src/main/java/com/scrotifybanking/payeemanagement/service/CustomerServiceImpl.java
|
62ddf29b31ee90b536ce07aaf42b89dbe12846d8
|
[] |
no_license
|
Mahendran-Natarajan/Mock_Hack_Workspace
|
https://github.com/Mahendran-Natarajan/Mock_Hack_Workspace
|
c9c553ca9838b37c90fca02c07a5f7def76356f7
|
81912c15833bc2bba7037866c064a16995b9e1b7
|
refs/heads/master
| 2020-12-06T14:00:10.662000 | 2020-01-08T04:59:59 | 2020-01-08T04:59:59 | 232,480,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.scrotifybanking.payeemanagement.service;
import com.scrotifybanking.payeemanagement.dto.LoginRequestDto;
import com.scrotifybanking.payeemanagement.dto.LoginResponseDto;
import com.scrotifybanking.payeemanagement.entity.Customer;
import com.scrotifybanking.payeemanagement.exception.CustomException;
import com.scrotifybanking.payeemanagement.repository.CustomerRepository;
import com.scrotifybanking.payeemanagement.util.ScrotifyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* The type Customer service.
*
* @author Mahendran
*/
@Service
public class CustomerServiceImpl implements CustomerService {
/**
* The constant logger.
*/
public static final Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);
/**
* The Customer repository.
*/
@Autowired
CustomerRepository customerRepository;
/**
* This method is used to login a customer and admin
*/
@Override
public Optional<LoginResponseDto> loginCustomer(LoginRequestDto loginRequestDto) {
logger.info("Login customer ");
LoginResponseDto loginResponseDto = new LoginResponseDto();
Optional<LoginResponseDto> loginResponseDtoOptional = Optional.empty();
Long customerId = loginRequestDto.getId();
String password = loginRequestDto.getPassword();
Optional<Customer> customer = customerRepository.findByCustomerId(customerId);
if (customer.isPresent()) {
logger.info("Login customer present");
loginResponseDtoOptional = customer
.filter(cust -> cust.getCustomerPassword().equals(password))
.map(cust -> {
BeanUtils.copyProperties(cust, loginResponseDto);
return loginResponseDto;
});
loginResponseDto.setStatusCode(ScrotifyConstant.SUCCESS_CODE);
loginResponseDto.setMessage(ScrotifyConstant.SUCCESS_MESSAGE);
} else {
logger.info("Login customer not present");
loginResponseDto.setStatusCode(ScrotifyConstant.FAILURE_CODE);
loginResponseDto.setMessage(ScrotifyConstant.INVALID_MESSAGE);
}
return loginResponseDtoOptional;
}
}
|
UTF-8
|
Java
| 2,458 |
java
|
CustomerServiceImpl.java
|
Java
|
[
{
"context": ";\n\n/**\n * The type Customer service.\n *\n * @author Mahendran\n */\n@Service\npublic class CustomerServiceImpl impl",
"end": 751,
"score": 0.9092687368392944,
"start": 742,
"tag": "NAME",
"value": "Mahendran"
}
] | null |
[] |
package com.scrotifybanking.payeemanagement.service;
import com.scrotifybanking.payeemanagement.dto.LoginRequestDto;
import com.scrotifybanking.payeemanagement.dto.LoginResponseDto;
import com.scrotifybanking.payeemanagement.entity.Customer;
import com.scrotifybanking.payeemanagement.exception.CustomException;
import com.scrotifybanking.payeemanagement.repository.CustomerRepository;
import com.scrotifybanking.payeemanagement.util.ScrotifyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* The type Customer service.
*
* @author Mahendran
*/
@Service
public class CustomerServiceImpl implements CustomerService {
/**
* The constant logger.
*/
public static final Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);
/**
* The Customer repository.
*/
@Autowired
CustomerRepository customerRepository;
/**
* This method is used to login a customer and admin
*/
@Override
public Optional<LoginResponseDto> loginCustomer(LoginRequestDto loginRequestDto) {
logger.info("Login customer ");
LoginResponseDto loginResponseDto = new LoginResponseDto();
Optional<LoginResponseDto> loginResponseDtoOptional = Optional.empty();
Long customerId = loginRequestDto.getId();
String password = loginRequestDto.getPassword();
Optional<Customer> customer = customerRepository.findByCustomerId(customerId);
if (customer.isPresent()) {
logger.info("Login customer present");
loginResponseDtoOptional = customer
.filter(cust -> cust.getCustomerPassword().equals(password))
.map(cust -> {
BeanUtils.copyProperties(cust, loginResponseDto);
return loginResponseDto;
});
loginResponseDto.setStatusCode(ScrotifyConstant.SUCCESS_CODE);
loginResponseDto.setMessage(ScrotifyConstant.SUCCESS_MESSAGE);
} else {
logger.info("Login customer not present");
loginResponseDto.setStatusCode(ScrotifyConstant.FAILURE_CODE);
loginResponseDto.setMessage(ScrotifyConstant.INVALID_MESSAGE);
}
return loginResponseDtoOptional;
}
}
| 2,458 | 0.713181 | 0.712368 | 64 | 37.40625 | 28.201683 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
4
|
feb68e672b432c01d2f9ca8145cd19bf1fd0c667
| 1,726,576,890,547 |
a64dc928c5e31dde78d03ac79d2c1496151a8ec0
|
/src/test/java/com/amazon/strings/PalindromeTest.java
|
c57b74839f56db3ffbab289b71f5fb915ccdaf20
|
[] |
no_license
|
apalakurthi/leetcode-tests
|
https://github.com/apalakurthi/leetcode-tests
|
d102099d72659716f1e1830d25ac2d653ea826dd
|
43428e404cd2fc33ed745dc44f860b8d4a94f1f0
|
refs/heads/master
| 2022-12-27T19:38:29.955000 | 2020-06-02T23:54:50 | 2020-06-02T23:54:50 | 268,932,872 | 0 | 0 | null | false | 2020-10-13T22:31:26 | 2020-06-02T23:51:11 | 2020-06-03T00:04:52 | 2020-10-13T22:31:25 | 18 | 0 | 0 | 1 |
Java
| false | false |
package com.amazon.strings;
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void isPalindrome() {
Palindrome palindrome = new Palindrome();
assertTrue(palindrome.isPalindrome("A man, a plan, a canal: Panama"));
assertFalse(palindrome.isPalindrome("race a car"));
assertFalse(palindrome.isPalindrome("0P"));
}
}
|
UTF-8
|
Java
| 389 |
java
|
PalindromeTest.java
|
Java
|
[] | null |
[] |
package com.amazon.strings;
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void isPalindrome() {
Palindrome palindrome = new Palindrome();
assertTrue(palindrome.isPalindrome("A man, a plan, a canal: Panama"));
assertFalse(palindrome.isPalindrome("race a car"));
assertFalse(palindrome.isPalindrome("0P"));
}
}
| 389 | 0.719794 | 0.717224 | 16 | 23.3125 | 22.557478 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
4
|
b145d04936c7757333237a751ed074b6ebe1bb68
| 26,895,085,234,378 |
2db8b859f85e2c5f2a308f2a224e4e1be75fb509
|
/java-datas-model/src/main/java/fr/snasello/datas/model/SortDirection.java
|
3df0ac1050cae33a8e2999ae7a7b5f71b7a1f147
|
[
"Apache-2.0"
] |
permissive
|
snasello/java-datas
|
https://github.com/snasello/java-datas
|
f97e4aa363c0e222797fc725c9938f7a7aedcc67
|
d9435b0f6b01c1d4007d1d74b3d6a74bb192b985
|
refs/heads/master
| 2020-04-18T09:08:40.291000 | 2019-02-09T19:29:16 | 2019-02-09T19:29:16 | 167,423,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.snasello.datas.model;
/**
* Sort Direction ASC or DESC
*
* @author Samuel Nasello
*
*/
public enum SortDirection {
ASC,DSC;
}
|
UTF-8
|
Java
| 161 |
java
|
SortDirection.java
|
Java
|
[
{
"context": "**\r\n * Sort Direction ASC or DESC\r\n * \r\n * @author Samuel Nasello\r\n *\r\n */\r\npublic enum SortDirection {\r\n\t\r\n\tASC,DS",
"end": 102,
"score": 0.9998874068260193,
"start": 88,
"tag": "NAME",
"value": "Samuel Nasello"
}
] | null |
[] |
package fr.snasello.datas.model;
/**
* Sort Direction ASC or DESC
*
* @author <NAME>
*
*/
public enum SortDirection {
ASC,DSC;
}
| 153 | 0.602484 | 0.602484 | 13 | 10.384615 | 12.187879 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
4
|
73895045d55fd5250c6bf1876448d3ec333d642e
| 566,935,718,195 |
bd240155831986a4ed0bc56b38c8af1835b52332
|
/automation/src/test/java/com/infigo/automation/GeneralUserFunctionality.java
|
ad87a3fe8c88669b494fd39d28c6aeabe01d9d09
|
[] |
no_license
|
heerqa/infigo-automation
|
https://github.com/heerqa/infigo-automation
|
671f55db117d03efa95675953c2d07cce1d3ddcf
|
4b375de581b10d5a4c07cbd4cf262ab7199f3ebe
|
refs/heads/master
| 2021-03-13T00:00:33.541000 | 2015-03-02T18:04:02 | 2015-03-02T18:04:02 | 28,533,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.infigo.automation;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.ErrorCollector;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class GeneralUserFunctionality extends CatFishFunctionality {
@Rule
public ErrorCollector collector = new ErrorCollector();
public GeneralUserFunctionality(WebDriver e) {
super(e);
driver = e;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private WebDriver driver;
TestData testData=new TestData();
public boolean ifElementPresent(By by)throws Throwable{
try {
driver.findElement(by);
return true;
}
catch (Throwable t) {
return false;
}
}
public void clickMYShoppingBasket()throws Throwable {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
}
public void testvalidLogin() throws Throwable {
if (BrowserUtils.getInstance().isShouldLogin()) {
testValidLoginToInfigo();
}
}
public void testValidLoginToInfigo() throws Throwable{
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
String username =EnvSetUP.getInstance().getproperties("username") ;
String password=EnvSetUP.getInstance().getproperties("password") ;
driver.get(baseurl);
driver.findElement(By.linkText("Log in")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("form > table.table-container > tbody > tr > td.item-value > #Email")).sendKeys(username);
driver.findElement(By.xpath("(//input[@id='Password'])[2]")).sendKeys(password);
driver.findElement(By.cssSelector("button.loginbutton")).click();
waitForElementToLoadandClick(By.linkText("My Shopping Basket"), 2);
Thread.sleep(2000);
}
public void searchProduct() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("The row val is :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
Assert.assertEquals(testData.productName(rownum), driver.findElement(By.cssSelector(".product-title>a")).getText());
rownum++;
} else {
hasnextrow=false;
}
}
}
public void addtoBasket() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("The row val is :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
System.out.println(driver.findElement(By.cssSelector(".cf_headerlinks_shoppngcart")).getText());
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
waitForElementToLoadandClick(By.cssSelector("input.productlistproductdetailbutton"), 20);
waitForElementToLoadandClick(By.cssSelector(".productvariantaddtocartbutton"), 5);
waitForElementToLoadandClick(By.cssSelector(".tt.nextStepButton.btn.btn-success.btn-lg"), 5);
waitForElementToLoadandClick(By.xpath("html/body/div[7]/div[3]/div/button[1]"), 5);
Thread.sleep(10000);
System.out.println(driver.findElement(By.cssSelector(".cf_headerlinks_shoppngcart")).getText());
rownum++;
} else {
hasnextrow=false;
}
}
}
public void emailtoFriend() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("poduct name :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("input.productlistproductdetailbutton")).click();
driver.findElement(By.cssSelector("input.productemailafriendbutton")).click();
driver.findElement(By.id("FriendEmail")).clear();
driver.findElement(By.id("FriendEmail")).sendKeys("test@yopmail.com");
driver.findElement(By.id("PersonalMessage")).clear();
driver.findElement(By.id("PersonalMessage")).sendKeys("test");
driver.findElement(By.id("send-email")).click();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.cssSelector("div.emailafriend-box")).getText().contains("Your message has been sent"));
rownum++;
} else {
hasnextrow=false;
}
}
}
public void catfish_addMembeshipLetter() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("poduct name :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("input.productlistproductdetailbutton")).click();
driver.findElement(By.cssSelector("input.productemailafriendbutton")).click();
driver.findElement(By.id("FriendEmail")).clear();
driver.findElement(By.id("FriendEmail")).sendKeys("test@yopmail.com");
driver.findElement(By.id("PersonalMessage")).clear();
driver.findElement(By.id("PersonalMessage")).sendKeys("test");
driver.findElement(By.id("send-email")).click();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.cssSelector("div.emailafriend-box")).getText().contains("Your message has been sent"));
rownum++;
} else {
hasnextrow=false;
}
}
}
}
|
UTF-8
|
Java
| 7,057 |
java
|
GeneralUserFunctionality.java
|
Java
|
[
{
"context": "g username =EnvSetUP.getInstance().getproperties(\"username\") ;\n\t\t String password=EnvSetUP.getInstance().ge",
"end": 1548,
"score": 0.9993270039558411,
"start": 1540,
"tag": "USERNAME",
"value": "username"
},
{
"context": "river.findElement(By.id(\"FriendEmail\")).sendKeys(\"test@yopmail.com\");\n\t\t driver.findElement(By.id(\"PersonalMessag",
"end": 5253,
"score": 0.9998877644538879,
"start": 5237,
"tag": "EMAIL",
"value": "test@yopmail.com"
},
{
"context": "river.findElement(By.id(\"FriendEmail\")).sendKeys(\"test@yopmail.com\");\n\t\t driver.findElement(By.id(\"PersonalMessag",
"end": 6639,
"score": 0.9999212622642517,
"start": 6623,
"tag": "EMAIL",
"value": "test@yopmail.com"
}
] | null |
[] |
package com.infigo.automation;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.ErrorCollector;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class GeneralUserFunctionality extends CatFishFunctionality {
@Rule
public ErrorCollector collector = new ErrorCollector();
public GeneralUserFunctionality(WebDriver e) {
super(e);
driver = e;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private WebDriver driver;
TestData testData=new TestData();
public boolean ifElementPresent(By by)throws Throwable{
try {
driver.findElement(by);
return true;
}
catch (Throwable t) {
return false;
}
}
public void clickMYShoppingBasket()throws Throwable {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
}
public void testvalidLogin() throws Throwable {
if (BrowserUtils.getInstance().isShouldLogin()) {
testValidLoginToInfigo();
}
}
public void testValidLoginToInfigo() throws Throwable{
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
String username =EnvSetUP.getInstance().getproperties("username") ;
String password=EnvSetUP.getInstance().getproperties("password") ;
driver.get(baseurl);
driver.findElement(By.linkText("Log in")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("form > table.table-container > tbody > tr > td.item-value > #Email")).sendKeys(username);
driver.findElement(By.xpath("(//input[@id='Password'])[2]")).sendKeys(password);
driver.findElement(By.cssSelector("button.loginbutton")).click();
waitForElementToLoadandClick(By.linkText("My Shopping Basket"), 2);
Thread.sleep(2000);
}
public void searchProduct() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("The row val is :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
Assert.assertEquals(testData.productName(rownum), driver.findElement(By.cssSelector(".product-title>a")).getText());
rownum++;
} else {
hasnextrow=false;
}
}
}
public void addtoBasket() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("The row val is :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
System.out.println(driver.findElement(By.cssSelector(".cf_headerlinks_shoppngcart")).getText());
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
waitForElementToLoadandClick(By.cssSelector("input.productlistproductdetailbutton"), 20);
waitForElementToLoadandClick(By.cssSelector(".productvariantaddtocartbutton"), 5);
waitForElementToLoadandClick(By.cssSelector(".tt.nextStepButton.btn.btn-success.btn-lg"), 5);
waitForElementToLoadandClick(By.xpath("html/body/div[7]/div[3]/div/button[1]"), 5);
Thread.sleep(10000);
System.out.println(driver.findElement(By.cssSelector(".cf_headerlinks_shoppngcart")).getText());
rownum++;
} else {
hasnextrow=false;
}
}
}
public void emailtoFriend() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("poduct name :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("input.productlistproductdetailbutton")).click();
driver.findElement(By.cssSelector("input.productemailafriendbutton")).click();
driver.findElement(By.id("FriendEmail")).clear();
driver.findElement(By.id("FriendEmail")).sendKeys("<EMAIL>");
driver.findElement(By.id("PersonalMessage")).clear();
driver.findElement(By.id("PersonalMessage")).sendKeys("test");
driver.findElement(By.id("send-email")).click();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.cssSelector("div.emailafriend-box")).getText().contains("Your message has been sent"));
rownum++;
} else {
hasnextrow=false;
}
}
}
public void catfish_addMembeshipLetter() throws Throwable{
boolean hasnextrow=true;
int rownum=1;
while (hasnextrow) {
System.out.println("poduct name :"+testData.productName(rownum));
if (!testData.productName(rownum).isEmpty()) {
String baseurl =EnvSetUP.getInstance().getproperties("baseurl") ;
driver.get(baseurl);
driver.findElement(By.linkText("My Shopping Basket")).click();
Thread.sleep(2000);
driver.findElement(By.id("small-searchterms")).clear();
driver.findElement(By.id("small-searchterms")).sendKeys(testData.productName(rownum));
driver.findElement(By.id("btn-small-search")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("input.productlistproductdetailbutton")).click();
driver.findElement(By.cssSelector("input.productemailafriendbutton")).click();
driver.findElement(By.id("FriendEmail")).clear();
driver.findElement(By.id("FriendEmail")).sendKeys("<EMAIL>");
driver.findElement(By.id("PersonalMessage")).clear();
driver.findElement(By.id("PersonalMessage")).sendKeys("test");
driver.findElement(By.id("send-email")).click();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.cssSelector("div.emailafriend-box")).getText().contains("Your message has been sent"));
rownum++;
} else {
hasnextrow=false;
}
}
}
}
| 7,039 | 0.698172 | 0.687828 | 214 | 31.967289 | 31.836525 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.794392 | false | false |
4
|
4a92954123cb22edbd3d6a045d988be6c3a0bd4c
| 566,935,717,470 |
ad1bea82f6ad761ff4e0cdf279b87674667fa79a
|
/Unit1/Sub1.2/VisualCounter.java
|
c3c7f30528806de91993647440ea4becd4072505
|
[] |
no_license
|
Sangs3112/Algorithms
|
https://github.com/Sangs3112/Algorithms
|
5947da9b93d29ced42872209df02965be65f4375
|
ede8a99227f03799f9ad4f7299564b6645524133
|
refs/heads/master
| 2023-02-10T23:27:55.464000 | 2021-01-09T09:23:53 | 2021-01-09T09:23:53 | 321,322,070 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import edu.princeton.cs.algs4.StdDraw;
/**
* Author: Sangs Date:2020.12.22 Function:《算法》P71 1.2.10
* Questiion:编写一个类VisualCounter,支持加一和减一操作。它的构造函数接收两个参数N和max
* 其中N指定了最大操作次数,max指定了计数器的最大绝对值。 作为副作用,用图像显示每次计数器变化后的值
*/
public class VisualCounter{
private final int maxOpt;
private final int maxCount;
private int opt;
private int count;
public VisualCounter(int N, int max){
maxOpt = N;
maxCount = max;
}
public void increment(){
if(opt < maxOpt && Math.abs(count) < maxCount){
opt++;
count++;
}
}
public void decreament(){
if(opt < maxOpt && Math.abs(count) < maxCount){
opt++;
count--;
}
}
public int tally()
{return count;}
public int optTimes()
{return opt;}
public boolean isEnd()
{return opt>=maxOpt || Math.abs(count) >= maxCount;}
public void Draw(){
StdDraw.setXscale(0,maxOpt);
StdDraw.setYscale(-1.0*maxCount, maxCount);
StdDraw.setPenRadius(0.01);
StdDraw.point(opt, count);
}
}
|
UTF-8
|
Java
| 1,257 |
java
|
VisualCounter.java
|
Java
|
[
{
"context": "rt edu.princeton.cs.algs4.StdDraw;\n\n/**\n * Author: Sangs Date:2020.12.22 Function:《算法》P71 1.2.10\n * Questi",
"end": 60,
"score": 0.9832509160041809,
"start": 55,
"tag": "USERNAME",
"value": "Sangs"
}
] | null |
[] |
import edu.princeton.cs.algs4.StdDraw;
/**
* Author: Sangs Date:2020.12.22 Function:《算法》P71 1.2.10
* Questiion:编写一个类VisualCounter,支持加一和减一操作。它的构造函数接收两个参数N和max
* 其中N指定了最大操作次数,max指定了计数器的最大绝对值。 作为副作用,用图像显示每次计数器变化后的值
*/
public class VisualCounter{
private final int maxOpt;
private final int maxCount;
private int opt;
private int count;
public VisualCounter(int N, int max){
maxOpt = N;
maxCount = max;
}
public void increment(){
if(opt < maxOpt && Math.abs(count) < maxCount){
opt++;
count++;
}
}
public void decreament(){
if(opt < maxOpt && Math.abs(count) < maxCount){
opt++;
count--;
}
}
public int tally()
{return count;}
public int optTimes()
{return opt;}
public boolean isEnd()
{return opt>=maxOpt || Math.abs(count) >= maxCount;}
public void Draw(){
StdDraw.setXscale(0,maxOpt);
StdDraw.setYscale(-1.0*maxCount, maxCount);
StdDraw.setPenRadius(0.01);
StdDraw.point(opt, count);
}
}
| 1,257 | 0.590537 | 0.571429 | 48 | 21.895834 | 18.104143 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
4
|
6994cb3da32ac8dbd8663df173d9205126d5e4f1
| 19,413,252,212,870 |
a5cca4a4f0872d62db89653bc4113b81468fe07d
|
/app/src/main/java/embedstock/com/br/embedstock/AutenticacaoActivity.java
|
7c698638d1c1bffd604111746018044013facb67
|
[] |
no_license
|
luizf4/EmbedStock
|
https://github.com/luizf4/EmbedStock
|
bef1063c00549ec99132f60323ac7ae6e4e8a662
|
e29215a9bd9c56eb90fc33021e39c5b5e804e103
|
refs/heads/master
| 2020-07-15T11:19:29.688000 | 2016-11-22T02:18:03 | 2016-11-22T02:18:03 | 73,963,476 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package embedstock.com.br.embedstock;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import embedstock.com.br.embedstock.DB.BDEmbedStock;
import embedstock.com.br.embedstock.model.Usuario;
public class AutenticacaoActivity extends Activity {
//Usuario autenticacao = new Usuario();
private BDEmbedStock dbUsuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autenticacao);
dbUsuario = new BDEmbedStock(this);
}
public void autenticar(View view) {
EditText usuario = (EditText) findViewById(R.id.text_usuario);
EditText senha = (EditText) findViewById(R.id.text_senha);
Usuario user = new Usuario();
user.setUsuario(usuario.getText().toString());
user.setSenha(usuario.getText().toString());
user.setNivel_Acesso("1");
dbUsuario.salvarUsuario(user);
if(dbUsuario.autenticarUsuario(usuario.getText().toString(),
senha.getText().toString()) == true){
Toast.makeText(this, "Usuário " + usuario.getText() +
" Autenticado", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
//limpaCaixas();
finish();
}else{
Toast.makeText(this, "Usuário ou Senha incorreto", Toast.LENGTH_SHORT).show();
limpaCaixas();
}
}
/**
* Método para limpar as EditTexts e focar a caixa "usuário"
*/
public void limpaCaixas(){
((EditText) findViewById(R.id.text_usuario)).setText("");
((EditText) findViewById(R.id.text_senha)).setText("");
findViewById(R.id.text_usuario).requestFocus();
}
}
|
UTF-8
|
Java
| 1,905 |
java
|
AutenticacaoActivity.java
|
Java
|
[
{
"context": "ario.getText().toString());\n user.setSenha(usuario.getText().toString());\n user.setNivel_Aces",
"end": 971,
"score": 0.7152248620986938,
"start": 964,
"tag": "PASSWORD",
"value": "usuario"
}
] | null |
[] |
package embedstock.com.br.embedstock;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import embedstock.com.br.embedstock.DB.BDEmbedStock;
import embedstock.com.br.embedstock.model.Usuario;
public class AutenticacaoActivity extends Activity {
//Usuario autenticacao = new Usuario();
private BDEmbedStock dbUsuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autenticacao);
dbUsuario = new BDEmbedStock(this);
}
public void autenticar(View view) {
EditText usuario = (EditText) findViewById(R.id.text_usuario);
EditText senha = (EditText) findViewById(R.id.text_senha);
Usuario user = new Usuario();
user.setUsuario(usuario.getText().toString());
user.setSenha(<PASSWORD>.getText().toString());
user.setNivel_Acesso("1");
dbUsuario.salvarUsuario(user);
if(dbUsuario.autenticarUsuario(usuario.getText().toString(),
senha.getText().toString()) == true){
Toast.makeText(this, "Usuário " + usuario.getText() +
" Autenticado", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
//limpaCaixas();
finish();
}else{
Toast.makeText(this, "Usuário ou Senha incorreto", Toast.LENGTH_SHORT).show();
limpaCaixas();
}
}
/**
* Método para limpar as EditTexts e focar a caixa "usuário"
*/
public void limpaCaixas(){
((EditText) findViewById(R.id.text_usuario)).setText("");
((EditText) findViewById(R.id.text_senha)).setText("");
findViewById(R.id.text_usuario).requestFocus();
}
}
| 1,908 | 0.64808 | 0.647554 | 66 | 27.80303 | 25.192122 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
4
|
02e7750ae5c45fff7eb420398e1a385128425497
| 9,388,798,542,327 |
3f7703bc159d518afb50e7d1e43ec568f2c2aba4
|
/src/main/java/com/dojopuzzles/chequeporextenso/Centena.java
|
6618dd9e8d5b3b81a16cd6f68188e325aee220f9
|
[] |
no_license
|
j0a0m4/kata-4devs
|
https://github.com/j0a0m4/kata-4devs
|
84a84fca28fd6e52e6182853b74612d6df50a280
|
396dd9dc2f0592eb9e905d4d3aee22692b26f57f
|
refs/heads/master
| 2023-06-06T17:58:58.183000 | 2021-07-15T23:42:36 | 2021-07-15T23:42:36 | 380,592,116 | 6 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dojopuzzles.chequeporextenso;
public enum Centena {
ZERO,
CEM,
DUZENTOS,
TREZENTOS,
QUATROCENTOS,
QUINHENTOS,
SEISCENTOS,
SETECENTOS,
OITOCENTOS,
NOVECENTOS;
public static Centena from(int resto) {
return Centena.values()[resto];
}
}
|
UTF-8
|
Java
| 304 |
java
|
Centena.java
|
Java
|
[] | null |
[] |
package com.dojopuzzles.chequeporextenso;
public enum Centena {
ZERO,
CEM,
DUZENTOS,
TREZENTOS,
QUATROCENTOS,
QUINHENTOS,
SEISCENTOS,
SETECENTOS,
OITOCENTOS,
NOVECENTOS;
public static Centena from(int resto) {
return Centena.values()[resto];
}
}
| 304 | 0.641447 | 0.641447 | 18 | 15.888889 | 12.688091 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
4
|
308db3c21662a8539f5383330d77890dc5c21132
| 24,086,176,630,254 |
00b405c6ac35a9cc2d12c13d15ef2dd6c73e1140
|
/src/main/java/com/vn/ntt/enums/PokeType.java
|
e1a774cdbe770028e4b55e21da9c47b3c75c8e88
|
[] |
no_license
|
luongbangnguyen/hackathon-ntt
|
https://github.com/luongbangnguyen/hackathon-ntt
|
a7de88a876f80a7ec3bcb8e50f04963deca86e4d
|
e2400bf993a9c9379e30712eb84d7d645d2021ab
|
refs/heads/master
| 2021-01-10T07:42:59.107000 | 2016-04-19T06:31:23 | 2016-04-19T06:31:23 | 52,704,024 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vn.ntt.enums;
/**
* Created by bangnl on 3/9/16.
*/
public enum PokeType {
POKE(1), ACCEPT(2), CANCEL(3);
PokeType(int num){
this.num = num;
}
private int num;
public int getNum() {
return num;
}
}
|
UTF-8
|
Java
| 254 |
java
|
PokeType.java
|
Java
|
[
{
"context": "package com.vn.ntt.enums;\n\n/**\n * Created by bangnl on 3/9/16.\n */\npublic enum PokeType {\n POKE(1)",
"end": 51,
"score": 0.9995985627174377,
"start": 45,
"tag": "USERNAME",
"value": "bangnl"
}
] | null |
[] |
package com.vn.ntt.enums;
/**
* Created by bangnl on 3/9/16.
*/
public enum PokeType {
POKE(1), ACCEPT(2), CANCEL(3);
PokeType(int num){
this.num = num;
}
private int num;
public int getNum() {
return num;
}
}
| 254 | 0.547244 | 0.519685 | 16 | 14.875 | 11.602128 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false |
4
|
c053b80ccac1b28a0788f5cbd48ce1fc58ba0b0d
| 24,343,874,670,421 |
3155cb40d6f93931616dc9adc639865356234cef
|
/Lesson 23/Mezo Playing Zoma/src/app/App.java
|
59346711ec73b8a36e4b03c30809df8cfb0571c9
|
[] |
no_license
|
feyselmubarek/Introduction_to_CompetitiveProgramming
|
https://github.com/feyselmubarek/Introduction_to_CompetitiveProgramming
|
548184e4731b5b0789b00b9280bdc84640dc7d5d
|
f4b7bb5287ae8636148f24cc301a64596721de42
|
refs/heads/master
| 2020-09-13T07:14:14.745000 | 2020-04-04T11:30:06 | 2020-04-04T11:30:06 | 222,690,977 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package app;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int noOfCommands = scanner.nextInt();
scanner.nextLine();
scanner.nextLine();
System.out.println(noOfCommands + 1);
scanner.close();
}
}
|
UTF-8
|
Java
| 354 |
java
|
App.java
|
Java
|
[] | null |
[] |
package app;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int noOfCommands = scanner.nextInt();
scanner.nextLine();
scanner.nextLine();
System.out.println(noOfCommands + 1);
scanner.close();
}
}
| 354 | 0.627119 | 0.624294 | 16 | 21.1875 | 19.593426 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
4
|
0889c796ca1657f580c716e608981f50760f69ab
| 30,820,685,321,153 |
e086fd92289d00d8a042ce8bd8f13e7878d40f16
|
/src/main/java/dev/themighty/tenantassociation/services/MeetingService.java
|
1a94102fc726cda94ca83f51aaa896fa9d734e38
|
[] |
no_license
|
dusanstankovic/tenant-association
|
https://github.com/dusanstankovic/tenant-association
|
09be71f23504c649edb2259d17025039f9e86b34
|
d47381589425a98caedb3c714454c229dbbfb089
|
refs/heads/master
| 2022-04-17T09:05:30.810000 | 2020-04-14T08:42:19 | 2020-04-14T08:42:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dev.themighty.tenantassociation.services;
import dev.themighty.tenantassociation.model.Meeting;
public interface MeetingService extends CrudService<Meeting, Long> {
// TODO: Implement MeetingService
}
|
UTF-8
|
Java
| 216 |
java
|
MeetingService.java
|
Java
|
[] | null |
[] |
package dev.themighty.tenantassociation.services;
import dev.themighty.tenantassociation.model.Meeting;
public interface MeetingService extends CrudService<Meeting, Long> {
// TODO: Implement MeetingService
}
| 216 | 0.814815 | 0.814815 | 8 | 26 | 26.916538 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
4
|
9918abb408c3d8fa91db6efb90186adba8019dc3
| 13,340,168,443,312 |
87bb31b68f52ed41332015f4355b74d3f05a08b7
|
/src/test/java/com/tenaciouspanda/jobstretchtest/SessionTester.java
|
4fb311487d435c5a8263772f189a7eec98a29cf2
|
[] |
no_license
|
TenaciousPanda/job-stretch
|
https://github.com/TenaciousPanda/job-stretch
|
addd6d90ec45555fe4d0ed233c64fe6344ff7df4
|
a07a33180130a248886714702f6341503a3ffebd
|
refs/heads/master
| 2021-01-12T13:31:23.454000 | 2016-12-13T20:01:23 | 2016-12-13T20:01:23 | 69,375,335 | 0 | 5 | null | false | 2016-12-13T20:01:23 | 2016-09-27T16:13:05 | 2016-10-04T02:13:36 | 2016-12-13T20:01:23 | 768 | 0 | 3 | 1 |
Java
| 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 com.tenaciouspanda.jobstretchtest;
import com.tenaciouspanda.jobstretch.Session;
import com.tenaciouspanda.jobstretch.database.Business;
import com.tenaciouspanda.jobstretch.database.User;
/**
*
* @author Simon
*/
public class SessionTester {
public void testAll(){
testAuthentication();
testSearchUnconnectedUser();
testSearchConnectedUser();
testSearchBusiness();
}
public void testAuthentication(){
Session s = new Session();
if(s.isAuthenticated())
throw new IllegalStateException("Session cannot be authenticated initially");
s.authenticate("test", "test");
if(!s.isAuthenticated())
throw new IllegalStateException("Session failed to authenticate");
s.logout();
if(s.isAuthenticated())
throw new IllegalStateException("Session failed to logout");
}
public void testSearchUnconnectedUser(){
Session s = new Session();
s.authenticate("test", "test");
User[] users = s.searchUnconnectedUser("","");
System.out.println("UNCONNECTED USERS");
for(User u : users){
System.out.println(u);
}
}
public void testSearchConnectedUser(){
Session s = new Session();
s.authenticate("test", "test");
User[] users = s.searchConnectedUser("est");
System.out.println("CONNECTED USERS");
for(User u : users){
System.out.println(u);
}
}
public void testSearchBusiness(){
Session s = new Session();
s.authenticate("test", "test");
Business[] businesses = s.searchBusinesses("");
System.out.println("BUSINESSES");
for(Business b : businesses){
System.out.println(b);
}
}
}
|
UTF-8
|
Java
| 2,081 |
java
|
SessionTester.java
|
Java
|
[
{
"context": "a.jobstretch.database.User;\r\n\r\n/**\r\n *\r\n * @author Simon\r\n */\r\npublic class SessionTester {\r\n public void",
"end": 422,
"score": 0.8323737978935242,
"start": 417,
"tag": "NAME",
"value": "Simon"
}
] | 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 com.tenaciouspanda.jobstretchtest;
import com.tenaciouspanda.jobstretch.Session;
import com.tenaciouspanda.jobstretch.database.Business;
import com.tenaciouspanda.jobstretch.database.User;
/**
*
* @author Simon
*/
public class SessionTester {
public void testAll(){
testAuthentication();
testSearchUnconnectedUser();
testSearchConnectedUser();
testSearchBusiness();
}
public void testAuthentication(){
Session s = new Session();
if(s.isAuthenticated())
throw new IllegalStateException("Session cannot be authenticated initially");
s.authenticate("test", "test");
if(!s.isAuthenticated())
throw new IllegalStateException("Session failed to authenticate");
s.logout();
if(s.isAuthenticated())
throw new IllegalStateException("Session failed to logout");
}
public void testSearchUnconnectedUser(){
Session s = new Session();
s.authenticate("test", "test");
User[] users = s.searchUnconnectedUser("","");
System.out.println("UNCONNECTED USERS");
for(User u : users){
System.out.println(u);
}
}
public void testSearchConnectedUser(){
Session s = new Session();
s.authenticate("test", "test");
User[] users = s.searchConnectedUser("est");
System.out.println("CONNECTED USERS");
for(User u : users){
System.out.println(u);
}
}
public void testSearchBusiness(){
Session s = new Session();
s.authenticate("test", "test");
Business[] businesses = s.searchBusinesses("");
System.out.println("BUSINESSES");
for(Business b : businesses){
System.out.println(b);
}
}
}
| 2,081 | 0.597309 | 0.597309 | 65 | 30.015385 | 21.160553 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569231 | false | false |
4
|
53c6f6adbea361f838fa1835ff251b9277f159d2
| 22,978,075,097,412 |
7d06a8f3e172c748c95bda8a8ecc55bc0d8e7a99
|
/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java
|
8f151119de78f88529fce9bd5f8ab9c43d6e36fa
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
moparisthebest/beehive
|
https://github.com/moparisthebest/beehive
|
6810bfa1b54d999ad925c7457ff938a449136029
|
b89fd16d938d5f82a6c31e88ca04d328ec33be3e
|
refs/heads/master
| 2023-08-25T09:03:07.733000 | 2020-11-19T06:47:34 | 2020-11-27T01:11:02 | 19,042,261 | 1 | 1 |
Apache-2.0
| false | 2022-06-29T19:28:12 | 2014-04-22T19:03:37 | 2020-11-27T01:15:37 | 2022-06-29T19:28:11 | 26,724 | 1 | 1 | 3 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Header:$
*/
package org.apache.beehive.netui.pageflow;
import org.apache.beehive.netui.core.urls.FreezableMutableURI;
import org.apache.beehive.netui.core.urls.MutableURI;
import org.apache.beehive.netui.core.urls.URIContext;
import org.apache.beehive.netui.core.urls.URLRewriterService;
import org.apache.beehive.netui.core.urls.URLType;
import org.apache.beehive.netui.core.urltemplates.URLTemplatesFactory;
import org.apache.beehive.netui.pageflow.internal.ActionResultImpl;
import org.apache.beehive.netui.pageflow.internal.InternalUtils;
import org.apache.beehive.netui.pageflow.internal.InternalConstants;
import org.apache.beehive.netui.pageflow.internal.AdapterManager;
import org.apache.beehive.netui.pageflow.internal.PageFlowRequestWrapper;
import org.apache.beehive.netui.pageflow.internal.URIContextFactory;
import org.apache.beehive.netui.pageflow.internal.DefaultURLTemplatesFactory;
import org.apache.beehive.netui.pageflow.scoping.ScopedRequest;
import org.apache.beehive.netui.pageflow.scoping.ScopedResponse;
import org.apache.beehive.netui.pageflow.scoping.ScopedServletUtils;
import org.apache.beehive.netui.pageflow.handler.StorageHandler;
import org.apache.beehive.netui.pageflow.handler.Handlers;
import org.apache.beehive.netui.util.internal.InternalStringBuilder;
import org.apache.beehive.netui.util.internal.FileUtils;
import org.apache.beehive.netui.util.internal.ServletUtils;
import org.apache.beehive.netui.util.internal.concurrent.InternalConcurrentHashMap;
import org.apache.beehive.netui.util.config.ConfigUtil;
import org.apache.beehive.netui.util.config.bean.UrlConfig;
import org.apache.beehive.netui.util.logging.Logger;
import org.apache.beehive.netui.script.common.ImplicitObjectUtil;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.upload.MultipartRequestWrapper;
import org.apache.struts.util.RequestUtils;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintStream;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Utility methods related to Page Flow.
*/
public class PageFlowUtils
implements PageFlowConstants, InternalConstants
{
private static final Logger _log = Logger.getInstance( PageFlowUtils.class );
private static final String PREVENT_CACHE_ATTR = InternalConstants.ATTR_PREFIX + "preventCache";
private static final String ACTION_URI_ATTR = ATTR_PREFIX + "_actionURI";
private static final int PAGEFLOW_EXTENSION_LEN = PAGEFLOW_EXTENSION.length();
private static final String DEFAULT_AUTORESOLVE_EXTENSIONS[] = new String[]{ ACTION_EXTENSION, PAGEFLOW_EXTENSION };
/** Map of Struts module prefix to Map of form-type-name to form-name. */
private static Map/*< String, Map< String, List< String > > >*/ _formNameMaps =
new InternalConcurrentHashMap/*< String, Map< String, List< String > > >*/();
/**
* Get the Struts module path for a URI. This is the parent directory, relative to the web
* application root, of the file referenced by the URI.
*
* @param request the current HttpServletRequest.
* @param requestURI the URI for which to get the Struts module path.
*/
public static String getModulePath( HttpServletRequest request, String requestURI )
{
return getModulePathForRelativeURI( getRelativeURI( request, requestURI, null ) );
}
/**
* Get the Struts module path for the current request URI. This is the parent directory,
* relative to the web application root, of the file referenced by the request URI.
*
* @param request the current HttpServletRequest.
*/
public static String getModulePath( HttpServletRequest request )
{
return getModulePathForRelativeURI( InternalUtils.getDecodedServletPath( request ) );
}
/**
* Get the Struts module path for a URI that is relative to the web application root.
*
* @param uri the URI for which to get the module path.
*/
public static String getModulePathForRelativeURI( String uri )
{
if ( uri == null ) return null;
assert uri.length() > 0;
assert uri.charAt( 0 ) == '/' : uri;
// Strip off the actual page name (e.g., some_page.jsp)
int slash = uri.lastIndexOf( '/' );
uri = uri.substring( 0, slash );
return uri;
}
/**
* Get the request URI, relative to the URI of the given PageFlowController.
*
* @param request the current HttpServletRequest.
* @param relativeTo a PageFlowController to which the returned URI should be relative, or
* <code>null</code> if the returned URI should be relative to the webapp root.
*/
public static String getRelativeURI( HttpServletRequest request, PageFlowController relativeTo )
{
if ( relativeTo == null ) return InternalUtils.getDecodedServletPath( request );
return getRelativeURI( request, InternalUtils.getDecodedURI( request ), relativeTo );
}
/**
* Get a URI relative to the URI of the given PageFlowController.
*
* @param request the current HttpServletRequest.
* @param uri the URI which should be made relative.
* @param relativeTo a PageFlowController to which the returned URI should be relative, or
* <code>null</code> if the returned URI should be relative to the webapp root.
*/
public static String getRelativeURI( HttpServletRequest request, String uri, PageFlowController relativeTo )
{
String contextPath = request.getContextPath();
if ( relativeTo != null ) contextPath += relativeTo.getModulePath();
int overlap = uri.indexOf( contextPath + '/' );
if ( overlap == -1 ) return null;
return uri.substring( overlap + contextPath.length() );
}
/**
* Get a URI for the "begin" action in the PageFlowController associated with the given
* request URI.
*
* @return a String that is the URI for the "begin" action in the PageFlowController associated
* with the given request URI.
*/
public static String getBeginActionURI( String requestURI )
{
// Translate this to a request for the begin action ("begin.do") for this PageFlowController.
InternalStringBuilder retVal = new InternalStringBuilder();
int lastSlash = requestURI.lastIndexOf( '/' );
if ( lastSlash != -1 )
{
retVal.append( requestURI.substring( 0, lastSlash ) );
}
retVal.append( '/' ).append( BEGIN_ACTION_NAME ).append( ACTION_EXTENSION );
return retVal.toString();
}
/**
* Get the stack of nested page flows for the current user session. Create and store an empty
* stack if none exists.
*
* @deprecated Use {@link PageFlowStack#get(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest
* @return a {@link PageFlowStack} of nested page flows ({@link PageFlowController}s) for the current user session.
*/
public static Stack getPageFlowStack( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return PageFlowStack.get( request, servletContext, true ).getLegacyStack();
}
/**
* Destroys the stack of {@link PageFlowController}s that have invoked nested page flows.
*
* @deprecated Use {@link PageFlowStack#destroy} instead.
*
* @param request the current HttpServletRequest.
*/
public static void destroyPageFlowStack( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
PageFlowStack.get( request, servletContext ).destroy( request );
}
/**
* Get the {@link PageFlowController} that is nesting the current one.
* @deprecated Use {@link #getNestingPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest.
* @return the nesting {@link PageFlowController}, or <code>null</code> if the current one
* is not being nested.
*/
public static PageFlowController getNestingPageFlow( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getNestingPageFlow( request, servletContext );
}
/**
* Get the {@link PageFlowController} that is nesting the current one.
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the nesting {@link PageFlowController}, or <code>null</code> if the current one
* is not being nested.
*/
public static PageFlowController getNestingPageFlow( HttpServletRequest request, ServletContext servletContext )
{
PageFlowStack jpfStack = PageFlowStack.get( request, servletContext, false );
if ( jpfStack != null && ! jpfStack.isEmpty() )
{
PageFlowController top = jpfStack.peek().getPageFlow();
return top;
}
return null;
}
/**
* Get the current {@link PageFlowController}.
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the current PageFlowController from the user session, or <code>null</code> if there is none.
*/
public static PageFlowController getCurrentPageFlow( HttpServletRequest request, ServletContext servletContext )
{
ActionResolver cur = getCurrentActionResolver( request, servletContext );
if (cur != null && cur.isPageFlow()) {
PageFlowController pfc = (PageFlowController) cur;
pfc.reinitializeIfNecessary(request, null, servletContext);
return pfc;
}
return null;
}
/**
/**
* Get the current PageFlowController.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest.
* @return the current PageFlowController from the user session, or <code>null</code>
* if there is none.
*/
public static PageFlowController getCurrentPageFlow( HttpServletRequest request )
{
ActionResolver cur = getCurrentActionResolver( request );
return cur != null && cur.isPageFlow() ? ( PageFlowController ) cur : null;
}
/**
* Get the current ActionResolver.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @return the current ActionResolver from the user session, or <code>null</code> if there is none.
*/
public static ActionResolver getCurrentActionResolver( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getCurrentActionResolver( request, servletContext );
}
/**
* Get the current ActionResolver.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the current ActionResolver from the user session, or <code>null</code> if there is none.
*/
public static ActionResolver getCurrentActionResolver( HttpServletRequest request, ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
//
// First see if the current page flow is a long-lived, which is stored in its own attribute.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath = ( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( currentLongLivedModulePath != null )
{
return getLongLivedPageFlow( currentLongLivedModulePath, unwrappedRequest );
}
else
{
String currentJpfAttrName = ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
return ( ActionResolver ) sh.getAttribute( rc, currentJpfAttrName );
}
}
/**
* Get the current {@link GlobalApp} instance.
*
* @deprecated Use {@link #getSharedFlow} instead.
* @param request the current HttpServletRequest.
* @return the current {@link GlobalApp} from the user session, or <code>null</code> if none
* exists.
*/
public static GlobalApp getGlobalApp( HttpServletRequest request )
{
SharedFlowController sf = getSharedFlow( InternalConstants.GLOBALAPP_CLASSNAME, request );
return sf instanceof GlobalApp ? ( GlobalApp ) sf : null;
}
/**
* Get the a map of shared flow name to shared flow instance, based on the names defined in the
* {@link org.apache.beehive.netui.pageflow.annotations.Jpf.Controller#sharedFlowRefs sharedFlowRefs} attribute
* of the {@link org.apache.beehive.netui.pageflow.annotations.Jpf.Controller @Jpf.Controller} annotation on the
* <strong>current page flow</strong>.
*
* @param request the current HttpServletRequest, which is used to determine the current page flow.
* @return a Map of shared flow name (string) to shared flow instance ({@link SharedFlowController}).
*/
public static Map/*< String, SharedFlowController >*/ getSharedFlows( HttpServletRequest request )
{
Map/*< String, SharedFlowController >*/ sharedFlows = ImplicitObjectUtil.getSharedFlow( request );
return sharedFlows != null ? sharedFlows : Collections.EMPTY_MAP;
}
/**
* Get the shared flow with the given class name.
* @deprecated Use {@link #getSharedFlow(String, HttpServletRequest, ServletContext)} instead.
*
* @param sharedFlowClassName the class name of the shared flow to retrieve.
* @param request the current HttpServletRequest.
* @return the {@link SharedFlowController} of the given class name which is stored in the user session.
*/
public static SharedFlowController getSharedFlow( String sharedFlowClassName, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getSharedFlow( sharedFlowClassName, request, servletContext );
}
/**
* Get the shared flow with the given class name.
*
* @param sharedFlowClassName the class name of the shared flow to retrieve.
* @param request the current HttpServletRequest.
* @return the {@link SharedFlowController} of the given class name which is stored in the user session.
*/
public static SharedFlowController getSharedFlow( String sharedFlowClassName, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX
+ sharedFlowClassName, request);
SharedFlowController sf = (SharedFlowController) sh.getAttribute(rc, attrName);
if (sf != null) {
sf.reinitializeIfNecessary(request, null, servletContext);
}
return sf;
}
/**
* Destroy the current {@link SharedFlowController} of the given class name.
* @deprecated Use {@link #removeSharedFlow(String, HttpServletRequest, ServletContext)} instead.
* @param sharedFlowClassName the class name of the current SharedFlowController to destroy.
* @param request the current HttpServletRequest.
*/
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
removeSharedFlow( sharedFlowClassName, request, servletContext );
}
/**
* Destroy the current {@link SharedFlowController} of the given class name.
* @param sharedFlowClassName the class name of the current SharedFlowController to destroy.
* @param request the current HttpServletRequest.
*/
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX
+ sharedFlowClassName, request);
sh.removeAttribute(rc, attrName);
}
/**
* Remove a "long-lived" page flow from the session. Once it is created, a long-lived page flow
* is never removed from the session unless this method or {@link PageFlowController#remove} is
* called. Navigating to another page flow hides the current long-lived controller, but does not
* remove it.
* @deprecated Use {@link #removeLongLivedPageFlow(String, HttpServletRequest, ServletContext)} instead.
*/
public static void removeLongLivedPageFlow( String modulePath, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
removeLongLivedPageFlow( modulePath, request, servletContext );
}
/**
* Remove a "long-lived" page flow from the session. Once it is created, a long-lived page flow
* is never removed from the session unless this method or {@link PageFlowController#remove} is
* called. Navigating to another page flow hides the current long-lived controller, but does not
* remove it.
*/
public static void removeLongLivedPageFlow( String modulePath, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = InternalUtils.getLongLivedFlowAttr( modulePath );
attrName = ScopedServletUtils.getScopedSessionAttrName( attrName, unwrappedRequest );
sh.removeAttribute( rc, attrName );
//
// Now, if the current page flow is long-lived, remove the reference.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath =
( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( modulePath.equals( currentLongLivedModulePath ) )
{
sh.removeAttribute( rc, currentLongLivedAttrName );
}
}
/**
* Get the long-lived page flow instance associated with the given module (directory) path.
* @deprecated Use {@link #getLongLivedPageFlow(String, HttpServletRequest, ServletContext)} instead.
*
* @param modulePath the webapp-relative path to the directory containing the long-lived page flow.
* @param request the current HttpServletRequest.
* @return the long-lived page flow instance associated with the given module, or <code>null</code> if none is found.
*/
public static PageFlowController getLongLivedPageFlow( String modulePath, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getLongLivedPageFlow( modulePath, request, servletContext );
}
/**
* Get the long-lived page flow instance associated with the given module (directory) path.
*
* @param modulePath the webapp-relative path to the directory containing the long-lived page flow.
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the long-lived page flow instance associated with the given module, or <code>null</code> if none is found.
*/
public static PageFlowController getLongLivedPageFlow( String modulePath, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = InternalUtils.getLongLivedFlowAttr( modulePath );
attrName = ScopedServletUtils.getScopedSessionAttrName( attrName, unwrappedRequest );
PageFlowController retVal = ( PageFlowController ) sh.getAttribute( rc, attrName );
return retVal;
}
/**
* Make any form beans in the given {@link Forward} object available as attributets in the
* request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param fwd the {@link Forward} object that contains the ActionForm instances to be
* made available in the request/session (as appropriate).
* @param request the current HttpServletRequest.
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
*/
public static void setOutputForms( ActionMapping mapping, Forward fwd, HttpServletRequest request,
boolean overwrite )
{
if ( fwd == null ) return;
//
// *If* there is a target action mapping, set output forms for it.
//
if ( mapping != null ) setOutputForms( mapping, fwd.getOutputForms(), request, overwrite );
InternalUtils.setForwardedFormBean( request, fwd.getFirstOutputForm( request ) );
}
/**
* Make any form beans in the given {@link Forward} object available as attributets in the
* request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param fwd the {@link Forward} object that contains the ActionForm instances to be
* made available in the request/session (as appropriate).
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, Forward fwd, HttpServletRequest request )
{
if ( fwd == null )
{
return;
}
if ( mapping != null )
{
setOutputForms( mapping, fwd.getOutputForms(), request );
}
InternalUtils.setForwardedFormBean( request, fwd.getFirstOutputForm( request ) );
}
/**
* Make a set of form beans available as attributets in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param outputForms an array of ActionForm instances to be made available in the
* request/session (as appropriate).
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms,
HttpServletRequest request )
{
setOutputForms( mapping, outputForms, request, true );
}
/**
* Make a set of form beans available as attributets in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param outputForms an array of ActionForm instances to be made available in the
* request/session (as appropriate).
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms,
HttpServletRequest request, boolean overwrite )
{
try
{
//
// Now set any output forms in the request or session, as appropriate.
//
assert mapping.getScope() == null
|| mapping.getScope().equals( "request" )
|| mapping.getScope().equals( "session" )
: mapping.getScope();
for ( int i = 0; i < outputForms.length; ++i )
{
setOutputForm( mapping, outputForms[i], request, overwrite );
}
}
catch ( Exception e )
{
_log.error( "Error while setting Struts form-beans", e );
}
}
private static List/*< String >*/ getFormNamesFromModuleConfig( String formBeanClassName, ModuleConfig moduleConfig )
{
String modulePrefix = moduleConfig.getPrefix();
Map/*< String, List< String > >*/ formNameMap = ( Map ) _formNameMaps.get( modulePrefix ); // map of form-type-name to form-name
if ( formNameMap == null )
{
formNameMap = new HashMap/*< String, List< String > >*/();
FormBeanConfig[] formBeans = moduleConfig.findFormBeanConfigs();
for ( int j = 0; j < formBeans.length; ++j )
{
assert formBeans[j] != null;
String formBeanType = InternalUtils.getFormBeanType( formBeans[j] );
List/*< String >*/ formBeanNames = ( List ) formNameMap.get( formBeanType );
if ( formBeanNames == null )
{
formBeanNames = new ArrayList/*< String >*/();
formNameMap.put( formBeanType, formBeanNames );
}
formBeanNames.add( formBeans[j].getName() );
}
_formNameMaps.put( modulePrefix, formNameMap );
}
return ( List ) formNameMap.get( formBeanClassName );
}
/**
* Make a form bean available as an attributet in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param form an ActionForm instance to be made available in the request/session
* (as appropriate).
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
* @param request the current HttpServletRequest.
*/
public static void setOutputForm( ActionMapping mapping, ActionForm form,
HttpServletRequest request, boolean overwrite )
{
if ( form != null )
{
ModuleConfig moduleConfig = mapping.getModuleConfig();
Class formClass = InternalUtils.unwrapFormBean( form ).getClass();
//
// Get the names of *all* form beans of the desired type, and blast out this instance under all those names.
//
List formNames = getFormNamesFromModuleConfig( formClass.getName(), moduleConfig );
List additionalFormNames = null;
//
// formNames is a statically-scoped list. Below, we create a dynamic list of form names that correspond
// to *implemented interfaces* of the given form bean class.
//
Class[] interfaces = formClass.getInterfaces();
for ( int i = 0; i < interfaces.length; i++ )
{
Class formInterface = interfaces[i];
List toAdd = getFormNamesFromModuleConfig( formInterface.getName(), moduleConfig );
if ( toAdd != null )
{
if ( additionalFormNames == null ) additionalFormNames = new ArrayList();
additionalFormNames.addAll( toAdd );
}
}
// Do the same for all superclasses of the form bean class.
for (Class i = formClass.getSuperclass(); i != null; i = i.getSuperclass()) {
List toAdd = getFormNamesFromModuleConfig( i.getName(), moduleConfig );
if ( toAdd != null )
{
if ( additionalFormNames == null ) additionalFormNames = new ArrayList();
additionalFormNames.addAll( toAdd );
}
}
if ( formNames == null && additionalFormNames == null )
{
String formName = generateFormBeanName( formClass, request );
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
else
{
if ( formNames != null )
{
for ( Iterator i = formNames.iterator(); i.hasNext(); )
{
String formName = ( String ) i.next();
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
}
if ( additionalFormNames != null )
{
for ( Iterator i = additionalFormNames.iterator(); i.hasNext(); )
{
String formName = ( String ) i.next();
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
}
}
}
}
/**
* Get the name for the type of a ActionForm instance. Use a name looked up from
* the current Struts module, or, if none is found, create one.
*
* @param formInstance the ActionForm instance whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
public static String getFormBeanName( ActionForm formInstance, HttpServletRequest request )
{
return getFormBeanName( formInstance.getClass(), request );
}
/**
* Get the name for an ActionForm type. Use a name looked up from the current Struts module, or,
* if none is found, create one.
*
* @param formBeanClass the ActionForm-derived class whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
public static String getFormBeanName( Class formBeanClass, HttpServletRequest request )
{
ModuleConfig moduleConfig = RequestUtils.getRequestModuleConfig( request );
List/*< String >*/ names = getFormNamesFromModuleConfig( formBeanClass.getName(), moduleConfig );
if ( names != null )
{
assert names.size() > 0; // getFormNamesFromModuleConfig returns null or a nonempty list
return ( String ) names.get( 0 );
}
return generateFormBeanName( formBeanClass, request );
}
/**
* Create the name for a form bean type.
*
* @param formBeanClass the class whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
private static String generateFormBeanName( Class formBeanClass, HttpServletRequest request )
{
ModuleConfig moduleConfig = RequestUtils.getRequestModuleConfig( request );
String formBeanClassName = formBeanClass.getName();
//
// A form-bean wasn't found for this type, so we'll create a name. First try and create
// name that is a camelcased version of the classname without all of its package/outer-class
// qualifiers. If one with that name already exists, munge the fully-qualified classname.
//
String formType = formBeanClassName;
int lastQualifier = formType.lastIndexOf( '$' );
if ( lastQualifier == -1 )
{
lastQualifier = formType.lastIndexOf( '.' );
}
String formName = formType.substring( lastQualifier + 1 );
formName = Character.toLowerCase( formName.charAt( 0 ) ) + formName.substring( 1 );
if ( moduleConfig.findFormBeanConfig( formName ) != null )
{
formName = formType.replace( '.', '_' ).replace( '$', '_' );
assert moduleConfig.findFormBeanConfig( formName ) == null : formName;
}
return formName;
}
/**
* Get the class name of a {@link PageFlowController}, given the URI to it.
*
* @param uri the URI to the {@link PageFlowController}, which should be relative to the
* web application root (i.e., it should not include the context path).
*/
public static String getPageFlowClassName( String uri )
{
assert uri != null;
assert uri.length() > 0;
if ( uri.charAt( 0 ) == '/' ) uri = uri.substring( 1 );
assert FileUtils.osSensitiveEndsWith( uri, PAGEFLOW_EXTENSION ) : uri;
if ( FileUtils.osSensitiveEndsWith( uri, PAGEFLOW_EXTENSION ) )
{
uri = uri.substring( 0, uri.length() - PAGEFLOW_EXTENSION_LEN );
}
return uri.replace( '/', '.' );
}
/**
* Get the class name of a {@link PageFlowController}, given the URI to it.
*
* @deprecated Use {@link #getPageFlowClassName(String)} instead.
*
* @param uri the URI to the {@link PageFlowController}, which should be relative to the
* web application root (i.e., it should not include the context path).
*/
public static String getJpfClassName( String uri )
{
return getPageFlowClassName( uri );
}
/**
* Get the URI for a {@link PageFlowController}, given its class name.
*
* @param className the name of the {@link PageFlowController} class.
* @return a String that is the URI for the {@link PageFlowController}, relative to the web
* application root (i.e., not including the context path).
*/
public static String getPageFlowURI( String className )
{
return '/' + className.replace( '.', '/' ) + PAGEFLOW_EXTENSION;
}
/**
* @deprecated Use {@link PageFlowActionServlet#getModuleConfPath} instead.
*
* Get the path to the Struts module configration file (e.g.,
* "/WEB-INF/classes/_pageflow/struts-config-someModule") for a given module
* path (e.g., "someModule"), according to the PageFlow convention.
*
* @param modulePath the Struts module path.
* @return a String that is the path to the Struts configuration file, relative to the
* web application root.
*/
public static String getModuleConfPath( String modulePath )
{
return new PageFlowActionServlet.DefaultModuleConfigLocator().getModuleConfigPath( modulePath );
}
/**
* Get the most recent action URI that was processed by {@link FlowController#execute}.
*
* @param request the current ServletRequest.
* @return a String that is the most recent action URI. This is only valid during a request
* that has been forwarded from the action URI.
*/
public static String getActionURI( ServletRequest request )
{
return ( String ) request.getAttribute( ACTION_URI_ATTR );
}
/**
* Sets the most recent action URI that was processed by {@link FlowController#execute}.
*/
static void setActionURI( HttpServletRequest request )
{
request.setAttribute( ACTION_URI_ATTR, InternalUtils.getDecodedURI( request ) );
}
/**
* Tell whether a web application resource requires a secure transport protocol. This is
* determined from web.xml; for example, the following block specifies that all resources under
* /login require a secure transport protocol.
* <pre>
* <security-constraint>
* <web-resource-collection>
* <web-resource-name>Secure PageFlow - begin</web-resource-name>
* <url-pattern>/login/*</url-pattern>
* </web-resource-collection>
* <user-data-constraint>
* <transport-guarantee>CONFIDENTIAL</transport-guarantee>
* </user-data-constraint>
* </security-constraint>
* </pre>
*
* @param uri a webapp-relative URI for a resource. There must not be query parameters or a scheme
* on the URI.
* @param request the current request.
* @return <code>Boolean.TRUE</code> if a transport-guarantee of <code>CONFIDENTIAL</code> or
* <code>INTEGRAL</code> is associated with the given resource; <code>Boolean.FALSE</code>
* a transport-guarantee of <code>NONE</code> is associated with the given resource; or
* <code>null</code> if there is no transport-guarantee associated with the given resource.
*/
public static SecurityProtocol getSecurityProtocol( String uri, ServletContext servletContext,
HttpServletRequest request )
{
return AdapterManager.getServletContainerAdapter( servletContext ).getSecurityProtocol( uri, request );
}
/**
* @deprecated Use {@link #getSecurityProtocol(String, ServletContext, HttpServletRequest)} instead.
*/
public static Boolean isSecureResource( String uri, ServletContext context )
{
// TODO: once DefaultServletContainerAdapter has this functionality, delegate to it.
return null;
}
/**
* Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag.
* The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context.
*
* @deprecated Use {@link #addActionOutput} instead.
* @param name the name of the action output.
* @param value the value of the action output.
* @param request the current ServletRequest.
*/
public static void addPageInput( String name, Object value, ServletRequest request )
{
addActionOutput( name, value, request );
}
/**
* Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag.
* The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context.
*
* @param name the name of the action output.
* @param value the value of the action output.
* @param request the current ServletRequest.
*/
public static void addActionOutput( String name, Object value, ServletRequest request )
{
Map map = InternalUtils.getActionOutputMap( request, true );
if ( map.containsKey( name ) )
{
if ( _log.isWarnEnabled() )
{
_log.warn( "Overwriting action output\"" + name + "\"." );
}
}
map.put( name, value );
}
/**
* Get a named action output that was registered in the current request.
*
* @deprecated Use {@link #getActionOutput} instead.
* @param name the name of the action output.
* @param request the current ServletRequest
* @see #addActionOutput
*/
public static Object getPageInput( String name, ServletRequest request )
{
return getActionOutput( name, request );
}
/**
* Get a named action output that was registered in the current request.
*
* @param name the name of the action output.
* @param request the current ServletRequest
* @see #addActionOutput
*/
public static Object getActionOutput( String name, ServletRequest request )
{
Map map = InternalUtils.getActionOutputMap( request, false );
return map != null ? map.get( name ) : null;
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param messageArgs an array of arguments for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, Object[] messageArgs,
ServletRequest request )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param messageArg an argument for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, Object messageArg,
ServletRequest request )
{
addActionError( request, propertyName, messageKey, new Object[]{ messageArg } );
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, ServletRequest request )
{
addActionError( request, propertyName, messageKey );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArgs zero or more arguments to the message.
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object[] messageArgs )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, null ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg an argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg )
{
Object[] messageArgs = new Object[]{ messageArg };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg1 the first argument to the message
* @param messageArg2 the second argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg1, Object messageArg2 )
{
Object[] messageArgs = new Object[]{ messageArg1, messageArg2 };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg1 the first argument to the message
* @param messageArg2 the second argument to the message
* @param messageArg3 the third argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg1, Object messageArg2, Object messageArg3 )
{
Object[] messageArgs = new Object[]{ messageArg1, messageArg2, messageArg3 };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message as an expression that will be evaluated and shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param expression the JSP 2.0-style expression (e.g., <code>${pageFlow.myProperty}</code>) or literal string
* that will be used as the message.
* @param messageArgs zero or more arguments to the message.
*/
public static void addActionErrorExpression( HttpServletRequest request, String propertyName, String expression,
Object[] messageArgs )
{
ExpressionMessage msg = new ExpressionMessage( expression, messageArgs );
InternalUtils.addActionError( propertyName, msg, request );
}
/**
* Resolve the given action to a URI by running an entire request-processing cycle on the given ScopedRequest
* and ScopedResponse.
* @exclude
*
* @param context the current ServletContext
* @param request the ServletRequest, which must be a {@link ScopedRequest}.
* @param response the ServletResponse, which must be a {@link ScopedResponse}.
* @param actionOverride if not <code>null</code>, this qualified action-path is used to construct an action
* URI which is set as the request URI. The action-path <strong>must</strong> begin with '/',
* which makes it qualified from the webapp root.
* @param autoResolveExtensions a list of URI extensions (e.g., ".do", ".jpf") that will be auto-resolved, i.e.,
* on which this method will be recursively called. If <code>null</code>, the
* default extensions ".do" and ".jpf" will be used.
*/
public static ActionResult strutsLookup( ServletContext context, ServletRequest request,
HttpServletResponse response, String actionOverride,
String[] autoResolveExtensions )
throws Exception
{
ScopedRequest scopedRequest = ScopedServletUtils.unwrapRequest( request );
ScopedResponse scopedResponse = ScopedServletUtils.unwrapResponse( response );
assert scopedRequest != null : request.getClass().getName();
assert scopedResponse != null : response.getClass().getName();
assert request instanceof HttpServletRequest : request.getClass().getName();
if ( scopedRequest == null )
{
throw new IllegalArgumentException( "request must be of type " + ScopedRequest.class.getName() );
}
if ( scopedResponse == null )
{
throw new IllegalArgumentException( "response must be of type " + ScopedResponse.class.getName() );
}
ActionServlet as = InternalUtils.getActionServlet( context );
if ( actionOverride != null )
{
// The action must be fully-qualified with its module path.
assert actionOverride.charAt( 0 ) == '/' : actionOverride;
InternalStringBuilder uri = new InternalStringBuilder( scopedRequest.getContextPath() );
uri.append( actionOverride );
uri.append( PageFlowConstants.ACTION_EXTENSION );
scopedRequest.setRequestURI( uri.toString() );
}
//
// In case the request was already forwarded once, clear out the recorded forwarded-URI. This
// will allow us to tell whether processing the request actually forwarded somewhere.
//
scopedRequest.setForwardedURI( null );
//
// Now process the request. We create a PageFlowRequestWrapper for pageflow-specific request-scoped info.
//
PageFlowRequestWrapper wrappedRequest = PageFlowRequestWrapper.wrapRequest( ( HttpServletRequest ) request );
wrappedRequest.setScopedLookup( true );
if (as != null)
{
as.doGet( wrappedRequest, scopedResponse ); // this just calls process() -- same as doPost()
}
else
{
// The normal servlet initialization has not completed yet
// so rather than call doGet() directly, aquire the request
// dispatcher from the unwrapped outer request and call
// forward to trigger the servlet initialization.
HttpServletRequest req = scopedRequest.getOuterRequest();
RequestDispatcher rd = req.getRequestDispatcher(scopedRequest.getRequestURI());
rd.forward(wrappedRequest, scopedResponse);
}
String returnURI;
if ( ! scopedResponse.didRedirect() )
{
returnURI = scopedRequest.getForwardedURI();
if ( autoResolveExtensions == null )
{
autoResolveExtensions = DEFAULT_AUTORESOLVE_EXTENSIONS;
}
if ( returnURI != null )
{
for ( int i = 0; i < autoResolveExtensions.length; ++i )
{
if ( FileUtils.uriEndsWith( returnURI, autoResolveExtensions[i] ) )
{
scopedRequest.doForward();
return strutsLookup( context, wrappedRequest, scopedResponse, null, autoResolveExtensions );
}
}
}
}
else
{
returnURI = scopedResponse.getRedirectURI();
}
RequestContext requestContext = new RequestContext( scopedRequest, scopedResponse );
Handlers.get( context ).getStorageHandler().applyChanges( requestContext );
if ( returnURI != null )
{
return new ActionResultImpl( returnURI, scopedResponse.didRedirect(), scopedResponse.getStatusCode(),
scopedResponse.getStatusMessage(), scopedResponse.isError() );
}
else
{
return null;
}
}
/**
* If the given request is a MultipartRequestWrapper (Struts class that doesn't extend
* HttpServletRequestWrapper), return the wrapped request; otherwise, return the given request.
* @exclude
*/
public static HttpServletRequest unwrapMultipart( HttpServletRequest request )
{
if ( request instanceof MultipartRequestWrapper )
{
request = ( ( MultipartRequestWrapper ) request ).getRequest();
}
return request;
}
/**
* Get or create the current {@link GlobalApp} instance.
* @deprecated Use {@link #getGlobalApp} instead.
*
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse
* @return the current {@link GlobalApp} from the user session, or a newly-instantiated one
* (based on the user's Global.app file) if none was in the session. Failing that,
* return <code>null</code>.
*/
public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return ensureGlobalApp( request, response, servletContext );
}
/**
* Get or create the current {@link GlobalApp} instance.
* @deprecated Use {@link #getSharedFlow} instead.
*
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse
* @return the current {@link GlobalApp} from the user session, or a newly-instantiated one
* (based on the user's Global.app file) if none was in the session. Failing that,
* return <code>null</code>.
*/
public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext )
{
GlobalApp ga = getGlobalApp( request );
if ( ga != null )
{
ga.reinitialize( request, response, servletContext );
}
else
{
ga = FlowControllerFactory.getGlobalApp( request, response, servletContext );
}
return ga;
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getBindingUpdateErrors} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static Map getBindingUpdateErrors( ServletRequest request )
{
return InternalUtils.getBindingUpdateErrors( request );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#ensureModuleConfig} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static ModuleConfig ensureModuleConfig( String modulePath, ServletRequest request, ServletContext context )
{
return InternalUtils.ensureModuleConfig( modulePath, context );
}
/**
* @deprecated This will be removed with no replacement in a future release.
*/
public static ModuleConfig getGlobalAppConfig( ServletContext servletContext )
{
return InternalUtils.getModuleConfig( GLOBALAPP_MODULE_CONTEXT_PATH, servletContext );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getModuleConfig} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static ModuleConfig getModuleConfig( String modulePath, ServletContext context )
{
return InternalUtils.getModuleConfig( modulePath, context );
}
/**
* Get the file extension from a file name.
* @deprecated Use {@link FileUtils#getFileExtension} instead.
*
* @param filename the file name.
* @return the file extension (everything after the last '.'), or the empty string if there is no file extension.
*/
public static String getFileExtension( String filename )
{
return FileUtils.getFileExtension( filename );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getFlowControllerClassName} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static String getPageFlowClassName( String modulePath, ServletRequest request, ServletContext context )
{
return InternalUtils.getFlowControllerClassName( modulePath, request, context );
}
/**
* @deprecated This method no longer has any effect, and will be removed without replacement in a future release.
*/
public static boolean ensureAppDeployment( HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext )
{
return false;
}
/**
* Tell whether a given URI is absolute, i.e., whether it contains a scheme-part (e.g., "http:").
* @deprecated Use {@link FileUtils#isAbsoluteURI} instead.
*
* @param uri the URI to test.
* @return <code>true</code> if the given URI is absolute.
*/
public static boolean isAbsoluteURI( String uri )
{
return FileUtils.isAbsoluteURI( uri );
}
/**
* @deprecated Use {@link #getCurrentPageFlow} instead.
*/
public static final PageFlowController ensureCurrentPageFlow( HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext )
{
try
{
FlowControllerFactory factory = FlowControllerFactory.get( servletContext );
return factory.getPageFlowForRequest( new RequestContext( request, response ) );
}
catch ( InstantiationException e )
{
_log.error( "Could not instantiate PageFlowController for request " + request.getRequestURI(), e );
}
catch ( IllegalAccessException e )
{
_log.error( "Could not instantiate PageFlowController for request " + request.getRequestURI(), e );
}
return null;
}
/**
* @deprecated Use {@link #getCurrentPageFlow} instead.
*/
public static final PageFlowController ensureCurrentPageFlow( HttpServletRequest request,
HttpServletResponse response )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
if ( servletContext == null && _log.isWarnEnabled() )
{
_log.warn( "could not get ServletContext from request " + request );
}
return ensureCurrentPageFlow( request, response, servletContext );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#addBindingUpdateError} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void addBindingUpdateError( ServletRequest request, String expression, String message, Throwable e )
{
InternalUtils.addBindingUpdateError( request, expression, message, e );
}
/**
* @deprecated This is an internal utility. {@link ServletUtils#dumpRequest} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void dumpRequest( HttpServletRequest request, PrintStream output )
{
ServletUtils.dumpRequest( request, output );
}
/**
* @deprecated This is an internal utility. {@link ServletUtils#dumpServletContext} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void dumpServletContext( ServletContext context, PrintStream output )
{
ServletUtils.dumpServletContext( context, output );
}
/**
* @deprecated Use {@link ServletUtils#preventCache} instead.
*/
public static void preventCache( HttpServletResponse response )
{
ServletUtils.preventCache( response );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#setCurrentActionResolver} can be used, but it is
* not guaranteed to be supported in the future. This method will be removed in the next version.
*/
public static void setCurrentActionResolver( ActionResolver resolver, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
InternalUtils.setCurrentActionResolver( resolver, request, servletContext );
}
/**
* Create a raw action URI, which can be modified before being sent through the registered URL rewriting chain
* using {@link URLRewriterService#rewriteURL}. Use {@link #getRewrittenActionURI} to get a fully-rewritten URI.
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param actionName the action name to convert into a MutableURI; may be qualified with a path from the webapp
* root, in which case the parent directory from the current request is <i>not</i> used.
* @return a MutableURI for the given action, suitable for URL rewriting.
* @throws URISyntaxException if there is a problem converting the action URI (derived from processing the given
* action name) into a MutableURI.
*/
public static MutableURI getActionURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String actionName )
throws URISyntaxException
{
if ( actionName.length() < 1 ) throw new IllegalArgumentException( "actionName must be non-empty" );
/*
* The implementation for HttpServletRequest method getContextPath()
* is not consistant across containers. The spec says the "container
* does not decode this string." However, the string returned in
* Tomcat is decoded. (See Tomcat bugzilla bug 39503) Also this method
* returns a decoded string in some containers if the request is a
* forward where the RequestDispatcher was acquired using a relative
* path. It seems that it is only the space character in the context
* path that causes us issues using the java.net.URI class in our
* MutableURI.setURI(). So,... check for a decoded space and encode it.
*/
String contextPath = request.getContextPath();
if (contextPath.indexOf(' ') != -1) {
contextPath = contextPath.replace(" ", "%20");
}
InternalStringBuilder actionURI = new InternalStringBuilder(contextPath);
if ( actionName.charAt( 0 ) != '/' )
{
actionURI.append( InternalUtils.getModulePathFromReqAttr( request ) );
actionURI.append( '/' );
}
actionURI.append( actionName );
if ( ! actionName.endsWith( ACTION_EXTENSION ) ) actionURI.append( ACTION_EXTENSION );
FreezableMutableURI uri = new FreezableMutableURI();
uri.setEncoding( response.getCharacterEncoding() );
uri.setPath( actionURI.toString() );
return uri;
}
/**
* Create a fully-rewritten URI given an action name and parameters.
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param actionName the action name to convert into a fully-rewritten URI; may be qualified with a path from the
* webapp root, in which case the parent directory from the current request is <i>not</i> used.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this url.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there is a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenActionURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String actionName, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
MutableURI uri = getActionURI( servletContext, request, response, actionName );
if ( params != null ) uri.addParameters( params, false );
if ( fragment != null ) uri.setFragment( uri.encode( fragment ) );
boolean needsToBeSecure = needsToBeSecure( servletContext, request, uri.getPath(), true );
URLRewriterService.rewriteURL( servletContext, request, response, uri, URLType.ACTION, needsToBeSecure );
String key = getURLTemplateKey( URLType.ACTION, needsToBeSecure );
URIContext uriContext = URIContextFactory.getInstance( forXML );
return URLRewriterService.getTemplatedURL( servletContext, request, uri, key, uriContext );
}
/**
* Create a fully-rewritten URI given a path and parameters.
*
* <p> Calls the rewriter service using a type of {@link URLType#RESOURCE}. </p>
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param path the path to process into a fully-rewritten URI.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this URI.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there's a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenResourceURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
return rewriteResourceOrHrefURL( servletContext, request, response, path, params, fragment, forXML, URLType.RESOURCE );
}
/**
* Create a fully-rewritten URI given a path and parameters.
*
* <p> Calls the rewriter service using a type of {@link URLType#ACTION}. </p>
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param path the path to process into a fully-rewritten URI.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this URI.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there's a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenHrefURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
return rewriteResourceOrHrefURL( servletContext, request, response, path, params, fragment, forXML, URLType.ACTION );
}
private static String rewriteResourceOrHrefURL( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML, URLType urlType )
throws URISyntaxException
{
boolean encoded = false;
UrlConfig urlConfig = ConfigUtil.getConfig().getUrlConfig();
if (urlConfig != null) {
encoded = !urlConfig.isUrlEncodeUrls();
}
FreezableMutableURI uri = new FreezableMutableURI();
uri.setEncoding( response.getCharacterEncoding() );
uri.setURI( path, encoded );
if ( params != null )
{
uri.addParameters( params, false );
}
if ( fragment != null )
{
uri.setFragment( uri.encode( fragment ) );
}
URIContext uriContext = URIContextFactory.getInstance( forXML );
if ( uri.isAbsolute() )
{
return uri.getURIString( uriContext );
}
if ( path.length() != 0 && path.charAt( 0 ) != '/' )
{
String reqUri = request.getRequestURI();
String reqPath = reqUri.substring( 0, reqUri.lastIndexOf( '/' ) + 1 );
uri.setPath( reqPath + uri.getPath() );
}
boolean needsToBeSecure = needsToBeSecure( servletContext, request, uri.getPath(), true );
URLRewriterService.rewriteURL( servletContext, request, response, uri, urlType, needsToBeSecure );
String key = getURLTemplateKey( urlType, needsToBeSecure );
return URLRewriterService.getTemplatedURL( servletContext, request, uri, key, uriContext );
}
/**
* Tell whether a given URI should be written to be secure.
* @param context the current ServletContext.
* @param request the current HttpServletRequest.
* @param uri the URI to check.
* @param stripContextPath if <code>true</code>, strip the webapp context path from the URI before
* processing it.
* @return <code>true</code> when:
* <ul>
* <li>the given URI is configured in the deployment descriptor to be secure (according to
* {@link SecurityProtocol}), or
* <li>the given URI is not configured in the deployment descriptor, and the current request
* is secure ({@link HttpServletRequest#isSecure} returns
* <code>true</code>).
* </ul>
* <code>false</code> when:
* <ul>
* <li>the given URI is configured explicitly in the deployment descriptor to be unsecure
* (according to {@link SecurityProtocol}), or
* <li>the given URI is not configured in the deployment descriptor, and the current request
* is unsecure ({@link HttpServletRequest#isSecure} returns
* <code>false</code>).
* </ul>
*/
public static boolean needsToBeSecure(ServletContext context, ServletRequest request,
String uri, boolean stripContextPath)
{
// Get the web-app relative path for security check
String secureCheck = uri;
if (stripContextPath) {
String contextPath = ((HttpServletRequest) request).getContextPath();
if (secureCheck.startsWith(contextPath)) {
secureCheck = secureCheck.substring(contextPath.length());
}
}
boolean secure = false;
if (secureCheck.indexOf('?') > -1) {
secureCheck = secureCheck.substring(0, secureCheck.indexOf('?'));
}
SecurityProtocol sp = getSecurityProtocol(secureCheck, context, (HttpServletRequest) request);
if (sp.equals(SecurityProtocol.UNSPECIFIED)) {
secure = request.isSecure();
}
else {
secure = sp.equals(SecurityProtocol.SECURE);
}
return secure;
}
/**
* Returns a key for the URL template type given the URL type and a
* flag indicating a secure URL or not.
*
* @param urlType the type of URL (ACTION, RESOURCE).
* @param needsToBeSecure indicates that the template should be for a secure URL.
* @return the key/type of template to use.
*/
public static String getURLTemplateKey( URLType urlType, boolean needsToBeSecure )
{
String key = URLTemplatesFactory.ACTION_TEMPLATE;
if ( urlType.equals( URLType.ACTION ) )
{
if ( needsToBeSecure )
{
key = URLTemplatesFactory.SECURE_ACTION_TEMPLATE;
}
else
{
key = URLTemplatesFactory.ACTION_TEMPLATE;
}
}
else if ( urlType.equals( URLType.RESOURCE ) )
{
if ( needsToBeSecure )
{
key = URLTemplatesFactory.SECURE_RESOURCE_TEMPLATE;
}
else
{
key = URLTemplatesFactory.RESOURCE_TEMPLATE;
}
}
return key;
}
/**
* Get an uninitialized instance of a container specific URLTemplatesFactory
* from the ServletContainerAdapter. If none exists, this returns an instance
* of {@link DefaultURLTemplatesFactory}. Caller should then set the known
* and required tokens, call the {@link URLTemplatesFactory#load(javax.servlet.ServletContext)}
* method and {@link URLTemplatesFactory#initServletContext(javax.servlet.ServletContext,
* org.apache.beehive.netui.core.urltemplates.URLTemplatesFactory)}.
*
* <p>
* IMPORTANT NOTE - Always try to get the application instance from the ServletContext
* by calling {@link URLTemplatesFactory#getURLTemplatesFactory(javax.servlet.ServletContext)}.
* Then, if a new URLTemplatesFactory must be created, call this method.
* </p>
*
* @param servletContext
* @return a container specific implementation of URLTemplatesFactory, or
* {@link DefaultURLTemplatesFactory}.
*/
public static URLTemplatesFactory createURLTemplatesFactory( ServletContext servletContext )
{
// get the URLTemplatesFactory from the containerAdapter.
ServletContainerAdapter containerAdapter = AdapterManager.getServletContainerAdapter( servletContext );
URLTemplatesFactory factory = (URLTemplatesFactory) containerAdapter.getFactory( URLTemplatesFactory.class, null, null );
// if there's no URLTemplatesFactory, use our default impl.
if ( factory == null )
{
factory = new DefaultURLTemplatesFactory();
}
return factory;
}
/**
* Make sure that when this page is rendered, it will set headers in the response to prevent caching.
* Because these headers are lost on server forwards, we set a request attribute to cause the headers
* to be set right before the page is rendered. This attribute can be read via
* {@link #isPreventCache(javax.servlet.ServletRequest)}.
*
* @param request the servlet request
*/
static void setPreventCache( ServletRequest request ) {
assert request != null;
request.setAttribute(PREVENT_CACHE_ATTR, Boolean.TRUE);
}
/**
* Internal getter that reports whether this request should prevent caching. This flag is set via the
* {@link #setPreventCache(javax.servlet.ServletRequest)} attribute.
* @param request the servlet request
* @return <code>true</code> if the framework has set the prevent cache flag
*/
static boolean isPreventCache(ServletRequest request) {
assert request != null;
return request.getAttribute(PREVENT_CACHE_ATTR) != null;
}
}
|
UTF-8
|
Java
| 80,113 |
java
|
PageFlowUtils.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Header:$
*/
package org.apache.beehive.netui.pageflow;
import org.apache.beehive.netui.core.urls.FreezableMutableURI;
import org.apache.beehive.netui.core.urls.MutableURI;
import org.apache.beehive.netui.core.urls.URIContext;
import org.apache.beehive.netui.core.urls.URLRewriterService;
import org.apache.beehive.netui.core.urls.URLType;
import org.apache.beehive.netui.core.urltemplates.URLTemplatesFactory;
import org.apache.beehive.netui.pageflow.internal.ActionResultImpl;
import org.apache.beehive.netui.pageflow.internal.InternalUtils;
import org.apache.beehive.netui.pageflow.internal.InternalConstants;
import org.apache.beehive.netui.pageflow.internal.AdapterManager;
import org.apache.beehive.netui.pageflow.internal.PageFlowRequestWrapper;
import org.apache.beehive.netui.pageflow.internal.URIContextFactory;
import org.apache.beehive.netui.pageflow.internal.DefaultURLTemplatesFactory;
import org.apache.beehive.netui.pageflow.scoping.ScopedRequest;
import org.apache.beehive.netui.pageflow.scoping.ScopedResponse;
import org.apache.beehive.netui.pageflow.scoping.ScopedServletUtils;
import org.apache.beehive.netui.pageflow.handler.StorageHandler;
import org.apache.beehive.netui.pageflow.handler.Handlers;
import org.apache.beehive.netui.util.internal.InternalStringBuilder;
import org.apache.beehive.netui.util.internal.FileUtils;
import org.apache.beehive.netui.util.internal.ServletUtils;
import org.apache.beehive.netui.util.internal.concurrent.InternalConcurrentHashMap;
import org.apache.beehive.netui.util.config.ConfigUtil;
import org.apache.beehive.netui.util.config.bean.UrlConfig;
import org.apache.beehive.netui.util.logging.Logger;
import org.apache.beehive.netui.script.common.ImplicitObjectUtil;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.upload.MultipartRequestWrapper;
import org.apache.struts.util.RequestUtils;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintStream;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Utility methods related to Page Flow.
*/
public class PageFlowUtils
implements PageFlowConstants, InternalConstants
{
private static final Logger _log = Logger.getInstance( PageFlowUtils.class );
private static final String PREVENT_CACHE_ATTR = InternalConstants.ATTR_PREFIX + "preventCache";
private static final String ACTION_URI_ATTR = ATTR_PREFIX + "_actionURI";
private static final int PAGEFLOW_EXTENSION_LEN = PAGEFLOW_EXTENSION.length();
private static final String DEFAULT_AUTORESOLVE_EXTENSIONS[] = new String[]{ ACTION_EXTENSION, PAGEFLOW_EXTENSION };
/** Map of Struts module prefix to Map of form-type-name to form-name. */
private static Map/*< String, Map< String, List< String > > >*/ _formNameMaps =
new InternalConcurrentHashMap/*< String, Map< String, List< String > > >*/();
/**
* Get the Struts module path for a URI. This is the parent directory, relative to the web
* application root, of the file referenced by the URI.
*
* @param request the current HttpServletRequest.
* @param requestURI the URI for which to get the Struts module path.
*/
public static String getModulePath( HttpServletRequest request, String requestURI )
{
return getModulePathForRelativeURI( getRelativeURI( request, requestURI, null ) );
}
/**
* Get the Struts module path for the current request URI. This is the parent directory,
* relative to the web application root, of the file referenced by the request URI.
*
* @param request the current HttpServletRequest.
*/
public static String getModulePath( HttpServletRequest request )
{
return getModulePathForRelativeURI( InternalUtils.getDecodedServletPath( request ) );
}
/**
* Get the Struts module path for a URI that is relative to the web application root.
*
* @param uri the URI for which to get the module path.
*/
public static String getModulePathForRelativeURI( String uri )
{
if ( uri == null ) return null;
assert uri.length() > 0;
assert uri.charAt( 0 ) == '/' : uri;
// Strip off the actual page name (e.g., some_page.jsp)
int slash = uri.lastIndexOf( '/' );
uri = uri.substring( 0, slash );
return uri;
}
/**
* Get the request URI, relative to the URI of the given PageFlowController.
*
* @param request the current HttpServletRequest.
* @param relativeTo a PageFlowController to which the returned URI should be relative, or
* <code>null</code> if the returned URI should be relative to the webapp root.
*/
public static String getRelativeURI( HttpServletRequest request, PageFlowController relativeTo )
{
if ( relativeTo == null ) return InternalUtils.getDecodedServletPath( request );
return getRelativeURI( request, InternalUtils.getDecodedURI( request ), relativeTo );
}
/**
* Get a URI relative to the URI of the given PageFlowController.
*
* @param request the current HttpServletRequest.
* @param uri the URI which should be made relative.
* @param relativeTo a PageFlowController to which the returned URI should be relative, or
* <code>null</code> if the returned URI should be relative to the webapp root.
*/
public static String getRelativeURI( HttpServletRequest request, String uri, PageFlowController relativeTo )
{
String contextPath = request.getContextPath();
if ( relativeTo != null ) contextPath += relativeTo.getModulePath();
int overlap = uri.indexOf( contextPath + '/' );
if ( overlap == -1 ) return null;
return uri.substring( overlap + contextPath.length() );
}
/**
* Get a URI for the "begin" action in the PageFlowController associated with the given
* request URI.
*
* @return a String that is the URI for the "begin" action in the PageFlowController associated
* with the given request URI.
*/
public static String getBeginActionURI( String requestURI )
{
// Translate this to a request for the begin action ("begin.do") for this PageFlowController.
InternalStringBuilder retVal = new InternalStringBuilder();
int lastSlash = requestURI.lastIndexOf( '/' );
if ( lastSlash != -1 )
{
retVal.append( requestURI.substring( 0, lastSlash ) );
}
retVal.append( '/' ).append( BEGIN_ACTION_NAME ).append( ACTION_EXTENSION );
return retVal.toString();
}
/**
* Get the stack of nested page flows for the current user session. Create and store an empty
* stack if none exists.
*
* @deprecated Use {@link PageFlowStack#get(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest
* @return a {@link PageFlowStack} of nested page flows ({@link PageFlowController}s) for the current user session.
*/
public static Stack getPageFlowStack( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return PageFlowStack.get( request, servletContext, true ).getLegacyStack();
}
/**
* Destroys the stack of {@link PageFlowController}s that have invoked nested page flows.
*
* @deprecated Use {@link PageFlowStack#destroy} instead.
*
* @param request the current HttpServletRequest.
*/
public static void destroyPageFlowStack( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
PageFlowStack.get( request, servletContext ).destroy( request );
}
/**
* Get the {@link PageFlowController} that is nesting the current one.
* @deprecated Use {@link #getNestingPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest.
* @return the nesting {@link PageFlowController}, or <code>null</code> if the current one
* is not being nested.
*/
public static PageFlowController getNestingPageFlow( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getNestingPageFlow( request, servletContext );
}
/**
* Get the {@link PageFlowController} that is nesting the current one.
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the nesting {@link PageFlowController}, or <code>null</code> if the current one
* is not being nested.
*/
public static PageFlowController getNestingPageFlow( HttpServletRequest request, ServletContext servletContext )
{
PageFlowStack jpfStack = PageFlowStack.get( request, servletContext, false );
if ( jpfStack != null && ! jpfStack.isEmpty() )
{
PageFlowController top = jpfStack.peek().getPageFlow();
return top;
}
return null;
}
/**
* Get the current {@link PageFlowController}.
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the current PageFlowController from the user session, or <code>null</code> if there is none.
*/
public static PageFlowController getCurrentPageFlow( HttpServletRequest request, ServletContext servletContext )
{
ActionResolver cur = getCurrentActionResolver( request, servletContext );
if (cur != null && cur.isPageFlow()) {
PageFlowController pfc = (PageFlowController) cur;
pfc.reinitializeIfNecessary(request, null, servletContext);
return pfc;
}
return null;
}
/**
/**
* Get the current PageFlowController.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @param request the current HttpServletRequest.
* @return the current PageFlowController from the user session, or <code>null</code>
* if there is none.
*/
public static PageFlowController getCurrentPageFlow( HttpServletRequest request )
{
ActionResolver cur = getCurrentActionResolver( request );
return cur != null && cur.isPageFlow() ? ( PageFlowController ) cur : null;
}
/**
* Get the current ActionResolver.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
* @return the current ActionResolver from the user session, or <code>null</code> if there is none.
*/
public static ActionResolver getCurrentActionResolver( HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getCurrentActionResolver( request, servletContext );
}
/**
* Get the current ActionResolver.
* @deprecated Use {@link #getCurrentPageFlow(HttpServletRequest, ServletContext)} instead.
*
*
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the current ActionResolver from the user session, or <code>null</code> if there is none.
*/
public static ActionResolver getCurrentActionResolver( HttpServletRequest request, ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
//
// First see if the current page flow is a long-lived, which is stored in its own attribute.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath = ( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( currentLongLivedModulePath != null )
{
return getLongLivedPageFlow( currentLongLivedModulePath, unwrappedRequest );
}
else
{
String currentJpfAttrName = ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
return ( ActionResolver ) sh.getAttribute( rc, currentJpfAttrName );
}
}
/**
* Get the current {@link GlobalApp} instance.
*
* @deprecated Use {@link #getSharedFlow} instead.
* @param request the current HttpServletRequest.
* @return the current {@link GlobalApp} from the user session, or <code>null</code> if none
* exists.
*/
public static GlobalApp getGlobalApp( HttpServletRequest request )
{
SharedFlowController sf = getSharedFlow( InternalConstants.GLOBALAPP_CLASSNAME, request );
return sf instanceof GlobalApp ? ( GlobalApp ) sf : null;
}
/**
* Get the a map of shared flow name to shared flow instance, based on the names defined in the
* {@link org.apache.beehive.netui.pageflow.annotations.Jpf.Controller#sharedFlowRefs sharedFlowRefs} attribute
* of the {@link org.apache.beehive.netui.pageflow.annotations.Jpf.Controller @Jpf.Controller} annotation on the
* <strong>current page flow</strong>.
*
* @param request the current HttpServletRequest, which is used to determine the current page flow.
* @return a Map of shared flow name (string) to shared flow instance ({@link SharedFlowController}).
*/
public static Map/*< String, SharedFlowController >*/ getSharedFlows( HttpServletRequest request )
{
Map/*< String, SharedFlowController >*/ sharedFlows = ImplicitObjectUtil.getSharedFlow( request );
return sharedFlows != null ? sharedFlows : Collections.EMPTY_MAP;
}
/**
* Get the shared flow with the given class name.
* @deprecated Use {@link #getSharedFlow(String, HttpServletRequest, ServletContext)} instead.
*
* @param sharedFlowClassName the class name of the shared flow to retrieve.
* @param request the current HttpServletRequest.
* @return the {@link SharedFlowController} of the given class name which is stored in the user session.
*/
public static SharedFlowController getSharedFlow( String sharedFlowClassName, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getSharedFlow( sharedFlowClassName, request, servletContext );
}
/**
* Get the shared flow with the given class name.
*
* @param sharedFlowClassName the class name of the shared flow to retrieve.
* @param request the current HttpServletRequest.
* @return the {@link SharedFlowController} of the given class name which is stored in the user session.
*/
public static SharedFlowController getSharedFlow( String sharedFlowClassName, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX
+ sharedFlowClassName, request);
SharedFlowController sf = (SharedFlowController) sh.getAttribute(rc, attrName);
if (sf != null) {
sf.reinitializeIfNecessary(request, null, servletContext);
}
return sf;
}
/**
* Destroy the current {@link SharedFlowController} of the given class name.
* @deprecated Use {@link #removeSharedFlow(String, HttpServletRequest, ServletContext)} instead.
* @param sharedFlowClassName the class name of the current SharedFlowController to destroy.
* @param request the current HttpServletRequest.
*/
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
removeSharedFlow( sharedFlowClassName, request, servletContext );
}
/**
* Destroy the current {@link SharedFlowController} of the given class name.
* @param sharedFlowClassName the class name of the current SharedFlowController to destroy.
* @param request the current HttpServletRequest.
*/
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX
+ sharedFlowClassName, request);
sh.removeAttribute(rc, attrName);
}
/**
* Remove a "long-lived" page flow from the session. Once it is created, a long-lived page flow
* is never removed from the session unless this method or {@link PageFlowController#remove} is
* called. Navigating to another page flow hides the current long-lived controller, but does not
* remove it.
* @deprecated Use {@link #removeLongLivedPageFlow(String, HttpServletRequest, ServletContext)} instead.
*/
public static void removeLongLivedPageFlow( String modulePath, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
removeLongLivedPageFlow( modulePath, request, servletContext );
}
/**
* Remove a "long-lived" page flow from the session. Once it is created, a long-lived page flow
* is never removed from the session unless this method or {@link PageFlowController#remove} is
* called. Navigating to another page flow hides the current long-lived controller, but does not
* remove it.
*/
public static void removeLongLivedPageFlow( String modulePath, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = InternalUtils.getLongLivedFlowAttr( modulePath );
attrName = ScopedServletUtils.getScopedSessionAttrName( attrName, unwrappedRequest );
sh.removeAttribute( rc, attrName );
//
// Now, if the current page flow is long-lived, remove the reference.
//
String currentLongLivedAttrName =
ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );
String currentLongLivedModulePath =
( String ) sh.getAttribute( rc, currentLongLivedAttrName );
if ( modulePath.equals( currentLongLivedModulePath ) )
{
sh.removeAttribute( rc, currentLongLivedAttrName );
}
}
/**
* Get the long-lived page flow instance associated with the given module (directory) path.
* @deprecated Use {@link #getLongLivedPageFlow(String, HttpServletRequest, ServletContext)} instead.
*
* @param modulePath the webapp-relative path to the directory containing the long-lived page flow.
* @param request the current HttpServletRequest.
* @return the long-lived page flow instance associated with the given module, or <code>null</code> if none is found.
*/
public static PageFlowController getLongLivedPageFlow( String modulePath, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return getLongLivedPageFlow( modulePath, request, servletContext );
}
/**
* Get the long-lived page flow instance associated with the given module (directory) path.
*
* @param modulePath the webapp-relative path to the directory containing the long-lived page flow.
* @param request the current HttpServletRequest.
* @param servletContext the current ServletContext.
* @return the long-lived page flow instance associated with the given module, or <code>null</code> if none is found.
*/
public static PageFlowController getLongLivedPageFlow( String modulePath, HttpServletRequest request,
ServletContext servletContext )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = InternalUtils.getLongLivedFlowAttr( modulePath );
attrName = ScopedServletUtils.getScopedSessionAttrName( attrName, unwrappedRequest );
PageFlowController retVal = ( PageFlowController ) sh.getAttribute( rc, attrName );
return retVal;
}
/**
* Make any form beans in the given {@link Forward} object available as attributets in the
* request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param fwd the {@link Forward} object that contains the ActionForm instances to be
* made available in the request/session (as appropriate).
* @param request the current HttpServletRequest.
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
*/
public static void setOutputForms( ActionMapping mapping, Forward fwd, HttpServletRequest request,
boolean overwrite )
{
if ( fwd == null ) return;
//
// *If* there is a target action mapping, set output forms for it.
//
if ( mapping != null ) setOutputForms( mapping, fwd.getOutputForms(), request, overwrite );
InternalUtils.setForwardedFormBean( request, fwd.getFirstOutputForm( request ) );
}
/**
* Make any form beans in the given {@link Forward} object available as attributets in the
* request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param fwd the {@link Forward} object that contains the ActionForm instances to be
* made available in the request/session (as appropriate).
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, Forward fwd, HttpServletRequest request )
{
if ( fwd == null )
{
return;
}
if ( mapping != null )
{
setOutputForms( mapping, fwd.getOutputForms(), request );
}
InternalUtils.setForwardedFormBean( request, fwd.getFirstOutputForm( request ) );
}
/**
* Make a set of form beans available as attributets in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param outputForms an array of ActionForm instances to be made available in the
* request/session (as appropriate).
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms,
HttpServletRequest request )
{
setOutputForms( mapping, outputForms, request, true );
}
/**
* Make a set of form beans available as attributets in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param outputForms an array of ActionForm instances to be made available in the
* request/session (as appropriate).
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
* @param request the current HttpServletRequest.
*/
public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms,
HttpServletRequest request, boolean overwrite )
{
try
{
//
// Now set any output forms in the request or session, as appropriate.
//
assert mapping.getScope() == null
|| mapping.getScope().equals( "request" )
|| mapping.getScope().equals( "session" )
: mapping.getScope();
for ( int i = 0; i < outputForms.length; ++i )
{
setOutputForm( mapping, outputForms[i], request, overwrite );
}
}
catch ( Exception e )
{
_log.error( "Error while setting Struts form-beans", e );
}
}
private static List/*< String >*/ getFormNamesFromModuleConfig( String formBeanClassName, ModuleConfig moduleConfig )
{
String modulePrefix = moduleConfig.getPrefix();
Map/*< String, List< String > >*/ formNameMap = ( Map ) _formNameMaps.get( modulePrefix ); // map of form-type-name to form-name
if ( formNameMap == null )
{
formNameMap = new HashMap/*< String, List< String > >*/();
FormBeanConfig[] formBeans = moduleConfig.findFormBeanConfigs();
for ( int j = 0; j < formBeans.length; ++j )
{
assert formBeans[j] != null;
String formBeanType = InternalUtils.getFormBeanType( formBeans[j] );
List/*< String >*/ formBeanNames = ( List ) formNameMap.get( formBeanType );
if ( formBeanNames == null )
{
formBeanNames = new ArrayList/*< String >*/();
formNameMap.put( formBeanType, formBeanNames );
}
formBeanNames.add( formBeans[j].getName() );
}
_formNameMaps.put( modulePrefix, formNameMap );
}
return ( List ) formNameMap.get( formBeanClassName );
}
/**
* Make a form bean available as an attributet in the request/session (as appropriate).
*
* @param mapping the ActionMapping for the current Struts action being processed.
* @param form an ActionForm instance to be made available in the request/session
* (as appropriate).
* @param overwrite if <code>false</code> a form from <code>fwd</code> will only be set
* in the request if there is no existing form with the same name.
* @param request the current HttpServletRequest.
*/
public static void setOutputForm( ActionMapping mapping, ActionForm form,
HttpServletRequest request, boolean overwrite )
{
if ( form != null )
{
ModuleConfig moduleConfig = mapping.getModuleConfig();
Class formClass = InternalUtils.unwrapFormBean( form ).getClass();
//
// Get the names of *all* form beans of the desired type, and blast out this instance under all those names.
//
List formNames = getFormNamesFromModuleConfig( formClass.getName(), moduleConfig );
List additionalFormNames = null;
//
// formNames is a statically-scoped list. Below, we create a dynamic list of form names that correspond
// to *implemented interfaces* of the given form bean class.
//
Class[] interfaces = formClass.getInterfaces();
for ( int i = 0; i < interfaces.length; i++ )
{
Class formInterface = interfaces[i];
List toAdd = getFormNamesFromModuleConfig( formInterface.getName(), moduleConfig );
if ( toAdd != null )
{
if ( additionalFormNames == null ) additionalFormNames = new ArrayList();
additionalFormNames.addAll( toAdd );
}
}
// Do the same for all superclasses of the form bean class.
for (Class i = formClass.getSuperclass(); i != null; i = i.getSuperclass()) {
List toAdd = getFormNamesFromModuleConfig( i.getName(), moduleConfig );
if ( toAdd != null )
{
if ( additionalFormNames == null ) additionalFormNames = new ArrayList();
additionalFormNames.addAll( toAdd );
}
}
if ( formNames == null && additionalFormNames == null )
{
String formName = generateFormBeanName( formClass, request );
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
else
{
if ( formNames != null )
{
for ( Iterator i = formNames.iterator(); i.hasNext(); )
{
String formName = ( String ) i.next();
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
}
if ( additionalFormNames != null )
{
for ( Iterator i = additionalFormNames.iterator(); i.hasNext(); )
{
String formName = ( String ) i.next();
InternalUtils.setFormInScope( formName, form, mapping, request, overwrite );
}
}
}
}
}
/**
* Get the name for the type of a ActionForm instance. Use a name looked up from
* the current Struts module, or, if none is found, create one.
*
* @param formInstance the ActionForm instance whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
public static String getFormBeanName( ActionForm formInstance, HttpServletRequest request )
{
return getFormBeanName( formInstance.getClass(), request );
}
/**
* Get the name for an ActionForm type. Use a name looked up from the current Struts module, or,
* if none is found, create one.
*
* @param formBeanClass the ActionForm-derived class whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
public static String getFormBeanName( Class formBeanClass, HttpServletRequest request )
{
ModuleConfig moduleConfig = RequestUtils.getRequestModuleConfig( request );
List/*< String >*/ names = getFormNamesFromModuleConfig( formBeanClass.getName(), moduleConfig );
if ( names != null )
{
assert names.size() > 0; // getFormNamesFromModuleConfig returns null or a nonempty list
return ( String ) names.get( 0 );
}
return generateFormBeanName( formBeanClass, request );
}
/**
* Create the name for a form bean type.
*
* @param formBeanClass the class whose type will determine the name.
* @param request the current HttpServletRequest, which contains a reference to the current Struts module.
* @return the name found in the Struts module, or, if none is found, a name that is either:
* <ul>
* <li>a camel-cased version of the base class name (minus any package or outer-class
* qualifiers, or, if that name is already taken,</li>
* <li>the full class name, with '.' and '$' replaced by '_'.</li>
* </ul>
*/
private static String generateFormBeanName( Class formBeanClass, HttpServletRequest request )
{
ModuleConfig moduleConfig = RequestUtils.getRequestModuleConfig( request );
String formBeanClassName = formBeanClass.getName();
//
// A form-bean wasn't found for this type, so we'll create a name. First try and create
// name that is a camelcased version of the classname without all of its package/outer-class
// qualifiers. If one with that name already exists, munge the fully-qualified classname.
//
String formType = formBeanClassName;
int lastQualifier = formType.lastIndexOf( '$' );
if ( lastQualifier == -1 )
{
lastQualifier = formType.lastIndexOf( '.' );
}
String formName = formType.substring( lastQualifier + 1 );
formName = Character.toLowerCase( formName.charAt( 0 ) ) + formName.substring( 1 );
if ( moduleConfig.findFormBeanConfig( formName ) != null )
{
formName = formType.replace( '.', '_' ).replace( '$', '_' );
assert moduleConfig.findFormBeanConfig( formName ) == null : formName;
}
return formName;
}
/**
* Get the class name of a {@link PageFlowController}, given the URI to it.
*
* @param uri the URI to the {@link PageFlowController}, which should be relative to the
* web application root (i.e., it should not include the context path).
*/
public static String getPageFlowClassName( String uri )
{
assert uri != null;
assert uri.length() > 0;
if ( uri.charAt( 0 ) == '/' ) uri = uri.substring( 1 );
assert FileUtils.osSensitiveEndsWith( uri, PAGEFLOW_EXTENSION ) : uri;
if ( FileUtils.osSensitiveEndsWith( uri, PAGEFLOW_EXTENSION ) )
{
uri = uri.substring( 0, uri.length() - PAGEFLOW_EXTENSION_LEN );
}
return uri.replace( '/', '.' );
}
/**
* Get the class name of a {@link PageFlowController}, given the URI to it.
*
* @deprecated Use {@link #getPageFlowClassName(String)} instead.
*
* @param uri the URI to the {@link PageFlowController}, which should be relative to the
* web application root (i.e., it should not include the context path).
*/
public static String getJpfClassName( String uri )
{
return getPageFlowClassName( uri );
}
/**
* Get the URI for a {@link PageFlowController}, given its class name.
*
* @param className the name of the {@link PageFlowController} class.
* @return a String that is the URI for the {@link PageFlowController}, relative to the web
* application root (i.e., not including the context path).
*/
public static String getPageFlowURI( String className )
{
return '/' + className.replace( '.', '/' ) + PAGEFLOW_EXTENSION;
}
/**
* @deprecated Use {@link PageFlowActionServlet#getModuleConfPath} instead.
*
* Get the path to the Struts module configration file (e.g.,
* "/WEB-INF/classes/_pageflow/struts-config-someModule") for a given module
* path (e.g., "someModule"), according to the PageFlow convention.
*
* @param modulePath the Struts module path.
* @return a String that is the path to the Struts configuration file, relative to the
* web application root.
*/
public static String getModuleConfPath( String modulePath )
{
return new PageFlowActionServlet.DefaultModuleConfigLocator().getModuleConfigPath( modulePath );
}
/**
* Get the most recent action URI that was processed by {@link FlowController#execute}.
*
* @param request the current ServletRequest.
* @return a String that is the most recent action URI. This is only valid during a request
* that has been forwarded from the action URI.
*/
public static String getActionURI( ServletRequest request )
{
return ( String ) request.getAttribute( ACTION_URI_ATTR );
}
/**
* Sets the most recent action URI that was processed by {@link FlowController#execute}.
*/
static void setActionURI( HttpServletRequest request )
{
request.setAttribute( ACTION_URI_ATTR, InternalUtils.getDecodedURI( request ) );
}
/**
* Tell whether a web application resource requires a secure transport protocol. This is
* determined from web.xml; for example, the following block specifies that all resources under
* /login require a secure transport protocol.
* <pre>
* <security-constraint>
* <web-resource-collection>
* <web-resource-name>Secure PageFlow - begin</web-resource-name>
* <url-pattern>/login/*</url-pattern>
* </web-resource-collection>
* <user-data-constraint>
* <transport-guarantee>CONFIDENTIAL</transport-guarantee>
* </user-data-constraint>
* </security-constraint>
* </pre>
*
* @param uri a webapp-relative URI for a resource. There must not be query parameters or a scheme
* on the URI.
* @param request the current request.
* @return <code>Boolean.TRUE</code> if a transport-guarantee of <code>CONFIDENTIAL</code> or
* <code>INTEGRAL</code> is associated with the given resource; <code>Boolean.FALSE</code>
* a transport-guarantee of <code>NONE</code> is associated with the given resource; or
* <code>null</code> if there is no transport-guarantee associated with the given resource.
*/
public static SecurityProtocol getSecurityProtocol( String uri, ServletContext servletContext,
HttpServletRequest request )
{
return AdapterManager.getServletContainerAdapter( servletContext ).getSecurityProtocol( uri, request );
}
/**
* @deprecated Use {@link #getSecurityProtocol(String, ServletContext, HttpServletRequest)} instead.
*/
public static Boolean isSecureResource( String uri, ServletContext context )
{
// TODO: once DefaultServletContainerAdapter has this functionality, delegate to it.
return null;
}
/**
* Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag.
* The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context.
*
* @deprecated Use {@link #addActionOutput} instead.
* @param name the name of the action output.
* @param value the value of the action output.
* @param request the current ServletRequest.
*/
public static void addPageInput( String name, Object value, ServletRequest request )
{
addActionOutput( name, value, request );
}
/**
* Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag.
* The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context.
*
* @param name the name of the action output.
* @param value the value of the action output.
* @param request the current ServletRequest.
*/
public static void addActionOutput( String name, Object value, ServletRequest request )
{
Map map = InternalUtils.getActionOutputMap( request, true );
if ( map.containsKey( name ) )
{
if ( _log.isWarnEnabled() )
{
_log.warn( "Overwriting action output\"" + name + "\"." );
}
}
map.put( name, value );
}
/**
* Get a named action output that was registered in the current request.
*
* @deprecated Use {@link #getActionOutput} instead.
* @param name the name of the action output.
* @param request the current ServletRequest
* @see #addActionOutput
*/
public static Object getPageInput( String name, ServletRequest request )
{
return getActionOutput( name, request );
}
/**
* Get a named action output that was registered in the current request.
*
* @param name the name of the action output.
* @param request the current ServletRequest
* @see #addActionOutput
*/
public static Object getActionOutput( String name, ServletRequest request )
{
Map map = InternalUtils.getActionOutputMap( request, false );
return map != null ? map.get( name ) : null;
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param messageArgs an array of arguments for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, Object[] messageArgs,
ServletRequest request )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param messageArg an argument for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, Object messageArg,
ServletRequest request )
{
addActionError( request, propertyName, messageKey, new Object[]{ messageArg } );
}
/**
* Add a validation error that will be shown with the Errors and Error tags.
* @deprecated Use {@link #addActionError(ServletRequest, String, String, Object[])} instead.
*
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the error message.
* @param request the current ServletRequest.
*/
public static void addValidationError( String propertyName, String messageKey, ServletRequest request )
{
addActionError( request, propertyName, messageKey );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArgs zero or more arguments to the message.
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object[] messageArgs )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey )
{
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, null ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg an argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg )
{
Object[] messageArgs = new Object[]{ messageArg };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg1 the first argument to the message
* @param messageArg2 the second argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg1, Object messageArg2 )
{
Object[] messageArgs = new Object[]{ messageArg1, messageArg2 };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message that will be shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param messageKey the message-resources key for the message.
* @param messageArg1 the first argument to the message
* @param messageArg2 the second argument to the message
* @param messageArg3 the third argument to the message
*/
public static void addActionError( ServletRequest request, String propertyName, String messageKey,
Object messageArg1, Object messageArg2, Object messageArg3 )
{
Object[] messageArgs = new Object[]{ messageArg1, messageArg2, messageArg3 };
InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request );
}
/**
* Add a property-related message as an expression that will be evaluated and shown with the Errors and Error tags.
*
* @param request the current ServletRequest.
* @param propertyName the name of the property with which to associate this error.
* @param expression the JSP 2.0-style expression (e.g., <code>${pageFlow.myProperty}</code>) or literal string
* that will be used as the message.
* @param messageArgs zero or more arguments to the message.
*/
public static void addActionErrorExpression( HttpServletRequest request, String propertyName, String expression,
Object[] messageArgs )
{
ExpressionMessage msg = new ExpressionMessage( expression, messageArgs );
InternalUtils.addActionError( propertyName, msg, request );
}
/**
* Resolve the given action to a URI by running an entire request-processing cycle on the given ScopedRequest
* and ScopedResponse.
* @exclude
*
* @param context the current ServletContext
* @param request the ServletRequest, which must be a {@link ScopedRequest}.
* @param response the ServletResponse, which must be a {@link ScopedResponse}.
* @param actionOverride if not <code>null</code>, this qualified action-path is used to construct an action
* URI which is set as the request URI. The action-path <strong>must</strong> begin with '/',
* which makes it qualified from the webapp root.
* @param autoResolveExtensions a list of URI extensions (e.g., ".do", ".jpf") that will be auto-resolved, i.e.,
* on which this method will be recursively called. If <code>null</code>, the
* default extensions ".do" and ".jpf" will be used.
*/
public static ActionResult strutsLookup( ServletContext context, ServletRequest request,
HttpServletResponse response, String actionOverride,
String[] autoResolveExtensions )
throws Exception
{
ScopedRequest scopedRequest = ScopedServletUtils.unwrapRequest( request );
ScopedResponse scopedResponse = ScopedServletUtils.unwrapResponse( response );
assert scopedRequest != null : request.getClass().getName();
assert scopedResponse != null : response.getClass().getName();
assert request instanceof HttpServletRequest : request.getClass().getName();
if ( scopedRequest == null )
{
throw new IllegalArgumentException( "request must be of type " + ScopedRequest.class.getName() );
}
if ( scopedResponse == null )
{
throw new IllegalArgumentException( "response must be of type " + ScopedResponse.class.getName() );
}
ActionServlet as = InternalUtils.getActionServlet( context );
if ( actionOverride != null )
{
// The action must be fully-qualified with its module path.
assert actionOverride.charAt( 0 ) == '/' : actionOverride;
InternalStringBuilder uri = new InternalStringBuilder( scopedRequest.getContextPath() );
uri.append( actionOverride );
uri.append( PageFlowConstants.ACTION_EXTENSION );
scopedRequest.setRequestURI( uri.toString() );
}
//
// In case the request was already forwarded once, clear out the recorded forwarded-URI. This
// will allow us to tell whether processing the request actually forwarded somewhere.
//
scopedRequest.setForwardedURI( null );
//
// Now process the request. We create a PageFlowRequestWrapper for pageflow-specific request-scoped info.
//
PageFlowRequestWrapper wrappedRequest = PageFlowRequestWrapper.wrapRequest( ( HttpServletRequest ) request );
wrappedRequest.setScopedLookup( true );
if (as != null)
{
as.doGet( wrappedRequest, scopedResponse ); // this just calls process() -- same as doPost()
}
else
{
// The normal servlet initialization has not completed yet
// so rather than call doGet() directly, aquire the request
// dispatcher from the unwrapped outer request and call
// forward to trigger the servlet initialization.
HttpServletRequest req = scopedRequest.getOuterRequest();
RequestDispatcher rd = req.getRequestDispatcher(scopedRequest.getRequestURI());
rd.forward(wrappedRequest, scopedResponse);
}
String returnURI;
if ( ! scopedResponse.didRedirect() )
{
returnURI = scopedRequest.getForwardedURI();
if ( autoResolveExtensions == null )
{
autoResolveExtensions = DEFAULT_AUTORESOLVE_EXTENSIONS;
}
if ( returnURI != null )
{
for ( int i = 0; i < autoResolveExtensions.length; ++i )
{
if ( FileUtils.uriEndsWith( returnURI, autoResolveExtensions[i] ) )
{
scopedRequest.doForward();
return strutsLookup( context, wrappedRequest, scopedResponse, null, autoResolveExtensions );
}
}
}
}
else
{
returnURI = scopedResponse.getRedirectURI();
}
RequestContext requestContext = new RequestContext( scopedRequest, scopedResponse );
Handlers.get( context ).getStorageHandler().applyChanges( requestContext );
if ( returnURI != null )
{
return new ActionResultImpl( returnURI, scopedResponse.didRedirect(), scopedResponse.getStatusCode(),
scopedResponse.getStatusMessage(), scopedResponse.isError() );
}
else
{
return null;
}
}
/**
* If the given request is a MultipartRequestWrapper (Struts class that doesn't extend
* HttpServletRequestWrapper), return the wrapped request; otherwise, return the given request.
* @exclude
*/
public static HttpServletRequest unwrapMultipart( HttpServletRequest request )
{
if ( request instanceof MultipartRequestWrapper )
{
request = ( ( MultipartRequestWrapper ) request ).getRequest();
}
return request;
}
/**
* Get or create the current {@link GlobalApp} instance.
* @deprecated Use {@link #getGlobalApp} instead.
*
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse
* @return the current {@link GlobalApp} from the user session, or a newly-instantiated one
* (based on the user's Global.app file) if none was in the session. Failing that,
* return <code>null</code>.
*/
public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
return ensureGlobalApp( request, response, servletContext );
}
/**
* Get or create the current {@link GlobalApp} instance.
* @deprecated Use {@link #getSharedFlow} instead.
*
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse
* @return the current {@link GlobalApp} from the user session, or a newly-instantiated one
* (based on the user's Global.app file) if none was in the session. Failing that,
* return <code>null</code>.
*/
public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext )
{
GlobalApp ga = getGlobalApp( request );
if ( ga != null )
{
ga.reinitialize( request, response, servletContext );
}
else
{
ga = FlowControllerFactory.getGlobalApp( request, response, servletContext );
}
return ga;
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getBindingUpdateErrors} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static Map getBindingUpdateErrors( ServletRequest request )
{
return InternalUtils.getBindingUpdateErrors( request );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#ensureModuleConfig} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static ModuleConfig ensureModuleConfig( String modulePath, ServletRequest request, ServletContext context )
{
return InternalUtils.ensureModuleConfig( modulePath, context );
}
/**
* @deprecated This will be removed with no replacement in a future release.
*/
public static ModuleConfig getGlobalAppConfig( ServletContext servletContext )
{
return InternalUtils.getModuleConfig( GLOBALAPP_MODULE_CONTEXT_PATH, servletContext );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getModuleConfig} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static ModuleConfig getModuleConfig( String modulePath, ServletContext context )
{
return InternalUtils.getModuleConfig( modulePath, context );
}
/**
* Get the file extension from a file name.
* @deprecated Use {@link FileUtils#getFileExtension} instead.
*
* @param filename the file name.
* @return the file extension (everything after the last '.'), or the empty string if there is no file extension.
*/
public static String getFileExtension( String filename )
{
return FileUtils.getFileExtension( filename );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#getFlowControllerClassName} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static String getPageFlowClassName( String modulePath, ServletRequest request, ServletContext context )
{
return InternalUtils.getFlowControllerClassName( modulePath, request, context );
}
/**
* @deprecated This method no longer has any effect, and will be removed without replacement in a future release.
*/
public static boolean ensureAppDeployment( HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext )
{
return false;
}
/**
* Tell whether a given URI is absolute, i.e., whether it contains a scheme-part (e.g., "http:").
* @deprecated Use {@link FileUtils#isAbsoluteURI} instead.
*
* @param uri the URI to test.
* @return <code>true</code> if the given URI is absolute.
*/
public static boolean isAbsoluteURI( String uri )
{
return FileUtils.isAbsoluteURI( uri );
}
/**
* @deprecated Use {@link #getCurrentPageFlow} instead.
*/
public static final PageFlowController ensureCurrentPageFlow( HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext )
{
try
{
FlowControllerFactory factory = FlowControllerFactory.get( servletContext );
return factory.getPageFlowForRequest( new RequestContext( request, response ) );
}
catch ( InstantiationException e )
{
_log.error( "Could not instantiate PageFlowController for request " + request.getRequestURI(), e );
}
catch ( IllegalAccessException e )
{
_log.error( "Could not instantiate PageFlowController for request " + request.getRequestURI(), e );
}
return null;
}
/**
* @deprecated Use {@link #getCurrentPageFlow} instead.
*/
public static final PageFlowController ensureCurrentPageFlow( HttpServletRequest request,
HttpServletResponse response )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
if ( servletContext == null && _log.isWarnEnabled() )
{
_log.warn( "could not get ServletContext from request " + request );
}
return ensureCurrentPageFlow( request, response, servletContext );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#addBindingUpdateError} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void addBindingUpdateError( ServletRequest request, String expression, String message, Throwable e )
{
InternalUtils.addBindingUpdateError( request, expression, message, e );
}
/**
* @deprecated This is an internal utility. {@link ServletUtils#dumpRequest} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void dumpRequest( HttpServletRequest request, PrintStream output )
{
ServletUtils.dumpRequest( request, output );
}
/**
* @deprecated This is an internal utility. {@link ServletUtils#dumpServletContext} can be used, but it is
* not guaranteed to be supported in the future.
*/
public static void dumpServletContext( ServletContext context, PrintStream output )
{
ServletUtils.dumpServletContext( context, output );
}
/**
* @deprecated Use {@link ServletUtils#preventCache} instead.
*/
public static void preventCache( HttpServletResponse response )
{
ServletUtils.preventCache( response );
}
/**
* @deprecated This is an internal utility. {@link InternalUtils#setCurrentActionResolver} can be used, but it is
* not guaranteed to be supported in the future. This method will be removed in the next version.
*/
public static void setCurrentActionResolver( ActionResolver resolver, HttpServletRequest request )
{
ServletContext servletContext = InternalUtils.getServletContext( request );
InternalUtils.setCurrentActionResolver( resolver, request, servletContext );
}
/**
* Create a raw action URI, which can be modified before being sent through the registered URL rewriting chain
* using {@link URLRewriterService#rewriteURL}. Use {@link #getRewrittenActionURI} to get a fully-rewritten URI.
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param actionName the action name to convert into a MutableURI; may be qualified with a path from the webapp
* root, in which case the parent directory from the current request is <i>not</i> used.
* @return a MutableURI for the given action, suitable for URL rewriting.
* @throws URISyntaxException if there is a problem converting the action URI (derived from processing the given
* action name) into a MutableURI.
*/
public static MutableURI getActionURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String actionName )
throws URISyntaxException
{
if ( actionName.length() < 1 ) throw new IllegalArgumentException( "actionName must be non-empty" );
/*
* The implementation for HttpServletRequest method getContextPath()
* is not consistant across containers. The spec says the "container
* does not decode this string." However, the string returned in
* Tomcat is decoded. (See Tomcat bugzilla bug 39503) Also this method
* returns a decoded string in some containers if the request is a
* forward where the RequestDispatcher was acquired using a relative
* path. It seems that it is only the space character in the context
* path that causes us issues using the java.net.URI class in our
* MutableURI.setURI(). So,... check for a decoded space and encode it.
*/
String contextPath = request.getContextPath();
if (contextPath.indexOf(' ') != -1) {
contextPath = contextPath.replace(" ", "%20");
}
InternalStringBuilder actionURI = new InternalStringBuilder(contextPath);
if ( actionName.charAt( 0 ) != '/' )
{
actionURI.append( InternalUtils.getModulePathFromReqAttr( request ) );
actionURI.append( '/' );
}
actionURI.append( actionName );
if ( ! actionName.endsWith( ACTION_EXTENSION ) ) actionURI.append( ACTION_EXTENSION );
FreezableMutableURI uri = new FreezableMutableURI();
uri.setEncoding( response.getCharacterEncoding() );
uri.setPath( actionURI.toString() );
return uri;
}
/**
* Create a fully-rewritten URI given an action name and parameters.
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param actionName the action name to convert into a fully-rewritten URI; may be qualified with a path from the
* webapp root, in which case the parent directory from the current request is <i>not</i> used.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this url.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there is a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenActionURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String actionName, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
MutableURI uri = getActionURI( servletContext, request, response, actionName );
if ( params != null ) uri.addParameters( params, false );
if ( fragment != null ) uri.setFragment( uri.encode( fragment ) );
boolean needsToBeSecure = needsToBeSecure( servletContext, request, uri.getPath(), true );
URLRewriterService.rewriteURL( servletContext, request, response, uri, URLType.ACTION, needsToBeSecure );
String key = getURLTemplateKey( URLType.ACTION, needsToBeSecure );
URIContext uriContext = URIContextFactory.getInstance( forXML );
return URLRewriterService.getTemplatedURL( servletContext, request, uri, key, uriContext );
}
/**
* Create a fully-rewritten URI given a path and parameters.
*
* <p> Calls the rewriter service using a type of {@link URLType#RESOURCE}. </p>
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param path the path to process into a fully-rewritten URI.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this URI.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there's a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenResourceURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
return rewriteResourceOrHrefURL( servletContext, request, response, path, params, fragment, forXML, URLType.RESOURCE );
}
/**
* Create a fully-rewritten URI given a path and parameters.
*
* <p> Calls the rewriter service using a type of {@link URLType#ACTION}. </p>
*
* @param servletContext the current ServletContext.
* @param request the current HttpServletRequest.
* @param response the current HttpServletResponse.
* @param path the path to process into a fully-rewritten URI.
* @param params the additional parameters to include in the URI query.
* @param fragment the fragment (anchor or location) for this URI.
* @param forXML flag indicating that the query of the uri should be written
* using the "&amp;" entity, rather than the character, '&'.
* @return a fully-rewritten URI for the given action.
* @throws URISyntaxException if there's a problem converting the action URI (derived
* from processing the given action name) into a MutableURI.
*/
public static String getRewrittenHrefURI( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML )
throws URISyntaxException
{
return rewriteResourceOrHrefURL( servletContext, request, response, path, params, fragment, forXML, URLType.ACTION );
}
private static String rewriteResourceOrHrefURL( ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, String path, Map params,
String fragment, boolean forXML, URLType urlType )
throws URISyntaxException
{
boolean encoded = false;
UrlConfig urlConfig = ConfigUtil.getConfig().getUrlConfig();
if (urlConfig != null) {
encoded = !urlConfig.isUrlEncodeUrls();
}
FreezableMutableURI uri = new FreezableMutableURI();
uri.setEncoding( response.getCharacterEncoding() );
uri.setURI( path, encoded );
if ( params != null )
{
uri.addParameters( params, false );
}
if ( fragment != null )
{
uri.setFragment( uri.encode( fragment ) );
}
URIContext uriContext = URIContextFactory.getInstance( forXML );
if ( uri.isAbsolute() )
{
return uri.getURIString( uriContext );
}
if ( path.length() != 0 && path.charAt( 0 ) != '/' )
{
String reqUri = request.getRequestURI();
String reqPath = reqUri.substring( 0, reqUri.lastIndexOf( '/' ) + 1 );
uri.setPath( reqPath + uri.getPath() );
}
boolean needsToBeSecure = needsToBeSecure( servletContext, request, uri.getPath(), true );
URLRewriterService.rewriteURL( servletContext, request, response, uri, urlType, needsToBeSecure );
String key = getURLTemplateKey( urlType, needsToBeSecure );
return URLRewriterService.getTemplatedURL( servletContext, request, uri, key, uriContext );
}
/**
* Tell whether a given URI should be written to be secure.
* @param context the current ServletContext.
* @param request the current HttpServletRequest.
* @param uri the URI to check.
* @param stripContextPath if <code>true</code>, strip the webapp context path from the URI before
* processing it.
* @return <code>true</code> when:
* <ul>
* <li>the given URI is configured in the deployment descriptor to be secure (according to
* {@link SecurityProtocol}), or
* <li>the given URI is not configured in the deployment descriptor, and the current request
* is secure ({@link HttpServletRequest#isSecure} returns
* <code>true</code>).
* </ul>
* <code>false</code> when:
* <ul>
* <li>the given URI is configured explicitly in the deployment descriptor to be unsecure
* (according to {@link SecurityProtocol}), or
* <li>the given URI is not configured in the deployment descriptor, and the current request
* is unsecure ({@link HttpServletRequest#isSecure} returns
* <code>false</code>).
* </ul>
*/
public static boolean needsToBeSecure(ServletContext context, ServletRequest request,
String uri, boolean stripContextPath)
{
// Get the web-app relative path for security check
String secureCheck = uri;
if (stripContextPath) {
String contextPath = ((HttpServletRequest) request).getContextPath();
if (secureCheck.startsWith(contextPath)) {
secureCheck = secureCheck.substring(contextPath.length());
}
}
boolean secure = false;
if (secureCheck.indexOf('?') > -1) {
secureCheck = secureCheck.substring(0, secureCheck.indexOf('?'));
}
SecurityProtocol sp = getSecurityProtocol(secureCheck, context, (HttpServletRequest) request);
if (sp.equals(SecurityProtocol.UNSPECIFIED)) {
secure = request.isSecure();
}
else {
secure = sp.equals(SecurityProtocol.SECURE);
}
return secure;
}
/**
* Returns a key for the URL template type given the URL type and a
* flag indicating a secure URL or not.
*
* @param urlType the type of URL (ACTION, RESOURCE).
* @param needsToBeSecure indicates that the template should be for a secure URL.
* @return the key/type of template to use.
*/
public static String getURLTemplateKey( URLType urlType, boolean needsToBeSecure )
{
String key = URLTemplatesFactory.ACTION_TEMPLATE;
if ( urlType.equals( URLType.ACTION ) )
{
if ( needsToBeSecure )
{
key = URLTemplatesFactory.SECURE_ACTION_TEMPLATE;
}
else
{
key = URLTemplatesFactory.ACTION_TEMPLATE;
}
}
else if ( urlType.equals( URLType.RESOURCE ) )
{
if ( needsToBeSecure )
{
key = URLTemplatesFactory.SECURE_RESOURCE_TEMPLATE;
}
else
{
key = URLTemplatesFactory.RESOURCE_TEMPLATE;
}
}
return key;
}
/**
* Get an uninitialized instance of a container specific URLTemplatesFactory
* from the ServletContainerAdapter. If none exists, this returns an instance
* of {@link DefaultURLTemplatesFactory}. Caller should then set the known
* and required tokens, call the {@link URLTemplatesFactory#load(javax.servlet.ServletContext)}
* method and {@link URLTemplatesFactory#initServletContext(javax.servlet.ServletContext,
* org.apache.beehive.netui.core.urltemplates.URLTemplatesFactory)}.
*
* <p>
* IMPORTANT NOTE - Always try to get the application instance from the ServletContext
* by calling {@link URLTemplatesFactory#getURLTemplatesFactory(javax.servlet.ServletContext)}.
* Then, if a new URLTemplatesFactory must be created, call this method.
* </p>
*
* @param servletContext
* @return a container specific implementation of URLTemplatesFactory, or
* {@link DefaultURLTemplatesFactory}.
*/
public static URLTemplatesFactory createURLTemplatesFactory( ServletContext servletContext )
{
// get the URLTemplatesFactory from the containerAdapter.
ServletContainerAdapter containerAdapter = AdapterManager.getServletContainerAdapter( servletContext );
URLTemplatesFactory factory = (URLTemplatesFactory) containerAdapter.getFactory( URLTemplatesFactory.class, null, null );
// if there's no URLTemplatesFactory, use our default impl.
if ( factory == null )
{
factory = new DefaultURLTemplatesFactory();
}
return factory;
}
/**
* Make sure that when this page is rendered, it will set headers in the response to prevent caching.
* Because these headers are lost on server forwards, we set a request attribute to cause the headers
* to be set right before the page is rendered. This attribute can be read via
* {@link #isPreventCache(javax.servlet.ServletRequest)}.
*
* @param request the servlet request
*/
static void setPreventCache( ServletRequest request ) {
assert request != null;
request.setAttribute(PREVENT_CACHE_ATTR, Boolean.TRUE);
}
/**
* Internal getter that reports whether this request should prevent caching. This flag is set via the
* {@link #setPreventCache(javax.servlet.ServletRequest)} attribute.
* @param request the servlet request
* @return <code>true</code> if the framework has set the prevent cache flag
*/
static boolean isPreventCache(ServletRequest request) {
assert request != null;
return request.getAttribute(PREVENT_CACHE_ATTR) != null;
}
}
| 80,113 | 0.642443 | 0.641694 | 1,770 | 44.261581 | 37.266865 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529379 | false | false |
4
|
b52b7b0b9d5ba1beb76b8bfa46c24da8822f9dba
| 13,846,974,576,630 |
b60e026f3daf93962d0295bd35f9c4359d9556aa
|
/TestProject/src/others/CoinChange.java
|
24bde6aceeabe9197d373b9ffbb9525a8a772b25
|
[] |
no_license
|
harshit027/Algorithms
|
https://github.com/harshit027/Algorithms
|
6cf9088c860db464c565e245e8e1509ccf94f7f6
|
9c0e06d451262cc02e0e3622d7039aaa9f1cb1da
|
refs/heads/master
| 2021-01-17T14:50:55.178000 | 2017-08-21T03:10:11 | 2017-08-21T03:10:11 | 55,386,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package others;
public class CoinChange {
public static void main(String args[])
{
int[] S={1,2,3};
int sum=5;
System.out.println(count(S,S.length,sum));
}
public static int count(int [] S, int noOfCoins, int sum)
{
if(sum==0)
return 1;
if(sum < 0)
return 0;
if(sum >0 && noOfCoins<=0)
return 0;
return count(S, noOfCoins-1, sum) + count(S, noOfCoins, sum-S[noOfCoins-1]);
}
}
|
UTF-8
|
Java
| 418 |
java
|
CoinChange.java
|
Java
|
[] | null |
[] |
package others;
public class CoinChange {
public static void main(String args[])
{
int[] S={1,2,3};
int sum=5;
System.out.println(count(S,S.length,sum));
}
public static int count(int [] S, int noOfCoins, int sum)
{
if(sum==0)
return 1;
if(sum < 0)
return 0;
if(sum >0 && noOfCoins<=0)
return 0;
return count(S, noOfCoins-1, sum) + count(S, noOfCoins, sum-S[noOfCoins-1]);
}
}
| 418 | 0.610048 | 0.578947 | 25 | 15.72 | 19.576557 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.12 | false | false |
4
|
6c428903499fbce1d3190c29058d82a8658ec167
| 5,909,875,011,046 |
476754af7c3897dca96c6223c5d8968f07247ec4
|
/src/main/java/com/firm/investment/project/service/IProjectProgressService.java
|
6c1ed0f7b426cfb64a3eda4e5d5b4dd7d08f56e8
|
[] |
no_license
|
vipliao/Investment
|
https://github.com/vipliao/Investment
|
af1b3c77a1f1affebd95e40205db1ec5e0ae2e54
|
6e7a53919930f2dfba9d347cf351355884f36290
|
refs/heads/master
| 2020-04-23T07:05:26.028000 | 2019-02-16T11:27:57 | 2019-02-16T11:27:57 | 170,996,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.firm.investment.project.service;
import java.util.List;
import com.firm.investment.base.service.IBaseService;
import com.firm.investment.project.entity.ProjectProgressEntity;
import com.firm.investment.project.vo.ProjectProgressVO;
public interface IProjectProgressService extends IBaseService<ProjectProgressEntity, ProjectProgressVO>{
List<ProjectProgressVO> queryPjtProgressByPjtId(String projectId) throws Exception;
List<ProjectProgressVO> queryPjtProgressByStepId(String stepId) throws Exception;
}
|
UTF-8
|
Java
| 527 |
java
|
IProjectProgressService.java
|
Java
|
[] | null |
[] |
package com.firm.investment.project.service;
import java.util.List;
import com.firm.investment.base.service.IBaseService;
import com.firm.investment.project.entity.ProjectProgressEntity;
import com.firm.investment.project.vo.ProjectProgressVO;
public interface IProjectProgressService extends IBaseService<ProjectProgressEntity, ProjectProgressVO>{
List<ProjectProgressVO> queryPjtProgressByPjtId(String projectId) throws Exception;
List<ProjectProgressVO> queryPjtProgressByStepId(String stepId) throws Exception;
}
| 527 | 0.851992 | 0.851992 | 15 | 34.133335 | 36.132843 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false |
4
|
765d1446df07c3f384972e68338cdda537b4a885
| 26,731,876,506,743 |
a3576d872c0ea9588029579b38c6017059d1e448
|
/ClientThread.java
|
3cf38f8289a7d9eeb6402e86518b4fed9ba4fe71
|
[] |
no_license
|
fr4nca/client-server-java
|
https://github.com/fr4nca/client-server-java
|
ef51ada312b40005795ed383dd77ab10bef2fefe
|
eaebe9c7fa9668e71c88b31a7160d6f7b33d6e70
|
refs/heads/master
| 2020-05-06T15:40:50.090000 | 2019-04-08T20:01:25 | 2019-04-08T20:01:25 | 179,152,160 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
class ClientThread extends Thread {
String linha = null;
Socket cliente = null;
Scanner entrada = null;
public ClientThread(Socket cliente, String nome) {
this.cliente = cliente;
this.setName(nome);
}
public String getIpAddress() {
return this.cliente.getInetAddress().getHostAddress();
}
public int getPortNumber() {
return this.cliente.getPort();
}
public void close() {
try {
this.cliente.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
entrada = new Scanner(this.cliente.getInputStream());
while (entrada.hasNextLine()) {
linha = entrada.nextLine();
if (linha.equals("Exit")) {
System.out.println("Deixando o servidor..");
close();
Server.removeCliente(this);
break;
}
System.out.println(this.getName() + " diz: " + linha);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println(this.getName() + " fechou a conexão");
cliente.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
UTF-8
|
Java
| 1,158 |
java
|
ClientThread.java
|
Java
|
[] | null |
[] |
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
class ClientThread extends Thread {
String linha = null;
Socket cliente = null;
Scanner entrada = null;
public ClientThread(Socket cliente, String nome) {
this.cliente = cliente;
this.setName(nome);
}
public String getIpAddress() {
return this.cliente.getInetAddress().getHostAddress();
}
public int getPortNumber() {
return this.cliente.getPort();
}
public void close() {
try {
this.cliente.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
entrada = new Scanner(this.cliente.getInputStream());
while (entrada.hasNextLine()) {
linha = entrada.nextLine();
if (linha.equals("Exit")) {
System.out.println("Deixando o servidor..");
close();
Server.removeCliente(this);
break;
}
System.out.println(this.getName() + " diz: " + linha);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println(this.getName() + " fechou a conexão");
cliente.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 1,158 | 0.645635 | 0.645635 | 56 | 19.678572 | 16.783396 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.392857 | false | false |
4
|
daea459af365c3026a21d615f1a95159bccb046a
| 29,076,928,654,020 |
4008f0de61896c1600a9671327c047e556027359
|
/src/main/java/com/luckyzz/sporegame/world/SpawningPart.java
|
be5ee4b3a622554be541f70641c374931c2922d4
|
[] |
no_license
|
luckyzet/Spore
|
https://github.com/luckyzet/Spore
|
4a0ea8a0843cb2fc9ca5a7cf1a3cae764fd5e0a0
|
076aa630ba75d3cfe1561b93b17dc1d34a564cd8
|
refs/heads/master
| 2023-07-09T07:35:43.798000 | 2021-08-21T23:33:30 | 2021-08-21T23:33:30 | 398,667,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.luckyzz.sporegame.world;
import com.luckyzz.sporegame.character.level.CharacterLevel;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
public enum SpawningPart {
SPAWN(0, SporeWorldType.SPAWN),
FIRST(1, SporeWorldType.ARENA, 1,2,3,4,5,6,7,8,9,10),
SECOND(2, SporeWorldType.ARENA, 11,12,13,14,15,16,17,18,19,20),
THIRD(3, SporeWorldType.ARENA, 21,22,23,24,25,26,27,28,29,30),
FOURTH(4, SporeWorldType.ARENA, 31,32,33,34,35,36,37,38,39,40);
private final int index;
private final SporeWorldType type;
private final List<Integer> levels;
SpawningPart(final int index, @NotNull final SporeWorldType type, @NotNull final Integer... levels) {
this.index = index;
this.type = type;
this.levels = Arrays.asList(levels);
}
public static @NotNull SpawningPart fromIndex(final int index) {
for (final SpawningPart value : values()) {
if(value.index == index) {
return value;
}
}
throw new IllegalArgumentException();
}
public static @NotNull SpawningPart fromLevels(final int index) {
for (final SpawningPart value : values()) {
if(value.levels.contains(index)) {
return value;
}
}
throw new IllegalArgumentException();
}
public int getIndex() {
return index;
}
public @NotNull SporeWorldType getWorldType() {
return type;
}
public @NotNull List<Integer> getLevels() {
return levels;
}
public boolean isSpawningPart(@NotNull final CharacterLevel level) {
return levels.contains(level.getIndex());
}
}
|
UTF-8
|
Java
| 1,728 |
java
|
SpawningPart.java
|
Java
|
[] | null |
[] |
package com.luckyzz.sporegame.world;
import com.luckyzz.sporegame.character.level.CharacterLevel;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
public enum SpawningPart {
SPAWN(0, SporeWorldType.SPAWN),
FIRST(1, SporeWorldType.ARENA, 1,2,3,4,5,6,7,8,9,10),
SECOND(2, SporeWorldType.ARENA, 11,12,13,14,15,16,17,18,19,20),
THIRD(3, SporeWorldType.ARENA, 21,22,23,24,25,26,27,28,29,30),
FOURTH(4, SporeWorldType.ARENA, 31,32,33,34,35,36,37,38,39,40);
private final int index;
private final SporeWorldType type;
private final List<Integer> levels;
SpawningPart(final int index, @NotNull final SporeWorldType type, @NotNull final Integer... levels) {
this.index = index;
this.type = type;
this.levels = Arrays.asList(levels);
}
public static @NotNull SpawningPart fromIndex(final int index) {
for (final SpawningPart value : values()) {
if(value.index == index) {
return value;
}
}
throw new IllegalArgumentException();
}
public static @NotNull SpawningPart fromLevels(final int index) {
for (final SpawningPart value : values()) {
if(value.levels.contains(index)) {
return value;
}
}
throw new IllegalArgumentException();
}
public int getIndex() {
return index;
}
public @NotNull SporeWorldType getWorldType() {
return type;
}
public @NotNull List<Integer> getLevels() {
return levels;
}
public boolean isSpawningPart(@NotNull final CharacterLevel level) {
return levels.contains(level.getIndex());
}
}
| 1,728 | 0.637731 | 0.59375 | 61 | 27.327869 | 24.83831 | 105 | false | false | 29 | 0.050347 | 0 | 0 | 0 | 0 | 1.163934 | false | false |
4
|
c1d3aeef7b5ea0016db52f30cba8e95162b99168
| 4,166,118,295,583 |
083b8f723445f7d5e586f35cf90a27134161fe9f
|
/src/main/java/com/adrian/alkemyChallenge/repository/MovieRepository.java
|
3c1ce289ba5c80fed85e0eaddd489e19a48ac9a5
|
[] |
no_license
|
adrian010/alkemy
|
https://github.com/adrian010/alkemy
|
86fe7f96e57d82d6a7d457fbd1e8043b8cb8b74b
|
abeb58a592f325b06e0abc1bf399357c9a150c44
|
refs/heads/main
| 2023-08-25T05:50:46.221000 | 2021-10-31T22:13:37 | 2021-10-31T22:13:37 | 372,324,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.adrian.alkemyChallenge.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.adrian.alkemyChallenge.model.Movie;
public interface MovieRepository extends JpaRepository<Movie, Long>{
List<Movie> findByTitle(String title);
List<Movie> findAllByOrderByDateCreatedAsc();
List<Movie> findAllByOrderByDateCreatedDesc();
List<Movie> findByGenreId(Long genreId);
}
|
UTF-8
|
Java
| 439 |
java
|
MovieRepository.java
|
Java
|
[] | null |
[] |
package com.adrian.alkemyChallenge.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.adrian.alkemyChallenge.model.Movie;
public interface MovieRepository extends JpaRepository<Movie, Long>{
List<Movie> findByTitle(String title);
List<Movie> findAllByOrderByDateCreatedAsc();
List<Movie> findAllByOrderByDateCreatedDesc();
List<Movie> findByGenreId(Long genreId);
}
| 439 | 0.808656 | 0.808656 | 19 | 22.105263 | 24.395632 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.842105 | false | false |
4
|
3aeded2146e63db2b723ae9cf914a395e7fd6feb
| 9,698,036,212,372 |
aeed60d78780a5ea87043a3a5650be412a5e4ebc
|
/selenium/src/main/java/com/test/basics/CssSelectors.java
|
712ea6ae8dcbc2f1ddbc35878c8b34b122fcde87
|
[] |
no_license
|
srikanthgurram/selenium_training
|
https://github.com/srikanthgurram/selenium_training
|
5f4c77549a4b3050fdb86b329fd966f3c33a54a2
|
48a204ec422052f4394e8cfe0b592598c99783bd
|
refs/heads/master
| 2021-01-11T12:17:04.941000 | 2017-03-08T18:53:21 | 2017-03-08T18:53:21 | 76,511,559 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.test.basics;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Created by srikanth on 11/1/17.
*/
public class CssSelectors {
String baseUrl = "http://getbootstrap.com/examples/signin/";
WebDriver driver;
/**
* step1: Open URL in chrome
* step2: Enter Text in email, pwd
* step3: select the checkbox
* step4: click on Singin Button
*/
@BeforeClass
public void openBrowser(){
// get the chromedriver instance
System.setProperty("webdriver.chrome.driver",
"/home/srikanth/Downloads/softwares/drivers/chromedriver");
driver = new ChromeDriver();
driver.get(baseUrl);
}
@AfterClass
public void quitBrowser(){
// driver.quit();
}
@Test
public void verifyLoginPage(){
// enter text in email
WebElement emailField = driver.findElement(
By.cssSelector("input#inputEmail.form-control"));
//enter text in pwd
WebElement pwdField = driver.findElement(
By.cssSelector("input#inputPassword.form-control"));
// select the checkbox
WebElement rememberCheckBox = driver.findElement(
By.cssSelector("div.checkbox input"));
//click on the sign in button
WebElement signInBtn = driver.findElement(
By.cssSelector("button.btn.btn-lg.btn-primary.btn-block"));
// actions
emailField.sendKeys("user123@gmail.com");
pwdField.sendKeys("Welcome123");
rememberCheckBox.click();
signInBtn.click();
}
}
|
UTF-8
|
Java
| 1,833 |
java
|
CssSelectors.java
|
Java
|
[
{
"context": "rt org.testng.annotations.Test;\n\n/**\n * Created by srikanth on 11/1/17.\n */\npublic class CssSelectors {\n S",
"end": 330,
"score": 0.9996115565299988,
"start": 322,
"tag": "USERNAME",
"value": "srikanth"
},
{
"context": "\n\n // actions\n emailField.sendKeys(\"user123@gmail.com\");\n pwdField.sendKeys(\"Welcome123\");\n ",
"end": 1718,
"score": 0.9999123215675354,
"start": 1701,
"tag": "EMAIL",
"value": "user123@gmail.com"
},
{
"context": "(\"user123@gmail.com\");\n pwdField.sendKeys(\"Welcome123\");\n rememberCheckBox.click();\n sign",
"end": 1759,
"score": 0.9990940093994141,
"start": 1749,
"tag": "PASSWORD",
"value": "Welcome123"
}
] | null |
[] |
package com.test.basics;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Created by srikanth on 11/1/17.
*/
public class CssSelectors {
String baseUrl = "http://getbootstrap.com/examples/signin/";
WebDriver driver;
/**
* step1: Open URL in chrome
* step2: Enter Text in email, pwd
* step3: select the checkbox
* step4: click on Singin Button
*/
@BeforeClass
public void openBrowser(){
// get the chromedriver instance
System.setProperty("webdriver.chrome.driver",
"/home/srikanth/Downloads/softwares/drivers/chromedriver");
driver = new ChromeDriver();
driver.get(baseUrl);
}
@AfterClass
public void quitBrowser(){
// driver.quit();
}
@Test
public void verifyLoginPage(){
// enter text in email
WebElement emailField = driver.findElement(
By.cssSelector("input#inputEmail.form-control"));
//enter text in pwd
WebElement pwdField = driver.findElement(
By.cssSelector("input#inputPassword.form-control"));
// select the checkbox
WebElement rememberCheckBox = driver.findElement(
By.cssSelector("div.checkbox input"));
//click on the sign in button
WebElement signInBtn = driver.findElement(
By.cssSelector("button.btn.btn-lg.btn-primary.btn-block"));
// actions
emailField.sendKeys("<EMAIL>");
pwdField.sendKeys("<PASSWORD>");
rememberCheckBox.click();
signInBtn.click();
}
}
| 1,823 | 0.643753 | 0.63557 | 65 | 27.200001 | 21.242338 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369231 | false | false |
4
|
a847d60f103ebd17419ffd022353ba6ff8b74f63
| 33,535,104,717,002 |
61aa634ce7451851c2e562c9f8094f986f41e916
|
/src/com/seleniumpractice/FileUploadPopUpHandler.java
|
a1fadc1af97489bd5c001530c40e844b229d69ca
|
[] |
no_license
|
manjunathnp/SeleniumPractice
|
https://github.com/manjunathnp/SeleniumPractice
|
5dc1b99d2a85f762666a63d4bfb962982a428af0
|
7830a287d61c85f0a21bd2da631d7416d4846ccb
|
refs/heads/master
| 2021-06-10T02:19:52.376000 | 2021-04-18T08:40:27 | 2021-04-18T08:40:27 | 130,397,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.seleniumpractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUploadPopUpHandler {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
System.out.println("Chrome Browser Launched Successfully!");
driver.manage().window().maximize();
//Launch File Uploader site
driver.get("https://html.com/input-type-file/");
//Upload file
WebElement fileUploadBtn = driver.findElement(By.xpath("//input[@id='fileupload']"));
fileUploadBtn.sendKeys("C:\\Users\\acer\\Desktop\\TestFile.txt");
}
}
|
UTF-8
|
Java
| 773 |
java
|
FileUploadPopUpHandler.java
|
Java
|
[] | null |
[] |
package com.seleniumpractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUploadPopUpHandler {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
System.out.println("Chrome Browser Launched Successfully!");
driver.manage().window().maximize();
//Launch File Uploader site
driver.get("https://html.com/input-type-file/");
//Upload file
WebElement fileUploadBtn = driver.findElement(By.xpath("//input[@id='fileupload']"));
fileUploadBtn.sendKeys("C:\\Users\\acer\\Desktop\\TestFile.txt");
}
}
| 773 | 0.741268 | 0.741268 | 26 | 28.73077 | 27.147118 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false |
4
|
569f35f4f70418bbf860b89531adbfe7259bd22f
| 13,211,319,404,221 |
86d2613b9d317ca345483404d272745f03e7aac0
|
/backend/src/main/java/com/deviget/minesweeperapi/repository/BoardRepository.java
|
f8e2aec84d358b8147489a574707d3d90240dd17
|
[] |
no_license
|
cvallejosh1/minesweeper
|
https://github.com/cvallejosh1/minesweeper
|
17c70993a7d0d529f51397c81241470fb21094c8
|
33fdb863ae9fe81fc18c767b0f14ec1a7cb43a98
|
refs/heads/main
| 2023-04-20T13:52:16.517000 | 2021-05-11T04:25:42 | 2021-05-11T04:25:42 | 364,115,393 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.deviget.minesweeperapi.repository;
import com.deviget.minesweeperapi.repository.entity.BoardEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BoardRepository extends JpaRepository<BoardEntity, Integer> {
}
|
UTF-8
|
Java
| 320 |
java
|
BoardRepository.java
|
Java
|
[] | null |
[] |
package com.deviget.minesweeperapi.repository;
import com.deviget.minesweeperapi.repository.entity.BoardEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BoardRepository extends JpaRepository<BoardEntity, Integer> {
}
| 320 | 0.85625 | 0.85625 | 10 | 31 | 29.883106 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
4
|
489bc0235791b2267696669ca7d6e18d8bdb6e39
| 13,700,945,737,257 |
9113a0b3b9e541417e108a0418a931a6d5fdf503
|
/app/src/main/java/com/jizni/ximalaya/fragmnet/fragment_recommend_viewpager/Fragment_ImageView.java
|
420d0bddfefc773ec1b4a45b76cb25f853bde600
|
[] |
no_license
|
ximalayafm/XiMaLaYa
|
https://github.com/ximalayafm/XiMaLaYa
|
03937f7aa3697d54c6cc749c0fbc06e8296da0cd
|
1073841083b8b22ed529221096b17e24d04fe3bd
|
refs/heads/master
| 2020-02-26T13:48:14.710000 | 2016-07-27T10:00:12 | 2016-07-27T10:00:12 | 64,205,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jizni.ximalaya.fragmnet.fragment_recommend_viewpager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.jizni.ximalaya.R;
import com.jizni.ximalaya.activity.Recommend_viewpager_fragment_imageView_webView_Activity;
import com.squareup.picasso.Picasso;
/**
* Created by jinzhe on 2016/7/22.
*/
public class Fragment_ImageView extends Fragment implements View.OnClickListener {
private View view;
private ImageView fragment_imageView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_recommend_viewpager, container, false);
initView(view);
String path=getArguments().getString("path");
Picasso.with(getActivity()).load(path).into(fragment_imageView);
return view;
}
private void initView(View view) {
fragment_imageView = (ImageView) view.findViewById(R.id.fragment_imageView);
fragment_imageView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fragment_imageView:
Intent intent=new Intent(getActivity(), Recommend_viewpager_fragment_imageView_webView_Activity.class);
startActivity(intent);
break;
}
}
}
|
UTF-8
|
Java
| 1,617 |
java
|
Fragment_ImageView.java
|
Java
|
[
{
"context": "t com.squareup.picasso.Picasso;\n\n/**\n * Created by jinzhe on 2016/7/22.\n */\npublic class Fragment_ImageView",
"end": 518,
"score": 0.9996570944786072,
"start": 512,
"tag": "USERNAME",
"value": "jinzhe"
}
] | null |
[] |
package com.jizni.ximalaya.fragmnet.fragment_recommend_viewpager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.jizni.ximalaya.R;
import com.jizni.ximalaya.activity.Recommend_viewpager_fragment_imageView_webView_Activity;
import com.squareup.picasso.Picasso;
/**
* Created by jinzhe on 2016/7/22.
*/
public class Fragment_ImageView extends Fragment implements View.OnClickListener {
private View view;
private ImageView fragment_imageView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_recommend_viewpager, container, false);
initView(view);
String path=getArguments().getString("path");
Picasso.with(getActivity()).load(path).into(fragment_imageView);
return view;
}
private void initView(View view) {
fragment_imageView = (ImageView) view.findViewById(R.id.fragment_imageView);
fragment_imageView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fragment_imageView:
Intent intent=new Intent(getActivity(), Recommend_viewpager_fragment_imageView_webView_Activity.class);
startActivity(intent);
break;
}
}
}
| 1,617 | 0.714904 | 0.709957 | 51 | 30.705883 | 29.187222 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568627 | false | false |
4
|
ec2463bcb19de737795235030140cb41f226573d
| 23,244,363,034,305 |
4131ec8cffaa36b207e38a34880135c6deb24aa9
|
/xwidget/src/main/java/com/mic/customview/xx.java
|
9e3e7499ec0411b19a7d284e174ae85d6af67c1e
|
[] |
no_license
|
lpjhblpj/FimicsJoke
|
https://github.com/lpjhblpj/FimicsJoke
|
bb3dfbb4ee8ab4440226a4ac3a73bad348cfe14a
|
fde1cb6c0907c9b8706962bfff4bb91884a6c130
|
refs/heads/master
| 2018-10-25T20:17:04.943000 | 2018-08-26T13:01:58 | 2018-08-26T13:01:58 | 143,539,150 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mic.customview;
public class xx {
}
|
UTF-8
|
Java
| 49 |
java
|
xx.java
|
Java
|
[] | null |
[] |
package com.mic.customview;
public class xx {
}
| 49 | 0.734694 | 0.734694 | 4 | 11.25 | 11.321992 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
4
|
60611d02fca7a950509f3e118bc468bfecb0b2a5
| 11,647,951,327,471 |
3a8ecc6542a97247ea8e391a328041ae573ea1d0
|
/src/main/java/org/superops/demo/moviebooking/model/db/Theatre.java
|
a71f585740f29275b622c3cacbd55588801d39e6
|
[] |
no_license
|
niranjanramesh1997/booking-application
|
https://github.com/niranjanramesh1997/booking-application
|
553df34d99385c8bbc127f4368d7dd1a22551c6f
|
9da3b8be2bfc8c113d1943fe80b8791c83c163ab
|
refs/heads/master
| 2023-07-04T02:24:40.366000 | 2021-08-03T05:37:00 | 2021-08-03T05:37:00 | 392,202,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.superops.demo.moviebooking.model.db;
import lombok.*;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity(name = "THEATRE")
public class Theatre {
@Id
private Long theatreId;
private String theatreName;
private Integer totalScreens;
@OneToOne
@JoinColumn(name = "locationId", referencedColumnName = "locationId")
private Location location;
}
|
UTF-8
|
Java
| 435 |
java
|
Theatre.java
|
Java
|
[] | null |
[] |
package org.superops.demo.moviebooking.model.db;
import lombok.*;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity(name = "THEATRE")
public class Theatre {
@Id
private Long theatreId;
private String theatreName;
private Integer totalScreens;
@OneToOne
@JoinColumn(name = "locationId", referencedColumnName = "locationId")
private Location location;
}
| 435 | 0.737931 | 0.737931 | 23 | 17.913044 | 17.569521 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false |
4
|
57994b9c2c377e27489c0e834905f18335224c33
| 17,119,739,709,897 |
988c5ee650f747a4fb4392e866daeafd627e270c
|
/beautifulworld/src/com/internousdev/beautifulworlds/dto/MCategoryDTO.java
|
a54bc3f9542aa4bad98efcbabbfec7920920167f
|
[] |
no_license
|
kohsuke184/mySite
|
https://github.com/kohsuke184/mySite
|
c1fc6c672964472ab913b709f48ce218cfb4cf53
|
a1ab066b9bf94abd5e82c459dcfadc27a11bc856
|
refs/heads/master
| 2020-05-03T09:21:14.095000 | 2019-04-13T06:53:39 | 2019-04-13T06:53:39 | 178,552,064 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.internousdev.beautifulworlds.dto;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class MCategoryDTO {
private int id;
private int categoryId;
private String categoryName;
private String categoryDescription;
private Date insertDate;
private Date updateDate;
}
|
UTF-8
|
Java
| 322 |
java
|
MCategoryDTO.java
|
Java
|
[] | null |
[] |
package com.internousdev.beautifulworlds.dto;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class MCategoryDTO {
private int id;
private int categoryId;
private String categoryName;
private String categoryDescription;
private Date insertDate;
private Date updateDate;
}
| 322 | 0.807453 | 0.807453 | 15 | 20.466667 | 12.333513 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.066667 | false | false |
4
|
398f315277d53834b13ed9637805e1c399c3cd08
| 17,119,739,709,327 |
4c5f934a0f2751db7e21bdf7b4dde337fc142e97
|
/src/aufgabenReitz/ViewZinsrechnerEins.java
|
1257d915aacd73929dd99e353a858801dd3ad0b7
|
[] |
no_license
|
GruppeLuca-Adrian-Tom-Jonathan/ISE
|
https://github.com/GruppeLuca-Adrian-Tom-Jonathan/ISE
|
62e62f41911aba8a05c85782dbce4f431bc08eed
|
5d10822977dc8649e171db4adedc3036a5e5e948
|
refs/heads/master
| 2020-04-01T04:08:48.278000 | 2018-11-25T15:23:44 | 2018-11-25T15:23:44 | 152,709,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package aufgabenReitz;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class ViewZinsrechnerEins extends JFrame {
JPanel contentPane;
JLabel lblZinsrechner;
JLabel lblZinssatz;
JLabel lblLaufzeit;
JLabel lblAnlagebetrag;
JScrollPane scrollPane;
JTextArea textArea;
JTextField txtZinssatz;
JTextField txtLaufzeit;
JTextField txtAnlagebetrag;
public ViewZinsrechnerEins() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 430, 450, 330);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblZinsrechner = new JLabel("Zinsrechner 1");
lblZinsrechner.setBounds(176, 6, 90, 16);
contentPane.add(lblZinsrechner);
lblZinssatz = new JLabel("Zinssatz");
lblZinssatz.setBounds(6, 36, 76, 16);
contentPane.add(lblZinssatz);
txtZinssatz = new JTextField();
txtZinssatz.setBounds(94, 31, 130, 26);
contentPane.add(txtZinssatz);
txtZinssatz.setColumns(10);
lblLaufzeit = new JLabel("Laufzeit");
lblLaufzeit.setBounds(6, 64, 76, 16);
contentPane.add(lblLaufzeit);
txtLaufzeit = new JTextField();
txtLaufzeit.setBounds(94, 59, 130, 26);
contentPane.add(txtLaufzeit);
txtLaufzeit.setColumns(10);
lblAnlagebetrag = new JLabel("Anlagebetrag");
lblAnlagebetrag.setBounds(6, 92, 84, 16);
contentPane.add(lblAnlagebetrag);
txtAnlagebetrag = new JTextField();
txtAnlagebetrag.setBounds(94, 87, 130, 26);
contentPane.add(txtAnlagebetrag);
txtAnlagebetrag.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(6, 120, 438, 182);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
|
UTF-8
|
Java
| 1,914 |
java
|
ViewZinsrechnerEins.java
|
Java
|
[] | null |
[] |
package aufgabenReitz;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class ViewZinsrechnerEins extends JFrame {
JPanel contentPane;
JLabel lblZinsrechner;
JLabel lblZinssatz;
JLabel lblLaufzeit;
JLabel lblAnlagebetrag;
JScrollPane scrollPane;
JTextArea textArea;
JTextField txtZinssatz;
JTextField txtLaufzeit;
JTextField txtAnlagebetrag;
public ViewZinsrechnerEins() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 430, 450, 330);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblZinsrechner = new JLabel("Zinsrechner 1");
lblZinsrechner.setBounds(176, 6, 90, 16);
contentPane.add(lblZinsrechner);
lblZinssatz = new JLabel("Zinssatz");
lblZinssatz.setBounds(6, 36, 76, 16);
contentPane.add(lblZinssatz);
txtZinssatz = new JTextField();
txtZinssatz.setBounds(94, 31, 130, 26);
contentPane.add(txtZinssatz);
txtZinssatz.setColumns(10);
lblLaufzeit = new JLabel("Laufzeit");
lblLaufzeit.setBounds(6, 64, 76, 16);
contentPane.add(lblLaufzeit);
txtLaufzeit = new JTextField();
txtLaufzeit.setBounds(94, 59, 130, 26);
contentPane.add(txtLaufzeit);
txtLaufzeit.setColumns(10);
lblAnlagebetrag = new JLabel("Anlagebetrag");
lblAnlagebetrag.setBounds(6, 92, 84, 16);
contentPane.add(lblAnlagebetrag);
txtAnlagebetrag = new JTextField();
txtAnlagebetrag.setBounds(94, 87, 130, 26);
contentPane.add(txtAnlagebetrag);
txtAnlagebetrag.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(6, 120, 438, 182);
contentPane.add(scrollPane);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
| 1,914 | 0.747126 | 0.700627 | 73 | 25.219177 | 15.312495 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.575342 | false | false |
4
|
257a7870e8818769e8bb2b0ecffcbbb3f3273706
| 32,203,664,808,856 |
cec0ddfb053a084fe4a5d7f027d5b7223eff0761
|
/src/main/java/com/project/PizzaExpress/service/deliverymanManage/quit/IDeleteDeliverymanService.java
|
661217ba0aed48672b969314ff4bc9b1f2c782c5
|
[] |
no_license
|
pizzaexpress07team/BackgroundSystem
|
https://github.com/pizzaexpress07team/BackgroundSystem
|
302d7390c2eb51f10ebf8cc41052c20c5e69e429
|
4851dddc2ce44d899dc96c7d0f5c305a71461124
|
refs/heads/master
| 2020-04-25T21:42:59.974000 | 2019-05-07T13:56:18 | 2019-05-07T13:56:18 | 173,088,435 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.project.PizzaExpress.service.deliverymanManage.quit;
import com.alibaba.fastjson.JSONObject;
public interface IDeleteDeliverymanService {
JSONObject deleteDeliveryman(String d_id);
}
|
UTF-8
|
Java
| 201 |
java
|
IDeleteDeliverymanService.java
|
Java
|
[] | null |
[] |
package com.project.PizzaExpress.service.deliverymanManage.quit;
import com.alibaba.fastjson.JSONObject;
public interface IDeleteDeliverymanService {
JSONObject deleteDeliveryman(String d_id);
}
| 201 | 0.830846 | 0.830846 | 7 | 27.714285 | 24.765842 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
4
|
e4f40c3f35d55b265f68bbd1d58140be0c7cdc00
| 21,973,052,738,175 |
fb24523f2dabc30717221834c94199cb2fcc0f7a
|
/lsn16_jit/src/main/java/Compile.java
|
2061588f36f1f18b5b44ac0e7fe79aa0f7061c07
|
[] |
no_license
|
botwy/maven_lsn
|
https://github.com/botwy/maven_lsn
|
1050940ff52c0fed053c4ae1ac2ec0d44ac507ff
|
e87c6f011832b20c50c9c5e180f51ead75d8bb6b
|
refs/heads/master
| 2021-08-18T16:55:57.106000 | 2017-11-23T10:38:29 | 2017-11-23T10:38:29 | 103,979,032 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Compile {
}
Алексей Шипилев по Модели памяти 2 часа лекции, по поводу строк
Черемин Руслан
Роман Елизаров То что должен знать программист
виртуальные вызовы методов
СоларКьюб
Сонар плагин
стайл чекеры
цикломатическая сложность метода не может больше 12 (трай кэтч цикл условие
Миллион котировок в секунду
|
UTF-8
|
Java
| 635 |
java
|
Compile.java
|
Java
|
[
{
"context": "public class Compile {\n}\n\n\n Алексей Шипилев по Модели памяти 2 часа лекции, по поводу строк\n ",
"end": 46,
"score": 0.9997323751449585,
"start": 31,
"tag": "NAME",
"value": "Алексей Шипилев"
},
{
"context": "дели памяти 2 часа лекции, по поводу строк\n Черемин Руслан\n Роман Елизаров То что должен знать програ",
"end": 117,
"score": 0.9991931915283203,
"start": 103,
"tag": "NAME",
"value": "Черемин Руслан"
},
{
"context": "ии, по поводу строк\n Черемин Руслан\n Роман Елизаров То что должен знать программист\n\n виртуаль",
"end": 140,
"score": 0.9997777938842773,
"start": 126,
"tag": "NAME",
"value": "Роман Елизаров"
},
{
"context": "ммист\n\n виртуальные вызовы методов\n\n СоларКьюб\n Сонар плагин\n стайл чекеры\n\n ",
"end": 227,
"score": 0.8901039958000183,
"start": 218,
"tag": "NAME",
"value": "СоларКьюб"
},
{
"context": "туальные вызовы методов\n\n СоларКьюб\n Сонар плагин\n стайл чекеры\n\n цикломатическая сло",
"end": 248,
"score": 0.9630988240242004,
"start": 236,
"tag": "NAME",
"value": "Сонар плагин"
}
] | null |
[] |
public class Compile {
}
<NAME> по Модели памяти 2 часа лекции, по поводу строк
<NAME>
<NAME> То что должен знать программист
виртуальные вызовы методов
СоларКьюб
<NAME>
стайл чекеры
цикломатическая сложность метода не может больше 12 (трай кэтч цикл условие
Миллион котировок в секунду
| 553 | 0.682051 | 0.674359 | 16 | 23.4375 | 24.929823 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.0625 | false | false |
4
|
e344b864b3722111d08e70dfcf947a3d7cdbefef
| 16,681,653,014,342 |
cd5b776d3a95bf228c07ccc68d63385ac971a91b
|
/igreja/src/main/java/sistema/SuggestionboxBean.java
|
f04ad6e11da7899252fdd9c780e2a825efcd9a50
|
[] |
no_license
|
lfrancisquini/projetointegrador
|
https://github.com/lfrancisquini/projetointegrador
|
6198f6390678c870987ddef357fd24432de2ff6e
|
aac4a81074cfc18a67be07bc69c4262d13e949ca
|
refs/heads/master
| 2016-09-10T04:14:23.381000 | 2016-06-15T20:50:15 | 2016-06-15T20:50:15 | 56,515,935 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sistema;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
import com.forj.cirrus.infra.spring.Escopo;
/**
* {Descrita resumida sobre a classe}.
*
* @author Lucas Francisquini
* @version 1.0 - 04/05/2016
* @since 04/05/2016
*/
@Named
@Scope(Escopo.SESSION)
public class SuggestionboxBean {
private List<String> lista;
public SuggestionboxBean() {
lista = new ArrayList();
}
public List<String> complemento(Object event) {
String prefixo = event.toString().toLowerCase();
List<String> retorno = new ArrayList();
for (int pos = 0; pos < lista.size(); pos++) {
if (lista.get(pos).toLowerCase().startsWith(prefixo)) {
retorno.add(lista.get(pos));
}
}
return retorno;
}
}
|
UTF-8
|
Java
| 799 |
java
|
SuggestionboxBean.java
|
Java
|
[
{
"context": "{Descrita resumida sobre a classe}.\n * \n * @author Lucas Francisquini\n * @version 1.0 - 04/05/2016\n * @since 04/05/2016",
"end": 273,
"score": 0.9998610615730286,
"start": 255,
"tag": "NAME",
"value": "Lucas Francisquini"
}
] | null |
[] |
package sistema;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
import com.forj.cirrus.infra.spring.Escopo;
/**
* {Descrita resumida sobre a classe}.
*
* @author <NAME>
* @version 1.0 - 04/05/2016
* @since 04/05/2016
*/
@Named
@Scope(Escopo.SESSION)
public class SuggestionboxBean {
private List<String> lista;
public SuggestionboxBean() {
lista = new ArrayList();
}
public List<String> complemento(Object event) {
String prefixo = event.toString().toLowerCase();
List<String> retorno = new ArrayList();
for (int pos = 0; pos < lista.size(); pos++) {
if (lista.get(pos).toLowerCase().startsWith(prefixo)) {
retorno.add(lista.get(pos));
}
}
return retorno;
}
}
| 787 | 0.697121 | 0.673342 | 40 | 18.975 | 18.122482 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025 | false | false |
4
|
ecb57fe200a39c31c515d67dcbe8d00455757130
| 35,124,242,575,754 |
e341c59842bb776c59e6a703dcb0249b4e7b0590
|
/src/Client.java
|
bcc120462b1a38e3d0df95fdcc83839a03de919b
|
[] |
no_license
|
ummeasalma/Chat-App
|
https://github.com/ummeasalma/Chat-App
|
b080be8a91845d622d87290a88aa264cb96dfbf3
|
8bcd5e81b4a63139770c79be31f3e9aecae4123a
|
refs/heads/master
| 2020-09-27T00:59:36.018000 | 2019-12-06T18:10:09 | 2019-12-06T18:10:09 | 226,384,166 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
private String notif = " *** ";
private ObjectInputStream sInput;
private ObjectOutputStream sOutput;
private Socket socket;
private String server, username;
private int port;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
Client(String server, int port, String username) {
this.server = server;
this.port = port;
this.username = username;
}
public boolean start() {
try {
socket = new Socket(server, port);
}
catch(Exception ec) {
display("Connection failed:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
/* Creating both Data Stream */
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}
// creates the Thread to listen from the server
new ListenFromServer().start();
try
{
sOutput.writeObject(username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}
return true;
}
private void display(String msg) {
System.out.println(msg);
}
void sendMessage(ChatMessage msg) {
try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}
private void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {}
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try{
if(socket != null) socket.close();
}
catch(Exception e) {}
}
public static void main(String[] args) {
int portNumber = 1500;
String serverAddress = "localhost";
String userName = "Anonymous";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the username: ");
userName = scan.nextLine();
switch(args.length) {
case 3:
serverAddress = args[2];
case 2:
try {
portNumber = Integer.parseInt(args[1]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: - java Client [username] [portNumber] [serverAddress]");
return;
}
case 1:
userName = args[0];
case 0:
break;
default:
System.out.println("Usage is: - java Client [username] [portNumber] [serverAddress]");
return;
}
Client client = new Client(serverAddress, portNumber, userName);
if(!client.start())
return;
System.out.println("\nHello!!! Welcome to the conversation");
System.out.println("Here is the instructions you need to follow");
System.out.println("1. Type the message to send who is in online");
System.out.println("2. Type #username<space>yourmessage to send message to someone");
System.out.println("3. Type ONLINE to see the active list");
System.out.println("4. Type LOGOUT to logoff from server");
while(true) {
System.out.print("~ ");
String msg = scan.nextLine();
if(msg.equalsIgnoreCase("LOGOUT")) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
break;
}
else if(msg.equalsIgnoreCase("ONLINE")) {
client.sendMessage(new ChatMessage(ChatMessage.ONLINE, ""));
}
else {
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg));
}
}
scan.close();
client.disconnect();
}
class ListenFromServer extends Thread {
public void run() {
while(true) {
try {
String msg = (String) sInput.readObject();
System.out.println(msg);
System.out.print("~ ");
}
catch(IOException e) {
display("Server has closed the connection: " + e );
break;
}
catch(ClassNotFoundException e2) {
}
}
}
}
}
|
UTF-8
|
Java
| 5,066 |
java
|
Client.java
|
Java
|
[
{
"context": "\n this.port = port;\n this.username = username;\n }\n\n public boolean start() {\n try ",
"end": 593,
"score": 0.9602971076965332,
"start": 585,
"tag": "USERNAME",
"value": "username"
},
{
"context": "Address = \"localhost\";\n String userName = \"Anonymous\";\n Scanner scan = new Scanner(System.in);\n",
"end": 2453,
"score": 0.9941934943199158,
"start": 2444,
"tag": "USERNAME",
"value": "Anonymous"
}
] | null |
[] |
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
private String notif = " *** ";
private ObjectInputStream sInput;
private ObjectOutputStream sOutput;
private Socket socket;
private String server, username;
private int port;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
Client(String server, int port, String username) {
this.server = server;
this.port = port;
this.username = username;
}
public boolean start() {
try {
socket = new Socket(server, port);
}
catch(Exception ec) {
display("Connection failed:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
/* Creating both Data Stream */
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}
// creates the Thread to listen from the server
new ListenFromServer().start();
try
{
sOutput.writeObject(username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}
return true;
}
private void display(String msg) {
System.out.println(msg);
}
void sendMessage(ChatMessage msg) {
try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}
private void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {}
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try{
if(socket != null) socket.close();
}
catch(Exception e) {}
}
public static void main(String[] args) {
int portNumber = 1500;
String serverAddress = "localhost";
String userName = "Anonymous";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the username: ");
userName = scan.nextLine();
switch(args.length) {
case 3:
serverAddress = args[2];
case 2:
try {
portNumber = Integer.parseInt(args[1]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: - java Client [username] [portNumber] [serverAddress]");
return;
}
case 1:
userName = args[0];
case 0:
break;
default:
System.out.println("Usage is: - java Client [username] [portNumber] [serverAddress]");
return;
}
Client client = new Client(serverAddress, portNumber, userName);
if(!client.start())
return;
System.out.println("\nHello!!! Welcome to the conversation");
System.out.println("Here is the instructions you need to follow");
System.out.println("1. Type the message to send who is in online");
System.out.println("2. Type #username<space>yourmessage to send message to someone");
System.out.println("3. Type ONLINE to see the active list");
System.out.println("4. Type LOGOUT to logoff from server");
while(true) {
System.out.print("~ ");
String msg = scan.nextLine();
if(msg.equalsIgnoreCase("LOGOUT")) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
break;
}
else if(msg.equalsIgnoreCase("ONLINE")) {
client.sendMessage(new ChatMessage(ChatMessage.ONLINE, ""));
}
else {
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg));
}
}
scan.close();
client.disconnect();
}
class ListenFromServer extends Thread {
public void run() {
while(true) {
try {
String msg = (String) sInput.readObject();
System.out.println(msg);
System.out.print("~ ");
}
catch(IOException e) {
display("Server has closed the connection: " + e );
break;
}
catch(ClassNotFoundException e2) {
}
}
}
}
}
| 5,066 | 0.505132 | 0.501974 | 176 | 27.789772 | 23.153542 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528409 | false | false |
4
|
31f766da0198dbfd8acbb7441af820e6dcc05825
| 4,758,823,813,367 |
21e39a60fd1bd6263fb0b422312f02a6483b98f2
|
/android/app/src/main/java/crazysheep/io/nina/bean/MediaStoreImageBean.java
|
d3f346d80118f3dc9e5c3298729458532c798d8a
|
[] |
no_license
|
yangli1120/nina
|
https://github.com/yangli1120/nina
|
46ffeab2692f75063bbc06e849adb0040d0798d1
|
820b6859fbdca7a3f5365182e74a8ec26189359c
|
refs/heads/master
| 2023-09-01T03:49:21.491000 | 2016-07-05T06:31:09 | 2016-07-05T06:31:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package crazysheep.io.nina.bean;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
/**
* system media store image bean, for gallery, see{@link crazysheep.io.nina.GalleryActivity}
*
* Created by crazysheep on 16/2/23.
*/
@ParcelablePlease
public class MediaStoreImageBean implements Parcelable {
public long id;
public String filepath;
public String title;
public static MediaStoreImageBean parseCursor(@NonNull Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID));
String filepath = cursor.getString(
cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
String title = cursor.getString(
cursor.getColumnIndex(MediaStore.Images.ImageColumns.TITLE));
return new MediaStoreImageBean(id, filepath, title);
}
public MediaStoreImageBean() {}
public MediaStoreImageBean(long id, String filepath, String title) {
this.id = id;
this.filepath = filepath;
this.title = title;
}
@Override
public String toString() {
return id + " - " + filepath;
}
///////////////// parcelable //////////////////////
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
MediaStoreImageBeanParcelablePlease.writeToParcel(this, dest, flags);
}
public static final Creator<MediaStoreImageBean> CREATOR = new Creator<MediaStoreImageBean>() {
public MediaStoreImageBean createFromParcel(Parcel source) {
MediaStoreImageBean target = new MediaStoreImageBean();
MediaStoreImageBeanParcelablePlease.readFromParcel(target, source);
return target;
}
public MediaStoreImageBean[] newArray(int size) {
return new MediaStoreImageBean[size];
}
};
}
|
UTF-8
|
Java
| 2,104 |
java
|
MediaStoreImageBean.java
|
Java
|
[
{
"context": "azysheep.io.nina.GalleryActivity}\n *\n * Created by crazysheep on 16/2/23.\n */\n@ParcelablePlease\npublic class Me",
"end": 399,
"score": 0.9996715784072876,
"start": 389,
"tag": "USERNAME",
"value": "crazysheep"
}
] | null |
[] |
package crazysheep.io.nina.bean;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
/**
* system media store image bean, for gallery, see{@link crazysheep.io.nina.GalleryActivity}
*
* Created by crazysheep on 16/2/23.
*/
@ParcelablePlease
public class MediaStoreImageBean implements Parcelable {
public long id;
public String filepath;
public String title;
public static MediaStoreImageBean parseCursor(@NonNull Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID));
String filepath = cursor.getString(
cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
String title = cursor.getString(
cursor.getColumnIndex(MediaStore.Images.ImageColumns.TITLE));
return new MediaStoreImageBean(id, filepath, title);
}
public MediaStoreImageBean() {}
public MediaStoreImageBean(long id, String filepath, String title) {
this.id = id;
this.filepath = filepath;
this.title = title;
}
@Override
public String toString() {
return id + " - " + filepath;
}
///////////////// parcelable //////////////////////
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
MediaStoreImageBeanParcelablePlease.writeToParcel(this, dest, flags);
}
public static final Creator<MediaStoreImageBean> CREATOR = new Creator<MediaStoreImageBean>() {
public MediaStoreImageBean createFromParcel(Parcel source) {
MediaStoreImageBean target = new MediaStoreImageBean();
MediaStoreImageBeanParcelablePlease.readFromParcel(target, source);
return target;
}
public MediaStoreImageBean[] newArray(int size) {
return new MediaStoreImageBean[size];
}
};
}
| 2,104 | 0.680133 | 0.677281 | 69 | 29.492754 | 28.468454 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507246 | false | false |
4
|
6ce3afc095a42d9a4700e08cf95d8ba280f13795
| 21,122,649,230,275 |
1319a49b6346ce270229770170d2a12723774bbd
|
/src/main/java/com/epsilon/metadata/image/distributed/app/ImageMetadataExtractorApp.java
|
a53a25eb661b91d1c58284b70552f1a77af08c6b
|
[] |
no_license
|
jduranmaster/EXIF-IMAGE-Distributed-Metadata-Extractor-MANAGER-POC-release-1.0.0
|
https://github.com/jduranmaster/EXIF-IMAGE-Distributed-Metadata-Extractor-MANAGER-POC-release-1.0.0
|
d1fa379f1408e46c96cd3059bdb8b15163ed3bbd
|
9356310cd3002c1be8b2287b68d6b67e92c19faf
|
refs/heads/master
| 2021-01-11T00:05:01.018000 | 2016-09-25T17:52:24 | 2016-09-25T17:52:24 | 69,179,764 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.epsilon.metadata.image.distributed.app;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.epsilon.metadata.image.distributed.core.ImageMetadataExtractor;
@Component
public class ImageMetadataExtractorApp {
private static final Log log = LogFactory.getLog(ImageMetadataExtractorApp.class);
public ImageMetadataExtractorApp() {
super();
}
public void run(String[] args) throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"/META-INF/spring/application-context.xml", ImageMetadataExtractorApp.class);
log.info("------------------------------------------");
log.info("Image Metada-Extractor Core Running ......");
log.info("------------------------------------------");
context.registerShutdownHook();
ImageMetadataExtractor imageMetadataExtractor = context.getBean(ImageMetadataExtractor.class);
log.info(new StringBuilder("File Path: ").append(args[1]).toString());
// call the logic that allows to print all the Image Metadata.
imageMetadataExtractor.printJPEGImageMetadataInfo(new File(args[1]));
}
}
|
UTF-8
|
Java
| 1,356 |
java
|
ImageMetadataExtractorApp.java
|
Java
|
[] | null |
[] |
package com.epsilon.metadata.image.distributed.app;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.epsilon.metadata.image.distributed.core.ImageMetadataExtractor;
@Component
public class ImageMetadataExtractorApp {
private static final Log log = LogFactory.getLog(ImageMetadataExtractorApp.class);
public ImageMetadataExtractorApp() {
super();
}
public void run(String[] args) throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"/META-INF/spring/application-context.xml", ImageMetadataExtractorApp.class);
log.info("------------------------------------------");
log.info("Image Metada-Extractor Core Running ......");
log.info("------------------------------------------");
context.registerShutdownHook();
ImageMetadataExtractor imageMetadataExtractor = context.getBean(ImageMetadataExtractor.class);
log.info(new StringBuilder("File Path: ").append(args[1]).toString());
// call the logic that allows to print all the Image Metadata.
imageMetadataExtractor.printJPEGImageMetadataInfo(new File(args[1]));
}
}
| 1,356 | 0.74705 | 0.745575 | 36 | 36.694443 | 31.241728 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false |
4
|
765a0104847279bfc507aecef938a702eb4ab338
| 34,265,249,123,243 |
5973ef0d94ba5e39fffae3fc82162b79e0a34871
|
/updated-stockmanagement/project/srccucu/test/java/com/capgemini/cucumberforestmanagementsystem/runner/Runner.java
|
ddd9f8a9f3b38c87d636898a5b2eda02ea2bbc42
|
[] |
no_license
|
Diksha1016/TY_CG_HTD_BangaloreNovember_JFS_DikshaKumari
|
https://github.com/Diksha1016/TY_CG_HTD_BangaloreNovember_JFS_DikshaKumari
|
3dfeb860e54eeab6ebd92c1a1656fbfc96773fa0
|
a3326be0da1c2e91efa2828dc7934e2e6641052b
|
refs/heads/master
| 2022-09-25T21:09:12.945000 | 2020-06-08T06:56:36 | 2020-06-08T06:56:36 | 225,846,327 | 0 | 0 | null | false | 2020-01-01T17:50:59 | 2019-12-04T11:02:01 | 2020-01-01T17:50:41 | 2020-01-01T17:50:58 | 9,907 | 0 | 0 | 1 |
JavaScript
| false | false |
package com.capgemini.cucumberforestmanagementsystem.runner;
import cucumber.api.CucumberOptions;
@CucumberOptions(features = ".//Feature", glue = "com.capgemini.cucumberforestmanagementsystem.stepdefinition", plugin = {
"pretty", "html:target/cucumber" }, monochrome = true)
public class Runner {
}
|
UTF-8
|
Java
| 307 |
java
|
Runner.java
|
Java
|
[] | null |
[] |
package com.capgemini.cucumberforestmanagementsystem.runner;
import cucumber.api.CucumberOptions;
@CucumberOptions(features = ".//Feature", glue = "com.capgemini.cucumberforestmanagementsystem.stepdefinition", plugin = {
"pretty", "html:target/cucumber" }, monochrome = true)
public class Runner {
}
| 307 | 0.775244 | 0.775244 | 10 | 29.700001 | 38.12886 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false |
4
|
7ce0a650f34c5c5bc910076d9f75ea2bcd0100d6
| 37,134,287,249,986 |
40074451d5efb09bb7e90afad2b4d91e3bd884c7
|
/eagle-core/src/main/java/in/hocg/eagle/modules/ums/mapstruct/AccountGroupMapping.java
|
c86fef7b7f1b29ac98b310c8a06dc118abda924d
|
[] |
no_license
|
zgwdg/eagle
|
https://github.com/zgwdg/eagle
|
744fc699662818a85a87a1d64a4b218d4c7e7ebd
|
f7d4037973b6ef046bf842117f79239fb1a81fca
|
refs/heads/master
| 2023-03-27T20:59:58.824000 | 2021-04-01T04:27:32 | 2021-04-01T04:27:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package in.hocg.eagle.modules.ums.mapstruct;
import in.hocg.eagle.modules.ums.entity.AccountGroup;
import in.hocg.eagle.modules.ums.pojo.qo.account.group.AccountGroupSaveQo;
import in.hocg.eagle.modules.ums.pojo.vo.account.group.AccountGroupComplexVo;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
/**
* Created by hocgin on 2020/2/15.
* email: hocgin@gmail.com
*
* @author hocgin
*/
@Mapper(componentModel = "spring")
public interface AccountGroupMapping {
@Mapping(target = "lastUpdater", ignore = true)
@Mapping(target = "lastUpdatedAt", ignore = true)
@Mapping(target = "creator", ignore = true)
AccountGroup asAccountGroup(AccountGroupSaveQo qo);
@Mapping(target = "memberSourceName", ignore = true)
@Mapping(target = "lastUpdaterName", ignore = true)
@Mapping(target = "groupTypeName", ignore = true)
@Mapping(target = "creatorName", ignore = true)
AccountGroupComplexVo asAccountGroupComplexVo(AccountGroup entity);
}
|
UTF-8
|
Java
| 984 |
java
|
AccountGroupMapping.java
|
Java
|
[
{
"context": ";\nimport org.mapstruct.Mapping;\n\n/**\n * Created by hocgin on 2020/2/15.\n * email: hocgin@gmail.com\n *\n * @a",
"end": 337,
"score": 0.9995966553688049,
"start": 331,
"tag": "USERNAME",
"value": "hocgin"
},
{
"context": "\n\n/**\n * Created by hocgin on 2020/2/15.\n * email: hocgin@gmail.com\n *\n * @author hocgin\n */\n@Mapper(componentModel =",
"end": 378,
"score": 0.9999299645423889,
"start": 362,
"tag": "EMAIL",
"value": "hocgin@gmail.com"
},
{
"context": "020/2/15.\n * email: hocgin@gmail.com\n *\n * @author hocgin\n */\n@Mapper(componentModel = \"spring\")\npublic int",
"end": 399,
"score": 0.9995934367179871,
"start": 393,
"tag": "USERNAME",
"value": "hocgin"
}
] | null |
[] |
package in.hocg.eagle.modules.ums.mapstruct;
import in.hocg.eagle.modules.ums.entity.AccountGroup;
import in.hocg.eagle.modules.ums.pojo.qo.account.group.AccountGroupSaveQo;
import in.hocg.eagle.modules.ums.pojo.vo.account.group.AccountGroupComplexVo;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
/**
* Created by hocgin on 2020/2/15.
* email: <EMAIL>
*
* @author hocgin
*/
@Mapper(componentModel = "spring")
public interface AccountGroupMapping {
@Mapping(target = "lastUpdater", ignore = true)
@Mapping(target = "lastUpdatedAt", ignore = true)
@Mapping(target = "creator", ignore = true)
AccountGroup asAccountGroup(AccountGroupSaveQo qo);
@Mapping(target = "memberSourceName", ignore = true)
@Mapping(target = "lastUpdaterName", ignore = true)
@Mapping(target = "groupTypeName", ignore = true)
@Mapping(target = "creatorName", ignore = true)
AccountGroupComplexVo asAccountGroupComplexVo(AccountGroup entity);
}
| 975 | 0.74187 | 0.734756 | 29 | 32.931034 | 25.138144 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false |
4
|
e6b575987b5aba7d0b8bb5465d7c07800220e7f3
| 31,138,512,942,601 |
b055c73107ccda14e79022e6a3d2d8507ca7993d
|
/src/main/java/edu/mum/cs/cs425/webapps/elibrary/controller/HomePageController.java
|
c105ddd11619907222385b5c87264a04a4b4a15b
|
[] |
no_license
|
charleswilliert/eLibrary
|
https://github.com/charleswilliert/eLibrary
|
50c772f3aaccdd44e865c4bb3d88b2f11d9145f1
|
b2edf916c99d7c67eb0708f804106ba496130937
|
refs/heads/master
| 2020-05-20T08:45:35.674000 | 2019-05-08T04:38:17 | 2019-05-08T04:38:17 | 185,481,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.mum.cs.cs425.webapps.elibrary.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomePageController {
@GetMapping(value= {"/","eLibrary","eLibrary/home"})
public String displayHomePge() {
return"home/index";
}
}
|
UTF-8
|
Java
| 334 |
java
|
HomePageController.java
|
Java
|
[] | null |
[] |
package edu.mum.cs.cs425.webapps.elibrary.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomePageController {
@GetMapping(value= {"/","eLibrary","eLibrary/home"})
public String displayHomePge() {
return"home/index";
}
}
| 334 | 0.763473 | 0.754491 | 16 | 19.875 | 22.098854 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false |
4
|
b3746d3f83028da91168b5fe5e01780938db7637
| 5,085,241,333,616 |
a3d0e30f54c0c88652baef79deaa5d28a5a368f9
|
/UIApplication/app/src/main/java/com/sun/ui/paint/CanvasVIew.java
|
b4fd3f72b9b11b80051e3fbb104b431df0d29c86
|
[] |
no_license
|
amylovesong/android_ui
|
https://github.com/amylovesong/android_ui
|
bfdde2f3f14f5f8c59f45fcde1cccaa241d8f58b
|
20254a9b7a77caa695b2a4c87426949ff62c50cf
|
refs/heads/master
| 2020-04-06T06:54:21.921000 | 2016-08-29T10:36:31 | 2016-08-29T10:36:31 | 60,015,195 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sun.ui.paint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.sun.ui.R;
/**
* Created by sunxiaoling on 16/6/11.
*/
public class CanvasView extends View {
private Paint mPaint;
private Rect rect1;
private Rect rect2;
private Path mPath;
private Region region1;
private Region region2;
private int count = 0;
public CanvasView(Context context) {
super(context);
init();
}
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4);
rect1 = new Rect(0, 0, 500, 500);
rect2 = new Rect(250, 250, 750, 750);
mPath = new Path();
mPath.moveTo(300, 300);
mPath.lineTo(450, 138);
mPath.lineTo(900, 600);
mPath.lineTo(480, 660);
mPath.close();
region1 = new Region(200, 200, 600, 600);
region2 = new Region(400, 400, 800, 800);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// setLayerType(LAYER_TYPE_SOFTWARE, null);
// canvas.drawColor(Color.GREEN);
/** Clip Rect*/
//// canvas.clipRect(0, 0, 500, 500);
// canvas.drawRect(rect1, mPaint);
// canvas.drawRect(rect2, mPaint);
//
//// final boolean flag = rect1.intersect(rect2);
// rect1.union(rect2);
//
// canvas.clipRect(rect1);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
/** Clip Path*/
// canvas.drawPath(mPath, mPaint);
// canvas.clipPath(mPath);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
/** Clip Region */
// canvas.save();
// canvas.clipRegion(region1);
//// canvas.clipRegion(region2, Region.Op.DIFFERENCE);
//// canvas.clipRegion(region2, Region.Op.INTERSECT);
//// canvas.clipRegion(region2, Region.Op.REPLACE);
//// canvas.clipRegion(region2, Region.Op.REVERSE_DIFFERENCE);
//// canvas.clipRegion(region2, Region.Op.UNION);
// canvas.clipRegion(region2, Region.Op.XOR);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
// canvas.restore();
// canvas.drawRect(region1.getBounds(), mPaint);
// canvas.drawRect(region2.getBounds(), mPaint);
/** Region VS. Rect*/
// final Rect rect = new Rect(0, 0, 400, 400);
// final Region region = new Region(400, 400, 800, 800);
//
// // Region不受Canvas的变换影响
// canvas.scale(0.75f, 0.75f);
//
// canvas.drawColor(Color.WHITE);
//
// canvas.save();
// canvas.clipRect(rect);
// canvas.drawColor(Color.RED);
// canvas.restore();
//
// canvas.save();
// canvas.clipRegion(region);
// canvas.drawColor(Color.BLUE);
// canvas.restore();
//
// mPaint.setColor(Color.GREEN);
// mPaint.setStrokeWidth(10);
// canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mPaint);
/** Layer */
// canvas.drawColor(Color.WHITE);
// mPaint.setStyle(Paint.Style.FILL);
// mPaint.setColor(Color.RED);
// canvas.drawRect(200, 200, 600, 600, mPaint);
//
//// canvas.save();
//// canvas.saveLayer(0, 0, 600, 600, null, Canvas.ALL_SAVE_FLAG);
// canvas.saveLayerAlpha(0, 0, 600, 600, 100, Canvas.ALL_SAVE_FLAG);
// canvas.rotate(30);
//
// mPaint.setColor(Color.BLUE);
// canvas.drawRect(300, 300, 500, 500, mPaint);
//
// canvas.restore();
//
// mPaint.setColor(Color.GREEN);
// canvas.drawCircle(400, 400, 80, mPaint);
/** Layer - restoreToCount(saveCount) & getSaveCount() */
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// canvas.drawColor(Color.WHITE);
// int saveID1 = canvas.save(Canvas.MATRIX_SAVE_FLAG);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// canvas.rotate(30);
//
// mPaint.setStyle(Paint.Style.FILL);
// mPaint.setColor(Color.RED);
// canvas.drawRect(200, 200, 600, 600, mPaint);
//
// canvas.restoreToCount(saveID1);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
//
// int saveID2 = canvas.save(Canvas.MATRIX_SAVE_FLAG);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// mPaint.setColor(Color.BLUE);
// canvas.drawRect(300, 300, 500, 500, mPaint);
//
//// canvas.restoreToCount(saveID1);
// canvas.restoreToCount(saveID2);
//
// mPaint.setColor(Color.GREEN);
// canvas.drawCircle(400, 400, 80, mPaint);
/** 变换 */
canvas.drawColor(Color.WHITE);
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
//// canvas.scale(0.8f, 0.5f);
// canvas.scale(0.8f, 0.5f, bitmap.getWidth() / 2, 0);//以(px, py)作为缩放的中心点
//// canvas.scale(1.0f, 1.0f, bitmap.getWidth(), 0);
// canvas.rotate(30);
// canvas.rotate(15, bitmap.getWidth() / 2, 0);
// canvas.skew(0.5f, 0.0f);
final Matrix matrix = new Matrix();
matrix.setScale(0.8f, 0.35f);
matrix.postTranslate(400, 400);
canvas.setMatrix(matrix);
canvas.drawBitmap(bitmap, 0, 0, null);
}
private void logMsg(String msg) {
Log.d(CanvasView.class.getSimpleName(), msg);
}
}
|
UTF-8
|
Java
| 6,070 |
java
|
CanvasVIew.java
|
Java
|
[
{
"context": "iew.View;\n\nimport com.sun.ui.R;\n\n/**\n * Created by sunxiaoling on 16/6/11.\n */\npublic class CanvasView extends V",
"end": 485,
"score": 0.9996416568756104,
"start": 474,
"tag": "USERNAME",
"value": "sunxiaoling"
}
] | null |
[] |
package com.sun.ui.paint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.sun.ui.R;
/**
* Created by sunxiaoling on 16/6/11.
*/
public class CanvasView extends View {
private Paint mPaint;
private Rect rect1;
private Rect rect2;
private Path mPath;
private Region region1;
private Region region2;
private int count = 0;
public CanvasView(Context context) {
super(context);
init();
}
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4);
rect1 = new Rect(0, 0, 500, 500);
rect2 = new Rect(250, 250, 750, 750);
mPath = new Path();
mPath.moveTo(300, 300);
mPath.lineTo(450, 138);
mPath.lineTo(900, 600);
mPath.lineTo(480, 660);
mPath.close();
region1 = new Region(200, 200, 600, 600);
region2 = new Region(400, 400, 800, 800);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// setLayerType(LAYER_TYPE_SOFTWARE, null);
// canvas.drawColor(Color.GREEN);
/** Clip Rect*/
//// canvas.clipRect(0, 0, 500, 500);
// canvas.drawRect(rect1, mPaint);
// canvas.drawRect(rect2, mPaint);
//
//// final boolean flag = rect1.intersect(rect2);
// rect1.union(rect2);
//
// canvas.clipRect(rect1);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
/** Clip Path*/
// canvas.drawPath(mPath, mPaint);
// canvas.clipPath(mPath);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
/** Clip Region */
// canvas.save();
// canvas.clipRegion(region1);
//// canvas.clipRegion(region2, Region.Op.DIFFERENCE);
//// canvas.clipRegion(region2, Region.Op.INTERSECT);
//// canvas.clipRegion(region2, Region.Op.REPLACE);
//// canvas.clipRegion(region2, Region.Op.REVERSE_DIFFERENCE);
//// canvas.clipRegion(region2, Region.Op.UNION);
// canvas.clipRegion(region2, Region.Op.XOR);
// canvas.drawColor(Color.parseColor("#90FFFFFF"));
// canvas.restore();
// canvas.drawRect(region1.getBounds(), mPaint);
// canvas.drawRect(region2.getBounds(), mPaint);
/** Region VS. Rect*/
// final Rect rect = new Rect(0, 0, 400, 400);
// final Region region = new Region(400, 400, 800, 800);
//
// // Region不受Canvas的变换影响
// canvas.scale(0.75f, 0.75f);
//
// canvas.drawColor(Color.WHITE);
//
// canvas.save();
// canvas.clipRect(rect);
// canvas.drawColor(Color.RED);
// canvas.restore();
//
// canvas.save();
// canvas.clipRegion(region);
// canvas.drawColor(Color.BLUE);
// canvas.restore();
//
// mPaint.setColor(Color.GREEN);
// mPaint.setStrokeWidth(10);
// canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mPaint);
/** Layer */
// canvas.drawColor(Color.WHITE);
// mPaint.setStyle(Paint.Style.FILL);
// mPaint.setColor(Color.RED);
// canvas.drawRect(200, 200, 600, 600, mPaint);
//
//// canvas.save();
//// canvas.saveLayer(0, 0, 600, 600, null, Canvas.ALL_SAVE_FLAG);
// canvas.saveLayerAlpha(0, 0, 600, 600, 100, Canvas.ALL_SAVE_FLAG);
// canvas.rotate(30);
//
// mPaint.setColor(Color.BLUE);
// canvas.drawRect(300, 300, 500, 500, mPaint);
//
// canvas.restore();
//
// mPaint.setColor(Color.GREEN);
// canvas.drawCircle(400, 400, 80, mPaint);
/** Layer - restoreToCount(saveCount) & getSaveCount() */
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// canvas.drawColor(Color.WHITE);
// int saveID1 = canvas.save(Canvas.MATRIX_SAVE_FLAG);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// canvas.rotate(30);
//
// mPaint.setStyle(Paint.Style.FILL);
// mPaint.setColor(Color.RED);
// canvas.drawRect(200, 200, 600, 600, mPaint);
//
// canvas.restoreToCount(saveID1);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
//
// int saveID2 = canvas.save(Canvas.MATRIX_SAVE_FLAG);
// logMsg("onDraw getSaveCount: " + canvas.getSaveCount());
// mPaint.setColor(Color.BLUE);
// canvas.drawRect(300, 300, 500, 500, mPaint);
//
//// canvas.restoreToCount(saveID1);
// canvas.restoreToCount(saveID2);
//
// mPaint.setColor(Color.GREEN);
// canvas.drawCircle(400, 400, 80, mPaint);
/** 变换 */
canvas.drawColor(Color.WHITE);
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
//// canvas.scale(0.8f, 0.5f);
// canvas.scale(0.8f, 0.5f, bitmap.getWidth() / 2, 0);//以(px, py)作为缩放的中心点
//// canvas.scale(1.0f, 1.0f, bitmap.getWidth(), 0);
// canvas.rotate(30);
// canvas.rotate(15, bitmap.getWidth() / 2, 0);
// canvas.skew(0.5f, 0.0f);
final Matrix matrix = new Matrix();
matrix.setScale(0.8f, 0.35f);
matrix.postTranslate(400, 400);
canvas.setMatrix(matrix);
canvas.drawBitmap(bitmap, 0, 0, null);
}
private void logMsg(String msg) {
Log.d(CanvasView.class.getSimpleName(), msg);
}
}
| 6,070 | 0.597945 | 0.552701 | 193 | 30.264248 | 21.409592 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.165803 | false | false |
4
|
e2fa819aac1a9d0cc9e40c9e6b9664cb4263257e
| 6,803,228,248,187 |
6e33079254d818af3de23a686b95988b6d6e1c61
|
/advanced-java/src/com/training/etiya/java/props/PropertyReader.java
|
7dc3f40f6c759e498611bc28054d30684e5332b2
|
[] |
no_license
|
osmanyaycioglu/etiya20210118
|
https://github.com/osmanyaycioglu/etiya20210118
|
7f86ae2ecafeb66110814c125dd9bca2066c96f7
|
9fb405582d05804806f00f285624c16c86c0a1c4
|
refs/heads/master
| 2023-03-02T16:30:33.139000 | 2021-01-22T13:41:50 | 2021-01-22T13:41:50 | 330,993,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.training.etiya.java.props;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class PropertyReader {
public static void main(final String[] args) {
try {
Properties propertiesLoc = new Properties();
File file = new File("prop.properties");
FileInputStream fileInputStreamLoc = new FileInputStream(file);
propertiesLoc.load(fileInputStreamLoc);
MyProperty myPropertyLoc = new MyProperty();
myPropertyLoc.setAppName(propertiesLoc.getProperty("app.conf.name"));
myPropertyLoc.setTest(propertiesLoc.getProperty("app.conf.test"));
myPropertyLoc.setDeneme(propertiesLoc.getProperty("xyz.abc.deneme"));
myPropertyLoc.setPort(Integer.parseInt(propertiesLoc.getProperty("app.conf.port")));
myPropertyLoc.setTestMest(propertiesLoc.getProperty("test.mest"));
myPropertyLoc.setConnectionPort(Integer.parseInt(propertiesLoc.getProperty("connection.port")));
System.out.println(myPropertyLoc);
} catch (Exception eLoc) {
eLoc.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,179 |
java
|
PropertyReader.java
|
Java
|
[] | null |
[] |
package com.training.etiya.java.props;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class PropertyReader {
public static void main(final String[] args) {
try {
Properties propertiesLoc = new Properties();
File file = new File("prop.properties");
FileInputStream fileInputStreamLoc = new FileInputStream(file);
propertiesLoc.load(fileInputStreamLoc);
MyProperty myPropertyLoc = new MyProperty();
myPropertyLoc.setAppName(propertiesLoc.getProperty("app.conf.name"));
myPropertyLoc.setTest(propertiesLoc.getProperty("app.conf.test"));
myPropertyLoc.setDeneme(propertiesLoc.getProperty("xyz.abc.deneme"));
myPropertyLoc.setPort(Integer.parseInt(propertiesLoc.getProperty("app.conf.port")));
myPropertyLoc.setTestMest(propertiesLoc.getProperty("test.mest"));
myPropertyLoc.setConnectionPort(Integer.parseInt(propertiesLoc.getProperty("connection.port")));
System.out.println(myPropertyLoc);
} catch (Exception eLoc) {
eLoc.printStackTrace();
}
}
}
| 1,179 | 0.677693 | 0.677693 | 28 | 41.107143 | 31.487343 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false |
4
|
c3baff592dc4ce2cb1ff783744b0b296db84ca5d
| 14,620,068,730,981 |
5cd3b06686354beaf8965aca4258c172f220f84d
|
/apriori/Apriori.java
|
13760bed32f778381811855c7f70971f535e19f7
|
[
"MIT"
] |
permissive
|
Danar00/Apriori-Algorithm
|
https://github.com/Danar00/Apriori-Algorithm
|
40627155bb7598c6613954f0cfa43c20aa5468e5
|
171f62cbfab65ba87d9965b9c3f77ec1879b0e6a
|
refs/heads/master
| 2020-05-07T09:32:15.558000 | 2019-04-09T14:12:13 | 2019-04-09T14:12:13 | 180,381,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package apriori;
import java.io.*;
import java.util.*;
class Apriori
{
public static void main(String args[])throws Exception
{
String data[] = {"1. Cleo", "2. Aqua", "3. Vit", "4. CLUB"
, "5. Equil"};
System.out.println("Data :");
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
int n,minSupport;
int max=0;
int maxLen=0;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Apriori ap=new Apriori();
System.out.print("Masukkan Jumlah Transaksi : ");
n=Integer.parseInt(in.readLine());
System.out.println("Transaksi : ");
String trans[]=new String[n];
for(int i=0;i<n;i++)
{
trans[i]=in.readLine();
for(int j=0;j<trans[i].length();j++)
{
if(Integer.parseInt(""+trans[i].charAt(j))>max)
max=Integer.parseInt(""+trans[i].charAt(j));
}
}
System.out.print("Masukkan Minimum Support : ");
minSupport=Integer.parseInt(in.readLine());
String str="";
for(int i=1;i<=max;i++)
str+=""+i;
ArrayList al;
max=0;
ArrayList<String> allItems=new ArrayList<String>();
for(int i=1;i<=str.length();i++)
{
al=ap.hitungTransaksi(str.substring(0,i));
for(int j=0;j<al.size();j++)
{
allItems.add(""+al.get(j));
if(new String(""+al.get(j)).length()>max)
max=new String(""+al.get(j)).length();
}
}
ArrayList<String> arr[]=new ArrayList[max];
for(int i=0;i<max;i++)
arr[i]=new ArrayList<String>();
for(int j=0;j<allItems.size();j++){
arr[( allItems.get(j).length())-1].add(allItems.get(j));
}
int count[]=new int[allItems.size()],l=0;
int index=0;
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
for(int k=0;k<n;k++)
{
for(int m=0;m<(arr[i].get(j).length());m++)
{
if(trans[k].indexOf(arr[i].get(j).charAt(m))==-1){
index=1;
}
}
if(index==0){
count[l]+=1;
}
index=0;
}
l++;
}
}
int k=0;
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
if(count[k]>=minSupport)
{
if(maxLen<arr[i].get(j).length()){
maxLen=arr[i].get(j).length();
}
}
k++;
}
}
k=0;
System.out.println("ItemSet | Sup");
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
if(count[k]>=minSupport)
{
System.out.println(arr[i].get(j)+" | "+count[k]);
}
k++;
}
System.out.println("=================");
}
}
ArrayList<String> hitungTransaksi(String str)
{
String temp="",match="";
int flag=0;
ArrayList<String> result=new ArrayList<String>();
if(str.length()==1)
{
result.add(str);
return result;
}
else
{
char ch=str.charAt(0);
String rem=str.substring(1);
ArrayList<String> a=hitungTransaksi(rem);
for(String p:a)
{
result.add(p);
ArrayList addn=insertItems(ch,p);
for(int i=0;i<addn.size();i++)
{
match=(String)addn.get(i);
flag=0;
for(int j=i+1;j<addn.size();j++)
{
temp=(String)addn.get(j);
for(int k=0;k<temp.length();k++)
{
for(int l=0;l<match.length();l++)
{
if(temp.charAt(k)==match.charAt(l)){
flag++;
}
}
}
if(flag>=match.length())
addn.remove(j);
}
}
result.addAll(addn);
}
return(result);
}
}
ArrayList<String> insertItems(char c,String str)
{
String temp="",match="";
int flag=0;
ArrayList<String> res=new ArrayList<String>();
for(int i=0;i<=str.length();i++)
{
res.add(str.substring(0,i)+c+str.substring(i));
}
for(int i=0;i<res.size();i++)
{
match=(String)res.get(i);
flag=0;
for(int j=i+1;j<res.size();j++)
{
temp=(String)res.get(j);
for(int k=0;k<temp.length();k++)
{
for(int l=0;l<match.length();l++)
{
if(temp.charAt(k)==match.charAt(l))
flag++;
}
}
if(flag>=match.length())
res.remove(j);
}
}
return(res);
}
}
|
UTF-8
|
Java
| 4,874 |
java
|
Apriori.java
|
Java
|
[] | null |
[] |
package apriori;
import java.io.*;
import java.util.*;
class Apriori
{
public static void main(String args[])throws Exception
{
String data[] = {"1. Cleo", "2. Aqua", "3. Vit", "4. CLUB"
, "5. Equil"};
System.out.println("Data :");
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
int n,minSupport;
int max=0;
int maxLen=0;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Apriori ap=new Apriori();
System.out.print("Masukkan Jumlah Transaksi : ");
n=Integer.parseInt(in.readLine());
System.out.println("Transaksi : ");
String trans[]=new String[n];
for(int i=0;i<n;i++)
{
trans[i]=in.readLine();
for(int j=0;j<trans[i].length();j++)
{
if(Integer.parseInt(""+trans[i].charAt(j))>max)
max=Integer.parseInt(""+trans[i].charAt(j));
}
}
System.out.print("Masukkan Minimum Support : ");
minSupport=Integer.parseInt(in.readLine());
String str="";
for(int i=1;i<=max;i++)
str+=""+i;
ArrayList al;
max=0;
ArrayList<String> allItems=new ArrayList<String>();
for(int i=1;i<=str.length();i++)
{
al=ap.hitungTransaksi(str.substring(0,i));
for(int j=0;j<al.size();j++)
{
allItems.add(""+al.get(j));
if(new String(""+al.get(j)).length()>max)
max=new String(""+al.get(j)).length();
}
}
ArrayList<String> arr[]=new ArrayList[max];
for(int i=0;i<max;i++)
arr[i]=new ArrayList<String>();
for(int j=0;j<allItems.size();j++){
arr[( allItems.get(j).length())-1].add(allItems.get(j));
}
int count[]=new int[allItems.size()],l=0;
int index=0;
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
for(int k=0;k<n;k++)
{
for(int m=0;m<(arr[i].get(j).length());m++)
{
if(trans[k].indexOf(arr[i].get(j).charAt(m))==-1){
index=1;
}
}
if(index==0){
count[l]+=1;
}
index=0;
}
l++;
}
}
int k=0;
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
if(count[k]>=minSupport)
{
if(maxLen<arr[i].get(j).length()){
maxLen=arr[i].get(j).length();
}
}
k++;
}
}
k=0;
System.out.println("ItemSet | Sup");
for(int i=0;i<max;i++)
{
for(int j=0;j<arr[i].size();j++)
{
if(count[k]>=minSupport)
{
System.out.println(arr[i].get(j)+" | "+count[k]);
}
k++;
}
System.out.println("=================");
}
}
ArrayList<String> hitungTransaksi(String str)
{
String temp="",match="";
int flag=0;
ArrayList<String> result=new ArrayList<String>();
if(str.length()==1)
{
result.add(str);
return result;
}
else
{
char ch=str.charAt(0);
String rem=str.substring(1);
ArrayList<String> a=hitungTransaksi(rem);
for(String p:a)
{
result.add(p);
ArrayList addn=insertItems(ch,p);
for(int i=0;i<addn.size();i++)
{
match=(String)addn.get(i);
flag=0;
for(int j=i+1;j<addn.size();j++)
{
temp=(String)addn.get(j);
for(int k=0;k<temp.length();k++)
{
for(int l=0;l<match.length();l++)
{
if(temp.charAt(k)==match.charAt(l)){
flag++;
}
}
}
if(flag>=match.length())
addn.remove(j);
}
}
result.addAll(addn);
}
return(result);
}
}
ArrayList<String> insertItems(char c,String str)
{
String temp="",match="";
int flag=0;
ArrayList<String> res=new ArrayList<String>();
for(int i=0;i<=str.length();i++)
{
res.add(str.substring(0,i)+c+str.substring(i));
}
for(int i=0;i<res.size();i++)
{
match=(String)res.get(i);
flag=0;
for(int j=i+1;j<res.size();j++)
{
temp=(String)res.get(j);
for(int k=0;k<temp.length();k++)
{
for(int l=0;l<match.length();l++)
{
if(temp.charAt(k)==match.charAt(l))
flag++;
}
}
if(flag>=match.length())
res.remove(j);
}
}
return(res);
}
}
| 4,874 | 0.435577 | 0.424908 | 194 | 24.123711 | 18.93519 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.335052 | false | false |
4
|
ee8492afb71648e6da512c60f6527c29aceb0bce
| 14,920,716,442,994 |
8d94fe94fbfa9f5252156bddfab185d870ab16e8
|
/app/src/main/java/presenter/DetailMatchArticlePresenter.java
|
7c5c6b2ddaed1f003206180d28212b8dd2e2bcf6
|
[] |
no_license
|
sunghyunpark/Ground
|
https://github.com/sunghyunpark/Ground
|
9793dd21102eac935f8fb2a0aa6316634c6ef00a
|
509180de183058c2c5c83fb65be4f070b60083f5
|
refs/heads/master
| 2020-03-20T23:18:33.438000 | 2018-11-22T04:29:20 | 2018-11-22T04:29:20 | 137,840,065 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package presenter;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import api.ApiClient;
import api.ApiInterface;
import api.response.ArticleEtcResponse;
import api.response.ArticleModelListResponse;
import api.response.CommentListResponse;
import api.response.CommonResponse;
import base.presenter.BasePresenter;
import model.CommentModel;
import presenter.view.DetailMatchArticleView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import util.Util;
import util.adapter.CommentAdapter;
public class DetailMatchArticlePresenter extends BasePresenter<DetailMatchArticleView>{
private Context context;
//Comment Data
private ArrayList<CommentModel> commentModelArrayList;
private CommentAdapter commentAdapter;
private ApiInterface apiService;
/**
* Comment
* @param context
* @param view
* @param commentModelArrayList
* @param commentAdapter
*/
public DetailMatchArticlePresenter(Context context, DetailMatchArticleView view, ArrayList<CommentModel> commentModelArrayList, CommentAdapter commentAdapter){
super(view);
this.context = context;
this.commentModelArrayList = commentModelArrayList;
this.commentAdapter = commentAdapter;
apiService = ApiClient.getClient().create(ApiInterface.class);
}
public void loadArticleData(String boardType, int areaNo, int articleNo, String uid){
Call<ArticleModelListResponse> call = apiService.getArticleData(boardType, areaNo, articleNo, uid);
call.enqueue(new Callback<ArticleModelListResponse>() {
@Override
public void onResponse(Call<ArticleModelListResponse> call, Response<ArticleModelListResponse> response) {
ArticleModelListResponse articleModelListResponse = response.body();
if(articleModelListResponse.getCode() == 200){
getView().loadArticleData(articleModelListResponse.getResult().get(0));
}
}
@Override
public void onFailure(Call<ArticleModelListResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
public void loadFavoriteState(final String boardType, final int areaNo, final int articleNo, final String uid){
Call<ArticleEtcResponse> call = apiService.getArticleEtcData(boardType, areaNo, articleNo, uid);
call.enqueue(new Callback<ArticleEtcResponse>() {
@Override
public void onResponse(Call<ArticleEtcResponse> call, Response<ArticleEtcResponse> response) {
ArticleEtcResponse articleEtcResponse = response.body();
if(articleEtcResponse.getCode() == 200){
getView().setFavoriteState(articleEtcResponse.getFavoriteState());
}
}
@Override
public void onFailure(Call<ArticleEtcResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 디테일 뷰 진입 시 하단 댓글 데이터를 불러온다.
* @param refresh
* @param articleNo
* @param commentNo
* @param areaNo
*/
public void loadComment(boolean refresh, int articleNo, final int commentNo, int areaNo, String boardType){
if(refresh)
commentModelArrayList.clear();
Call<CommentListResponse> call = apiService.getCommentList(boardType, articleNo, areaNo, commentNo);
call.enqueue(new Callback<CommentListResponse>() {
@Override
public void onResponse(Call<CommentListResponse> call, Response<CommentListResponse> response) {
CommentListResponse commentListResponse = response.body();
if(commentListResponse.getCode() == 200){
int size = commentListResponse.getResult().size();
if(size > 0){
getView().initComment(true);
for(CommentModel cm : commentListResponse.getResult()){
Collections.addAll(commentModelArrayList, cm);
}
commentAdapter.notifyDataSetChanged();
}else{
getView().initComment(false);
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommentListResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 디테일뷰 하단 댓글 입력 후 서버로 전송
* @param areaNo
* @param articleNo
* @param writerId
* @param comment
* @param boardType
*/
public void postComment(final int areaNo, final int articleNo, String writerId, String comment, final String boardType){
Call<CommonResponse> call = apiService.writeComment(areaNo, articleNo, writerId, comment, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "댓글을 작성하였습니다.");
loadComment(true, articleNo, 0, areaNo, boardType);
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 댓글 삭제
* @param boardType
* @param commentNo
* @param articleNo
* @param areaNo
*/
public void deleteComment(String boardType, int commentNo, int articleNo, int areaNo){
Call<CommonResponse> call = apiService.deleteComment(boardType, commentNo, articleNo, areaNo);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "댓글을 삭제하였습니다.");
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 해당 디테일뷰 좋아요
* @param articleNo
* @param uid
* @param boardType
* @param state
*/
public void postFavoriteState(int articleNo, String uid, String boardType, final String state){
Call<CommonResponse> call = apiService.postFavoriteState(state, articleNo, uid, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
if(state.equals("Y")){
Util.showToast(context,"좋아요를 눌렀습니다.");
}else{
Util.showToast(context, "좋아요를 취소했습니다.");
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 매치, 용병 게시글의 매칭 상태 변경 시 사용되는 메소드
* @param areaNo
* @param articleNo
* @param state
* @param boardType
*/
public void changeMatchState(int areaNo, int articleNo, final String state, String boardType){
Call<CommonResponse> call = apiService.changeMatchState(areaNo, articleNo, state, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
if(state.equals("Y")){
Util.showToast(context,"완료 상태로 변경되었습니다.");
}else{
Util.showToast(context, "진행중 상태로 변경되었습니다.");
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
public void deleteArticle(String boardType, int articleNo, String uid){
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CommonResponse> call = apiService.deleteBoard(boardType, articleNo, uid);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "게시글을 삭제하였습니다.");
getView().deleteArticle();
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
}
|
UTF-8
|
Java
| 11,795 |
java
|
DetailMatchArticlePresenter.java
|
Java
|
[] | null |
[] |
package presenter;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import api.ApiClient;
import api.ApiInterface;
import api.response.ArticleEtcResponse;
import api.response.ArticleModelListResponse;
import api.response.CommentListResponse;
import api.response.CommonResponse;
import base.presenter.BasePresenter;
import model.CommentModel;
import presenter.view.DetailMatchArticleView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import util.Util;
import util.adapter.CommentAdapter;
public class DetailMatchArticlePresenter extends BasePresenter<DetailMatchArticleView>{
private Context context;
//Comment Data
private ArrayList<CommentModel> commentModelArrayList;
private CommentAdapter commentAdapter;
private ApiInterface apiService;
/**
* Comment
* @param context
* @param view
* @param commentModelArrayList
* @param commentAdapter
*/
public DetailMatchArticlePresenter(Context context, DetailMatchArticleView view, ArrayList<CommentModel> commentModelArrayList, CommentAdapter commentAdapter){
super(view);
this.context = context;
this.commentModelArrayList = commentModelArrayList;
this.commentAdapter = commentAdapter;
apiService = ApiClient.getClient().create(ApiInterface.class);
}
public void loadArticleData(String boardType, int areaNo, int articleNo, String uid){
Call<ArticleModelListResponse> call = apiService.getArticleData(boardType, areaNo, articleNo, uid);
call.enqueue(new Callback<ArticleModelListResponse>() {
@Override
public void onResponse(Call<ArticleModelListResponse> call, Response<ArticleModelListResponse> response) {
ArticleModelListResponse articleModelListResponse = response.body();
if(articleModelListResponse.getCode() == 200){
getView().loadArticleData(articleModelListResponse.getResult().get(0));
}
}
@Override
public void onFailure(Call<ArticleModelListResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
public void loadFavoriteState(final String boardType, final int areaNo, final int articleNo, final String uid){
Call<ArticleEtcResponse> call = apiService.getArticleEtcData(boardType, areaNo, articleNo, uid);
call.enqueue(new Callback<ArticleEtcResponse>() {
@Override
public void onResponse(Call<ArticleEtcResponse> call, Response<ArticleEtcResponse> response) {
ArticleEtcResponse articleEtcResponse = response.body();
if(articleEtcResponse.getCode() == 200){
getView().setFavoriteState(articleEtcResponse.getFavoriteState());
}
}
@Override
public void onFailure(Call<ArticleEtcResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 디테일 뷰 진입 시 하단 댓글 데이터를 불러온다.
* @param refresh
* @param articleNo
* @param commentNo
* @param areaNo
*/
public void loadComment(boolean refresh, int articleNo, final int commentNo, int areaNo, String boardType){
if(refresh)
commentModelArrayList.clear();
Call<CommentListResponse> call = apiService.getCommentList(boardType, articleNo, areaNo, commentNo);
call.enqueue(new Callback<CommentListResponse>() {
@Override
public void onResponse(Call<CommentListResponse> call, Response<CommentListResponse> response) {
CommentListResponse commentListResponse = response.body();
if(commentListResponse.getCode() == 200){
int size = commentListResponse.getResult().size();
if(size > 0){
getView().initComment(true);
for(CommentModel cm : commentListResponse.getResult()){
Collections.addAll(commentModelArrayList, cm);
}
commentAdapter.notifyDataSetChanged();
}else{
getView().initComment(false);
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommentListResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 디테일뷰 하단 댓글 입력 후 서버로 전송
* @param areaNo
* @param articleNo
* @param writerId
* @param comment
* @param boardType
*/
public void postComment(final int areaNo, final int articleNo, String writerId, String comment, final String boardType){
Call<CommonResponse> call = apiService.writeComment(areaNo, articleNo, writerId, comment, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "댓글을 작성하였습니다.");
loadComment(true, articleNo, 0, areaNo, boardType);
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 댓글 삭제
* @param boardType
* @param commentNo
* @param articleNo
* @param areaNo
*/
public void deleteComment(String boardType, int commentNo, int articleNo, int areaNo){
Call<CommonResponse> call = apiService.deleteComment(boardType, commentNo, articleNo, areaNo);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "댓글을 삭제하였습니다.");
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 해당 디테일뷰 좋아요
* @param articleNo
* @param uid
* @param boardType
* @param state
*/
public void postFavoriteState(int articleNo, String uid, String boardType, final String state){
Call<CommonResponse> call = apiService.postFavoriteState(state, articleNo, uid, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
if(state.equals("Y")){
Util.showToast(context,"좋아요를 눌렀습니다.");
}else{
Util.showToast(context, "좋아요를 취소했습니다.");
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
/**
* 매치, 용병 게시글의 매칭 상태 변경 시 사용되는 메소드
* @param areaNo
* @param articleNo
* @param state
* @param boardType
*/
public void changeMatchState(int areaNo, int articleNo, final String state, String boardType){
Call<CommonResponse> call = apiService.changeMatchState(areaNo, articleNo, state, boardType);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
if(state.equals("Y")){
Util.showToast(context,"완료 상태로 변경되었습니다.");
}else{
Util.showToast(context, "진행중 상태로 변경되었습니다.");
}
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
public void deleteArticle(String boardType, int articleNo, String uid){
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CommonResponse> call = apiService.deleteBoard(boardType, articleNo, uid);
call.enqueue(new Callback<CommonResponse>() {
@Override
public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
CommonResponse commonResponse = response.body();
if(commonResponse.getCode() == 200){
Util.showToast(context, "게시글을 삭제하였습니다.");
getView().deleteArticle();
}else{
Util.showToast(context, "에러가 발생하였습니다. 잠시 후 다시 시도해주세요.");
}
}
@Override
public void onFailure(Call<CommonResponse> call, Throwable t) {
// Log error here since request failed
Log.e("tag", t.toString());
Util.showToast(context, "네트워크 연결상태를 확인해주세요.");
}
});
}
}
| 11,795 | 0.581767 | 0.579043 | 280 | 38.332142 | 31.328793 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.696429 | false | false |
4
|
40de5250f69f0eeb8f18db4edb90691c3a0183d7
| 5,334,349,430,045 |
42624c9384f11a8b26488ace89ab44f4b9ce9f66
|
/TestEvent9.java
|
859dbdc8fed20235ab8756dc6f8323ab9cef03e0
|
[] |
no_license
|
omlondhe/Java-Basics
|
https://github.com/omlondhe/Java-Basics
|
bd6da2d392f3708f01886254011baa9fede3a138
|
1266ed65fde26b42a96aaf78b498a963fc26a3ed
|
refs/heads/main
| 2023-01-29T00:27:37.709000 | 2020-12-01T06:49:28 | 2020-12-01T06:49:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.*;
import java.awt.event.*;
class TestEvent9 extends Frame implements MouseListener {
TextField one;
TextField two;
TextField add;
TextField subtract;
TextField multiply;
TextField divide;
TestEvent9() {
setSize(400, 400);
setLayout(new BorderLayout());
setVisible(true);
Font font = new Font("comicsans", Font.BOLD, 21);
Panel north = new Panel();
one = new TextField(21);
one.setFont(font);
two = new TextField(21);
two.setFont(font);
north.add(one);
north.add(two);
Button button = new Button("PERFORM");
button.addMouseListener(this);
Panel south = new Panel();
add = new TextField(21);
add.setFont(font);
subtract = new TextField(21);
subtract.setFont(font);
multiply = new TextField(21);
multiply.setFont(font);
divide = new TextField(21);
divide.setFont(font);
south.add(add);
south.add(subtract);
south.add(multiply);
south.add(divide);
add(north, BorderLayout.NORTH);
add(button);
add(south, BorderLayout.SOUTH);
}
public void mouseEntered(MouseEvent me) {
if (one != null && two != null){
add.setText("" + (Integer.parseInt(one.getText()) + Integer.parseInt(two.getText())));
subtract.setText("" + (Integer.parseInt(one.getText()) - Integer.parseInt(two.getText())));
multiply.setText("" + (Integer.parseInt(one.getText()) * Integer.parseInt(two.getText())));
divide.setText("" + (Integer.parseInt(one.getText()) / Integer.parseInt(two.getText())));
}
}
public void mouseExited(MouseEvent me) {
one.setText("");
two.setText("");
add.setText("");
subtract.setText("");
multiply.setText("");
divide.setText("");
}
public void mouseReleased(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
public void mouseClicked(MouseEvent me) {
}
public static void main(String []ar) {
new TestEvent9();
}
}
|
UTF-8
|
Java
| 1,857 |
java
|
TestEvent9.java
|
Java
|
[] | null |
[] |
import java.awt.*;
import java.awt.event.*;
class TestEvent9 extends Frame implements MouseListener {
TextField one;
TextField two;
TextField add;
TextField subtract;
TextField multiply;
TextField divide;
TestEvent9() {
setSize(400, 400);
setLayout(new BorderLayout());
setVisible(true);
Font font = new Font("comicsans", Font.BOLD, 21);
Panel north = new Panel();
one = new TextField(21);
one.setFont(font);
two = new TextField(21);
two.setFont(font);
north.add(one);
north.add(two);
Button button = new Button("PERFORM");
button.addMouseListener(this);
Panel south = new Panel();
add = new TextField(21);
add.setFont(font);
subtract = new TextField(21);
subtract.setFont(font);
multiply = new TextField(21);
multiply.setFont(font);
divide = new TextField(21);
divide.setFont(font);
south.add(add);
south.add(subtract);
south.add(multiply);
south.add(divide);
add(north, BorderLayout.NORTH);
add(button);
add(south, BorderLayout.SOUTH);
}
public void mouseEntered(MouseEvent me) {
if (one != null && two != null){
add.setText("" + (Integer.parseInt(one.getText()) + Integer.parseInt(two.getText())));
subtract.setText("" + (Integer.parseInt(one.getText()) - Integer.parseInt(two.getText())));
multiply.setText("" + (Integer.parseInt(one.getText()) * Integer.parseInt(two.getText())));
divide.setText("" + (Integer.parseInt(one.getText()) / Integer.parseInt(two.getText())));
}
}
public void mouseExited(MouseEvent me) {
one.setText("");
two.setText("");
add.setText("");
subtract.setText("");
multiply.setText("");
divide.setText("");
}
public void mouseReleased(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
public void mouseClicked(MouseEvent me) {
}
public static void main(String []ar) {
new TestEvent9();
}
}
| 1,857 | 0.675283 | 0.662897 | 78 | 22.807692 | 21.223511 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.128205 | false | false |
4
|
0f353c15ecb82d6d935706e046c29a38ac0f4b75
| 24,026,047,105,841 |
ad68873a002730a4e411cc209962eeaa26a900b8
|
/app/src/main/java/be/li/mymeal/adapters/viewholders/IngredientItemViewHolder.java
|
db0fb0119685a84b11001ebe653f9b39d68f792b
|
[] |
no_license
|
ArturLeee/artur.li
|
https://github.com/ArturLeee/artur.li
|
57079ec19fd61dc1d6ebe2f12be398efad888056
|
7c6f381efb2761388fc4d786fc15eacb2f845468
|
refs/heads/master
| 2022-11-30T18:01:36.145000 | 2020-08-15T18:30:14 | 2020-08-15T18:30:14 | 287,803,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package be.li.mymeal.adapters.viewholders;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.navigation.NavController;
import androidx.recyclerview.widget.RecyclerView;
import be.li.mymeal.databinding.IngredientListItemBinding;
import be.li.mymeal.entities.Ingredient;
import be.li.mymeal.ui.ingredients.IngredientsFragmentDirections;
public class IngredientItemViewHolder extends RecyclerView.ViewHolder {
private final IngredientListItemBinding binding;
private final NavController navController;
public IngredientItemViewHolder(@NonNull View root, NavController navController) {
super(root);
binding = DataBindingUtil.bind(root);
this.navController = navController;
}
public void setIngredient(Ingredient ingredient) {
binding.ingredientName.setText(ingredient.name);
binding.ingredientDescription.setText(ingredient.description);
binding.getRoot().setOnClickListener(v -> {
IngredientsFragmentDirections.CategoriesToMealsByCategoryFragment action = IngredientsFragmentDirections.categoriesToMealsByCategoryFragment(ingredient.name);
navController.navigate(action);
});
}
}
|
UTF-8
|
Java
| 1,263 |
java
|
IngredientItemViewHolder.java
|
Java
|
[] | null |
[] |
package be.li.mymeal.adapters.viewholders;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.navigation.NavController;
import androidx.recyclerview.widget.RecyclerView;
import be.li.mymeal.databinding.IngredientListItemBinding;
import be.li.mymeal.entities.Ingredient;
import be.li.mymeal.ui.ingredients.IngredientsFragmentDirections;
public class IngredientItemViewHolder extends RecyclerView.ViewHolder {
private final IngredientListItemBinding binding;
private final NavController navController;
public IngredientItemViewHolder(@NonNull View root, NavController navController) {
super(root);
binding = DataBindingUtil.bind(root);
this.navController = navController;
}
public void setIngredient(Ingredient ingredient) {
binding.ingredientName.setText(ingredient.name);
binding.ingredientDescription.setText(ingredient.description);
binding.getRoot().setOnClickListener(v -> {
IngredientsFragmentDirections.CategoriesToMealsByCategoryFragment action = IngredientsFragmentDirections.categoriesToMealsByCategoryFragment(ingredient.name);
navController.navigate(action);
});
}
}
| 1,263 | 0.782264 | 0.782264 | 35 | 35.085712 | 34.533936 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
4
|
cd5eb5aa3a5c40da2c43d06eabc295f3dc6c1116
| 19,834,159,023,911 |
c37b08c68eaafe050cad51bda2419ccfe00e3c4c
|
/app/src/main/java/net/iclassmate/teacherspace/application/MyApplication.java
|
c11a41288ed8f9141d5a415727e013a0decab93c
|
[] |
no_license
|
zhangyuxuan1024/xydteacher
|
https://github.com/zhangyuxuan1024/xydteacher
|
4414ac002c0547a3a74db5c329ac560559b89d55
|
f183e26ffc0568caf9e00e5f64bf1e73379df92b
|
refs/heads/master
| 2020-03-10T11:19:19.109000 | 2018-04-13T06:32:40 | 2018-04-13T06:32:40 | 129,354,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.iclassmate.teacherspace.application;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
/**
*
* Created by xyd on 2016/1/26.
*/
public class MyApplication extends Application {
// 获取到主线程的上下文
private static MyApplication mContext;
// 获取到主线程的hander;
private static Handler mMainThreadHander;
// 获取到主线程的looper
private static Looper mMainThreadLooper;
// 获取到主线程
private static Thread mMainThead;
// 获取到主线程的id
private static int mMainTheadId;
//版本信息类
private double versionCode;
private double versionSize;
private String versionMark;
private String versionUrl;
private String versionName;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
mMainThreadHander = new Handler();
mMainThreadLooper = getMainLooper();
mMainThead = Thread.currentThread();
mMainTheadId = android.os.Process.myTid();
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public double getVersionCode() {
return versionCode;
}
public void setVersionCode(double versionCode) {
this.versionCode = versionCode;
}
public double getVersionSize() {
return versionSize;
}
public void setVersionSize(double versionSize) {
this.versionSize = versionSize;
}
public String getVersionMark() {
return versionMark;
}
public void setVersionMark(String versionMark) {
this.versionMark = versionMark;
}
public String getVersionUrl() {
return versionUrl;
}
public void setVersionUrl(String versionUrl) {
this.versionUrl = versionUrl;
}
public static MyApplication getApplication() {
return mContext;
}
public static Handler getMainThreadHandler() {
return mMainThreadHander;
}
public static Looper getMainThreadLooper() {
return mMainThreadLooper;
}
public static Thread getMainThread() {
return mMainThead;
}
public static int getMainThreadId() {
return mMainTheadId;
}
}
|
UTF-8
|
Java
| 2,347 |
java
|
MyApplication.java
|
Java
|
[
{
"context": "r;\nimport android.os.Looper;\n\n/**\n *\n * Created by xyd on 2016/1/26.\n */\npublic class MyApplication exte",
"end": 160,
"score": 0.9995889663696289,
"start": 157,
"tag": "USERNAME",
"value": "xyd"
}
] | null |
[] |
package net.iclassmate.teacherspace.application;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
/**
*
* Created by xyd on 2016/1/26.
*/
public class MyApplication extends Application {
// 获取到主线程的上下文
private static MyApplication mContext;
// 获取到主线程的hander;
private static Handler mMainThreadHander;
// 获取到主线程的looper
private static Looper mMainThreadLooper;
// 获取到主线程
private static Thread mMainThead;
// 获取到主线程的id
private static int mMainTheadId;
//版本信息类
private double versionCode;
private double versionSize;
private String versionMark;
private String versionUrl;
private String versionName;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
mMainThreadHander = new Handler();
mMainThreadLooper = getMainLooper();
mMainThead = Thread.currentThread();
mMainTheadId = android.os.Process.myTid();
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public double getVersionCode() {
return versionCode;
}
public void setVersionCode(double versionCode) {
this.versionCode = versionCode;
}
public double getVersionSize() {
return versionSize;
}
public void setVersionSize(double versionSize) {
this.versionSize = versionSize;
}
public String getVersionMark() {
return versionMark;
}
public void setVersionMark(String versionMark) {
this.versionMark = versionMark;
}
public String getVersionUrl() {
return versionUrl;
}
public void setVersionUrl(String versionUrl) {
this.versionUrl = versionUrl;
}
public static MyApplication getApplication() {
return mContext;
}
public static Handler getMainThreadHandler() {
return mMainThreadHander;
}
public static Looper getMainThreadLooper() {
return mMainThreadLooper;
}
public static Thread getMainThread() {
return mMainThead;
}
public static int getMainThreadId() {
return mMainTheadId;
}
}
| 2,347 | 0.662395 | 0.659302 | 100 | 21.629999 | 17.972565 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false |
4
|
9a699cadcf187dff2a7510051edf24c4273659df
| 29,171,417,914,303 |
a337d2214a652bd89c9c04917e0a32bacebc7055
|
/src/vistas/Alquiler.java
|
67b6255815a905e1ccf8f6f59954927f4f5563da
|
[] |
no_license
|
alijmg20/SistemaHotelero
|
https://github.com/alijmg20/SistemaHotelero
|
eacc5c018a87f30ccc27402cf9be1622ddba6491
|
01578b4cc7ad427c8b6ae49727289ea0fb0cf742
|
refs/heads/main
| 2023-03-23T23:25:27.903000 | 2021-03-19T00:25:50 | 2021-03-19T00:25:50 | 349,254,299 | 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 vistas;
import Acciones.MAlquiler;
import java.sql.Date;
import javax.swing.JOptionPane;
public class Alquiler extends javax.swing.JInternalFrame {
MAlquiler alquiler = new MAlquiler();
public Alquiler() {
initComponents();
this.alquiler.obtenerClientes(cbclientes);
this.alquiler.obtenerPersonal(this.cbvendedores);
this.alquiler.obtenerhab(this.cbhabitaciones);
this.tablehab.setModel(alquiler.mostrarAlquileres());
}
/**
* 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();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtcodigo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtfechaent = new javax.swing.JFormattedTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
txtobservaciones = new javax.swing.JTextArea();
txtprecio = new javax.swing.JFormattedTextField();
txtfechasal = new javax.swing.JFormattedTextField();
jLabel9 = new javax.swing.JLabel();
cbvendedores = new javax.swing.JComboBox();
jLabel10 = new javax.swing.JLabel();
cbclientes = new javax.swing.JComboBox();
jLabel11 = new javax.swing.JLabel();
cbhabitaciones = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tablehab = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setTitle("Alquileres habitacion");
jPanel1.setBackground(new java.awt.Color(51, 51, 51));
jPanel2.setBackground(new java.awt.Color(51, 51, 51));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel1.setText("Alquileres de habitacion");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 10, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(51, 51, 51));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Opciones de Alquiler", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
jButton1.setText("nuevo");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("guardar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("modificar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Eliminar");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(53, 53, 53)
.addComponent(jButton2)
.addGap(49, 49, 49)
.addComponent(jButton3)
.addGap(43, 43, 43)
.addComponent(jButton4)
.addGap(41, 41, 41))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(51, 51, 51));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos de entrada de alquiler", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Codigo alquiler: ");
txtcodigo.setEnabled(false);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Precio alquiler :");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Fecha entrada :");
try {
txtfechaent.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####/##/##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtfechaent.setEnabled(false);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Vendedor :");
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Observaciones :");
txtobservaciones.setColumns(20);
txtobservaciones.setRows(5);
txtobservaciones.setEnabled(false);
jScrollPane3.setViewportView(txtobservaciones);
txtprecio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
txtprecio.setEnabled(false);
try {
txtfechasal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####/##/##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtfechasal.setEnabled(false);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Fecha salida :");
cbvendedores.setEnabled(false);
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Cliente: ");
cbclientes.setEnabled(false);
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(255, 255, 255));
jLabel11.setText("Habitaciones:");
cbhabitaciones.setEnabled(false);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Para las fechas es: ");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("año/mes/dia: ");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtcodigo, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addComponent(txtprecio)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(txtfechaent, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel7)
.addComponent(jLabel10)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtfechasal, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
.addComponent(cbvendedores, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbclientes, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbhabitaciones, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jLabel6))
.addContainerGap(16, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtprecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfechaent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfechasal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbvendedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbclientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbhabitaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(46, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
tablehab.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
tablehab.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablehabMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tablehab);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.txtcodigo.setEnabled(true);
this.txtfechaent.setEnabled(true);
this.txtprecio.setEnabled(true);
this.txtfechasal.setEnabled(true);
this.txtobservaciones.setEnabled(true);
this.cbclientes.setEnabled(true);
this.cbhabitaciones.setEnabled(true);
this.cbvendedores.setEnabled(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (!this.txtcodigo.getText().isEmpty() && !this.txtfechaent.getText().isEmpty() && !this.txtfechasal.getText().isEmpty() && !this.txtprecio.getText().isEmpty() && this.cbclientes.getSelectedIndex() > 0 && this.cbhabitaciones.getSelectedIndex() > 0 && this.cbvendedores.getSelectedIndex() > 0) {
String codigo = this.txtcodigo.getText();
String fechaString1 = this.txtfechaent.getText();
long fechaent = Date.parse(fechaString1);
Date fechaDate1 = new Date(fechaent);
String fechaString2 = this.txtfechasal.getText();
long fechasal = Date.parse(fechaString2);
Date fechaDate2 = new Date(fechasal);
float precio = Float.parseFloat(this.txtprecio.getText());
String vendedor = this.cbvendedores.getSelectedItem().toString();
String clientes = this.cbclientes.getSelectedItem().toString();
String habitacion = this.cbhabitaciones.getSelectedItem().toString();
String observaciones = " ";
observaciones = this.txtobservaciones.getText();
alquiler.insertarAlquiler(codigo, precio, fechaDate1, fechaDate2, observaciones, vendedor, clientes, habitacion);
this.tablehab.setModel(alquiler.mostrarAlquileres());
} else {
JOptionPane.showMessageDialog(null, "No ha ingresado por completo los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
if (!this.txtcodigo.getText().isEmpty() && !this.txtfechaent.getText().isEmpty() && !this.txtfechasal.getText().isEmpty() && !this.txtprecio.getText().isEmpty() && this.cbclientes.getSelectedIndex() > 0 && this.cbhabitaciones.getSelectedIndex() > 0 && this.cbvendedores.getSelectedIndex() > 0) {
String codigo = this.txtcodigo.getText();
String fechaString1 = this.txtfechaent.getText();
long fechaent = Date.parse(fechaString1);
Date fechaDate1 = new Date(fechaent);
String fechaString2 = this.txtfechasal.getText();
long fechasal = Date.parse(fechaString2);
Date fechaDate2 = new Date(fechasal);
float precio = Float.parseFloat(this.txtprecio.getText());
String vendedor = this.cbvendedores.getSelectedItem().toString();
String clientes = this.cbclientes.getSelectedItem().toString();
String habitacion = this.cbhabitaciones.getSelectedItem().toString();
String observaciones = " ";
observaciones = this.txtobservaciones.getText();
int decision = JOptionPane.showConfirmDialog(null, "¿Desea actualizar esta habitacion? ");
if (decision == 0) {
alquiler.actualizarAlquileres(codigo, precio, fechaDate1, fechaDate2, observaciones, vendedor, clientes, habitacion);
this.tablehab.setModel(alquiler.mostrarAlquileres());
}
} else {
JOptionPane.showMessageDialog(null, "No ha ingresado por completo los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
int filaSeleccionada = this.tablehab.getSelectedRow();
int decision = JOptionPane.showConfirmDialog(null, "¿Desea Eliminar este alquiler ? ");
String codigo = this.tablehab.getValueAt(filaSeleccionada, 0).toString();
if (decision == 0) {
this.alquiler.eliminarAlquiler(codigo);
this.tablehab.setModel(this.alquiler.mostrarAlquileres());
}
}//GEN-LAST:event_jButton4ActionPerformed
private void tablehabMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablehabMouseClicked
int filaSeleccionada = this.tablehab.rowAtPoint(evt.getPoint());
this.txtcodigo.setText(this.tablehab.getValueAt(filaSeleccionada, 0).toString());
this.txtprecio.setText(this.tablehab.getValueAt(filaSeleccionada, 1).toString());
this.txtfechaent.setText(this.tablehab.getValueAt(filaSeleccionada, 2).toString());
this.txtfechasal.setText(this.tablehab.getValueAt(filaSeleccionada, 3).toString());
this.txtobservaciones.setText(this.tablehab.getValueAt(filaSeleccionada, 4).toString());
this.cbvendedores.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 5).toString());
this.cbclientes.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 6).toString());
this.cbhabitaciones.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 7).toString());
}//GEN-LAST:event_tablehabMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cbclientes;
private javax.swing.JComboBox cbhabitaciones;
private javax.swing.JComboBox cbvendedores;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable tablehab;
private javax.swing.JTextField txtcodigo;
private javax.swing.JFormattedTextField txtfechaent;
private javax.swing.JFormattedTextField txtfechasal;
private javax.swing.JTextArea txtobservaciones;
private javax.swing.JFormattedTextField txtprecio;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 27,803 |
java
|
Alquiler.java
|
Java
|
[] | 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 vistas;
import Acciones.MAlquiler;
import java.sql.Date;
import javax.swing.JOptionPane;
public class Alquiler extends javax.swing.JInternalFrame {
MAlquiler alquiler = new MAlquiler();
public Alquiler() {
initComponents();
this.alquiler.obtenerClientes(cbclientes);
this.alquiler.obtenerPersonal(this.cbvendedores);
this.alquiler.obtenerhab(this.cbhabitaciones);
this.tablehab.setModel(alquiler.mostrarAlquileres());
}
/**
* 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();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtcodigo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtfechaent = new javax.swing.JFormattedTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
txtobservaciones = new javax.swing.JTextArea();
txtprecio = new javax.swing.JFormattedTextField();
txtfechasal = new javax.swing.JFormattedTextField();
jLabel9 = new javax.swing.JLabel();
cbvendedores = new javax.swing.JComboBox();
jLabel10 = new javax.swing.JLabel();
cbclientes = new javax.swing.JComboBox();
jLabel11 = new javax.swing.JLabel();
cbhabitaciones = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tablehab = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setTitle("Alquileres habitacion");
jPanel1.setBackground(new java.awt.Color(51, 51, 51));
jPanel2.setBackground(new java.awt.Color(51, 51, 51));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel1.setText("Alquileres de habitacion");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 10, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(51, 51, 51));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Opciones de Alquiler", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
jButton1.setText("nuevo");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("guardar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("modificar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Eliminar");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(53, 53, 53)
.addComponent(jButton2)
.addGap(49, 49, 49)
.addComponent(jButton3)
.addGap(43, 43, 43)
.addComponent(jButton4)
.addGap(41, 41, 41))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(51, 51, 51));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos de entrada de alquiler", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Codigo alquiler: ");
txtcodigo.setEnabled(false);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Precio alquiler :");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Fecha entrada :");
try {
txtfechaent.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####/##/##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtfechaent.setEnabled(false);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Vendedor :");
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Observaciones :");
txtobservaciones.setColumns(20);
txtobservaciones.setRows(5);
txtobservaciones.setEnabled(false);
jScrollPane3.setViewportView(txtobservaciones);
txtprecio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
txtprecio.setEnabled(false);
try {
txtfechasal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####/##/##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtfechasal.setEnabled(false);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Fecha salida :");
cbvendedores.setEnabled(false);
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Cliente: ");
cbclientes.setEnabled(false);
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(255, 255, 255));
jLabel11.setText("Habitaciones:");
cbhabitaciones.setEnabled(false);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Para las fechas es: ");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("año/mes/dia: ");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtcodigo, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addComponent(txtprecio)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(txtfechaent, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel7)
.addComponent(jLabel10)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtfechasal, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
.addComponent(cbvendedores, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbclientes, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbhabitaciones, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(jLabel6))
.addContainerGap(16, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtprecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfechaent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtfechasal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbvendedores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbclientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbhabitaciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(46, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
tablehab.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
tablehab.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablehabMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tablehab);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.txtcodigo.setEnabled(true);
this.txtfechaent.setEnabled(true);
this.txtprecio.setEnabled(true);
this.txtfechasal.setEnabled(true);
this.txtobservaciones.setEnabled(true);
this.cbclientes.setEnabled(true);
this.cbhabitaciones.setEnabled(true);
this.cbvendedores.setEnabled(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (!this.txtcodigo.getText().isEmpty() && !this.txtfechaent.getText().isEmpty() && !this.txtfechasal.getText().isEmpty() && !this.txtprecio.getText().isEmpty() && this.cbclientes.getSelectedIndex() > 0 && this.cbhabitaciones.getSelectedIndex() > 0 && this.cbvendedores.getSelectedIndex() > 0) {
String codigo = this.txtcodigo.getText();
String fechaString1 = this.txtfechaent.getText();
long fechaent = Date.parse(fechaString1);
Date fechaDate1 = new Date(fechaent);
String fechaString2 = this.txtfechasal.getText();
long fechasal = Date.parse(fechaString2);
Date fechaDate2 = new Date(fechasal);
float precio = Float.parseFloat(this.txtprecio.getText());
String vendedor = this.cbvendedores.getSelectedItem().toString();
String clientes = this.cbclientes.getSelectedItem().toString();
String habitacion = this.cbhabitaciones.getSelectedItem().toString();
String observaciones = " ";
observaciones = this.txtobservaciones.getText();
alquiler.insertarAlquiler(codigo, precio, fechaDate1, fechaDate2, observaciones, vendedor, clientes, habitacion);
this.tablehab.setModel(alquiler.mostrarAlquileres());
} else {
JOptionPane.showMessageDialog(null, "No ha ingresado por completo los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
if (!this.txtcodigo.getText().isEmpty() && !this.txtfechaent.getText().isEmpty() && !this.txtfechasal.getText().isEmpty() && !this.txtprecio.getText().isEmpty() && this.cbclientes.getSelectedIndex() > 0 && this.cbhabitaciones.getSelectedIndex() > 0 && this.cbvendedores.getSelectedIndex() > 0) {
String codigo = this.txtcodigo.getText();
String fechaString1 = this.txtfechaent.getText();
long fechaent = Date.parse(fechaString1);
Date fechaDate1 = new Date(fechaent);
String fechaString2 = this.txtfechasal.getText();
long fechasal = Date.parse(fechaString2);
Date fechaDate2 = new Date(fechasal);
float precio = Float.parseFloat(this.txtprecio.getText());
String vendedor = this.cbvendedores.getSelectedItem().toString();
String clientes = this.cbclientes.getSelectedItem().toString();
String habitacion = this.cbhabitaciones.getSelectedItem().toString();
String observaciones = " ";
observaciones = this.txtobservaciones.getText();
int decision = JOptionPane.showConfirmDialog(null, "¿Desea actualizar esta habitacion? ");
if (decision == 0) {
alquiler.actualizarAlquileres(codigo, precio, fechaDate1, fechaDate2, observaciones, vendedor, clientes, habitacion);
this.tablehab.setModel(alquiler.mostrarAlquileres());
}
} else {
JOptionPane.showMessageDialog(null, "No ha ingresado por completo los datos", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
int filaSeleccionada = this.tablehab.getSelectedRow();
int decision = JOptionPane.showConfirmDialog(null, "¿Desea Eliminar este alquiler ? ");
String codigo = this.tablehab.getValueAt(filaSeleccionada, 0).toString();
if (decision == 0) {
this.alquiler.eliminarAlquiler(codigo);
this.tablehab.setModel(this.alquiler.mostrarAlquileres());
}
}//GEN-LAST:event_jButton4ActionPerformed
private void tablehabMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablehabMouseClicked
int filaSeleccionada = this.tablehab.rowAtPoint(evt.getPoint());
this.txtcodigo.setText(this.tablehab.getValueAt(filaSeleccionada, 0).toString());
this.txtprecio.setText(this.tablehab.getValueAt(filaSeleccionada, 1).toString());
this.txtfechaent.setText(this.tablehab.getValueAt(filaSeleccionada, 2).toString());
this.txtfechasal.setText(this.tablehab.getValueAt(filaSeleccionada, 3).toString());
this.txtobservaciones.setText(this.tablehab.getValueAt(filaSeleccionada, 4).toString());
this.cbvendedores.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 5).toString());
this.cbclientes.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 6).toString());
this.cbhabitaciones.setSelectedItem(this.tablehab.getValueAt(filaSeleccionada, 7).toString());
}//GEN-LAST:event_tablehabMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cbclientes;
private javax.swing.JComboBox cbhabitaciones;
private javax.swing.JComboBox cbvendedores;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable tablehab;
private javax.swing.JTextField txtcodigo;
private javax.swing.JFormattedTextField txtfechaent;
private javax.swing.JFormattedTextField txtfechasal;
private javax.swing.JTextArea txtobservaciones;
private javax.swing.JFormattedTextField txtprecio;
// End of variables declaration//GEN-END:variables
}
| 27,803 | 0.667482 | 0.646655 | 496 | 55.048386 | 45.63311 | 305 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953629 | false | false |
4
|
6364b924fbbb14fe6343c6f67ad9294f72246f54
| 352,187,367,805 |
595d2c4baf12372684c8a0b27b4d3fd5627252e5
|
/app/autowired-qualifier/src/main/java/com/sistecma/springdesdecero/autowired/Printer.java
|
824902b5b82dcfed94f997bb9046771f6b8d6e18
|
[] |
no_license
|
sistecma/spring-desde-cero
|
https://github.com/sistecma/spring-desde-cero
|
5bd74d85403d186da3f6c7a33681f2a551a10c47
|
1d6d2d8f64781c93026f8bff1c97318282893068
|
refs/heads/master
| 2023-03-27T02:34:51.100000 | 2021-03-22T01:36:06 | 2021-03-22T01:36:06 | 324,667,172 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sistecma.springdesdecero.autowired;
public interface Printer {
public String print();
}
|
UTF-8
|
Java
| 102 |
java
|
Printer.java
|
Java
|
[] | null |
[] |
package com.sistecma.springdesdecero.autowired;
public interface Printer {
public String print();
}
| 102 | 0.794118 | 0.794118 | 5 | 19.4 | 17.511139 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
4
|
c427ddf02b2c8fb4766a97c7f92c8aff126614bf
| 18,433,999,684,402 |
71480afafd1055e457222ed448e1e1fea3ad0692
|
/innerware/src/main/java/com/sp/main/MainController.java
|
59866e32ec17caad5616696590b8473b2b60330d
|
[] |
no_license
|
ggyuhee/innerware
|
https://github.com/ggyuhee/innerware
|
7b53ba42081551307ddfa68084c76475d6255e57
|
d94e5225fcd9b49b3400d1b0fab9496c98b1e3a9
|
refs/heads/master
| 2018-02-07T19:14:02.354000 | 2017-07-28T08:33:51 | 2017-07-28T08:33:51 | 96,058,440 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sp.main;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sp.eapproval.Eapproval;
import com.sp.eapproval.EapprovalService;
import com.sp.freeBuseo.FreeBuseo;
import com.sp.freeBuseo.FreeBuseoService;
import com.sp.insa.Insa;
import com.sp.insa.InsaService;
import com.sp.insa.SessionInfo;
import com.sp.notice.Notice;
import com.sp.notice.NoticeService;
import com.sp.noticeBuseo.NoticeBuseo;
import com.sp.noticeBuseo.NoticeBuseoService;
@Controller("main.MainController")
public class MainController {
@Autowired
private InsaService service;
@Autowired
private NoticeBuseoService nbs;
@Autowired
private FreeBuseoService fbs;
@Autowired
private EapprovalService es;
@Autowired
private NoticeService ns;
@RequestMapping(value="/main")
public String main(Model model, HttpSession session) throws Exception{
SessionInfo info=(SessionInfo)session.getAttribute("insa");
Insa dto = service.readInsaF(info.geteCode());
int start = 1;
int end = 5;
Map<String, Object> map=new HashMap<>();
map.put("start", start);
map.put("end", end);
List<Notice> nList = ns.listNotice(map);
Iterator<Notice> it=nList.iterator();
while(it.hasNext()){
Notice data=(Notice)it.next();
data.setnCreated(data.getnCreated().substring(0,10));
}
map.put("bCode", info.getbCode());
List<NoticeBuseo> nbsList=nbs.listNoticeBuseo(map);
List<FreeBuseo> fbsList=fbs.listFreeBuseo(map);
map.put("mode", "nosign");
map.put("eCode", info.geteCode());
List<Eapproval> eList = es.listNosignEapproval(map);
model.addAttribute("dto", dto);
model.addAttribute("nbsList", nbsList);
model.addAttribute("eList", eList);
model.addAttribute("nList", nList);
model.addAttribute("fbsList", fbsList);
return ".main";
}
}
|
UTF-8
|
Java
| 2,183 |
java
|
MainController.java
|
Java
|
[] | null |
[] |
package com.sp.main;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sp.eapproval.Eapproval;
import com.sp.eapproval.EapprovalService;
import com.sp.freeBuseo.FreeBuseo;
import com.sp.freeBuseo.FreeBuseoService;
import com.sp.insa.Insa;
import com.sp.insa.InsaService;
import com.sp.insa.SessionInfo;
import com.sp.notice.Notice;
import com.sp.notice.NoticeService;
import com.sp.noticeBuseo.NoticeBuseo;
import com.sp.noticeBuseo.NoticeBuseoService;
@Controller("main.MainController")
public class MainController {
@Autowired
private InsaService service;
@Autowired
private NoticeBuseoService nbs;
@Autowired
private FreeBuseoService fbs;
@Autowired
private EapprovalService es;
@Autowired
private NoticeService ns;
@RequestMapping(value="/main")
public String main(Model model, HttpSession session) throws Exception{
SessionInfo info=(SessionInfo)session.getAttribute("insa");
Insa dto = service.readInsaF(info.geteCode());
int start = 1;
int end = 5;
Map<String, Object> map=new HashMap<>();
map.put("start", start);
map.put("end", end);
List<Notice> nList = ns.listNotice(map);
Iterator<Notice> it=nList.iterator();
while(it.hasNext()){
Notice data=(Notice)it.next();
data.setnCreated(data.getnCreated().substring(0,10));
}
map.put("bCode", info.getbCode());
List<NoticeBuseo> nbsList=nbs.listNoticeBuseo(map);
List<FreeBuseo> fbsList=fbs.listFreeBuseo(map);
map.put("mode", "nosign");
map.put("eCode", info.geteCode());
List<Eapproval> eList = es.listNosignEapproval(map);
model.addAttribute("dto", dto);
model.addAttribute("nbsList", nbsList);
model.addAttribute("eList", eList);
model.addAttribute("nList", nList);
model.addAttribute("fbsList", fbsList);
return ".main";
}
}
| 2,183 | 0.720568 | 0.718278 | 82 | 25.621952 | 19.261766 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.439024 | false | false |
4
|
e8da0e19e66e187459ccf8981ca4e34d8809d0f6
| 16,243,566,365,639 |
8bf7a38d48871434d5a9cb2a569318b5641c3558
|
/HelpingHands/src/edu/austincc/domain/VolunteerItems.java
|
c9059ce03cad71ea8c4bc00fe840023e1ed31978
|
[] |
no_license
|
jolakammu/HelpingHands
|
https://github.com/jolakammu/HelpingHands
|
29db01cffed13ca7a85e57ee33e99ffc5d2019be
|
d3ce161b70223d1ffdbbc9105ff8e7044d29f5a1
|
refs/heads/master
| 2021-01-19T17:11:59.095000 | 2015-07-08T16:31:08 | 2015-07-08T16:31:08 | 35,104,523 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.austincc.domain;
import java.util.Date;
public class VolunteerItems {
private int volunteertemId;
private String OrgName;
private String OrgCategory;
private String WorkDesc;
private int ManHrs;
private Date WorkBeginDtTime;
private int addressId;
private int elecCommuId;
private Address address;
private ElecctronicCommunication elecCommu;
public VolunteerItems(int volunteertemId, String orgName,
String orgCategory, String workDesc, int manHrs,
Date workBeginDtTime, int addressId, int elecCommuId,
Address address, ElecctronicCommunication elecCommu) {
super();
this.volunteertemId = volunteertemId;
this.OrgName = orgName;
this.OrgCategory = orgCategory;
this.WorkDesc = workDesc;
this.ManHrs = manHrs;
this.WorkBeginDtTime = workBeginDtTime;
this.addressId = addressId;
this.elecCommuId = elecCommuId;
this.address = address;
this.elecCommu = elecCommu;
}
public VolunteerItems(int volunteertemId, String orgName,
String orgCategory, String workDesc, int manHrs,
Date workBeginDtTime, int addressId, int elecCommuId) {
super();
this.volunteertemId = volunteertemId;
this.OrgName = orgName;
this.OrgCategory = orgCategory;
this.WorkDesc = workDesc;
this.ManHrs = manHrs;
this.WorkBeginDtTime = workBeginDtTime;
this.addressId = addressId;
this.elecCommuId = elecCommuId;
this.address = address;
this.elecCommu = elecCommu;
}
public int getVolunteertemId() {
return volunteertemId;
}
public void setVolunteertemId(int volunteertemId) {
this.volunteertemId = volunteertemId;
}
public String getOrgName() {
return OrgName;
}
public void setOrgName(String orgName) {
OrgName = orgName;
}
public String getOrgCategory() {
return OrgCategory;
}
public void setOrgCategory(String orgCategory) {
OrgCategory = orgCategory;
}
public String getWorkDesc() {
return WorkDesc;
}
public void setWorkDesc(String workDesc) {
WorkDesc = workDesc;
}
public int getManHrs() {
return ManHrs;
}
public void setManHrs(int manHrs) {
ManHrs = manHrs;
}
public Date getWorkBeginDtTime() {
return WorkBeginDtTime;
}
public void setWorkBeginDtTime(Date workBeginDtTime) {
WorkBeginDtTime = workBeginDtTime;
}
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}
public int getElecCommuId() {
return elecCommuId;
}
public void setElecCommuId(int elecCommuId) {
this.elecCommuId = elecCommuId;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ElecctronicCommunication getElecCommu() {
return elecCommu;
}
public void setElecCommu(ElecctronicCommunication elecCommu) {
this.elecCommu = elecCommu;
}
@Override
public String toString() {
return "VolunteerItems [volunteertemId=" + volunteertemId
+ ", OrgName=" + OrgName + ", OrgCategory=" + OrgCategory
+ ", WorkDesc=" + WorkDesc + ", ManHrs=" + ManHrs
+ ", WorkBeginDtTime=" + WorkBeginDtTime + ", addressId="
+ addressId + ", elecCommuId=" + elecCommuId + ", address="
+ address + ", elecCommu=" + elecCommu + "]";
}
}
|
UTF-8
|
Java
| 3,347 |
java
|
VolunteerItems.java
|
Java
|
[] | null |
[] |
package edu.austincc.domain;
import java.util.Date;
public class VolunteerItems {
private int volunteertemId;
private String OrgName;
private String OrgCategory;
private String WorkDesc;
private int ManHrs;
private Date WorkBeginDtTime;
private int addressId;
private int elecCommuId;
private Address address;
private ElecctronicCommunication elecCommu;
public VolunteerItems(int volunteertemId, String orgName,
String orgCategory, String workDesc, int manHrs,
Date workBeginDtTime, int addressId, int elecCommuId,
Address address, ElecctronicCommunication elecCommu) {
super();
this.volunteertemId = volunteertemId;
this.OrgName = orgName;
this.OrgCategory = orgCategory;
this.WorkDesc = workDesc;
this.ManHrs = manHrs;
this.WorkBeginDtTime = workBeginDtTime;
this.addressId = addressId;
this.elecCommuId = elecCommuId;
this.address = address;
this.elecCommu = elecCommu;
}
public VolunteerItems(int volunteertemId, String orgName,
String orgCategory, String workDesc, int manHrs,
Date workBeginDtTime, int addressId, int elecCommuId) {
super();
this.volunteertemId = volunteertemId;
this.OrgName = orgName;
this.OrgCategory = orgCategory;
this.WorkDesc = workDesc;
this.ManHrs = manHrs;
this.WorkBeginDtTime = workBeginDtTime;
this.addressId = addressId;
this.elecCommuId = elecCommuId;
this.address = address;
this.elecCommu = elecCommu;
}
public int getVolunteertemId() {
return volunteertemId;
}
public void setVolunteertemId(int volunteertemId) {
this.volunteertemId = volunteertemId;
}
public String getOrgName() {
return OrgName;
}
public void setOrgName(String orgName) {
OrgName = orgName;
}
public String getOrgCategory() {
return OrgCategory;
}
public void setOrgCategory(String orgCategory) {
OrgCategory = orgCategory;
}
public String getWorkDesc() {
return WorkDesc;
}
public void setWorkDesc(String workDesc) {
WorkDesc = workDesc;
}
public int getManHrs() {
return ManHrs;
}
public void setManHrs(int manHrs) {
ManHrs = manHrs;
}
public Date getWorkBeginDtTime() {
return WorkBeginDtTime;
}
public void setWorkBeginDtTime(Date workBeginDtTime) {
WorkBeginDtTime = workBeginDtTime;
}
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}
public int getElecCommuId() {
return elecCommuId;
}
public void setElecCommuId(int elecCommuId) {
this.elecCommuId = elecCommuId;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ElecctronicCommunication getElecCommu() {
return elecCommu;
}
public void setElecCommu(ElecctronicCommunication elecCommu) {
this.elecCommu = elecCommu;
}
@Override
public String toString() {
return "VolunteerItems [volunteertemId=" + volunteertemId
+ ", OrgName=" + OrgName + ", OrgCategory=" + OrgCategory
+ ", WorkDesc=" + WorkDesc + ", ManHrs=" + ManHrs
+ ", WorkBeginDtTime=" + WorkBeginDtTime + ", addressId="
+ addressId + ", elecCommuId=" + elecCommuId + ", address="
+ address + ", elecCommu=" + elecCommu + "]";
}
}
| 3,347 | 0.701524 | 0.701524 | 141 | 21.737589 | 18.981382 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.829787 | false | false |
4
|
7b412ac025cd60329f09a5dd1d00f94c26aee913
| 19,232,863,591,991 |
60daccfd954fdb5d6a58e11a6ff307d457b12df1
|
/src/main/java/com/kuyuner/core/sys/service/impl/LoginServiceImpl.java
|
a4f7c27f306c6585a08fc48056a016c290f055a0
|
[] |
no_license
|
mohatie/oa
|
https://github.com/mohatie/oa
|
0b29d340a5cf16722c412505f84a5b6aba637ffa
|
2f56fddde7b5e9e97e28e53e1ef5b8c1b45b970f
|
refs/heads/master
| 2022-12-16T19:28:17.400000 | 2019-06-25T11:42:57 | 2019-06-25T11:42:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kuyuner.core.sys.service.impl;
import com.kuyuner.core.sys.dao.LoginDao;
import com.kuyuner.core.sys.entity.User;
import com.kuyuner.core.sys.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 登陆服务实现接口
*
* @author Administrator
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginDao loginDao;
@Override
public User login(String username) {
return loginDao.login(username);
}
}
|
UTF-8
|
Java
| 570 |
java
|
LoginServiceImpl.java
|
Java
|
[
{
"context": "stereotype.Service;\n\n/**\n * 登陆服务实现接口\n *\n * @author Administrator\n */\n@Service\npublic class LoginServiceImpl implem",
"end": 332,
"score": 0.8774267435073853,
"start": 319,
"tag": "NAME",
"value": "Administrator"
}
] | null |
[] |
package com.kuyuner.core.sys.service.impl;
import com.kuyuner.core.sys.dao.LoginDao;
import com.kuyuner.core.sys.entity.User;
import com.kuyuner.core.sys.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 登陆服务实现接口
*
* @author Administrator
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginDao loginDao;
@Override
public User login(String username) {
return loginDao.login(username);
}
}
| 570 | 0.756318 | 0.756318 | 25 | 21.16 | 20.504984 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false |
4
|
b68b36eb116ceefb282c6ecce7679eb22647fa04
| 26,070,451,541,364 |
1072aee26ab12c3cb7f4353ea134ac710077e57e
|
/WebEngineering/lab8/WEB-INF/classes/Add.java
|
c77c3df650ca4620b0b24e9913d6aca0bd6cf60d
|
[] |
no_license
|
HassanFCS/Programming-Tasks
|
https://github.com/HassanFCS/Programming-Tasks
|
9924b4a09f6de6326b4d384f3fb30441f00fa612
|
5b1c7da65fe4d90836f1f94c5bfbcf6eaccbaa8c
|
refs/heads/master
| 2022-11-16T19:01:35.340000 | 2020-07-16T20:45:42 | 2020-07-16T20:45:42 | 280,150,533 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Add extends HttpServlet {
//Process the HTTP Get request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String cname=request.getParameter("cname");
String model=request.getParameter("model");
String price=request.getParameter("price");
out.println("<html>");
out.println("<head><title>Response</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1/mobileInfo";
Connection con=DriverManager.getConnection(url,"root","root");
Statement st=con.createStatement();
String query="INSERT INTO mobileOutlet(companyName,model,price) VALUES ('"+cname+"','"+model+"',"+price+")";
System.out.println(query);
int rs = st.executeUpdate( query );
if(rs==1){
out.println("Successfully Added");
}
else{
response.sendRedirect("/lab8/home.html");
}
out.println("</body></html>");
st.close();
con.close();
}catch(Exception e){
out.println(e);
}
}
}
|
UTF-8
|
Java
| 1,395 |
java
|
Add.java
|
Java
|
[
{
"context": "dbc.Driver\");\r\n\r\n String url = \"jdbc:mysql://127.0.0.1/mobileInfo\";\r\n\r\n Connection con=DriverManage",
"end": 744,
"score": 0.6790978908538818,
"start": 735,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Add extends HttpServlet {
//Process the HTTP Get request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String cname=request.getParameter("cname");
String model=request.getParameter("model");
String price=request.getParameter("price");
out.println("<html>");
out.println("<head><title>Response</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1/mobileInfo";
Connection con=DriverManager.getConnection(url,"root","root");
Statement st=con.createStatement();
String query="INSERT INTO mobileOutlet(companyName,model,price) VALUES ('"+cname+"','"+model+"',"+price+")";
System.out.println(query);
int rs = st.executeUpdate( query );
if(rs==1){
out.println("Successfully Added");
}
else{
response.sendRedirect("/lab8/home.html");
}
out.println("</body></html>");
st.close();
con.close();
}catch(Exception e){
out.println(e);
}
}
}
| 1,395 | 0.594265 | 0.58853 | 60 | 21.283333 | 25.890856 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false |
4
|
0c2c5c3afe80550e2d13ac6b647d95873c9e4883
| 24,498,493,522,652 |
8d4532ed0fa5aac7a9ee31c71fd5e3b46172fbd6
|
/AIOIMSPMLClient/src/com/ai/oimspmlclient/HeaderHandlerResolver.java
|
3d43caa596ad8f965c63addc9e4336b91ba9d9a3
|
[] |
no_license
|
ranajoy97/oimexamples
|
https://github.com/ranajoy97/oimexamples
|
314a6bd41cd897ca0bdfbb84bf4562284371d9ca
|
da8e33359520a6ada63e0baf2edf16963462f340
|
refs/heads/master
| 2021-01-10T05:38:51.188000 | 2012-10-17T13:36:39 | 2012-10-17T13:36:39 | 44,969,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ai.oimspmlclient;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
/**
*
* @author www.javadb.com
*/
public class HeaderHandlerResolver implements HandlerResolver {
private String userId;
private String password;
public HeaderHandlerResolver(String userId,String password) {
this.userId = userId;
this.password = password;
}
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
HeaderHandler hh = new HeaderHandler(userId,password);
handlerChain.add(hh);
return handlerChain;
}
}
|
UTF-8
|
Java
| 844 |
java
|
HeaderHandlerResolver.java
|
Java
|
[
{
"context": " this.userId = userId;\n this.password = password;\n }\n\npublic List<Handler> getHandlerChain(Port",
"end": 591,
"score": 0.9191145300865173,
"start": 583,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ai.oimspmlclient;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
/**
*
* @author www.javadb.com
*/
public class HeaderHandlerResolver implements HandlerResolver {
private String userId;
private String password;
public HeaderHandlerResolver(String userId,String password) {
this.userId = userId;
this.password = <PASSWORD>;
}
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
HeaderHandler hh = new HeaderHandler(userId,password);
handlerChain.add(hh);
return handlerChain;
}
}
| 846 | 0.720379 | 0.720379 | 37 | 21.837837 | 21.670149 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486486 | false | false |
4
|
d41e66ed218a69fa57117cdd8e2008fe12ca9b56
| 17,274,358,533,450 |
552921fe07b104d5e3f5220c835f59be7376a751
|
/oa-model/src/main/java/z_tknight/oa/model/entity/TTag.java
|
76e0984b866f6f3d3480568535ad25157912ff66
|
[] |
no_license
|
GimKing/OATeamProject
|
https://github.com/GimKing/OATeamProject
|
a817da50c2042bc61bb766897763bbd8635d21b5
|
7805a86c7a2fb85072c836e01a7eb6587dbd9cbe
|
refs/heads/master
| 2021-06-24T11:42:35.157000 | 2017-08-29T08:36:59 | 2017-08-29T08:36:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package z_tknight.oa.model.entity;
public class TTag {
/**
* 标签编号
*/
private Integer tagNo = null;
/**
* 标签内容
*/
private String tagName = null;
/**
* 所属看板空间编号
*/
private Integer boardSpaceNo = null;
/**
* 所属看板编号
*/
private Integer boardNo = null;
public void setTagNo(Integer tagNo) {
this.tagNo = tagNo;
}
public Integer getTagNo() {
return this.tagNo;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public String getTagName() {
return this.tagName;
}
public void setBoardSpaceNo(Integer boardSpaceNo) {
this.boardSpaceNo = boardSpaceNo;
}
public Integer getBoardSpaceNo() {
return this.boardSpaceNo;
}
public void setBoardNo(Integer boardNo) {
this.boardNo = boardNo;
}
public Integer getBoardNo() {
return this.boardNo;
}
}
|
UTF-8
|
Java
| 864 |
java
|
TTag.java
|
Java
|
[] | null |
[] |
package z_tknight.oa.model.entity;
public class TTag {
/**
* 标签编号
*/
private Integer tagNo = null;
/**
* 标签内容
*/
private String tagName = null;
/**
* 所属看板空间编号
*/
private Integer boardSpaceNo = null;
/**
* 所属看板编号
*/
private Integer boardNo = null;
public void setTagNo(Integer tagNo) {
this.tagNo = tagNo;
}
public Integer getTagNo() {
return this.tagNo;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public String getTagName() {
return this.tagName;
}
public void setBoardSpaceNo(Integer boardSpaceNo) {
this.boardSpaceNo = boardSpaceNo;
}
public Integer getBoardSpaceNo() {
return this.boardSpaceNo;
}
public void setBoardNo(Integer boardNo) {
this.boardNo = boardNo;
}
public Integer getBoardNo() {
return this.boardNo;
}
}
| 864 | 0.671951 | 0.671951 | 58 | 13.137931 | 14.767682 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.051724 | false | false |
4
|
065f49abb88e3098b665d17f67a279b22f709096
| 884,763,325,020 |
b194bcff5bb7f92e62b00ccb93107469524578ac
|
/NetBeansProjects/sambook/src/Learn/multiplclass1.java
|
2266e99f56a735156f8fe753b5910f4ec755ffd7
|
[] |
no_license
|
Kunwardev/Java-Projects
|
https://github.com/Kunwardev/Java-Projects
|
a0a37bc24acec7a6860dbbae08c09d695f84eed0
|
ecdeda71e34e332b7fe0b0a6f05f2ae560bf3f38
|
refs/heads/master
| 2021-01-11T21:31:39.542000 | 2017-02-16T14:41:05 | 2017-02-16T14:42:32 | 77,022,706 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Learn;
public class multiplclass1
{
public static void main(String[] args)
{
multiplclass2 mc = new multiplclass2();
mc.printmess();
}
}
|
UTF-8
|
Java
| 166 |
java
|
multiplclass1.java
|
Java
|
[] | null |
[] |
package Learn;
public class multiplclass1
{
public static void main(String[] args)
{
multiplclass2 mc = new multiplclass2();
mc.printmess();
}
}
| 166 | 0.650602 | 0.63253 | 10 | 15.6 | 15.698407 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
4
|
33941ea7235810752d87bc8dab75b438663281be
| 20,675,972,593,162 |
79bd41bba3e3893ddc6985c55b26fe51d25f3a09
|
/src/main/java/com/rcbank/mms/controller/CommonController.java
|
7fc0331692bf33f192765f88807027eadde93453
|
[] |
no_license
|
jimnie/mms
|
https://github.com/jimnie/mms
|
e20a9177fb1b1dced5fc72866de1e26ad99f0fa6
|
0f671ec7aab9430addc4ae528937588e81b2867c
|
refs/heads/master
| 2022-12-18T17:17:54.081000 | 2017-03-29T08:24:31 | 2017-03-29T08:24:31 | 53,824,856 | 1 | 0 | null | false | 2022-12-16T11:30:11 | 2016-03-14T03:42:32 | 2020-07-30T12:33:25 | 2022-12-16T11:30:08 | 3,861 | 0 | 0 | 23 |
JavaScript
| false | false |
package com.rcbank.mms.controller;
import com.rcbank.mms.service.MessageService;
import com.rcbank.mms.service.RSAService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
@Controller("commonController")
@RequestMapping("/common")
public class CommonController implements ServletContextAware {
@Resource(name = "messageServiceImpl")
private MessageService messageService;
@Resource(name = "rsaServiceImpl")
private RSAService rsaService;
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String main() {
return "/common/main";
}
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
@ResponseBody
private Map<String, String> publicKey(HttpServletRequest request) {
RSAPublicKey publicKey = rsaService.generateKey(request);
Map<String, String> data = new HashMap<String, String>();
data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray
()));
return data;
}
@RequestMapping("/error")
public String error() {
return "/common/error";
}
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
String requestType = request.getHeader("X-Requested-With");
if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
response.addHeader("loginStatus", "unauthorized");
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
return "/common/unauthorized";
}
@RequestMapping("/invalidSession")
public String invalidSession() {
return "/common/invalidSession";
}
}
|
UTF-8
|
Java
| 2,690 |
java
|
CommonController.java
|
Java
|
[] | null |
[] |
package com.rcbank.mms.controller;
import com.rcbank.mms.service.MessageService;
import com.rcbank.mms.service.RSAService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
@Controller("commonController")
@RequestMapping("/common")
public class CommonController implements ServletContextAware {
@Resource(name = "messageServiceImpl")
private MessageService messageService;
@Resource(name = "rsaServiceImpl")
private RSAService rsaService;
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String main() {
return "/common/main";
}
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
@ResponseBody
private Map<String, String> publicKey(HttpServletRequest request) {
RSAPublicKey publicKey = rsaService.generateKey(request);
Map<String, String> data = new HashMap<String, String>();
data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray
()));
return data;
}
@RequestMapping("/error")
public String error() {
return "/common/error";
}
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
String requestType = request.getHeader("X-Requested-With");
if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
response.addHeader("loginStatus", "unauthorized");
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
return "/common/unauthorized";
}
@RequestMapping("/invalidSession")
public String invalidSession() {
return "/common/invalidSession";
}
}
| 2,690 | 0.714498 | 0.710781 | 76 | 34.407894 | 25.391243 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false |
4
|
eb3fb2bf28dfded0f907bcacf2832a30807929f5
| 20,675,972,596,546 |
95359d41a1757273bd8935381c0db721a00336ae
|
/src/trustauthority/TAmodule.java
|
cec329d3e5ea25e79b889b5fc320ea60c40b9ba4
|
[] |
no_license
|
rmvpaps/Trustmodel
|
https://github.com/rmvpaps/Trustmodel
|
7b36be0bf4d56401c0056b3f7116d21de823be41
|
c376fed34124a70635c59cb09081b3db340ab0f6
|
refs/heads/master
| 2021-01-10T04:22:16.199000 | 2013-02-26T06:07:34 | 2013-02-26T06:07:34 | 8,426,020 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package trustauthority;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import monitor.WSLAParser;
import dataaccess.DB_TA;
public class TAmodule{
DB_TA db = new DB_TA();
static Date startup = new java.util.Date(0);
/*
* To be called to register a valid service provider
*/
public boolean registerServiceprovider(String orgname, String authkey) throws Myexception
{
String errormsg = "";
if(orgname == null || authkey == null)
{
errormsg = "All fields are required";
}
else
{
try
{
db.insertnewuser(orgname, authkey, "SP");
return true;
}
catch (Exception e) {
errormsg = e.getMessage();
}
}
throw new Myexception(errormsg);
}
/*
* To be called to register a valid service client entity
*/
public int registerServiceClient(String name, String email, String authkey) throws Myexception
{
String errormsg = "";
if(email==null || name == null || authkey == null)
{
errormsg = "All fields are required";
}
else
{
int cid = -111;
try
{
cid = db.storeWSclient(name, email);
db.insertnewuser(String.valueOf(cid), authkey, "SC");
return cid;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
throw new Myexception(errormsg);
}
/*
* To be called through web service to register a particular service with TA. Store advertised QoS also
* and return new WSDL link to be used
*/
public Wservice_db registerWebService(String orgname, String authkey, String wsdl, String qosurl, String category, String endpoint) throws Myexception
{
int sid = -1111;
String errormsg = "";
if(db.checkvaliduser(orgname,authkey,"SP"))
{
if(orgname!=null && endpoint != null && qosurl!=null)
{
try
{
Map<String,Double> advq = parseQos(qosurl);
sid = db.storeWservice(orgname, wsdl, qosurl, category,endpoint);
db.storeQadv(sid, advq);
/* Create a web service proxy at ~/services/sid and return the new WSDL
*/
String newurl = "http://localhost:8080/TrustModel/services/1/"+sid;
Wservice_db nws = new Wservice_db();
nws.setCategory(category);
nws.setOrgname(orgname);
nws.setQosurl(qosurl);
nws.setServid(sid);
nws.setWsdlurl(newurl);
return nws;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To be called through web service to register a particular service with TA. Store advertised QoS also
* and return new WSDL link to be used
*/
public Wservice_db registerWebService2(String orgname, String authkey, String wsdl, String category, Performance_sp pf,String endpoint) throws Myexception
{
int sid = -1111;
String errormsg = "";
if(db.checkvaliduser(orgname,authkey,"SP"))
{
if(orgname!=null && endpoint != null && pf!=null)
{
try
{
Map<String,Double> advq = pf.convert();
sid = db.storeWservice(orgname, wsdl, "not specified", category, endpoint);
db.storeQadv(sid, advq);
/* Create a web service proxy at ~/services/sid and return the new WSDL
*/
String newurl = "http://localhost:8080/TrustModel/services/1/"+sid;
Wservice_db nws = new Wservice_db();
nws.setCategory(category);
nws.setOrgname(orgname);
nws.setQosurl("not specified");
nws.setServid(sid);
nws.setWsdlurl(wsdl);
nws.setEndpoint(newurl);
return nws;
}
catch(Exception e)
{
errormsg = e.getMessage();
e.printStackTrace();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To be called from web service to start monitoring
* interactions between that service and client
*/
/*public void bindToService(int sid, int cid, String authkey, Qoswt wt[]) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
db.storeQweights(cid, sid,wt);
db.initializeDT(cid, sid);
return;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}*/
public Wservice_db bindToService(int sid, int cid, String authkey, Qoswt wt[]) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db ws = db.getWservDetails(sid);
db.storeQweights(cid, sid,wt);
db.initializeDT(cid, sid);
ws.setWsdlurl("http://localhost:8080/TrustManagementService/services/"+cid+"/"+sid);
return ws;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
public Wservice_db bindToService_sp(int sid, int cid, String authkey, Qoswt_sp wt) throws Myexception
{
String errmsg = "";
Qoswt[] wts = wt.convert();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db ws = db.getWservDetails(sid);
db.storeQweights(cid, sid,wts);
db.initializeDT(cid, sid);
ws.setEndpoint("http://localhost:8080/TrustModel/services/"+cid+"/"+sid);
return ws;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get the trust value of a particular service
* uses methods less efficient - multiple database calls
*/
public TrustResult getTrust_LS(int sid, int cid, String authkey) throws Myexception
{
String errmsg = "";
TrustResult tr = new TrustResult();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
double wtsum=0,dtsum=0,trust=0.5;
//perform the trust calculation
//get direct trust
DT dt1 = db.getDirtrust(sid, cid);
DT_sp dts = new DT_sp(dt1);
tr.setDt(dts);
List<Integer> clist = db.getClientwhointeracted(sid);
for(int i=0;i<clist.size();i++)
{
int cid2 = clist.get(i);
if(cid2==cid)
continue;
DT dt = db.getDirtrust(sid, cid2);
double rt = db.getRt(cid, cid2);
double ts = timediff(dt.getTs(),new Date());
System.out.println("cid1" + cid + "cid2" + cid2 + "dt" + dt.getValue() + "ref" + rt);
dtsum += rt * dt.getValue() /ts ;
wtsum += rt/ts;
}
//if someone has interacted before
if(clist.size()!=0)
{
//if direct experience
if(dt1!= null)
{
double exp1 = expe(dt1.freq);
trust = exp1*dt1.getValue() + (1-exp1)*(dtsum/wtsum);
}//if no direct experience
else
trust = dtsum/wtsum;
tr.setIndirect_trust(dtsum/wtsum);
}
tr.setOverall_trust(trust);
return tr;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get the trust value of a particular service
* uses method directly from database
*/
public TrustResult getTrust(int sid, int cid, String authkey) throws Myexception
{
String errmsg = "";
TrustResult tr = new TrustResult();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//perform the trust calculation
List<Transfertrust> lt= db.gettruststat(cid, sid);
DT dt= db.getDirtrust(sid, cid);
DT_sp dts = new DT_sp(dt);
tr.setDt(dts);
Date curr = new Date();
double dtsum=0,wtsum=0,trust=0.5;
for(int i=0; i<lt.size(); i++)
{
Transfertrust temp = lt.get(i);
System.out.println("cid1"+ temp.getCid1() + "cid2"+temp.getCid2() + "dt" + temp.getDirtrust() + "ref" + temp.getReftrust());
dtsum += temp.getDirtrust() * temp.getReftrust() /(timediff(temp.getTs(),curr));
wtsum += temp.getReftrust() /(timediff(temp.getTs(), curr));
}
//if someone has interacted before
if(wtsum!=0)
{
System.out.println("Considering recommendations");
//if direct experience
if(dt!= null)
{
System.out.println("Considering direct trust");
double exp1 = expe(dt.freq);
trust = exp1*dt.getValue() + (1-exp1)*(dtsum/wtsum);
}//if no direct experience
else
trust = dtsum/wtsum;
tr.setIndirect_trust(dtsum/wtsum);
}
else if(dt!= null)
{
trust = dt.getValue();
}
tr.setOverall_trust(trust);
return tr;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* Called from web service to accept user feedback on a service
*/
public void givefeedback(double val, int sid, int cid,String authkey) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//call to record feedback
DT dt= db.getDirtrust(sid, cid);
if(dt!=null || dt.getFreq()!=0)
{
if(val<0.3)
updateDT(sid, cid, false);
else if(val>.7)
updateDT(sid, cid, true);
}
else
errmsg = "No interactions recorded. Bind to service first";
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get performance details of a service based on its interaction with us
*/
public Performance getCurrentPerformance(int cid, String authkey, int sid) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//call to get performance details
Performance p = db.preparedigest(new Date(), sid, cid);
if(p==null)
errmsg="No performace recorded";
else
return p;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* to be called from web service to get performance details of a service as a whole
*/
public Performance getServicePerformance(int sid) throws Myexception
{
String errmsg = "";
try
{
//call to get performance details
Performance p = db.getPerformance(new Date(), sid);
if(p==null)
errmsg="No performace recorded";
else
return p;
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* to be called from web service to return all registered services
*
*/
public Wservice_db[] getregisteredservices(int cid,String authkey,String category) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db[] wsarray;
wsarray = db.findServices(category);
if(wsarray==null)
errmsg="No services registered";
else
return wsarray;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*************************************************************************************************************/
/*
* function to accept current rating of a service
*/
public void provideRating(int cid, int sid, Map<String,Double> monq) throws Exception
{
Map<String,Double> advq = db.getQadv(sid);
Map<String,Integer> wtq = db.getQweights(cid, sid);
if(wtq.size()==0 && cid==1)
wtq = getdefaultwt();
if(advq!=null && wtq!= null)
updateDT(sid, cid, CheckSatisfied(advq,wtq,monq));
try
{
db.dtrecord(cid, sid, db.getDirtrust(sid, cid).getValue());
}
catch(Exception e)
{
}
}
private Map<String,Integer> getdefaultwt()
{
Map<String,Integer> wtq = new HashMap<String, Integer>();
wtq.put("Availability",1);
wtq.put("Errorrate",1);
wtq.put("Exceptionrate",1);
wtq.put("MinResponsetime",1);
wtq.put("MaxResponsetime",1);
wtq.put("AvgResponsetime",1);
return wtq;
}
/*
* To update direct trust
* then reftrusts
*/
private void updateDT(int sid, int cid, boolean satisfied) throws Exception
{
DT dt = db.getDirtrust(sid, cid);
double tdiff = timediff(dt.getTs(),new Date());
System.out.println("old = "+dt.getValue() +"diff" + tdiff);
if(satisfied)
db.updateDT(cid, sid, 1 + 0.1*tdiff);
else
db.updateDT(cid, sid, 1 - 0.2*tdiff);
//update reftrust of all clients who have interacted before with this service
dt = db.getDirtrust(sid, cid);
System.out.println("new = "+dt.getValue());
List<Integer> lc = db.getClientwhointeracted(sid);
for(int i=0; i< lc.size();i++)
{
int cid2 = lc.get(i);
if(cid2==cid)
continue;
DT dt2 = db.getDirtrust(sid, cid2);
double diff = (dt2.getValue() - dt.getValue())/timediff(dt2.getTs(),dt.getTs());
if(diff < 0.2)
db.updateRT(cid, cid2, 1.1);
else if(diff > 0.5)
db.updateRT(cid, cid2, 0.8);
}
}
/*
* check whether an interaction is satisfactory
*/
private boolean CheckSatisfied(Map<String, Double> advqmap,
Map<String, Integer> wtmap, Map<String, Double> monq) throws Exception {
System.out.println("Check satisfied");
//calculate deviation
double deviation = 0,sum1=0,sum2=0;
for( String key:monq.keySet())
{
if(wtmap.containsKey(key) && advqmap.containsKey(key))
{
System.out.println(key);
//normalized difference
double diff = advqmap.get(key) - monq.get(key);
if((key=="AvgResponsetime")||(key=="MaxResponsetime")||(key=="MinResponsetime"))
{
diff = -diff/advqmap.get(key);
if(diff<-1)
diff = -1;
else if(diff > 1)
diff = 1;
}
if((key=="Exceptionrate")||(key=="Errorrate"))
{
diff = (1-monq.get(key)) -(1-advqmap.get(key));
}
sum1+= wtmap.get(key) * diff;
sum2+= wtmap.get(key);
}
}
if(sum2==0)
throw new Exception("Bad weights");
deviation = sum1/sum2;
if(deviation > 0.001)
{ System.out.println("not satisfied");
return false;
}
else
return true;
}
/*
* To parse a Qos spec and return a map
*/
private Map<String, Double> parseQos(String qosurl) throws ParserConfigurationException, SAXException, IOException
{
Map<String, Double> advq = new HashMap<String, Double>();
WSLAParser wsl = new WSLAParser(qosurl);
wsl.parse();
/*Hard coded - need to parse qos spec*/
advq.put("availability", .99);
advq.put("AvgResponsetime", 0.78);
advq.put("Errorrate", 0.99);
return advq;
}
/*
* To be called through web service to find the registered services in a category
*/
public Wservice_db[] findWebService(String email, String authkey, String category ) throws Myexception
{
String errormsg = "";
Wservice_db[] wsarr;
if(db.checkvaliduser(email,authkey,"SC"))
{
if(category!= null)
{
try
{
wsarr = db.findServices(category);
return wsarr;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To get value corresponding to time difference
*/
private double timediff(Date prev, Date curr)
{
return 1 + (curr.getTime() - prev.getTime())/(curr.getTime() - startup.getTime());
}
/*
* To get value corresponding to frequency
*/
private double expe(int freq)
{
return 1-(Math.exp(-freq));
}
/*
* To normalize performance values
*/
/*
public static void main(String[] args) throws Exception
{
TAmodule ta1 = new TAmodule();
//ta1.registerServiceprovider("RMVServices", "123456");
//ta1.registerWebService("RMVServices", "123456",
//"http://www.ebi.ac.uk/soaplab/typed/services/nucleic_composition.banana?WSDL",
//"http://www.ebi.ac.uk/soaplab/typed/services/nucleic_composition.banana?QOS", "genedatabase");
//ta1.registerServiceClient("m110405cs", "rini_mcs11@nitc.ac.in", "121212");
/*Qoswt[] wt = new Qoswt[2];
wt[0] = new Qoswt("Availability",5);
wt[1] = new Qoswt("responsetime",3);
ta1.bindToService(6,6,"131313",wt);*/
/*Map<String, Double> monq = new HashMap<String, Double>();
monq.put("Availability", 0.75);
ta1.provideRating(6, 6, monq);
System.out.println(ta1.getTrust(6, 8, "121212"));
}
*/
}
|
UTF-8
|
Java
| 16,899 |
java
|
TAmodule.java
|
Java
|
[
{
"context": "dvqmap.get(key) - monq.get(key);\n\t\t \tif((key==\"AvgResponsetime\")||(key==\"MaxResponsetime\")||(key==\"MinResponseti",
"end": 13981,
"score": 0.8293765187263489,
"start": 13966,
"tag": "KEY",
"value": "AvgResponsetime"
},
{
"context": "(key);\n\t\t \tif((key==\"AvgResponsetime\")||(key==\"MaxResponsetime\")||(key==\"MinResponsetime\"))\n\t\t \t{\n\t\t \t\tdif",
"end": 14007,
"score": 0.8023936152458191,
"start": 13992,
"tag": "KEY",
"value": "MaxResponsetime"
},
{
"context": "gResponsetime\")||(key==\"MaxResponsetime\")||(key==\"MinResponsetime\"))\n\t\t \t{\n\t\t \t\tdiff = -diff/advqmap.get(key)",
"end": 14033,
"score": 0.8128806948661804,
"start": 14018,
"tag": "KEY",
"value": "MinResponsetime"
},
{
"context": " \t\t\tdiff = 1;\n\t\t \t\t\n\t\t \t}\n\t\t \tif((key==\"Exceptionrate\")||(key==\"Errorrate\"))\n\t\t \t{\n\t\t \t\tdiff = (1",
"end": 14219,
"score": 0.8176617622375488,
"start": 14206,
"tag": "KEY",
"value": "Exceptionrate"
},
{
"context": "\t\t \t}\n\t\t \tif((key==\"Exceptionrate\")||(key==\"Errorrate\"))\n\t\t \t{\n\t\t \t\tdiff = (1-monq.get(key)) -(1-",
"end": 14239,
"score": 0.8088467717170715,
"start": 14230,
"tag": "KEY",
"value": "Errorrate"
},
{
"context": ");\n\t\t\n\t\t//ta1.registerServiceClient(\"m110405cs\", \"rini_mcs11@nitc.ac.in\", \"121212\");\n\t\t/*Qoswt[] wt = new Qoswt[2];\n\t\twt[",
"end": 16544,
"score": 0.9999271631240845,
"start": 16523,
"tag": "EMAIL",
"value": "rini_mcs11@nitc.ac.in"
}
] | null |
[] |
package trustauthority;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import monitor.WSLAParser;
import dataaccess.DB_TA;
public class TAmodule{
DB_TA db = new DB_TA();
static Date startup = new java.util.Date(0);
/*
* To be called to register a valid service provider
*/
public boolean registerServiceprovider(String orgname, String authkey) throws Myexception
{
String errormsg = "";
if(orgname == null || authkey == null)
{
errormsg = "All fields are required";
}
else
{
try
{
db.insertnewuser(orgname, authkey, "SP");
return true;
}
catch (Exception e) {
errormsg = e.getMessage();
}
}
throw new Myexception(errormsg);
}
/*
* To be called to register a valid service client entity
*/
public int registerServiceClient(String name, String email, String authkey) throws Myexception
{
String errormsg = "";
if(email==null || name == null || authkey == null)
{
errormsg = "All fields are required";
}
else
{
int cid = -111;
try
{
cid = db.storeWSclient(name, email);
db.insertnewuser(String.valueOf(cid), authkey, "SC");
return cid;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
throw new Myexception(errormsg);
}
/*
* To be called through web service to register a particular service with TA. Store advertised QoS also
* and return new WSDL link to be used
*/
public Wservice_db registerWebService(String orgname, String authkey, String wsdl, String qosurl, String category, String endpoint) throws Myexception
{
int sid = -1111;
String errormsg = "";
if(db.checkvaliduser(orgname,authkey,"SP"))
{
if(orgname!=null && endpoint != null && qosurl!=null)
{
try
{
Map<String,Double> advq = parseQos(qosurl);
sid = db.storeWservice(orgname, wsdl, qosurl, category,endpoint);
db.storeQadv(sid, advq);
/* Create a web service proxy at ~/services/sid and return the new WSDL
*/
String newurl = "http://localhost:8080/TrustModel/services/1/"+sid;
Wservice_db nws = new Wservice_db();
nws.setCategory(category);
nws.setOrgname(orgname);
nws.setQosurl(qosurl);
nws.setServid(sid);
nws.setWsdlurl(newurl);
return nws;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To be called through web service to register a particular service with TA. Store advertised QoS also
* and return new WSDL link to be used
*/
public Wservice_db registerWebService2(String orgname, String authkey, String wsdl, String category, Performance_sp pf,String endpoint) throws Myexception
{
int sid = -1111;
String errormsg = "";
if(db.checkvaliduser(orgname,authkey,"SP"))
{
if(orgname!=null && endpoint != null && pf!=null)
{
try
{
Map<String,Double> advq = pf.convert();
sid = db.storeWservice(orgname, wsdl, "not specified", category, endpoint);
db.storeQadv(sid, advq);
/* Create a web service proxy at ~/services/sid and return the new WSDL
*/
String newurl = "http://localhost:8080/TrustModel/services/1/"+sid;
Wservice_db nws = new Wservice_db();
nws.setCategory(category);
nws.setOrgname(orgname);
nws.setQosurl("not specified");
nws.setServid(sid);
nws.setWsdlurl(wsdl);
nws.setEndpoint(newurl);
return nws;
}
catch(Exception e)
{
errormsg = e.getMessage();
e.printStackTrace();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To be called from web service to start monitoring
* interactions between that service and client
*/
/*public void bindToService(int sid, int cid, String authkey, Qoswt wt[]) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
db.storeQweights(cid, sid,wt);
db.initializeDT(cid, sid);
return;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}*/
public Wservice_db bindToService(int sid, int cid, String authkey, Qoswt wt[]) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db ws = db.getWservDetails(sid);
db.storeQweights(cid, sid,wt);
db.initializeDT(cid, sid);
ws.setWsdlurl("http://localhost:8080/TrustManagementService/services/"+cid+"/"+sid);
return ws;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
public Wservice_db bindToService_sp(int sid, int cid, String authkey, Qoswt_sp wt) throws Myexception
{
String errmsg = "";
Qoswt[] wts = wt.convert();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db ws = db.getWservDetails(sid);
db.storeQweights(cid, sid,wts);
db.initializeDT(cid, sid);
ws.setEndpoint("http://localhost:8080/TrustModel/services/"+cid+"/"+sid);
return ws;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get the trust value of a particular service
* uses methods less efficient - multiple database calls
*/
public TrustResult getTrust_LS(int sid, int cid, String authkey) throws Myexception
{
String errmsg = "";
TrustResult tr = new TrustResult();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
double wtsum=0,dtsum=0,trust=0.5;
//perform the trust calculation
//get direct trust
DT dt1 = db.getDirtrust(sid, cid);
DT_sp dts = new DT_sp(dt1);
tr.setDt(dts);
List<Integer> clist = db.getClientwhointeracted(sid);
for(int i=0;i<clist.size();i++)
{
int cid2 = clist.get(i);
if(cid2==cid)
continue;
DT dt = db.getDirtrust(sid, cid2);
double rt = db.getRt(cid, cid2);
double ts = timediff(dt.getTs(),new Date());
System.out.println("cid1" + cid + "cid2" + cid2 + "dt" + dt.getValue() + "ref" + rt);
dtsum += rt * dt.getValue() /ts ;
wtsum += rt/ts;
}
//if someone has interacted before
if(clist.size()!=0)
{
//if direct experience
if(dt1!= null)
{
double exp1 = expe(dt1.freq);
trust = exp1*dt1.getValue() + (1-exp1)*(dtsum/wtsum);
}//if no direct experience
else
trust = dtsum/wtsum;
tr.setIndirect_trust(dtsum/wtsum);
}
tr.setOverall_trust(trust);
return tr;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get the trust value of a particular service
* uses method directly from database
*/
public TrustResult getTrust(int sid, int cid, String authkey) throws Myexception
{
String errmsg = "";
TrustResult tr = new TrustResult();
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//perform the trust calculation
List<Transfertrust> lt= db.gettruststat(cid, sid);
DT dt= db.getDirtrust(sid, cid);
DT_sp dts = new DT_sp(dt);
tr.setDt(dts);
Date curr = new Date();
double dtsum=0,wtsum=0,trust=0.5;
for(int i=0; i<lt.size(); i++)
{
Transfertrust temp = lt.get(i);
System.out.println("cid1"+ temp.getCid1() + "cid2"+temp.getCid2() + "dt" + temp.getDirtrust() + "ref" + temp.getReftrust());
dtsum += temp.getDirtrust() * temp.getReftrust() /(timediff(temp.getTs(),curr));
wtsum += temp.getReftrust() /(timediff(temp.getTs(), curr));
}
//if someone has interacted before
if(wtsum!=0)
{
System.out.println("Considering recommendations");
//if direct experience
if(dt!= null)
{
System.out.println("Considering direct trust");
double exp1 = expe(dt.freq);
trust = exp1*dt.getValue() + (1-exp1)*(dtsum/wtsum);
}//if no direct experience
else
trust = dtsum/wtsum;
tr.setIndirect_trust(dtsum/wtsum);
}
else if(dt!= null)
{
trust = dt.getValue();
}
tr.setOverall_trust(trust);
return tr;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* Called from web service to accept user feedback on a service
*/
public void givefeedback(double val, int sid, int cid,String authkey) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//call to record feedback
DT dt= db.getDirtrust(sid, cid);
if(dt!=null || dt.getFreq()!=0)
{
if(val<0.3)
updateDT(sid, cid, false);
else if(val>.7)
updateDT(sid, cid, true);
}
else
errmsg = "No interactions recorded. Bind to service first";
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* To be called from web service to get performance details of a service based on its interaction with us
*/
public Performance getCurrentPerformance(int cid, String authkey, int sid) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
//call to get performance details
Performance p = db.preparedigest(new Date(), sid, cid);
if(p==null)
errmsg="No performace recorded";
else
return p;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* to be called from web service to get performance details of a service as a whole
*/
public Performance getServicePerformance(int sid) throws Myexception
{
String errmsg = "";
try
{
//call to get performance details
Performance p = db.getPerformance(new Date(), sid);
if(p==null)
errmsg="No performace recorded";
else
return p;
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*
* to be called from web service to return all registered services
*
*/
public Wservice_db[] getregisteredservices(int cid,String authkey,String category) throws Myexception
{
String errmsg = "";
try
{
if(db.checkvaliduser(String.valueOf(cid), authkey, "SC"))
{
Wservice_db[] wsarray;
wsarray = db.findServices(category);
if(wsarray==null)
errmsg="No services registered";
else
return wsarray;
}
else
{
errmsg = "Authentication failed";
}
}
catch(Exception e)
{
errmsg = e.getMessage();
}
throw new Myexception(errmsg);
}
/*************************************************************************************************************/
/*
* function to accept current rating of a service
*/
public void provideRating(int cid, int sid, Map<String,Double> monq) throws Exception
{
Map<String,Double> advq = db.getQadv(sid);
Map<String,Integer> wtq = db.getQweights(cid, sid);
if(wtq.size()==0 && cid==1)
wtq = getdefaultwt();
if(advq!=null && wtq!= null)
updateDT(sid, cid, CheckSatisfied(advq,wtq,monq));
try
{
db.dtrecord(cid, sid, db.getDirtrust(sid, cid).getValue());
}
catch(Exception e)
{
}
}
private Map<String,Integer> getdefaultwt()
{
Map<String,Integer> wtq = new HashMap<String, Integer>();
wtq.put("Availability",1);
wtq.put("Errorrate",1);
wtq.put("Exceptionrate",1);
wtq.put("MinResponsetime",1);
wtq.put("MaxResponsetime",1);
wtq.put("AvgResponsetime",1);
return wtq;
}
/*
* To update direct trust
* then reftrusts
*/
private void updateDT(int sid, int cid, boolean satisfied) throws Exception
{
DT dt = db.getDirtrust(sid, cid);
double tdiff = timediff(dt.getTs(),new Date());
System.out.println("old = "+dt.getValue() +"diff" + tdiff);
if(satisfied)
db.updateDT(cid, sid, 1 + 0.1*tdiff);
else
db.updateDT(cid, sid, 1 - 0.2*tdiff);
//update reftrust of all clients who have interacted before with this service
dt = db.getDirtrust(sid, cid);
System.out.println("new = "+dt.getValue());
List<Integer> lc = db.getClientwhointeracted(sid);
for(int i=0; i< lc.size();i++)
{
int cid2 = lc.get(i);
if(cid2==cid)
continue;
DT dt2 = db.getDirtrust(sid, cid2);
double diff = (dt2.getValue() - dt.getValue())/timediff(dt2.getTs(),dt.getTs());
if(diff < 0.2)
db.updateRT(cid, cid2, 1.1);
else if(diff > 0.5)
db.updateRT(cid, cid2, 0.8);
}
}
/*
* check whether an interaction is satisfactory
*/
private boolean CheckSatisfied(Map<String, Double> advqmap,
Map<String, Integer> wtmap, Map<String, Double> monq) throws Exception {
System.out.println("Check satisfied");
//calculate deviation
double deviation = 0,sum1=0,sum2=0;
for( String key:monq.keySet())
{
if(wtmap.containsKey(key) && advqmap.containsKey(key))
{
System.out.println(key);
//normalized difference
double diff = advqmap.get(key) - monq.get(key);
if((key=="AvgResponsetime")||(key=="MaxResponsetime")||(key=="MinResponsetime"))
{
diff = -diff/advqmap.get(key);
if(diff<-1)
diff = -1;
else if(diff > 1)
diff = 1;
}
if((key=="Exceptionrate")||(key=="Errorrate"))
{
diff = (1-monq.get(key)) -(1-advqmap.get(key));
}
sum1+= wtmap.get(key) * diff;
sum2+= wtmap.get(key);
}
}
if(sum2==0)
throw new Exception("Bad weights");
deviation = sum1/sum2;
if(deviation > 0.001)
{ System.out.println("not satisfied");
return false;
}
else
return true;
}
/*
* To parse a Qos spec and return a map
*/
private Map<String, Double> parseQos(String qosurl) throws ParserConfigurationException, SAXException, IOException
{
Map<String, Double> advq = new HashMap<String, Double>();
WSLAParser wsl = new WSLAParser(qosurl);
wsl.parse();
/*Hard coded - need to parse qos spec*/
advq.put("availability", .99);
advq.put("AvgResponsetime", 0.78);
advq.put("Errorrate", 0.99);
return advq;
}
/*
* To be called through web service to find the registered services in a category
*/
public Wservice_db[] findWebService(String email, String authkey, String category ) throws Myexception
{
String errormsg = "";
Wservice_db[] wsarr;
if(db.checkvaliduser(email,authkey,"SC"))
{
if(category!= null)
{
try
{
wsarr = db.findServices(category);
return wsarr;
}
catch(Exception e)
{
errormsg = e.getMessage();
}
}
else
{
errormsg = "All fields are required";
}
}
else
{
errormsg = "Authentication failed";
}
throw new Myexception(errormsg);
}
/*
* To get value corresponding to time difference
*/
private double timediff(Date prev, Date curr)
{
return 1 + (curr.getTime() - prev.getTime())/(curr.getTime() - startup.getTime());
}
/*
* To get value corresponding to frequency
*/
private double expe(int freq)
{
return 1-(Math.exp(-freq));
}
/*
* To normalize performance values
*/
/*
public static void main(String[] args) throws Exception
{
TAmodule ta1 = new TAmodule();
//ta1.registerServiceprovider("RMVServices", "123456");
//ta1.registerWebService("RMVServices", "123456",
//"http://www.ebi.ac.uk/soaplab/typed/services/nucleic_composition.banana?WSDL",
//"http://www.ebi.ac.uk/soaplab/typed/services/nucleic_composition.banana?QOS", "genedatabase");
//ta1.registerServiceClient("m110405cs", "<EMAIL>", "121212");
/*Qoswt[] wt = new Qoswt[2];
wt[0] = new Qoswt("Availability",5);
wt[1] = new Qoswt("responsetime",3);
ta1.bindToService(6,6,"131313",wt);*/
/*Map<String, Double> monq = new HashMap<String, Double>();
monq.put("Availability", 0.75);
ta1.provideRating(6, 6, monq);
System.out.println(ta1.getTrust(6, 8, "121212"));
}
*/
}
| 16,885 | 0.618439 | 0.607077 | 747 | 21.62249 | 24.769285 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.149933 | false | false |
4
|
11c4663041773c3b74f509b9a56f0c16055d5d1b
| 10,857,677,385,788 |
68e1cd5051d6234cd5289655cb942b155a2d7f14
|
/app/src/main/java/com/yikangcheng/admin/yikang/activity/adapter/LiveShopRecyclerAdapter.java
|
627bd6f03f4e7771e72daa73d9b844cb6bbbfc5f
|
[] |
no_license
|
hi-noikiy/YiKang
|
https://github.com/hi-noikiy/YiKang
|
8855d63d831f24b4dd08efbd3499063ece99ef2e
|
661289f027c1b18bacece18d16af03a13da2fef9
|
refs/heads/master
| 2022-03-26T23:25:29.630000 | 2019-11-27T10:27:26 | 2019-11-27T10:27:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yikangcheng.admin.yikang.activity.adapter;
import android.support.annotation.NonNull;
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.LinearLayout;
import android.widget.TextView;
import com.yikangcheng.admin.yikang.R;
/**
* 作者:古祥坤 on 2019/7/14 15:19
* 邮箱:1724959985@qq.com
*/
public class LiveShopRecyclerAdapter extends RecyclerView.Adapter<LiveShopRecyclerAdapter.Vh> {
@NonNull
@Override
public Vh onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_shop_recycler_item, parent, false);
return new Vh(view);
}
@Override
public void onBindViewHolder(@NonNull Vh vh, final int position) {
if (position == getItemCount() - 1) {
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setMargins(0, 0, 0, 150);
vh.itemView.setLayoutParams(layout);
vh.fenge_xian.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return 5;
}
class Vh extends RecyclerView.ViewHolder {
View fenge_xian;
public Vh(View itemView) {
super(itemView);
fenge_xian = itemView.findViewById(R.id.fenge_xian);
}
}
}
|
UTF-8
|
Java
| 1,579 |
java
|
LiveShopRecyclerAdapter.java
|
Java
|
[
{
"context": "import com.yikangcheng.admin.yikang.R;\n\n/**\n * 作者:古祥坤 on 2019/7/14 15:19\n * 邮箱:1724959985@qq.com\n */\npu",
"end": 394,
"score": 0.9930893778800964,
"start": 391,
"tag": "NAME",
"value": "古祥坤"
},
{
"context": "yikang.R;\n\n/**\n * 作者:古祥坤 on 2019/7/14 15:19\n * 邮箱:1724959985@qq.com\n */\npublic class LiveShopRecyclerAdapter extends ",
"end": 437,
"score": 0.999876856803894,
"start": 420,
"tag": "EMAIL",
"value": "1724959985@qq.com"
}
] | null |
[] |
package com.yikangcheng.admin.yikang.activity.adapter;
import android.support.annotation.NonNull;
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.LinearLayout;
import android.widget.TextView;
import com.yikangcheng.admin.yikang.R;
/**
* 作者:古祥坤 on 2019/7/14 15:19
* 邮箱:<EMAIL>
*/
public class LiveShopRecyclerAdapter extends RecyclerView.Adapter<LiveShopRecyclerAdapter.Vh> {
@NonNull
@Override
public Vh onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_shop_recycler_item, parent, false);
return new Vh(view);
}
@Override
public void onBindViewHolder(@NonNull Vh vh, final int position) {
if (position == getItemCount() - 1) {
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setMargins(0, 0, 0, 150);
vh.itemView.setLayoutParams(layout);
vh.fenge_xian.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return 5;
}
class Vh extends RecyclerView.ViewHolder {
View fenge_xian;
public Vh(View itemView) {
super(itemView);
fenge_xian = itemView.findViewById(R.id.fenge_xian);
}
}
}
| 1,569 | 0.686099 | 0.66688 | 51 | 29.607843 | 28.273232 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54902 | false | false |
4
|
01ff7f20a6afc579ad6cf2c8467a3c7e5c5d5bcc
| 20,538,533,655,791 |
dac1794dfbdb182af8c3a33fe34cafd29905c291
|
/kam.demo/src/main/java/com/kam/config/Config.java
|
b3f5b397cc43e87063dcb46cf8784eff9f5381c3
|
[
"Apache-2.0"
] |
permissive
|
Tim1999/spring-framework-5.0.x
|
https://github.com/Tim1999/spring-framework-5.0.x
|
7d4628c786c0a7284959030de1b4a757727b36d5
|
8355750beb9bdbca1fabd3d4dd71c3d1ebbb57f1
|
refs/heads/master
| 2020-06-14T00:19:33.256000 | 2019-04-24T07:53:08 | 2019-04-24T07:53:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kam.config;
import com.kam.EnableKam;
import com.kam.MyFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@EnableKam
@ComponentScan("com.kam")
public class Config {
}
|
UTF-8
|
Java
| 382 |
java
|
Config.java
|
Java
|
[] | null |
[] |
package com.kam.config;
import com.kam.EnableKam;
import com.kam.MyFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@EnableKam
@ComponentScan("com.kam")
public class Config {
}
| 382 | 0.835079 | 0.835079 | 14 | 26.285715 | 20.837564 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
4
|
0c97c948500c1afa0d302fe2700f53ccb56d8382
| 6,614,249,660,797 |
4f70eb96a211710c7b7c3eab72722f40e11040d7
|
/Trap_Water.java
|
5955e9d1ea3edf50ab3d5ddcd069395ad1edb73c
|
[] |
no_license
|
vibinmarish/Data_Structures_Algorithms
|
https://github.com/vibinmarish/Data_Structures_Algorithms
|
156fc2235d329879ca22710da0c71285ede97bd5
|
957a57f6cd3b765502801579ebb96416799da7b2
|
refs/heads/master
| 2023-01-08T12:30:24.536000 | 2020-11-05T22:17:36 | 2020-11-05T22:17:36 | 208,479,904 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Trap{
static int trappingWater(int a[], int n) {
int left[]=new int[n];
int right[]=new int[n];
left[0]=a[0];
right[n-1]=a[n-1];
for(int i=1;i<n;i++)
{
left[i]=Math.max(left[i-1],a[i]); //We store the maximum value from left to right
}
for(int i=n-2;i>=0;i--)
{
right[i]=Math.max(right[i+1],a[i]); //We store the maximum value from right to left
}
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+(Math.min(right[i],left[i])-a[i]); //We subtract the current element value with the min value of both left and right array
}
return sum;
}
}
|
UTF-8
|
Java
| 807 |
java
|
Trap_Water.java
|
Java
|
[] | null |
[] |
class Trap{
static int trappingWater(int a[], int n) {
int left[]=new int[n];
int right[]=new int[n];
left[0]=a[0];
right[n-1]=a[n-1];
for(int i=1;i<n;i++)
{
left[i]=Math.max(left[i-1],a[i]); //We store the maximum value from left to right
}
for(int i=n-2;i>=0;i--)
{
right[i]=Math.max(right[i+1],a[i]); //We store the maximum value from right to left
}
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+(Math.min(right[i],left[i])-a[i]); //We subtract the current element value with the min value of both left and right array
}
return sum;
}
}
| 807 | 0.429988 | 0.416357 | 29 | 25.827587 | 31.317142 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758621 | false | false |
4
|
b093f8e1ab7a9fa16bf0c14da135cf9cafeb3789
| 27,977,416,984,096 |
7b8d2313c00441011a76cc92e287b2e123870e00
|
/app/src/main/java/com/pylon/emarketpos/controllers/AmbulantPrintForm.java
|
930747c7e917b961d5b57309ad92c550db63162e
|
[] |
no_license
|
hambog00111/android-posv2
|
https://github.com/hambog00111/android-posv2
|
28d986a8279d6f841d2c9330e7b6fe8f1b649c57
|
63b88d2e62f730fc1c1e3a90c9d7b8ee068b8112
|
refs/heads/master
| 2020-06-28T04:05:15.625000 | 2019-01-10T08:15:18 | 2019-01-10T08:15:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pylon.emarketpos.controllers;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.pylon.emarketpos.R;
import com.pylon.emarketpos.tasks.*;
public class AmbulantPrintForm extends Fragment implements OnClickListener{
private EditText OwnerName, Business, Amount;
private Button ambPrint;
private String[] SendInfo;
private String CustID;
private InputMethodManager imm;
public static String SEARCH_DATA;
public AmbulantPrintForm() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ambulant_print_form, container, false);
Bundle x = getArguments();
OwnerName = (EditText) view.findViewById(R.id.Print_AmbName);
Business = (EditText) view.findViewById(R.id.Print_Business);
Amount = (EditText) view.findViewById(R.id.Print_Amount);
ambPrint = (Button) view.findViewById(R.id.btnPrintAmb);
imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
OwnerName.setText(x.getString("AmbOwner"));
Business.setText(x.getString("AmbBusiness"));
CustID = x.getString("CustomerID");
SEARCH_DATA = x.getString("DATA_SEARCH");
Amount.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
ambPrint.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view) {
final String pOwnerName = OwnerName.getText().toString();
final String pBusiness = Business.getText().toString();
final String pAmount = Amount.getText().toString();
SendInfo = new String[10];
SendInfo[0] = "ambulant";
SendInfo[1] = SEARCH_DATA;
SendInfo[2] = pOwnerName;
SendInfo[3] = pBusiness;
SendInfo[4] = pAmount;
SendInfo[5] = new DatabaseHelper(getContext()).getDeviceUser();
SendInfo[6] = CustID;
if(pAmount.isEmpty()){
Toast.makeText(getContext(), "Amount cannot be empty", Toast.LENGTH_SHORT).show();
} else {
new SavePayment(getContext(), this).execute(SendInfo);
}
}
}
|
UTF-8
|
Java
| 2,639 |
java
|
AmbulantPrintForm.java
|
Java
|
[] | null |
[] |
package com.pylon.emarketpos.controllers;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.pylon.emarketpos.R;
import com.pylon.emarketpos.tasks.*;
public class AmbulantPrintForm extends Fragment implements OnClickListener{
private EditText OwnerName, Business, Amount;
private Button ambPrint;
private String[] SendInfo;
private String CustID;
private InputMethodManager imm;
public static String SEARCH_DATA;
public AmbulantPrintForm() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ambulant_print_form, container, false);
Bundle x = getArguments();
OwnerName = (EditText) view.findViewById(R.id.Print_AmbName);
Business = (EditText) view.findViewById(R.id.Print_Business);
Amount = (EditText) view.findViewById(R.id.Print_Amount);
ambPrint = (Button) view.findViewById(R.id.btnPrintAmb);
imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
OwnerName.setText(x.getString("AmbOwner"));
Business.setText(x.getString("AmbBusiness"));
CustID = x.getString("CustomerID");
SEARCH_DATA = x.getString("DATA_SEARCH");
Amount.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
ambPrint.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view) {
final String pOwnerName = OwnerName.getText().toString();
final String pBusiness = Business.getText().toString();
final String pAmount = Amount.getText().toString();
SendInfo = new String[10];
SendInfo[0] = "ambulant";
SendInfo[1] = SEARCH_DATA;
SendInfo[2] = pOwnerName;
SendInfo[3] = pBusiness;
SendInfo[4] = pAmount;
SendInfo[5] = new DatabaseHelper(getContext()).getDeviceUser();
SendInfo[6] = CustID;
if(pAmount.isEmpty()){
Toast.makeText(getContext(), "Amount cannot be empty", Toast.LENGTH_SHORT).show();
} else {
new SavePayment(getContext(), this).execute(SendInfo);
}
}
}
| 2,639 | 0.687003 | 0.683213 | 70 | 36.700001 | 25.279778 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.828571 | false | false |
4
|
2a02fb000f18279cf5ee2ed96fe90aa637d551c2
| 18,090,402,294,873 |
f0b6f3c7d3a4bc39468e25f75fe2b1ce09ad934a
|
/springFramework/src/main/java/com/luopo/easySpring/springMVC/util/DispatcherServlet.java
|
b788adf512e932d2216a0c5d0dc6ff2f75cfdebe
|
[] |
no_license
|
luopoQAQ/VeryVeryVeryEasySpring
|
https://github.com/luopoQAQ/VeryVeryVeryEasySpring
|
fd6a51d64172dd3074ce3f92e821b05a16d2e377
|
f2d7269e36459a97348a9a2a5b4616980e6e6bfe
|
refs/heads/master
| 2020-07-16T14:55:59.071000 | 2019-09-03T02:42:58 | 2019-09-03T02:42:58 | 205,810,202 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.luopo.easySpring.springMVC.util;
import javax.servlet.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class DispatcherServlet implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//重写该servlet,并扔给tomcat
//该servlet主要是将得到的请求扔给映射处理器,映射处理器全都被封装好存在银蛇处理器的管理器中
//直接遍历该映射管理器,如果有匹配的映射处理器,就处理,并将结果写入响应
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
for (MappingHandler mappingHandler : HandlerManager.mappingHandlerList) {
try {
//有可以处理的映射处理器,则处理,将结果写入响应,并返回
if (mappingHandler.handle(req, res)) {
return;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//否则响应体写入错误信息
res.getWriter().println("404 Not Found!");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
|
UTF-8
|
Java
| 1,524 |
java
|
DispatcherServlet.java
|
Java
|
[] | null |
[] |
package com.luopo.easySpring.springMVC.util;
import javax.servlet.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class DispatcherServlet implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//重写该servlet,并扔给tomcat
//该servlet主要是将得到的请求扔给映射处理器,映射处理器全都被封装好存在银蛇处理器的管理器中
//直接遍历该映射管理器,如果有匹配的映射处理器,就处理,并将结果写入响应
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
for (MappingHandler mappingHandler : HandlerManager.mappingHandlerList) {
try {
//有可以处理的映射处理器,则处理,将结果写入响应,并返回
if (mappingHandler.handle(req, res)) {
return;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//否则响应体写入错误信息
res.getWriter().println("404 Not Found!");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
| 1,524 | 0.625585 | 0.623245 | 50 | 24.639999 | 23.606575 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26 | false | false |
4
|
831e86da1b7231c730e671fc81f4de524b1f2397
| 18,090,402,296,534 |
5c416240206ef02a18c416d314cbebcdbd71f721
|
/LitoralEsential/app/src/main/java/com/litoralesential/ObjectiveDetails.java
|
b87dbbf9ef871caeb727641cd4001d0b078060db
|
[] |
no_license
|
aseitan/litoral-esential
|
https://github.com/aseitan/litoral-esential
|
ffc27abed19f72815dc74953cf9a0dea39f6794a
|
c311895d5c780706faa71cc59ee9d9322948b9b4
|
refs/heads/master
| 2020-12-01T22:40:52.303000 | 2014-08-19T21:30:00 | 2014-08-19T21:30:00 | 66,064,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.litoralesential;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
public class ObjectiveDetails extends Fragment
{
static Objective chosenObjective;
private MapView mMapView;
private GoogleMap mMap;
public static ObjectiveDetails newInstance(Objective obj)
{
ObjectiveDetails objective = new ObjectiveDetails();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putParcelable("objective", obj);
objective.setArguments(args);
chosenObjective = obj;
return objective;
}
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle mBundle = getArguments();
chosenObjective = mBundle.getParcelable("objective");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = null;
try
{
rootView = inflater.inflate(R.layout.fragment_obiectiv_map_complete, container, false);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
MapsInitializer.initialize(getActivity());
}
catch (Exception e)
{
e.printStackTrace();
}
if(rootView != null)
{
mMapView = (MapView) rootView.findViewById(R.id.map);
if(mMapView != null)
{
mMapView.onCreate(savedInstanceState);
mMapView.setClickable(false);
mMapView.getMap().getUiSettings().setAllGesturesEnabled(false);
String mapObjectiveName = "";
LatLng objPosition = new LatLng(0, 0);
if(chosenObjective != null)
{
mapObjectiveName = chosenObjective.name;
String position = chosenObjective.GPSposition;
if(position.length() > 4) position = position.substring(1, position.length() - 4);
String[] pos = position.split(",");
if(pos.length == 2)
{
double lati = Double.parseDouble(pos[0]);
double lngi = Double.parseDouble(pos[1]);
objPosition = new LatLng(lati, lngi);
}
}
mMapView.getMap().addMarker(new MarkerOptions().position(objPosition).title(mapObjectiveName));
mMapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(objPosition, 15));
mMapView.getMap().animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
ImageView objectiveImage = (ImageView) rootView.findViewById(R.id.imageObjective);
if(objectiveImage != null)
{
String objID = Integer.toString(chosenObjective.id);
Bitmap bm = null;
try
{
bm = BitmapFactory.decodeFile(Utils.externalPathRoot + File.separator + Utils.OBJECTIVE_IMAGE_PREFIX + objID);
}
catch(Exception e){}
if(bm != null)
{
objectiveImage.setImageBitmap(bm);
}
}
TextView objectiveName = (TextView) rootView.findViewById(R.id.objectiveName);
if(objectiveName != null)
{
if(chosenObjective!= null && chosenObjective.name.length() > 0)
objectiveName.setText(chosenObjective.name);
else
objectiveName.setText("-");
}
TextView objectiveDescription = (TextView) rootView.findViewById(R.id.objectiveDescription);
if(objectiveDescription != null)
{
if(chosenObjective != null && chosenObjective.description.length() > 0)
objectiveDescription.setText(chosenObjective.description);
else
objectiveDescription.setText("");
}
TextView objectivePhone = (TextView) rootView.findViewById(R.id.objectivePhone);
if(objectivePhone != null)
{
if(chosenObjective != null && chosenObjective.telephone.length() > 0)
objectivePhone.setText(chosenObjective.telephone);
else
objectivePhone.setText("-");
}
TextView objectiveWebsite = (TextView) rootView.findViewById(R.id.objectiveWebsite);
if(objectiveWebsite != null)
{
if(chosenObjective != null && chosenObjective.website.length() > 0)
{
objectiveWebsite.setText(chosenObjective.website);
objectiveWebsite.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String url = chosenObjective.website;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
else
objectiveWebsite.setText("-");
}
}
return rootView;
}
@Override
public void onResume()
{
super.onResume();
mMapView.onResume();
}
@Override
public void onPause()
{
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy()
{
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
|
UTF-8
|
Java
| 6,725 |
java
|
ObjectiveDetails.java
|
Java
|
[] | null |
[] |
package com.litoralesential;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
public class ObjectiveDetails extends Fragment
{
static Objective chosenObjective;
private MapView mMapView;
private GoogleMap mMap;
public static ObjectiveDetails newInstance(Objective obj)
{
ObjectiveDetails objective = new ObjectiveDetails();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putParcelable("objective", obj);
objective.setArguments(args);
chosenObjective = obj;
return objective;
}
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle mBundle = getArguments();
chosenObjective = mBundle.getParcelable("objective");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = null;
try
{
rootView = inflater.inflate(R.layout.fragment_obiectiv_map_complete, container, false);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
MapsInitializer.initialize(getActivity());
}
catch (Exception e)
{
e.printStackTrace();
}
if(rootView != null)
{
mMapView = (MapView) rootView.findViewById(R.id.map);
if(mMapView != null)
{
mMapView.onCreate(savedInstanceState);
mMapView.setClickable(false);
mMapView.getMap().getUiSettings().setAllGesturesEnabled(false);
String mapObjectiveName = "";
LatLng objPosition = new LatLng(0, 0);
if(chosenObjective != null)
{
mapObjectiveName = chosenObjective.name;
String position = chosenObjective.GPSposition;
if(position.length() > 4) position = position.substring(1, position.length() - 4);
String[] pos = position.split(",");
if(pos.length == 2)
{
double lati = Double.parseDouble(pos[0]);
double lngi = Double.parseDouble(pos[1]);
objPosition = new LatLng(lati, lngi);
}
}
mMapView.getMap().addMarker(new MarkerOptions().position(objPosition).title(mapObjectiveName));
mMapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(objPosition, 15));
mMapView.getMap().animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
ImageView objectiveImage = (ImageView) rootView.findViewById(R.id.imageObjective);
if(objectiveImage != null)
{
String objID = Integer.toString(chosenObjective.id);
Bitmap bm = null;
try
{
bm = BitmapFactory.decodeFile(Utils.externalPathRoot + File.separator + Utils.OBJECTIVE_IMAGE_PREFIX + objID);
}
catch(Exception e){}
if(bm != null)
{
objectiveImage.setImageBitmap(bm);
}
}
TextView objectiveName = (TextView) rootView.findViewById(R.id.objectiveName);
if(objectiveName != null)
{
if(chosenObjective!= null && chosenObjective.name.length() > 0)
objectiveName.setText(chosenObjective.name);
else
objectiveName.setText("-");
}
TextView objectiveDescription = (TextView) rootView.findViewById(R.id.objectiveDescription);
if(objectiveDescription != null)
{
if(chosenObjective != null && chosenObjective.description.length() > 0)
objectiveDescription.setText(chosenObjective.description);
else
objectiveDescription.setText("");
}
TextView objectivePhone = (TextView) rootView.findViewById(R.id.objectivePhone);
if(objectivePhone != null)
{
if(chosenObjective != null && chosenObjective.telephone.length() > 0)
objectivePhone.setText(chosenObjective.telephone);
else
objectivePhone.setText("-");
}
TextView objectiveWebsite = (TextView) rootView.findViewById(R.id.objectiveWebsite);
if(objectiveWebsite != null)
{
if(chosenObjective != null && chosenObjective.website.length() > 0)
{
objectiveWebsite.setText(chosenObjective.website);
objectiveWebsite.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String url = chosenObjective.website;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
else
objectiveWebsite.setText("-");
}
}
return rootView;
}
@Override
public void onResume()
{
super.onResume();
mMapView.onResume();
}
@Override
public void onPause()
{
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy()
{
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
| 6,725 | 0.550929 | 0.547955 | 207 | 30.47826 | 27.910801 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642512 | false | false |
4
|
2169026532ac09bd9ae6e2b604a0542d663a129d
| 2,173,253,461,936 |
20f819f532f78bc986f4e26d5e90c357a58db8cd
|
/src/main/java/Web/task4/HttpServer.java
|
758f26b554d03a0100d54865d3c1721030496152
|
[] |
no_license
|
zhaoqiqi779955/WorkPlace
|
https://github.com/zhaoqiqi779955/WorkPlace
|
8dec3da33b0c6dca947752063ece41bcf6ef7ebf
|
83f692b070f36686d113206dca047e24728c25ef
|
refs/heads/master
| 2023-03-07T13:54:13.065000 | 2021-02-21T13:27:16 | 2021-02-21T13:27:16 | 255,625,432 | 0 | 0 | null | false | 2021-02-21T13:31:24 | 2020-04-14T14:02:57 | 2021-02-21T13:31:07 | 2021-02-21T13:31:23 | 3 | 0 | 0 | 1 |
Java
| false | false |
package Web.task4;
import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.lang.Thread.sleep;
public class HttpServer extends JFrame implements Runnable {
ServerSocket serverSocket = null;
FileManager fileManager = null;//管理文件
public HttpServer() {
try {
serverSocket = new ServerSocket(8888);
fileManager = new FileManager("Practice/resource");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
HttpServer server = new HttpServer();
Thread thread = new Thread(server);
thread.start();
System.out.println("服务器已启动");
}
public void run() {
//创建线程池
ExecutorService pool = Executors.newFixedThreadPool(100);//创建一个线程池
while (true) {
try {
Socket socketAtServer = serverSocket.accept();
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
String now = formatter.format(date);
//为每一个客户端创建一个handler来处理
Handler handler = new Handler(socketAtServer, fileManager);//提交入线程池
pool.submit(handler);
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
class Handler implements Runnable {//用于处理每一个客户端请求
ArrayList<String> responseContent = new ArrayList<>(); //响应信息
Socket socket = null;
FileManager fileManager = null;
HashMap<String, String> requestMap = new HashMap();
String protocol;//传输协议
String requestType;//请求类型
String filePath;//请求资源路径
OutputStream out = null;
InputStream in = null;
public Handler(Socket soc, FileManager manager) {
socket = soc;
fileManager = manager;
System.out.println("已连接主机: " + socket.getInetAddress().getCanonicalHostName()+ "端口: " + socket.getPort());
}
void analyseRequest(InputStream in) throws IOException {//分析请求信息
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
System.out.println("请求信息:");
boolean isFirst = true;
String str = null;
while ((str = reader.readLine()) != null) {
if (str.equals("")) break;
System.out.println(str);
if (isFirst) {
analyseFirstLine(str);
isFirst = false;
} else addRequestToMap(str);
}
System.out.println("接受请求完毕");
}
//设置Content-Length
void setContentLength(long length) {
responseContent.add("Content-Length: " + length);
}
void setCode(String code, String message) {
responseContent.add(protocol + " " + code + " " + message);
}
void setContentType(String type, String charset) {
responseContent.add("Content-Type: " + type + "; charset=" + charset);
}
void setContentType(String type)//默认utf-8
{
setContentType(type, "utf-8");
}
void setLastModified(String date) {
responseContent.add("Last-Modified: " + date);
}
void addCookie(Cookie cookie)
{
StringBuffer con=new StringBuffer("Set-Cookie: ");
con.append(cookie.getName()+"="+cookie.getValue());
if(cookie.getMaxAge()!=null)
{
con.append("; Max-Age="+cookie.getMaxAge());
}
if(cookie.getPath()!=null)
{
con.append("; path="+cookie.getPath());
}
if(cookie.getDomain()!=null)
{
con.append("; domain="+cookie.getDomain());
}
//con.append("; httponly\r\n");//防止第三方攻击
responseContent.add(con.toString());
}
void addRequestToMap(String str)//将请求信息存入map中
{
String s[] = str.split("\\:");
requestMap.put(s[0].trim(), s[1].trim());
}
void analyseFirstLine(String str)//分析第一行,获取请求类型,和资源
{
String[] s = str.split("\\s");
requestType = s[0];
//System.out.println("类型:" + s[0]);
filePath = s[1];
if(filePath.equals("/")) filePath="/p3.html";
// System.out.println("路径为:" + filePath);
protocol = s[2];
}
//处理GET
long getRange()
{
if( requestMap.containsKey("Range"))
{
String len=requestMap.get("Range");
int start=len.indexOf('=');
int end=len.indexOf('-');
String length=len.substring(start,end);
System.out.println(length);
return Long.parseLong(length);
}
else return 0;
}
void handleGET(OutputStream out) {
long size = fileManager.getFileSize(filePath);
if (size >= 0) { //表示文件存在
setCode("202", "OK");
int loc = filePath.lastIndexOf('.');
//设置文件类型
String contentType = analyseFileType(filePath);
setContentType(contentType);
setContentLength(size);
// 创建cookie
Cookie cookie=new Cookie("username","zhangsan");
//设置cookie最大有效时间
cookie.setMaxAge(3*24*60*60);
addCookie(cookie);
setLastModified(fileManager.getLastModified(filePath));
} else setCode("404", "not found");
respondToClient(out, responseContent);
if (size > 0) {
long start=getRange();
System.out.println("开始位置:"+start);
fileManager.transferResource(filePath, out,start);
}
try {
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
String analyseFileType(String filename)//分析文件类型
{
String fileType;
String regText=".*\\.(txt|html)$";//常见文本
String regImage=".*\\.(jpeg|GPEG|jpg|JPG|png|PNG)$";//常见图像
String regAudio=".*\\.(mp3|MP3|MPEG|mpeg|wma|WMA)$";//常见音频
int loc=filename.lastIndexOf('.');
if(loc==-1) return "application/octet-stream";
if(filename.matches(regText)) {
String suffix=filename.substring(loc+1);
fileType="text/"+suffix;
}
else if(filename.matches(regImage))
{
String suffix=filename.substring(loc+1);
fileType="image/"+suffix;
}
else if(filename.matches(regAudio))
{
String suffix=filename.substring(loc+1);
fileType="audio/"+suffix;
}
else { String suffix=filename.substring(loc+1);
fileType="application/"+suffix;
}
return fileType;
}
//处理PUT
void handlePUT(InputStream in) {
responseContent.clear();
setCode("200", "OK");
respondToClient(out, responseContent);
fileManager.saveResource(filePath, in, false);
}
void handleHEAD(OutputStream out) {
long size = fileManager.getFileSize(filePath);
if (size >= 0) { //表示文件存在
setCode("202", "OK");
int loc = filePath.lastIndexOf('.');
String contentType =analyseFileType(filePath);
setContentType(contentType);
setContentLength(size);
setLastModified(fileManager.getLastModified(filePath));
} else setCode("404", "not found");
respondToClient(out, responseContent);
}
void handlePOST(OutputStream out,InputStream in)
{
setCode("202", "OK");
setContentType("html/text");
respondToClient(out,responseContent);
String news="已经收到你的表单";
try {
out.write(news.getBytes("utf-8"));
out.flush();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
void respondToClient(OutputStream out, ArrayList<String> content) {//响应头信息
System.out.println("返回信息:");
for (int i = 0; i < content.size(); i++) {
System.out.println(content.get(i));
}
int i = 0;
while (i < content.size()) {
try {
out.write(content.get(i).getBytes());
out.write("\r\n".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
break;
}
i++;
}
try {
out.write("\r\n".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
analyseRequest(in);
if (requestType.equalsIgnoreCase("GET")) handleGET(out);
else if (requestType.equalsIgnoreCase("PUT")) {
System.out.println("上传");
handlePUT(in);
} else if (requestType.equalsIgnoreCase("HEAD")) handleHEAD(out);
else if(requestType.equalsIgnoreCase("POST"))
handlePOST(out,in);
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Cookie {
String name=null;
String value=null;
String path=null;//作用路径
String domain=null;//作用域
String MaxAge=null;//最大有效时间
public Cookie(String k, String v) {
name = k;
value = v;
}
void setMaxAge(int time)
{
MaxAge=""+time;
}
void setPath(String path1) {
path = path1;
}
void setDomain(String dm) {
domain = dm;
}
String getName()
{
return name;
}
String getValue()
{
return value;
}
String getMaxAge() {
return MaxAge;
}
String getDomain()
{
return domain;
}
String getPath()
{
return path;
}
}
|
UTF-8
|
Java
| 10,854 |
java
|
HttpServer.java
|
Java
|
[
{
"context": "\n Cookie cookie=new Cookie(\"username\",\"zhangsan\");\n //设置cookie最大有效时间\n cooki",
"end": 5360,
"score": 0.9996774196624756,
"start": 5352,
"tag": "USERNAME",
"value": "zhangsan"
}
] | null |
[] |
package Web.task4;
import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.lang.Thread.sleep;
public class HttpServer extends JFrame implements Runnable {
ServerSocket serverSocket = null;
FileManager fileManager = null;//管理文件
public HttpServer() {
try {
serverSocket = new ServerSocket(8888);
fileManager = new FileManager("Practice/resource");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
HttpServer server = new HttpServer();
Thread thread = new Thread(server);
thread.start();
System.out.println("服务器已启动");
}
public void run() {
//创建线程池
ExecutorService pool = Executors.newFixedThreadPool(100);//创建一个线程池
while (true) {
try {
Socket socketAtServer = serverSocket.accept();
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
String now = formatter.format(date);
//为每一个客户端创建一个handler来处理
Handler handler = new Handler(socketAtServer, fileManager);//提交入线程池
pool.submit(handler);
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
class Handler implements Runnable {//用于处理每一个客户端请求
ArrayList<String> responseContent = new ArrayList<>(); //响应信息
Socket socket = null;
FileManager fileManager = null;
HashMap<String, String> requestMap = new HashMap();
String protocol;//传输协议
String requestType;//请求类型
String filePath;//请求资源路径
OutputStream out = null;
InputStream in = null;
public Handler(Socket soc, FileManager manager) {
socket = soc;
fileManager = manager;
System.out.println("已连接主机: " + socket.getInetAddress().getCanonicalHostName()+ "端口: " + socket.getPort());
}
void analyseRequest(InputStream in) throws IOException {//分析请求信息
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
System.out.println("请求信息:");
boolean isFirst = true;
String str = null;
while ((str = reader.readLine()) != null) {
if (str.equals("")) break;
System.out.println(str);
if (isFirst) {
analyseFirstLine(str);
isFirst = false;
} else addRequestToMap(str);
}
System.out.println("接受请求完毕");
}
//设置Content-Length
void setContentLength(long length) {
responseContent.add("Content-Length: " + length);
}
void setCode(String code, String message) {
responseContent.add(protocol + " " + code + " " + message);
}
void setContentType(String type, String charset) {
responseContent.add("Content-Type: " + type + "; charset=" + charset);
}
void setContentType(String type)//默认utf-8
{
setContentType(type, "utf-8");
}
void setLastModified(String date) {
responseContent.add("Last-Modified: " + date);
}
void addCookie(Cookie cookie)
{
StringBuffer con=new StringBuffer("Set-Cookie: ");
con.append(cookie.getName()+"="+cookie.getValue());
if(cookie.getMaxAge()!=null)
{
con.append("; Max-Age="+cookie.getMaxAge());
}
if(cookie.getPath()!=null)
{
con.append("; path="+cookie.getPath());
}
if(cookie.getDomain()!=null)
{
con.append("; domain="+cookie.getDomain());
}
//con.append("; httponly\r\n");//防止第三方攻击
responseContent.add(con.toString());
}
void addRequestToMap(String str)//将请求信息存入map中
{
String s[] = str.split("\\:");
requestMap.put(s[0].trim(), s[1].trim());
}
void analyseFirstLine(String str)//分析第一行,获取请求类型,和资源
{
String[] s = str.split("\\s");
requestType = s[0];
//System.out.println("类型:" + s[0]);
filePath = s[1];
if(filePath.equals("/")) filePath="/p3.html";
// System.out.println("路径为:" + filePath);
protocol = s[2];
}
//处理GET
long getRange()
{
if( requestMap.containsKey("Range"))
{
String len=requestMap.get("Range");
int start=len.indexOf('=');
int end=len.indexOf('-');
String length=len.substring(start,end);
System.out.println(length);
return Long.parseLong(length);
}
else return 0;
}
void handleGET(OutputStream out) {
long size = fileManager.getFileSize(filePath);
if (size >= 0) { //表示文件存在
setCode("202", "OK");
int loc = filePath.lastIndexOf('.');
//设置文件类型
String contentType = analyseFileType(filePath);
setContentType(contentType);
setContentLength(size);
// 创建cookie
Cookie cookie=new Cookie("username","zhangsan");
//设置cookie最大有效时间
cookie.setMaxAge(3*24*60*60);
addCookie(cookie);
setLastModified(fileManager.getLastModified(filePath));
} else setCode("404", "not found");
respondToClient(out, responseContent);
if (size > 0) {
long start=getRange();
System.out.println("开始位置:"+start);
fileManager.transferResource(filePath, out,start);
}
try {
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
String analyseFileType(String filename)//分析文件类型
{
String fileType;
String regText=".*\\.(txt|html)$";//常见文本
String regImage=".*\\.(jpeg|GPEG|jpg|JPG|png|PNG)$";//常见图像
String regAudio=".*\\.(mp3|MP3|MPEG|mpeg|wma|WMA)$";//常见音频
int loc=filename.lastIndexOf('.');
if(loc==-1) return "application/octet-stream";
if(filename.matches(regText)) {
String suffix=filename.substring(loc+1);
fileType="text/"+suffix;
}
else if(filename.matches(regImage))
{
String suffix=filename.substring(loc+1);
fileType="image/"+suffix;
}
else if(filename.matches(regAudio))
{
String suffix=filename.substring(loc+1);
fileType="audio/"+suffix;
}
else { String suffix=filename.substring(loc+1);
fileType="application/"+suffix;
}
return fileType;
}
//处理PUT
void handlePUT(InputStream in) {
responseContent.clear();
setCode("200", "OK");
respondToClient(out, responseContent);
fileManager.saveResource(filePath, in, false);
}
void handleHEAD(OutputStream out) {
long size = fileManager.getFileSize(filePath);
if (size >= 0) { //表示文件存在
setCode("202", "OK");
int loc = filePath.lastIndexOf('.');
String contentType =analyseFileType(filePath);
setContentType(contentType);
setContentLength(size);
setLastModified(fileManager.getLastModified(filePath));
} else setCode("404", "not found");
respondToClient(out, responseContent);
}
void handlePOST(OutputStream out,InputStream in)
{
setCode("202", "OK");
setContentType("html/text");
respondToClient(out,responseContent);
String news="已经收到你的表单";
try {
out.write(news.getBytes("utf-8"));
out.flush();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
void respondToClient(OutputStream out, ArrayList<String> content) {//响应头信息
System.out.println("返回信息:");
for (int i = 0; i < content.size(); i++) {
System.out.println(content.get(i));
}
int i = 0;
while (i < content.size()) {
try {
out.write(content.get(i).getBytes());
out.write("\r\n".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
break;
}
i++;
}
try {
out.write("\r\n".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
analyseRequest(in);
if (requestType.equalsIgnoreCase("GET")) handleGET(out);
else if (requestType.equalsIgnoreCase("PUT")) {
System.out.println("上传");
handlePUT(in);
} else if (requestType.equalsIgnoreCase("HEAD")) handleHEAD(out);
else if(requestType.equalsIgnoreCase("POST"))
handlePOST(out,in);
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Cookie {
String name=null;
String value=null;
String path=null;//作用路径
String domain=null;//作用域
String MaxAge=null;//最大有效时间
public Cookie(String k, String v) {
name = k;
value = v;
}
void setMaxAge(int time)
{
MaxAge=""+time;
}
void setPath(String path1) {
path = path1;
}
void setDomain(String dm) {
domain = dm;
}
String getName()
{
return name;
}
String getValue()
{
return value;
}
String getMaxAge() {
return MaxAge;
}
String getDomain()
{
return domain;
}
String getPath()
{
return path;
}
}
| 10,854 | 0.544765 | 0.538809 | 390 | 25.692308 | 21.232237 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561538 | false | false |
3
|
b970d9cc52132e0a1942caaea07a833b84863a6a
| 6,004,364,287,484 |
662e4c8a71207abedd4d28c793e86fc9e95b9cb7
|
/src/main/java/com/resource/service/EmployeeService.java
|
05d6ab735020ad73c42915b285e0b8441a1bb520
|
[] |
no_license
|
chethana613/ResourceManagement
|
https://github.com/chethana613/ResourceManagement
|
ea3f4c8d1cf2406e138a8fa017b7aa72eb12472d
|
995ad911f0c23926f8d786945751e0a0ea6d37d4
|
refs/heads/master
| 2020-12-28T04:37:06.851000 | 2020-02-04T11:00:10 | 2020-02-04T11:00:10 | 238,183,403 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.resource.service;
import java.util.List;
import java.util.Optional;
import com.resource.dto.EmployeeDetailResponseDto;
import com.resource.dto.LoginRequestDto;
import com.resource.dto.LoginResponseDto;
import com.resource.dto.ResourceListResponseDto;
import com.resource.entity.Employee;
import com.resource.exception.EmployeeNotFoundException;
public interface EmployeeService {
/**
* @author PriyaDharshini S.
* @since 2020-01-28. This method will authenticate the employee.
* @return LoginResponseDto which has status message and statusCode.
* @param loginRequestDto - details of the user login
* @throws EmployeeNotFoundException it will throw the exception if the employee
* is not there.
*
*/
LoginResponseDto authenticateEmployee(LoginRequestDto loginRequestDto) throws EmployeeNotFoundException;
public EmployeeDetailResponseDto getEmployeeDetails(Long employeeId) throws EmployeeNotFoundException;
/**
* @author Sri Keerthna.
* @since 2020-01-28. In this method list of bench resources are fetched from
* database and displayed.
* @return ResourceListResponseDto which has bench resource details.
* @throws EmployeeNotFoundException if the bench resource list is empty then it
* will throw an error.
*/
public List<ResourceListResponseDto> resourceList() throws EmployeeNotFoundException;
Optional<Employee> getEmployeeById(Long employeeId);
}
|
UTF-8
|
Java
| 1,486 |
java
|
EmployeeService.java
|
Java
|
[
{
"context": "blic interface EmployeeService {\n\n\t/**\n\t * @author PriyaDharshini S.\n\t * @since 2020-01-28. This method will authenti",
"end": 429,
"score": 0.9994931221008301,
"start": 413,
"tag": "NAME",
"value": "PriyaDharshini S"
},
{
"context": "hrows EmployeeNotFoundException;\n\n\t/**\n\t * @author Sri Keerthna.\n\t * @since 2020-01-28. In this method list of be",
"end": 1009,
"score": 0.999841034412384,
"start": 997,
"tag": "NAME",
"value": "Sri Keerthna"
}
] | null |
[] |
package com.resource.service;
import java.util.List;
import java.util.Optional;
import com.resource.dto.EmployeeDetailResponseDto;
import com.resource.dto.LoginRequestDto;
import com.resource.dto.LoginResponseDto;
import com.resource.dto.ResourceListResponseDto;
import com.resource.entity.Employee;
import com.resource.exception.EmployeeNotFoundException;
public interface EmployeeService {
/**
* @author <NAME>.
* @since 2020-01-28. This method will authenticate the employee.
* @return LoginResponseDto which has status message and statusCode.
* @param loginRequestDto - details of the user login
* @throws EmployeeNotFoundException it will throw the exception if the employee
* is not there.
*
*/
LoginResponseDto authenticateEmployee(LoginRequestDto loginRequestDto) throws EmployeeNotFoundException;
public EmployeeDetailResponseDto getEmployeeDetails(Long employeeId) throws EmployeeNotFoundException;
/**
* @author <NAME>.
* @since 2020-01-28. In this method list of bench resources are fetched from
* database and displayed.
* @return ResourceListResponseDto which has bench resource details.
* @throws EmployeeNotFoundException if the bench resource list is empty then it
* will throw an error.
*/
public List<ResourceListResponseDto> resourceList() throws EmployeeNotFoundException;
Optional<Employee> getEmployeeById(Long employeeId);
}
| 1,470 | 0.759085 | 0.748318 | 40 | 36.150002 | 31.629536 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.85 | false | false |
3
|
df6484301e7a77a6adacad3d28b07722b58390cf
| 14,413,910,246,397 |
46a4b48427e117890c2b554204273a3c2d6065e9
|
/src/main/java/org/perscholas/java_conditionals/ChineseZodiac.java
|
34395dfe2a94b5232aacc280db57b8c518164bcc
|
[] |
no_license
|
hryungk/CoreJavaBasics
|
https://github.com/hryungk/CoreJavaBasics
|
d0241a24bef53c03506b294849945db8ec0cb269
|
ce2b0054ec5f98e9d614e1297b69be1b9532f32a
|
refs/heads/master
| 2023-06-09T07:56:19.815000 | 2021-06-27T04:21:18 | 2021-06-27T04:21:18 | 377,281,281 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.perscholas.java_conditionals;
import java.util.Scanner;
/** Write a program that prompts the user to enter a year and displays teh animal for teh year. */
public class ChineseZodiac {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scan.nextInt();
scan.close();
String zodiac;
switch (year % 12) {
case 0:
zodiac = "monkey";
break;
case 1:
zodiac = "rooster";
break;
case 2:
zodiac = "dog";
break;
case 3:
zodiac = "pig";
break;
case 4:
zodiac = "rat";
break;
case 5:
zodiac = "ox";
break;
case 6:
zodiac = "tiger";
break;
case 7:
zodiac = "rabbit";
break;
case 8:
zodiac = "dragon";
break;
case 9:
zodiac = "snake";
break;
case 10:
zodiac = "horse";
break;
case 11:
zodiac = "sheep";
default:
zodiac = "Something's wrong with your input.";
break;
}
System.out.println("Chinese zodiac of the year " + year + ": " + zodiac);
}
}
|
UTF-8
|
Java
| 1,044 |
java
|
ChineseZodiac.java
|
Java
|
[] | null |
[] |
package org.perscholas.java_conditionals;
import java.util.Scanner;
/** Write a program that prompts the user to enter a year and displays teh animal for teh year. */
public class ChineseZodiac {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scan.nextInt();
scan.close();
String zodiac;
switch (year % 12) {
case 0:
zodiac = "monkey";
break;
case 1:
zodiac = "rooster";
break;
case 2:
zodiac = "dog";
break;
case 3:
zodiac = "pig";
break;
case 4:
zodiac = "rat";
break;
case 5:
zodiac = "ox";
break;
case 6:
zodiac = "tiger";
break;
case 7:
zodiac = "rabbit";
break;
case 8:
zodiac = "dragon";
break;
case 9:
zodiac = "snake";
break;
case 10:
zodiac = "horse";
break;
case 11:
zodiac = "sheep";
default:
zodiac = "Something's wrong with your input.";
break;
}
System.out.println("Chinese zodiac of the year " + year + ": " + zodiac);
}
}
| 1,044 | 0.600575 | 0.585249 | 57 | 17.31579 | 17.166019 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.701754 | false | false |
3
|
1a4d9ac98e6f46596277aa7d91f4bf740abf0e8d
| 9,491,877,763,899 |
2e2f604b417b5556f1219ab4621eb52cc6f112dd
|
/Board.java
|
f59b47262734c57ac6caed88c6b8c6936c375bd5
|
[] |
no_license
|
doddeman/Tetris
|
https://github.com/doddeman/Tetris
|
647243ec57c911912f1c2140d11385bbb0d020cb
|
7135e584a226d96f6bd9949dbac9c05101ab5943
|
refs/heads/master
| 2021-06-09T16:35:46.132000 | 2016-05-03T12:04:10 | 2016-05-03T12:04:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tetris;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Created by David on 2016-02-06.
*/
class Board {
//Fält
private final int width;
private final int height;
private static final int OUTSIDE_SIZE = 2;
//Skapa pekare till arrayen
private final SquareType[][] squares;
//Fallande tetromino
private Poly falling = null;
private int fallingX;
private int fallingY;
//BoardListeners
private final List<BoardListener> listeners;
//Poly-fabrik
private final TetrominoMaker myMaker;
//Timer
private Timer theTimer;
//konstruktor
Board(int width, int height) {
startTimer();
this.width = width;
this.height = height;
int newWidth = width + 4;
int newHeight = height + 4;
myMaker = new TetrominoMaker();
//Skapa Listan av listeners
listeners = new ArrayList<>();
//Skapa själva arrayen för spelplanen
squares = new SquareType[newWidth][newHeight];
//Sätt alla rutor till OUTSIDE
for (int i = 0; i < newWidth; i++) {
for (int j = 0; j < newHeight; j++) {
squares[i][j] = SquareType.OUTSIDE;
}
}
//Skriv över alla utom de två yttersta raderna och kolumnerna med EMPTY
for (int i = OUTSIDE_SIZE; i < newWidth - OUTSIDE_SIZE; i++) {
for (int j = OUTSIDE_SIZE; j < newHeight - OUTSIDE_SIZE; j++) {
squares[i][j] = SquareType.EMPTY;
}
}
}
//För spelet frammåt
private void tick(){
if (falling != null ){
fallingY++;
if(hasCollision()){
fallingY--;
fallingToBoard();
falling = null;
}
}
else{
this.falling = myMaker.getRandomPoly();
fallingX = width/2-1; //ger mitten av planen
fallingY = 0;
if(hasCollision()){
falling = null;
System.out.println("Game over");
theTimer.stop();
}
}
notifyListeners();
}
//tar bort vald rad
private void removeRow(int row){
for (int i = row; i > OUTSIDE_SIZE; i--){
for(int j = OUTSIDE_SIZE; j < squares.length - OUTSIDE_SIZE; j++){
setCell(j,i,getCell(j,i-1));
}
}
}
//Kollar om någon rad ska tas bort, kallar på removeRow
private void removeRows() {
for (int i = OUTSIDE_SIZE; i < squares[0].length - OUTSIDE_SIZE; i++){
boolean fullRow = true;
for(int j = OUTSIDE_SIZE; j < squares.length - OUTSIDE_SIZE; j++){
if(getCell(j,i) == SquareType.EMPTY){
fullRow = false;
break;
}
}
if (fullRow){
removeRow(i);
}
}
notifyListeners();
}
//Flytta falling ett steg till höger
public void moveRight(){
fallingX++;
if(hasCollision()){
fallingX--;
}
notifyListeners();
}
//Flytta falling ett steg till vänster
public void moveLeft(){
fallingX--;
if(hasCollision()){
fallingX++;
}
notifyListeners();
}
//Upptäcker kollision
private boolean hasCollision(){
if(falling != null){
for (int i = 0; i < falling.getPolyArray().length; i++) {
for (int j = 0; j < falling.getPolyArray()[0].length; j++) {
if(falling.getPolyCell(i,j) != SquareType.EMPTY){
if(getCell(fallingX + i + OUTSIDE_SIZE, fallingY + j + OUTSIDE_SIZE) != SquareType.EMPTY){
return true;
}
}
}
}
}
return false;
}
//konverterar falling till en del av spelplanen och kallar på removeRows
private void fallingToBoard(){
for (int i = 0; i < falling.getPolyArray().length; i++) {
for (int j = 0; j < falling.getPolyArray()[0].length; j++) {
if(falling.getPolyCell(i,j) != SquareType.EMPTY){
setCell(fallingX + i + OUTSIDE_SIZE, fallingY + j + OUTSIDE_SIZE, falling.getPolyCell(i, j));
}
}
}
removeRows();
}
//Tillsätter en cell i spelplanen ett Squaretype-värde. Används i fallingToBoard bland annat
private void setCell(int x, int y, SquareType s){
squares[x][y] = s;
notifyListeners();
}
//Hämta SquareType från viss position på spelplanen
public SquareType getCell(int x, int y) {
if (x >= 0 && x < width+4 && y >= 0 && y < height+4) {
return squares[x][y];
} else {
return SquareType.OUTSIDE;
}
}
//Lägg till BoardListener (används i testklass)
public void addBoardListener(BoardListener bl){
listeners.add(bl);
}
//Notify Listeners
private void notifyListeners(){
listeners.forEach(BoardListener::boardChanged);
}
//Getters
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Poly getFalling() {
return falling;
}
public int getFallingX() {
return fallingX;
}
public int getFallingY() {
return fallingY;
}
private void startTimer(){
final Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
tick();
}
};
theTimer = new Timer(200, action); //Godtycklig tid för timern
theTimer.setCoalesce(true);
theTimer.start();
}
// --Commented out by Inspection START (2016-04-01 11:58):
// --Commented out by Inspection START (2016-04-01 12:35):
//// //Slumpad spelplan (används inte längre)
//// public void slumpBoard() {
////
//// for (int i = 0; i < width; i++) {
//// for (int j = 0; j < height; j++) {
//// squares[i][j] = slumpSquareType();
//// }
//// }
//// notifyListeners();
//// }
//// --Commented out by Inspection STOP (2016-04-01 11:58)
// //Slumpad squaretype (används inte längre)
// private SquareType slumpSquareType(){
//
// Random random = new Random();
// int n = random.nextInt(SquareType.values().length);
// //SquareType.values() = lista av alla enumerationer
// //SquareType.values().length = 9
//
// return SquareType.values()[n];
// }
// --Commented out by Inspection STOP (2016-04-01 12:35)
}
|
UTF-8
|
Java
| 6,829 |
java
|
Board.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by David on 2016-02-06.\n */\nclass Board {\n\n //Fält\n ",
"end": 149,
"score": 0.9987227320671082,
"start": 144,
"tag": "NAME",
"value": "David"
}
] | null |
[] |
package tetris;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Created by David on 2016-02-06.
*/
class Board {
//Fält
private final int width;
private final int height;
private static final int OUTSIDE_SIZE = 2;
//Skapa pekare till arrayen
private final SquareType[][] squares;
//Fallande tetromino
private Poly falling = null;
private int fallingX;
private int fallingY;
//BoardListeners
private final List<BoardListener> listeners;
//Poly-fabrik
private final TetrominoMaker myMaker;
//Timer
private Timer theTimer;
//konstruktor
Board(int width, int height) {
startTimer();
this.width = width;
this.height = height;
int newWidth = width + 4;
int newHeight = height + 4;
myMaker = new TetrominoMaker();
//Skapa Listan av listeners
listeners = new ArrayList<>();
//Skapa själva arrayen för spelplanen
squares = new SquareType[newWidth][newHeight];
//Sätt alla rutor till OUTSIDE
for (int i = 0; i < newWidth; i++) {
for (int j = 0; j < newHeight; j++) {
squares[i][j] = SquareType.OUTSIDE;
}
}
//Skriv över alla utom de två yttersta raderna och kolumnerna med EMPTY
for (int i = OUTSIDE_SIZE; i < newWidth - OUTSIDE_SIZE; i++) {
for (int j = OUTSIDE_SIZE; j < newHeight - OUTSIDE_SIZE; j++) {
squares[i][j] = SquareType.EMPTY;
}
}
}
//För spelet frammåt
private void tick(){
if (falling != null ){
fallingY++;
if(hasCollision()){
fallingY--;
fallingToBoard();
falling = null;
}
}
else{
this.falling = myMaker.getRandomPoly();
fallingX = width/2-1; //ger mitten av planen
fallingY = 0;
if(hasCollision()){
falling = null;
System.out.println("Game over");
theTimer.stop();
}
}
notifyListeners();
}
//tar bort vald rad
private void removeRow(int row){
for (int i = row; i > OUTSIDE_SIZE; i--){
for(int j = OUTSIDE_SIZE; j < squares.length - OUTSIDE_SIZE; j++){
setCell(j,i,getCell(j,i-1));
}
}
}
//Kollar om någon rad ska tas bort, kallar på removeRow
private void removeRows() {
for (int i = OUTSIDE_SIZE; i < squares[0].length - OUTSIDE_SIZE; i++){
boolean fullRow = true;
for(int j = OUTSIDE_SIZE; j < squares.length - OUTSIDE_SIZE; j++){
if(getCell(j,i) == SquareType.EMPTY){
fullRow = false;
break;
}
}
if (fullRow){
removeRow(i);
}
}
notifyListeners();
}
//Flytta falling ett steg till höger
public void moveRight(){
fallingX++;
if(hasCollision()){
fallingX--;
}
notifyListeners();
}
//Flytta falling ett steg till vänster
public void moveLeft(){
fallingX--;
if(hasCollision()){
fallingX++;
}
notifyListeners();
}
//Upptäcker kollision
private boolean hasCollision(){
if(falling != null){
for (int i = 0; i < falling.getPolyArray().length; i++) {
for (int j = 0; j < falling.getPolyArray()[0].length; j++) {
if(falling.getPolyCell(i,j) != SquareType.EMPTY){
if(getCell(fallingX + i + OUTSIDE_SIZE, fallingY + j + OUTSIDE_SIZE) != SquareType.EMPTY){
return true;
}
}
}
}
}
return false;
}
//konverterar falling till en del av spelplanen och kallar på removeRows
private void fallingToBoard(){
for (int i = 0; i < falling.getPolyArray().length; i++) {
for (int j = 0; j < falling.getPolyArray()[0].length; j++) {
if(falling.getPolyCell(i,j) != SquareType.EMPTY){
setCell(fallingX + i + OUTSIDE_SIZE, fallingY + j + OUTSIDE_SIZE, falling.getPolyCell(i, j));
}
}
}
removeRows();
}
//Tillsätter en cell i spelplanen ett Squaretype-värde. Används i fallingToBoard bland annat
private void setCell(int x, int y, SquareType s){
squares[x][y] = s;
notifyListeners();
}
//Hämta SquareType från viss position på spelplanen
public SquareType getCell(int x, int y) {
if (x >= 0 && x < width+4 && y >= 0 && y < height+4) {
return squares[x][y];
} else {
return SquareType.OUTSIDE;
}
}
//Lägg till BoardListener (används i testklass)
public void addBoardListener(BoardListener bl){
listeners.add(bl);
}
//Notify Listeners
private void notifyListeners(){
listeners.forEach(BoardListener::boardChanged);
}
//Getters
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Poly getFalling() {
return falling;
}
public int getFallingX() {
return fallingX;
}
public int getFallingY() {
return fallingY;
}
private void startTimer(){
final Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
tick();
}
};
theTimer = new Timer(200, action); //Godtycklig tid för timern
theTimer.setCoalesce(true);
theTimer.start();
}
// --Commented out by Inspection START (2016-04-01 11:58):
// --Commented out by Inspection START (2016-04-01 12:35):
//// //Slumpad spelplan (används inte längre)
//// public void slumpBoard() {
////
//// for (int i = 0; i < width; i++) {
//// for (int j = 0; j < height; j++) {
//// squares[i][j] = slumpSquareType();
//// }
//// }
//// notifyListeners();
//// }
//// --Commented out by Inspection STOP (2016-04-01 11:58)
// //Slumpad squaretype (används inte längre)
// private SquareType slumpSquareType(){
//
// Random random = new Random();
// int n = random.nextInt(SquareType.values().length);
// //SquareType.values() = lista av alla enumerationer
// //SquareType.values().length = 9
//
// return SquareType.values()[n];
// }
// --Commented out by Inspection STOP (2016-04-01 12:35)
}
| 6,829 | 0.526463 | 0.514408 | 234 | 28.055555 | 22.092297 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
8a946ff7867ad0fefeb1cb1dc4544c46092c8e8d
| 30,580,167,184,687 |
ecedd45572e56c28327f3ca2576ffc3055a00dd8
|
/CodeProject/Server/ProjectCardServer/src/com/phoenixli/server/listenerServer/AbstractServer.java
|
37d62c33e55ea6d64e0d353d0fa552d3cd7e4e4e
|
[] |
no_license
|
ftcaicai/KaPai
|
https://github.com/ftcaicai/KaPai
|
0d28229f90b2f5d00dd9291764f035e7950f433e
|
ef4e64022bfd38279d57eeeb7c4871c55054a57e
|
refs/heads/master
| 2021-01-18T14:53:43.713000 | 2014-02-11T04:49:09 | 2014-02-11T04:49:09 | 15,152,892 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.phoenixli.server.listenerServer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
/**
* 游戏监听服务器
*
* @author rachel
*/
public class AbstractServer {
//监听端口
private int port;
private ServerBootstrap bootstrap;
private Channel bindChannel = null;
public AbstractServer() {
}
public void init(int port, ChannelPipelineFactory pipelineFactory) {
this.port = port;
// Start server with Nb of active threads = 2*NB CPU + 1 as maximum.
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
Runtime.getRuntime().availableProcessors() * 2 + 1);
// Configure the server.
bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress ", true);
}
public void startServer() {
// Bind and start to accept incoming connections.
bindChannel = bootstrap.bind(new InetSocketAddress(port));
}
public void closeServer() {
if (bindChannel != null) {
bindChannel.close();
}
}
}
|
UTF-8
|
Java
| 1,706 |
java
|
AbstractServer.java
|
Java
|
[
{
"context": "ocketChannelFactory;\n\n/**\n * 游戏监听服务器\n *\n * @author rachel\n */\npublic class AbstractServer {\n //监听端口\n ",
"end": 521,
"score": 0.9995121955871582,
"start": 515,
"tag": "USERNAME",
"value": "rachel"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.phoenixli.server.listenerServer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
/**
* 游戏监听服务器
*
* @author rachel
*/
public class AbstractServer {
//监听端口
private int port;
private ServerBootstrap bootstrap;
private Channel bindChannel = null;
public AbstractServer() {
}
public void init(int port, ChannelPipelineFactory pipelineFactory) {
this.port = port;
// Start server with Nb of active threads = 2*NB CPU + 1 as maximum.
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
Runtime.getRuntime().availableProcessors() * 2 + 1);
// Configure the server.
bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress ", true);
}
public void startServer() {
// Bind and start to accept incoming connections.
bindChannel = bootstrap.bind(new InetSocketAddress(port));
}
public void closeServer() {
if (bindChannel != null) {
bindChannel.close();
}
}
}
| 1,706 | 0.694181 | 0.691805 | 56 | 29.071428 | 27.191029 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
321962e44caa185e30e58071a4472acb2e626a6f
| 26,611,617,434,356 |
c0fb5870132f100ad12b3d45605ac0355e12ae10
|
/src/main/java/com/acme/web/domain/Visit.java
|
bcc49d17c7d3a5a55f546ce1f6830568817ec3b1
|
[] |
no_license
|
haiboewang/demo2
|
https://github.com/haiboewang/demo2
|
ad43f279bbd720e2033ac8695abc95591970aac8
|
db8efe09074ade90f7047f073908844e6b89ec8e
|
refs/heads/master
| 2020-05-17T22:01:45.688000 | 2013-10-02T06:07:49 | 2013-10-02T06:07:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.acme.web.domain;
import java.sql.Timestamp;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Visit extends BaseDomainObject {
@ManyToOne
@JoinColumn(name="visitor_id", nullable=false)
private Visitor visitor;
@OneToMany
@JoinColumn(name="visitor_id")
private Set<PageVisited> visitHistories;
@Column(name="start_dt", nullable=false)
private Timestamp startDateTime;
@Column(name="end_dt", nullable=true)
private Timestamp endDateTime;
public Visitor getVisitor() {
return visitor;
}
public void setVisitor(Visitor visitor) {
this.visitor = visitor;
}
public Timestamp getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Timestamp startDateTime) {
this.startDateTime = startDateTime;
}
public Timestamp getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Timestamp endDateTime) {
this.endDateTime = endDateTime;
}
}
|
UTF-8
|
Java
| 1,084 |
java
|
Visit.java
|
Java
|
[] | null |
[] |
package com.acme.web.domain;
import java.sql.Timestamp;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Visit extends BaseDomainObject {
@ManyToOne
@JoinColumn(name="visitor_id", nullable=false)
private Visitor visitor;
@OneToMany
@JoinColumn(name="visitor_id")
private Set<PageVisited> visitHistories;
@Column(name="start_dt", nullable=false)
private Timestamp startDateTime;
@Column(name="end_dt", nullable=true)
private Timestamp endDateTime;
public Visitor getVisitor() {
return visitor;
}
public void setVisitor(Visitor visitor) {
this.visitor = visitor;
}
public Timestamp getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Timestamp startDateTime) {
this.startDateTime = startDateTime;
}
public Timestamp getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Timestamp endDateTime) {
this.endDateTime = endDateTime;
}
}
| 1,084 | 0.770295 | 0.770295 | 51 | 20.254902 | 17.385866 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.156863 | false | false |
3
|
04f035c55cdd5aff063231f3cd00ca856dd06d81
| 3,332,894,682,952 |
7472f3a78cfeaf1085cf6102ec43201f7ae9476b
|
/bankApp.java
|
5dc4481ee8023e100e8c5d0fe37015581c70461e
|
[] |
no_license
|
ayush8791/small-java-GUI-bank-app
|
https://github.com/ayush8791/small-java-GUI-bank-app
|
4abd88a76a34e9272be9ae602d90acc29f763653
|
2a8200f8de15678d4f788913f271c2d1f031e166
|
refs/heads/master
| 2020-12-03T03:57:45.824000 | 2017-06-29T16:14:49 | 2017-06-29T16:14:49 | 95,794,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
class bankApp extends JFrame implements ActionListener
{
boolean log=false;
JLabel bnk,user,pass,wlcm,pic1;
JButton login,cncl;
JPanel p,p2;
JTextField l1;
JPasswordField l2;
static Container c;
static Connection con;
static ResultSet rs;
static Statement st;
public bankApp()
{
c=getContentPane();
login =new JButton("Login");
cncl =new JButton("Cancel");
bnk=new JLabel("Digi banking");
p=new JPanel();
ImageIcon j=new ImageIcon("C:\\java\\project bank\\ball.png");
pic1=new JLabel(j);
add(p);
p.add(pic1);
p.setBounds(0,0,1640,1070);
p.setLayout(null);
pic1.setBounds(0,0,j.getIconWidth()-400,j.getIconHeight()-400);
bnk.setFont(new Font("ELEPHANT",Font.PLAIN,16));
bnk.setForeground(Color.RED);
wlcm=new JLabel(" WELCOME TO DIGI BANKING PORTAL!");
wlcm.setFont(new Font("ELEPHANT",Font.PLAIN,30));
wlcm.setForeground(Color.RED);
user=new JLabel(" User name");
user.setFont(new Font("Lucida Fax",Font.PLAIN,16));
pass=new JLabel(" Password");
pass.setFont(new Font("Lucida Fax",Font.PLAIN,16));
l1=new JTextField(15);
l2=new JPasswordField(15);
l2.setEchoChar('*');
pic1.add(wlcm);
wlcm.setBounds(60,40,850,50);
pic1.add(user);
user.setBounds(400,250,130,40);
pic1.add(l1);
l1.setBounds(520,250,150,30);
pic1.add(pass);
pass.setBounds(400,280,130,40);
pic1.add(l2);
l2.setBounds(520,285,150,30);
pic1.add(login);
login.setBounds(488,330,80,30);
pic1.add(cncl);
cncl.setBounds(588,330,80,30);
pic1.add(bnk);
bnk.setBounds(50,600,150,50);
setLayout(null);
setVisible(true);
setSize(1650,1080);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
login.addActionListener(this);
cncl.addActionListener(this);
}
public static void main(String arr[]) throws Exception
{
new bankApp();
System.out.println("entering bankApp main block for very first database connection");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","DATABSE","oracle");
st=con.createStatement();
rs=st.executeQuery("select * from LOGIN");
System.out.println("exiting main block of bankApp connection close");
}
public void actionPerformed(ActionEvent e)
{
String custwelcome;
String a =(String)e.getActionCommand();
if(a.equals("Login"))
{
try{
while(rs.next())
{
System.out.println("entered loop for checking");
System.out.println(rs.getInt(1)+" - "+rs.getString(2)+" - "+rs.getString(4));
String s=rs.getString(2);
String pass=rs.getString(3);
String gender=rs.getString(4);
if(s.equalsIgnoreCase(l1.getText()) && pass.equals(l2.getText()) )
{
if(gender.equals("F"))
{
System.out.println("the retrieved username is Male");
custwelcome=new String("Welcome Mrs."+rs.getString(2));
}
else
{
System.out.println("the retrieved username is Female");
custwelcome=new String("Welcome Mr."+rs.getString(2));
}
String tbn=s.toUpperCase().concat("TABLE");
System.out.println("about to make the object for bankApptab2");
bankApptab2 tb2=new bankApptab2(custwelcome,tbn,c);
System.out.println("halt will now return me a panel");
p2=tb2.halt();
System.out.println("halt have given the panel");
c.removeAll();
p.removeAll();
c.add(p2);
p2.setBounds(0,0,1650,1080);
c.setSize(1655,1085);
c.setVisible(true);
log=true;
rs.close();
con.close();
}
}
}
catch(Exception ex)
{
System.out.println(ex);
}
if(log)
{System.out.println("details matched!!");
}
else
{
JOptionPane.showMessageDialog(this,"Wrong details!!");
l1.setText("");
l2.setText("");
}}
if(a.equals("Cancel"))
{
System.exit(0);
}
}
}
|
UTF-8
|
Java
| 3,681 |
java
|
bankApp.java
|
Java
|
[
{
"context": "\n{\r\n\tSystem.out.println(\"the retrieved username is Male\");\r\ncustwelcome=new String(\"Welcome Mrs.\"+rs.getS",
"end": 2777,
"score": 0.9920046925544739,
"start": 2773,
"tag": "USERNAME",
"value": "Male"
},
{
"context": "\n{\r\n\tSystem.out.println(\"the retrieved username is Female\");\r\ncustwelcome=new String(\"Welcome Mr.\"+rs.getSt",
"end": 2904,
"score": 0.9938299655914307,
"start": 2898,
"tag": "USERNAME",
"value": "Female"
}
] | null |
[] |
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
class bankApp extends JFrame implements ActionListener
{
boolean log=false;
JLabel bnk,user,pass,wlcm,pic1;
JButton login,cncl;
JPanel p,p2;
JTextField l1;
JPasswordField l2;
static Container c;
static Connection con;
static ResultSet rs;
static Statement st;
public bankApp()
{
c=getContentPane();
login =new JButton("Login");
cncl =new JButton("Cancel");
bnk=new JLabel("Digi banking");
p=new JPanel();
ImageIcon j=new ImageIcon("C:\\java\\project bank\\ball.png");
pic1=new JLabel(j);
add(p);
p.add(pic1);
p.setBounds(0,0,1640,1070);
p.setLayout(null);
pic1.setBounds(0,0,j.getIconWidth()-400,j.getIconHeight()-400);
bnk.setFont(new Font("ELEPHANT",Font.PLAIN,16));
bnk.setForeground(Color.RED);
wlcm=new JLabel(" WELCOME TO DIGI BANKING PORTAL!");
wlcm.setFont(new Font("ELEPHANT",Font.PLAIN,30));
wlcm.setForeground(Color.RED);
user=new JLabel(" User name");
user.setFont(new Font("Lucida Fax",Font.PLAIN,16));
pass=new JLabel(" Password");
pass.setFont(new Font("Lucida Fax",Font.PLAIN,16));
l1=new JTextField(15);
l2=new JPasswordField(15);
l2.setEchoChar('*');
pic1.add(wlcm);
wlcm.setBounds(60,40,850,50);
pic1.add(user);
user.setBounds(400,250,130,40);
pic1.add(l1);
l1.setBounds(520,250,150,30);
pic1.add(pass);
pass.setBounds(400,280,130,40);
pic1.add(l2);
l2.setBounds(520,285,150,30);
pic1.add(login);
login.setBounds(488,330,80,30);
pic1.add(cncl);
cncl.setBounds(588,330,80,30);
pic1.add(bnk);
bnk.setBounds(50,600,150,50);
setLayout(null);
setVisible(true);
setSize(1650,1080);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
login.addActionListener(this);
cncl.addActionListener(this);
}
public static void main(String arr[]) throws Exception
{
new bankApp();
System.out.println("entering bankApp main block for very first database connection");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","DATABSE","oracle");
st=con.createStatement();
rs=st.executeQuery("select * from LOGIN");
System.out.println("exiting main block of bankApp connection close");
}
public void actionPerformed(ActionEvent e)
{
String custwelcome;
String a =(String)e.getActionCommand();
if(a.equals("Login"))
{
try{
while(rs.next())
{
System.out.println("entered loop for checking");
System.out.println(rs.getInt(1)+" - "+rs.getString(2)+" - "+rs.getString(4));
String s=rs.getString(2);
String pass=rs.getString(3);
String gender=rs.getString(4);
if(s.equalsIgnoreCase(l1.getText()) && pass.equals(l2.getText()) )
{
if(gender.equals("F"))
{
System.out.println("the retrieved username is Male");
custwelcome=new String("Welcome Mrs."+rs.getString(2));
}
else
{
System.out.println("the retrieved username is Female");
custwelcome=new String("Welcome Mr."+rs.getString(2));
}
String tbn=s.toUpperCase().concat("TABLE");
System.out.println("about to make the object for bankApptab2");
bankApptab2 tb2=new bankApptab2(custwelcome,tbn,c);
System.out.println("halt will now return me a panel");
p2=tb2.halt();
System.out.println("halt have given the panel");
c.removeAll();
p.removeAll();
c.add(p2);
p2.setBounds(0,0,1650,1080);
c.setSize(1655,1085);
c.setVisible(true);
log=true;
rs.close();
con.close();
}
}
}
catch(Exception ex)
{
System.out.println(ex);
}
if(log)
{System.out.println("details matched!!");
}
else
{
JOptionPane.showMessageDialog(this,"Wrong details!!");
l1.setText("");
l2.setText("");
}}
if(a.equals("Cancel"))
{
System.exit(0);
}
}
}
| 3,681 | 0.706601 | 0.656072 | 141 | 24.120567 | 19.965387 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.106383 | false | false |
3
|
314e2c9480fb2d519aaded7f68838aa1c4df84ec
| 3,332,894,683,764 |
e1015ba44cbbae8cb752dd0295764fff801fc3e7
|
/app/src/main/java/com/jfl/org/authdbfirebase/entities/UserEntity.java
|
48fe4c66f1a402234201f3656ae8f2d1d6af83f0
|
[] |
no_license
|
josuesf/AuthDBFirebase
|
https://github.com/josuesf/AuthDBFirebase
|
122ecd20861fe8bc11cd3196adb1affbfe9f120c
|
fd20fb121dd327f8f8d851a409ed7f02364352bd
|
refs/heads/master
| 2020-05-02T00:41:41.905000 | 2019-03-26T04:44:41 | 2019-03-26T04:44:41 | 177,675,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jfl.org.authdbfirebase.entities;
import com.google.firebase.database.IgnoreExtraProperties;
@IgnoreExtraProperties
public class UserEntity {
public String name;
public String lastName;
public String age;
public String birthday;
public UserEntity() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public UserEntity(String name, String lastName, String age, String birthday) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.birthday = birthday;
}
}
|
UTF-8
|
Java
| 589 |
java
|
UserEntity.java
|
Java
|
[] | null |
[] |
package com.jfl.org.authdbfirebase.entities;
import com.google.firebase.database.IgnoreExtraProperties;
@IgnoreExtraProperties
public class UserEntity {
public String name;
public String lastName;
public String age;
public String birthday;
public UserEntity() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public UserEntity(String name, String lastName, String age, String birthday) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.birthday = birthday;
}
}
| 589 | 0.694397 | 0.694397 | 23 | 24.608696 | 23.846865 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false |
3
|
ee07006948197edbacf284e4738e5f76ca2604ce
| 33,371,895,922,484 |
7a1209593de09a95a3367fa2d729493df741ba4e
|
/Test2.java
|
62f862c564bc17eb2af26bf5a88756b890ac6d9e
|
[] |
no_license
|
Fredjpl/test
|
https://github.com/Fredjpl/test
|
6a34acf51bc9b43f6e598f213c611e07a592503b
|
4683c4da64ebcbcc646f547d71a962656da1934e
|
refs/heads/master
| 2021-01-24T00:02:58.964000 | 2018-02-24T14:45:53 | 2018-02-24T14:45:53 | 122,747,112 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] a = new int[26][26];
for (int i = 0; i < 20; i++)
for (int j = 3; j < 23; j++)
a[i][j] = s.nextInt();
int t = 0;
int max = 0;
for (int i = 0; i < 20; i++)
for (int j = 3; j < 23; j++) {
t = a[i][j] * a[i][j + 1] * a[i][j + 2] * a[i][j + 3];
if (t > max)
max = t;
t = a[i][j] * a[i + 1][j] * a[i + 2][j] * a[i + 3][j];
if (t > max)
max = t;
t = a[i][j] * a[i + 1][j + 1] * a[i + 2][j + 2] * a[i + 3][j + 3];
if (t > max)
max = t;
t = a[i][j]*a[i+1][j-1]*a[i+2][j-2]*a[i+3][j-3];
if (t > max)
max = t;
}
System.out.print(max);
}
}
|
UTF-8
|
Java
| 987 |
java
|
Test2.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] a = new int[26][26];
for (int i = 0; i < 20; i++)
for (int j = 3; j < 23; j++)
a[i][j] = s.nextInt();
int t = 0;
int max = 0;
for (int i = 0; i < 20; i++)
for (int j = 3; j < 23; j++) {
t = a[i][j] * a[i][j + 1] * a[i][j + 2] * a[i][j + 3];
if (t > max)
max = t;
t = a[i][j] * a[i + 1][j] * a[i + 2][j] * a[i + 3][j];
if (t > max)
max = t;
t = a[i][j] * a[i + 1][j + 1] * a[i + 2][j + 2] * a[i + 3][j + 3];
if (t > max)
max = t;
t = a[i][j]*a[i+1][j-1]*a[i+2][j-2]*a[i+3][j-3];
if (t > max)
max = t;
}
System.out.print(max);
}
}
| 987 | 0.309017 | 0.27153 | 30 | 31.9 | 19.738878 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766667 | false | false |
3
|
1cc8a3bf836847f044fbf70e160ebc97a8c539ba
| 29,910,152,264,171 |
4f7a4ffbb02fc70e09b7b84165facf97298b8e4a
|
/app/src/main/java/task/skywell/githubclient/data/model/SearchResult.java
|
a3a12c4ab82c2bff6bb67052d18e199b9ed630aa
|
[
"Apache-2.0"
] |
permissive
|
Dimowner/GithubClient
|
https://github.com/Dimowner/GithubClient
|
384d409c00d17733857d5eea5c5e26fcb6f2b71f
|
0d4b484cd4872cb8ed29ce391e665223dda98df1
|
refs/heads/master
| 2021-01-01T04:46:36.348000 | 2017-07-24T22:44:09 | 2017-07-24T22:44:09 | 97,239,184 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2017 Dmitriy Ponomarenko
*
* 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 task.skywell.githubclient.data.model;
import java.util.Arrays;
/**
* Created on 14.07.2017.
* @author Dimowner
*/
public class SearchResult {
private int total_count;
private GitHubRepository[] items;
public SearchResult(int total_count, GitHubRepository[] items) {
this.total_count = total_count;
this.items = items;
}
public int getTotalCount() {
return total_count;
}
public GitHubRepository[] getItems() {
return items;
}
@Override
public String toString() {
return "SearchResult{" +
"total_count=" + total_count +
", items=" + Arrays.toString(items) +
'}';
}
}
|
UTF-8
|
Java
| 1,220 |
java
|
SearchResult.java
|
Java
|
[
{
"context": "/*\n * Copyright 2017 Dmitriy Ponomarenko\n *\n * Licensed under the Apache License, Version ",
"end": 40,
"score": 0.9998514652252197,
"start": 21,
"tag": "NAME",
"value": "Dmitriy Ponomarenko"
},
{
"context": ".Arrays;\n\n/**\n * Created on 14.07.2017.\n * @author Dimowner\n */\npublic class SearchResult {\n\tprivate int tot",
"end": 725,
"score": 0.980986475944519,
"start": 717,
"tag": "NAME",
"value": "Dimowner"
}
] | null |
[] |
/*
* Copyright 2017 <NAME>
*
* 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 task.skywell.githubclient.data.model;
import java.util.Arrays;
/**
* Created on 14.07.2017.
* @author Dimowner
*/
public class SearchResult {
private int total_count;
private GitHubRepository[] items;
public SearchResult(int total_count, GitHubRepository[] items) {
this.total_count = total_count;
this.items = items;
}
public int getTotalCount() {
return total_count;
}
public GitHubRepository[] getItems() {
return items;
}
@Override
public String toString() {
return "SearchResult{" +
"total_count=" + total_count +
", items=" + Arrays.toString(items) +
'}';
}
}
| 1,207 | 0.710656 | 0.697541 | 49 | 23.897959 | 23.402637 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
3
|
38473ca05797c6f3d64b453ff90a122c889786be
| 807,453,871,297 |
908ff88275ed530a2ed623ce2a27080b06997b02
|
/src/Public_Key_System/Base64Utils.java
|
5a4340a6eb8decc34345d323df9e503bb8bd3df6
|
[] |
no_license
|
zhenmingda/ISP_Project
|
https://github.com/zhenmingda/ISP_Project
|
456665a6fb0ca57cb2f9f47eb5f64080e938b6be
|
5f2c2b42086e1e21fa2dbdf239d3ffd2d0f210c3
|
refs/heads/master
| 2020-04-10T01:52:09.616000 | 2018-03-07T15:19:03 | 2018-03-07T15:19:03 | 124,252,719 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Public_Key_System;
/**
* Created by zhenmingda on 2016/11/29.
*/
import org.bouncycastle.util.encoders.Base64;
public class Base64Utils {
//decode from base64 to bytes
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
//encode from bytes to base64
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
}
|
UTF-8
|
Java
| 466 |
java
|
Base64Utils.java
|
Java
|
[
{
"context": "package Public_Key_System;\n\n/**\n * Created by zhenmingda on 2016/11/29.\n */\n\nimport org.bouncycastle.util.",
"end": 56,
"score": 0.9994546175003052,
"start": 46,
"tag": "USERNAME",
"value": "zhenmingda"
}
] | null |
[] |
package Public_Key_System;
/**
* Created by zhenmingda on 2016/11/29.
*/
import org.bouncycastle.util.encoders.Base64;
public class Base64Utils {
//decode from base64 to bytes
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
//encode from bytes to base64
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
}
| 466 | 0.684549 | 0.633047 | 22 | 20.227272 | 22.502388 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false |
3
|
a147effda91b9879d856b2205974fdf67f6d4982
| 30,906,584,674,339 |
d0bc0a7421b1582244f0a3fc70ca9d8556ee3879
|
/src/main/java/com/ojas/gst/entity/CustomerRangeOfCode.java
|
e8d99bbae33fcfecc90412ccd9b268e2463cefe1
|
[] |
no_license
|
dhamotharang/GSTProject
|
https://github.com/dhamotharang/GSTProject
|
9743ab52716682ebd54c4ce42fcba5ba26906ba4
|
05784ffcece1ebe47b8773a4ae30758cde8e453a
|
refs/heads/master
| 2023-06-03T10:56:58.285000 | 2019-10-03T12:41:38 | 2019-10-03T12:41:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ojas.gst.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "customerRange_Code")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CustomerRangeOfCode implements com.ojas.gst.entity.Entity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String range1;
private String range2;
private String range3;
private String range4;
private String range5;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRange1() {
return range1;
}
public void setRange1(String range1) {
this.range1 = range1;
}
public String getRange2() {
return range2;
}
public void setRange2(String range2) {
this.range2 = range2;
}
public String getRange3() {
return range3;
}
public void setRange3(String range3) {
this.range3 = range3;
}
public String getRange4() {
return range4;
}
public void setRange4(String range4) {
this.range4 = range4;
}
public String getRange5() {
return range5;
}
public void setRange5(String range5) {
this.range5 = range5;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
UTF-8
|
Java
| 1,459 |
java
|
CustomerRangeOfCode.java
|
Java
|
[] | null |
[] |
package com.ojas.gst.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "customerRange_Code")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CustomerRangeOfCode implements com.ojas.gst.entity.Entity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String range1;
private String range2;
private String range3;
private String range4;
private String range5;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRange1() {
return range1;
}
public void setRange1(String range1) {
this.range1 = range1;
}
public String getRange2() {
return range2;
}
public void setRange2(String range2) {
this.range2 = range2;
}
public String getRange3() {
return range3;
}
public void setRange3(String range3) {
this.range3 = range3;
}
public String getRange4() {
return range4;
}
public void setRange4(String range4) {
this.range4 = range4;
}
public String getRange5() {
return range5;
}
public void setRange5(String range5) {
this.range5 = range5;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| 1,459 | 0.735435 | 0.710761 | 74 | 18.716217 | 17.434448 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.337838 | false | false |
3
|
332b22248591874acefa9544b61e00c80babb832
| 8,873,402,458,320 |
856a987f9971e50fffada83bc800299d01951a33
|
/src/algorithm/Problem_611.java
|
e2259efedd0f6df1f32660a37c5b668f147a44f7
|
[] |
no_license
|
yasuo11/leetcode
|
https://github.com/yasuo11/leetcode
|
2dd9c114ffaffbc032b226044b158c2fbfd68df0
|
faddfcebc059e70abfb2c245d6b8b6824827b65c
|
refs/heads/master
| 2020-04-11T07:16:17.681000 | 2018-12-20T15:53:05 | 2018-12-20T15:53:05 | 161,605,743 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package algorithm;
import java.util.Arrays;
public class Problem_611 {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int res = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
continue;
for(int j = i+1; j < nums.length; j++){
for(int k = j+1; k < nums.length; k++){
if(nums[i] + nums[j] <= nums[k] || nums[k] - nums[i] >= nums[j])
break;
res++;
}
}
}
return res;
}
public int triangleNumber2(int[] nums) {
Arrays.sort(nums);
int res = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
continue;
int j = i+1;
int k = nums.length-1;
while(k > i+1)
{
if(nums[i] + nums[j] > nums[k] && nums[k] - nums[i] < nums[j])
{
res += k - j;
k--;
j = i+1;
}
else {
if (j + 1 >= k) {
k--;
j = i + 1;
}else
j++;
}
}
}
return res;
}
public int triangleNumber3(int[] nums) {
int n = nums.length;
int res = 0;
Arrays.sort(nums);
for (int i = n - 1; i >= 2; i--) {
int l = 0, r = i - 1;
while (l < r) {
if (nums[l] + nums[r] > nums[i]) {
res += r - l;
r--;
}else {
l++;
}
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {2,2,3,4};
System.out.println(new Problem_611().triangleNumber3(nums));
}
}
|
UTF-8
|
Java
| 1,942 |
java
|
Problem_611.java
|
Java
|
[] | null |
[] |
package algorithm;
import java.util.Arrays;
public class Problem_611 {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int res = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
continue;
for(int j = i+1; j < nums.length; j++){
for(int k = j+1; k < nums.length; k++){
if(nums[i] + nums[j] <= nums[k] || nums[k] - nums[i] >= nums[j])
break;
res++;
}
}
}
return res;
}
public int triangleNumber2(int[] nums) {
Arrays.sort(nums);
int res = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
continue;
int j = i+1;
int k = nums.length-1;
while(k > i+1)
{
if(nums[i] + nums[j] > nums[k] && nums[k] - nums[i] < nums[j])
{
res += k - j;
k--;
j = i+1;
}
else {
if (j + 1 >= k) {
k--;
j = i + 1;
}else
j++;
}
}
}
return res;
}
public int triangleNumber3(int[] nums) {
int n = nums.length;
int res = 0;
Arrays.sort(nums);
for (int i = n - 1; i >= 2; i--) {
int l = 0, r = i - 1;
while (l < r) {
if (nums[l] + nums[r] > nums[i]) {
res += r - l;
r--;
}else {
l++;
}
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {2,2,3,4};
System.out.println(new Problem_611().triangleNumber3(nums));
}
}
| 1,942 | 0.329042 | 0.312564 | 73 | 25.602739 | 16.817913 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630137 | false | false |
3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.