blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52e4b54c60294d34f4985a874dc565d871575f89 | b2d2d57b44c02883dfa12db810211bb0aaa1d804 | /src/com/generic/util/loggerUtils.java | c7993a56ab46b3a421c685d82ece5837d5cd84ef | [] | no_license | tariqalrob97/RayCatch | 30e0385f8d8b760ac8fbdfc38cc01b95bd04b0f7 | 48dfb75139acb3fd25d00fba3edd2b71b7a6d4b8 | refs/heads/master | 2020-06-29T06:21:11.906160 | 2019-11-12T07:32:39 | 2019-11-12T07:32:39 | 200,461,771 | 0 | 0 | null | 2019-08-04T07:40:44 | 2019-08-04T07:15:11 | Java | UTF-8 | Java | false | false | 698 | java | package com.generic.util;
import org.apache.log4j.Logger;
//import org.apache.log4j.Logger;
public class loggerUtils {
//private static ThreadLocal<Logger> loggers = new ThreadLocal<Logger>();
private String testName = "";
private Logger logs22;
public void debug(String msg) {
// System.out.println(msg);
logs22.debug(testName +" : "+ Thread.currentThread().getId() +" : " + msg);
Thread.currentThread().getThreadGroup();
//Reporter.log(msg, true );
}
public loggerUtils(String testNameincome) {
testName = testNameincome;
logs22 = Logger.getLogger("logs");
debug(">>logs init TEST:" +Thread.currentThread().getId()+" : " +testNameincome);
}
}
| [
"18301319+ibatta@users.noreply.github.com"
] | 18301319+ibatta@users.noreply.github.com |
f4066d6ced96c85600271618d3cccc7fef7e28d7 | dfb3f631ed8c18bd4605739f1ecb6e47d715a236 | /disconnect-highcharts/src/main/java/js/lang/external/highcharts/AnnotationsElliottWaveShapeOptions.java | ca928ed0cdcd8f5d61ccfe4bef828acfca4bbfb2 | [
"Apache-2.0"
] | permissive | fluorumlabs/disconnect-project | ceb788b901d1bf7cfc5ee676592f55f8a584a34e | 54f4ea5e6f05265ea985e1ee615cc3d59d5842b4 | refs/heads/master | 2022-12-26T11:26:46.539891 | 2020-08-20T16:37:19 | 2020-08-20T16:37:19 | 203,577,241 | 6 | 1 | Apache-2.0 | 2022-12-16T00:41:56 | 2019-08-21T12:14:42 | Java | UTF-8 | Java | false | false | 6,525 | java | package js.lang.external.highcharts;
import com.github.fluorumlabs.disconnect.core.annotations.Import;
import com.github.fluorumlabs.disconnect.core.annotations.NpmPackage;
import java.lang.String;
import javax.annotation.Nullable;
import js.lang.Any;
import js.lang.Unknown /* ( ColorString | GradientColorObject | PatternObject ) */;
import org.teavm.jso.JSProperty;
/**
* (Highstock) Options for annotation's shapes. Each shape inherits options from
* the shapeOptions object. An option from the shapeOptions can be overwritten
* by config for a specific shape.
*
*/
@NpmPackage(
name = "highcharts",
version = "^8.1.2"
)
@Import(
module = "highcharts/es-modules/masters/highcharts.src.js"
)
public interface AnnotationsElliottWaveShapeOptions extends Any {
/**
* (Highstock) Name of the dash style to use for the shape's stroke.
*
*/
@JSProperty("dashStyle")
@Nullable
DashStyle getDashStyle();
/**
* (Highstock) Name of the dash style to use for the shape's stroke.
*
*/
@JSProperty("dashStyle")
void setDashStyle(@Nullable DashStyle value);
/**
* (Highstock) The color of the shape's fill.
*
*/
@JSProperty("fill")
@Nullable
Unknown /* ( ColorString | GradientColorObject | PatternObject ) */ getFill();
/**
* (Highstock) The color of the shape's fill.
*
*/
@JSProperty("fill")
void setFill(@Nullable PatternObject value);
/**
* (Highstock) The color of the shape's fill.
*
*/
@JSProperty("fill")
void setFill(@Nullable String value);
/**
* (Highstock) The color of the shape's fill.
*
*/
@JSProperty("fill")
void setFill(@Nullable GradientColorObject value);
/**
* (Highstock) The height of the shape.
*
*/
@JSProperty("height")
double getHeight();
/**
* (Highstock) The height of the shape.
*
*/
@JSProperty("height")
void setHeight(double value);
/**
* (Highstock) The radius of the shape.
*
*/
@JSProperty("r")
double getR();
/**
* (Highstock) The radius of the shape.
*
*/
@JSProperty("r")
void setR(double value);
/**
* (Highstock) Defines additional snapping area around an annotation making
* this annotation to focus. Defined in pixels.
*
*/
@JSProperty("snap")
double getSnap();
/**
* (Highstock) Defines additional snapping area around an annotation making
* this annotation to focus. Defined in pixels.
*
*/
@JSProperty("snap")
void setSnap(double value);
/**
* (Highstock) The URL for an image to use as the annotation shape. Note,
* type has to be set to <code>'image'</code>.
*
*/
@JSProperty("src")
@Nullable
String getSrc();
/**
* (Highstock) The URL for an image to use as the annotation shape. Note,
* type has to be set to <code>'image'</code>.
*
*/
@JSProperty("src")
void setSrc(@Nullable String value);
/**
* (Highstock) The color of the shape's stroke.
*
*/
@JSProperty("stroke")
@Nullable
String getStroke();
/**
* (Highstock) The color of the shape's stroke.
*
*/
@JSProperty("stroke")
void setStroke(@Nullable String value);
/**
* (Highstock) The pixel stroke width of the shape.
*
*/
@JSProperty("strokeWidth")
double getStrokeWidth();
/**
* (Highstock) The pixel stroke width of the shape.
*
*/
@JSProperty("strokeWidth")
void setStrokeWidth(double value);
/**
* (Highstock) The type of the shape, e.g. circle or rectangle.
*
*/
@JSProperty("type")
@Nullable
String getType();
/**
* (Highstock) The type of the shape, e.g. circle or rectangle.
*
*/
@JSProperty("type")
void setType(@Nullable String value);
/**
* (Highstock) The width of the shape.
*
*/
@JSProperty("width")
double getWidth();
/**
* (Highstock) The width of the shape.
*
*/
@JSProperty("width")
void setWidth(double value);
static Builder builder() {
return new Builder();
}
final class Builder {
private final AnnotationsElliottWaveShapeOptions object = Any.empty();
private Builder() {
}
public AnnotationsElliottWaveShapeOptions build() {
return object;
}
/**
* (Highstock) Name of the dash style to use for the shape's stroke.
*
*/
public Builder dashStyle(@Nullable DashStyle value) {
object.setDashStyle(value);
return this;
}
/**
* (Highstock) The color of the shape's fill.
*
*/
public Builder fill(@Nullable PatternObject value) {
object.setFill(value);
return this;
}
/**
* (Highstock) The color of the shape's fill.
*
*/
public Builder fill(@Nullable String value) {
object.setFill(value);
return this;
}
/**
* (Highstock) The color of the shape's fill.
*
*/
public Builder fill(@Nullable GradientColorObject value) {
object.setFill(value);
return this;
}
/**
* (Highstock) The height of the shape.
*
*/
public Builder height(double value) {
object.setHeight(value);
return this;
}
/**
* (Highstock) The radius of the shape.
*
*/
public Builder r(double value) {
object.setR(value);
return this;
}
/**
* (Highstock) Defines additional snapping area around an annotation making
* this annotation to focus. Defined in pixels.
*
*/
public Builder snap(double value) {
object.setSnap(value);
return this;
}
/**
* (Highstock) The URL for an image to use as the annotation shape. Note,
* type has to be set to <code>'image'</code>.
*
*/
public Builder src(@Nullable String value) {
object.setSrc(value);
return this;
}
/**
* (Highstock) The color of the shape's stroke.
*
*/
public Builder stroke(@Nullable String value) {
object.setStroke(value);
return this;
}
/**
* (Highstock) The pixel stroke width of the shape.
*
*/
public Builder strokeWidth(double value) {
object.setStrokeWidth(value);
return this;
}
/**
* (Highstock) The type of the shape, e.g. circle or rectangle.
*
*/
public Builder type(@Nullable String value) {
object.setType(value);
return this;
}
/**
* (Highstock) The width of the shape.
*
*/
public Builder width(double value) {
object.setWidth(value);
return this;
}
}
}
| [
"fluorumlabs@users.noreply.github.com"
] | fluorumlabs@users.noreply.github.com |
196ba723d655f11bc06dc15640e7f2ad122c0bc4 | 5c71f8ef378960d2f4e09d6d00266bb30513d401 | /src/view/LoadGame.java | efe03026e2510fd778fdcd29e71faa81f3b928fb | [] | no_license | hhwcode/Plane | 25971f54a460a88c08cf8638dc623a7ab6cf867a | e07a9f675a0e691e2362cf555739cd18264c6386 | refs/heads/master | 2021-06-21T03:49:37.481902 | 2017-07-20T06:26:36 | 2017-07-20T06:26:36 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,496 | java | package view;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import Plane.Config;
import Plane.MusicPlayer;
/**
* 游戏加载页面
*
* @author Administrator
*
*/
public class LoadGame extends JPanel implements Runnable
{
private static final long serialVersionUID = 1L;
// 背景图片
public Image bg;
// 声明飞机图片
public Image logo_plane, bomb3;
public Font f;
// 飞机的xy
private int x = 0;
// 定义线程对象
private Thread thread;
// 加载动画的状态
private boolean logo_type = true;
public GameJPanel gameJPanel;
/**
* 构造方法
* @param gameJPanel
*/
public LoadGame(GameJPanel gameJPanel)
{
// 实例化背景图片
bg = new ImageIcon(Config.img_bg_level_2).getImage();
// 定义字体
f = new Font("", Font.BOLD, 25);
this.gameJPanel = gameJPanel;
this.setLayout(null);
}
/**
* 开始线程,重绘
*/
public void logoin()
{
MusicPlayer music = new MusicPlayer(Config.loading_sound);
music.play();
thread = new Thread(this);
thread.start();
}
/**
* 绘制背景(自动调用) 多次运行 线程在后台更新ui repaint
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(bg, 0, 0,480,700, null);
g.drawImage(new ImageIcon(Config.myPlane).getImage(),(Config.window_width - 116)/2, 30,120,79, null);
g.setColor(Color.WHITE);
g.drawRect(19,Config.window_height - 201, 440, 42);
g.setColor(Color.ORANGE);
g.fillRect(20,Config.window_height - 200, 440 * x/100, 40);
g.setColor(Color.ORANGE);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("全民飞机大战", (Config.window_width - 250)/2, 180);
g.setColor(Color.WHITE);
g.setFont(f);
g.drawString("游戏加载中...", 150,400);
}
/**
* 线程run方法
*/
@Override
public void run()
{
while (logo_type)
{
// 修改x坐标 重绘
x = x + 1;
repaint();
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
e.printStackTrace();
}
if (x > 100)
{
logo_type = false;//结束线程
}
}
logo_type = true;
x = 0;
// 游戏页面
PlaneJFrame.card.show(PlaneJFrame.mainJPanel, "gameJPanel");
// 开始游戏
gameJPanel.startGame();
}
}
| [
"1021457010@qq.com"
] | 1021457010@qq.com |
a7179256396e479782dba8c6a7e4921d17734090 | 02ebac56a263f5b31e008c2e6856e412fca8eae0 | /app/build/generated/source/r/debug/android/support/mediacompat/R.java | db972198e40aabab5b7cba279a817030ce6e6d33 | [] | no_license | akhilsurnedi5479/Birthday_Card | d6bbe26886f10ac1ad888247647e36e0b3695444 | 202ca61242c57081922bec636cead95d9c6a279f | refs/heads/master | 2020-03-06T18:43:40.335933 | 2018-03-27T16:12:24 | 2018-03-27T16:12:24 | 127,012,801 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,442 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.mediacompat;
public final class R {
public static final class attr {
public static final int font = 0x7f020070;
public static final int fontProviderAuthority = 0x7f020072;
public static final int fontProviderCerts = 0x7f020073;
public static final int fontProviderFetchStrategy = 0x7f020074;
public static final int fontProviderFetchTimeout = 0x7f020075;
public static final int fontProviderPackage = 0x7f020076;
public static final int fontProviderQuery = 0x7f020077;
public static final int fontStyle = 0x7f020078;
public static final int fontWeight = 0x7f020079;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f030000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f04003e;
public static final int notification_icon_bg_color = 0x7f04003f;
public static final int notification_material_background_media_default_color = 0x7f040040;
public static final int primary_text_default_material_dark = 0x7f040045;
public static final int ripple_material_light = 0x7f04004a;
public static final int secondary_text_default_material_dark = 0x7f04004b;
public static final int secondary_text_default_material_light = 0x7f04004c;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f05004a;
public static final int compat_button_inset_vertical_material = 0x7f05004b;
public static final int compat_button_padding_horizontal_material = 0x7f05004c;
public static final int compat_button_padding_vertical_material = 0x7f05004d;
public static final int compat_control_corner_material = 0x7f05004e;
public static final int notification_action_icon_size = 0x7f050058;
public static final int notification_action_text_size = 0x7f050059;
public static final int notification_big_circle_margin = 0x7f05005a;
public static final int notification_content_margin_start = 0x7f05005b;
public static final int notification_large_icon_height = 0x7f05005c;
public static final int notification_large_icon_width = 0x7f05005d;
public static final int notification_main_column_padding_top = 0x7f05005e;
public static final int notification_media_narrow_margin = 0x7f05005f;
public static final int notification_right_icon_size = 0x7f050060;
public static final int notification_right_side_padding_top = 0x7f050061;
public static final int notification_small_icon_background_padding = 0x7f050062;
public static final int notification_small_icon_size_as_large = 0x7f050063;
public static final int notification_subtext_size = 0x7f050064;
public static final int notification_top_pad = 0x7f050065;
public static final int notification_top_pad_large_text = 0x7f050066;
}
public static final class drawable {
public static final int notification_action_background = 0x7f060057;
public static final int notification_bg = 0x7f060058;
public static final int notification_bg_low = 0x7f060059;
public static final int notification_bg_low_normal = 0x7f06005a;
public static final int notification_bg_low_pressed = 0x7f06005b;
public static final int notification_bg_normal = 0x7f06005c;
public static final int notification_bg_normal_pressed = 0x7f06005d;
public static final int notification_icon_background = 0x7f06005e;
public static final int notification_template_icon_bg = 0x7f06005f;
public static final int notification_template_icon_low_bg = 0x7f060060;
public static final int notification_tile_bg = 0x7f060061;
public static final int notify_panel_notification_icon_bg = 0x7f060062;
}
public static final class id {
public static final int action0 = 0x7f070006;
public static final int action_container = 0x7f07000e;
public static final int action_divider = 0x7f070010;
public static final int action_image = 0x7f070011;
public static final int action_text = 0x7f070017;
public static final int actions = 0x7f070018;
public static final int async = 0x7f07001e;
public static final int blocking = 0x7f070021;
public static final int cancel_action = 0x7f070024;
public static final int chronometer = 0x7f070027;
public static final int end_padder = 0x7f070031;
public static final int forever = 0x7f070034;
public static final int icon = 0x7f070037;
public static final int icon_group = 0x7f070038;
public static final int info = 0x7f07003b;
public static final int italic = 0x7f07003c;
public static final int line1 = 0x7f07003d;
public static final int line3 = 0x7f07003e;
public static final int media_actions = 0x7f070041;
public static final int normal = 0x7f070047;
public static final int notification_background = 0x7f070048;
public static final int notification_main_column = 0x7f070049;
public static final int notification_main_column_container = 0x7f07004a;
public static final int right_icon = 0x7f070051;
public static final int right_side = 0x7f070052;
public static final int status_bar_latest_event_content = 0x7f07006d;
public static final int text = 0x7f070071;
public static final int text2 = 0x7f070072;
public static final int time = 0x7f070075;
public static final int title = 0x7f070076;
}
public static final class integer {
public static final int cancel_button_image_alpha = 0x7f080002;
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
public static final int notification_action = 0x7f09001c;
public static final int notification_action_tombstone = 0x7f09001d;
public static final int notification_media_action = 0x7f09001e;
public static final int notification_media_cancel_action = 0x7f09001f;
public static final int notification_template_big_media = 0x7f090020;
public static final int notification_template_big_media_custom = 0x7f090021;
public static final int notification_template_big_media_narrow = 0x7f090022;
public static final int notification_template_big_media_narrow_custom = 0x7f090023;
public static final int notification_template_custom_big = 0x7f090024;
public static final int notification_template_icon_group = 0x7f090025;
public static final int notification_template_lines_media = 0x7f090026;
public static final int notification_template_media = 0x7f090027;
public static final int notification_template_media_custom = 0x7f090028;
public static final int notification_template_part_chronometer = 0x7f090029;
public static final int notification_template_part_time = 0x7f09002a;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0b0021;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0c00fa;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00fb;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0c00fc;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00fd;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0c00fe;
public static final int TextAppearance_Compat_Notification_Media = 0x7f0c00ff;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c0100;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0c0101;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c0102;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0c0103;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c016b;
public static final int Widget_Compat_NotificationActionText = 0x7f0c016c;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f020072, 0x7f020073, 0x7f020074, 0x7f020075, 0x7f020076, 0x7f020077 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x7f020070, 0x7f020078, 0x7f020079 };
public static final int FontFamilyFont_font = 0;
public static final int FontFamilyFont_fontStyle = 1;
public static final int FontFamilyFont_fontWeight = 2;
}
}
| [
"akhilsurnedi5479@gmail.com"
] | akhilsurnedi5479@gmail.com |
050bde36e12f2bb737a490ebd91bc575026ad1f3 | 0818e54179fb1de01354f7d51c68b1d25ba178e2 | /src/main/java/hr/fer/zemris/java/hw11/jnotepadpp/local/LocalizationProvider.java | c3297827161e1a8e6806210bfba717a4d303933e | [] | no_license | ivanrezic/jNotepad | b7afb9a9df49a41141a7e0684b0c05c6a198dc3a | bc476169019d3cf84896c2250a4a3b59787e4bba | refs/heads/master | 2021-01-01T17:53:30.369932 | 2017-07-24T20:37:02 | 2017-07-24T20:37:02 | 98,187,770 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,536 | java | package hr.fer.zemris.java.hw11.jnotepadpp.local;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* <code>LocalizationProvider</code> is singleton instance that enables us to
* get current langueage values saved in property files.
*
* @author Ivan Rezic
*/
public class LocalizationProvider extends AbstractLocalizationProvider {
/** Current language. */
private String language;
/** Bundle which contains translation files. */
private ResourceBundle bundle;
/** {@linkplain LocalizationProvider} instance. */
private static final LocalizationProvider instance = new LocalizationProvider();
/**
* Constructor which instantiates new localization provider.
*/
private LocalizationProvider() {
setLanguage("en");
}
/**
* Gets the single instance of LocalizationProvider.
*
* @return single instance of LocalizationProvider
*/
public static LocalizationProvider getInstance() {
return instance;
}
@Override
public String getString(String key) {
return bundle.getString(key);
}
/**
* Method which sets given language as language.
*
* @param language
* New language.
*/
public void setLanguage(String language) {
this.language = language;
Locale locale = Locale.forLanguageTag(language);
bundle = ResourceBundle.getBundle("hr.fer.zemris.java.hw11.jnotepadpp.local.translation", locale);
fire();
}
/**
* Method used for getting property <code>Language</code>.
*
* @return Language.
*/
public String getLanguage() {
return language;
}
}
| [
"ivan.rezic1@gmail.com"
] | ivan.rezic1@gmail.com |
8a5c3f34f309f1f0c9a06a6ed1f42ae52cb679df | 9dc27aee0ec996d59978fce00974e103d3e6c698 | /src/main/java/com/gymadmin/services/impl/PaymentServiceImpl.java | 6c9105c2c353045081b8629bec66cc0af9fd8c4b | [] | no_license | MRodriguez08/gymadmin | c577ab268d82906e271fb03568b20e0b8823f729 | b60459e6c926eba4f5520b69134db4bb219fda37 | refs/heads/master | 2016-08-12T17:50:06.385173 | 2015-05-05T02:32:12 | 2015-05-05T02:32:12 | 49,207,293 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,180 | java | package com.gymadmin.services.impl;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.gymadmin.config.Constants;
import com.gymadmin.persistence.dao.CustomerDao;
import com.gymadmin.persistence.dao.PaymentDao;
import com.gymadmin.persistence.dao.PaymentStateDao;
import com.gymadmin.persistence.dao.SysParamDao;
import com.gymadmin.persistence.entities.CustomerEntity;
import com.gymadmin.persistence.entities.PaymentEntity;
import com.gymadmin.persistence.entities.PaymentStateEntity;
import com.gymadmin.repository.BusinessException;
import com.gymadmin.repository.DateTimeUtil;
import com.gymadmin.services.PaymentService;
/**
*
* @author mrodriguez
*/
@Component("paymentService")
public class PaymentServiceImpl implements PaymentService {
private static Logger logger = Logger.getLogger(PaymentServiceImpl.class);
@Autowired
private PaymentDao paymentDao;
@Autowired
private SysParamDao sysParamDao;
@Autowired
private PaymentStateDao paymentStateDao;
@Autowired
private CustomerDao customerDao;
public List<PaymentEntity> findAll() {
List<PaymentEntity> users = paymentDao.findAll();
return users;
}
public List<PaymentEntity> findByFilters(Map<String, Object> filters) {
return paymentDao.findByFilters(filters);
}
public PaymentEntity create(PaymentEntity d) throws Exception {
return d;
}
public PaymentEntity edit(PaymentEntity d) throws Exception {
paymentDao.merge(d);
return d;
}
public PaymentEntity pay(PaymentEntity d) throws Exception {
PaymentStateEntity paidState = paymentStateDao.findById(Constants.PAYMENT_STATE_PAID);
PaymentEntity p = paymentDao.findById(d.getId());
p.setState(paidState);
paymentDao.merge(p);
return p;
}
public PaymentEntity get(Integer id) throws Exception {
PaymentEntity entity = paymentDao.findById(id);
return entity;
}
public void delete(Integer id) throws Exception {
try {
PaymentEntity entity = paymentDao.findById(id);
entity.setState(paymentStateDao.findById(Constants.PAYMENT_STATE_CANCELLED));
paymentDao.merge(entity);
} catch (Exception e) {
logger.error(getClass().getCanonicalName() , e);
throw new BusinessException("Error al eliminar plan");
}
}
@Transactional(readOnly = false)
@Scheduled(fixedDelay = 10000, initialDelay = 5000)
public void generatePayments(){
try {
logger.info("Generating payments...");
Integer dueDateMonthDay = Integer.valueOf(sysParamDao.findById(Constants.SYSPARAM_DUE_DATE_MONTH_DAY).getValue());
List<CustomerEntity> customers = customerDao.findAllByState(true);
for (CustomerEntity e : customers){
//Si no hay cuotas pendientes o por vencer tengo que generar una nueva factura
List<PaymentEntity> activePayments = paymentDao.findActiveByCustomer(e.getId());
if (activePayments.size() == 0){
PaymentEntity newPayment = new PaymentEntity();
newPayment.setPaymentGenerationDate(new Date());
newPayment.setCustomer(e);
newPayment.setPlan(e.getPlan());
newPayment.setValidCost(e.getPlan().getCost());
newPayment.setPaymentDueDate(DateTimeUtil.getNextDueDate(e.getPaymentPlan().getMonthsCount(), dueDateMonthDay));
newPayment.setState(paymentStateDao.findById(Constants.PAYMENT_STATE_PENDING));
paymentDao.persist(newPayment);
}
}
} catch (Exception e) {
logger.error(getClass().getCanonicalName() , e);
}
}
@Transactional(readOnly = false)
@Scheduled(fixedDelay = 10000, initialDelay = 0)
public void updatePaymentsState() {
try {
logger.info("Updating payments state...");
Integer aboutToOverDays = Integer.valueOf(sysParamDao.findById(Constants.SYSPARAM_ABOUT_TO_OVERDUE_DAYS).getValue());
PaymentStateEntity aboutToOverdue = paymentStateDao.findById(Constants.PAYMENT_STATE_ABOUT_TO_OVERDUE);
PaymentStateEntity overdue = paymentStateDao.findById(Constants.PAYMENT_STATE_OVERDUE);
Float recharge = 1 + Float.valueOf(sysParamDao.findById(Constants.SYSPARAM_OVERDUE_RECHARGE).getValue()) / 100;
Date now = new Date();
List<PaymentEntity> payments = paymentDao.findActive();
for (PaymentEntity e : payments){
Boolean changed = false;
Integer remainingDays = DateTimeUtil.getRemainingDays(now, e.getPaymentDueDate());
if (remainingDays <= 0){ //aboutToOverdue -> overdue transition
e.setState(overdue);
//apply the recharge
e.setValidCost(e.getValidCost() * recharge);
changed = true;
} else if (remainingDays <= aboutToOverDays){ //pending -> aboutToOverdue transition
e.setState(aboutToOverdue);
changed = true;
}
if ( changed ){
paymentDao.merge(e);
}
}
} catch (Exception e) {
logger.error(getClass().getCanonicalName() , e);
}
}
}
| [
"mau.rod.81090@gmail.com"
] | mau.rod.81090@gmail.com |
535f42437aaec9a30577dd0bc7956d9de723a92c | e83d23138c3902a6a3109aa1d5a004213301eafc | /wkx007/src/main/java/com/orcl/frame/dao/AccountDao.java | 9984336f1539f43e2ca551885354160d326ec747 | [] | no_license | WKVeis/wkx007Test | 1d28b7c3a3463db8fa09bfd31cfa73fac202e1e6 | 35df46816f9a21f684543332e561ad43f03c505c | refs/heads/master | 2022-06-24T05:48:29.257698 | 2020-03-13T06:09:36 | 2020-03-13T06:09:36 | 200,402,278 | 0 | 0 | null | 2022-06-21T01:43:20 | 2019-08-03T17:20:54 | JavaScript | UTF-8 | Java | false | false | 633 | java | package com.orcl.frame.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.orcl.frame.model.Account;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* @author by weikaixiang
* @date 2019/8/1 0001
* @DESC:
*/
public interface AccountDao extends BaseMapper<Account> {
@Select("select *from ACCOUNT where USERNAME=#{userName} AND SEX=#{sex}")
// @Select("SELECT"
// +"*FROM ACCOUNT"
// +"WHERE USERNAME=#{userName}"
// +" AND SEX=#{sex}")
Account finBytwo(@Param("userName") String userName, @Param("sex") String sex);
}
| [
"2512668505@qq.com"
] | 2512668505@qq.com |
d166b0f074f2b603b27fae5d18f4c34fd4471483 | aec9894d4530593a464b8a4daf146d3f2b86f428 | /src/main/java/com/wjzc/framework/config/GenConfig.java | 410cd7b916448d02a1670df629f5404e1cdbda8c | [] | no_license | wqqing77/wjzc | f6a048126c93c499c070869419a87dc7343e9756 | 3b781d8d55c8f54088d7e876cb7d6729664adbf6 | refs/heads/master | 2023-03-04T01:07:35.802240 | 2021-02-13T02:56:29 | 2021-02-13T02:56:29 | 338,482,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,367 | java | package com.wjzc.framework.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 读取代码生成相关配置
*
* @author wjzc
*/
@Component
@ConfigurationProperties(prefix = "gen")
public class GenConfig {
/**
* 作者
*/
public static String author;
/**
* 生成包路径
*/
public static String packageName;
/**
* 自动去除表前缀,默认是true
*/
public static boolean autoRemovePre;
/**
* 表前缀(类名不会包含表前缀)
*/
public static String tablePrefix;
public static String getAuthor() {
return author;
}
public void setAuthor(String author) {
GenConfig.author = author;
}
public static String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
GenConfig.packageName = packageName;
}
public static boolean getAutoRemovePre() {
return autoRemovePre;
}
public void setAutoRemovePre(boolean autoRemovePre) {
GenConfig.autoRemovePre = autoRemovePre;
}
public static String getTablePrefix() {
return tablePrefix;
}
public void setTablePrefix(String tablePrefix) {
GenConfig.tablePrefix = tablePrefix;
}
}
| [
"wqqing77@163.com"
] | wqqing77@163.com |
6cf02d0a1833c3abb313cade002ede51addb80db | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_3/src/g/d/j/Calc_1_3_6398.java | 9579268e84a49812436de1386f004f233c6fcc7a | [] | no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | package g.d.j;
public class Calc_1_3_6398 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"christian.halstrick@sap.com"
] | christian.halstrick@sap.com |
1f5dd187d87a5be9698f6386b0ffefb532b022f8 | 5af4e82cfd03ab53fbbd74220f923c051caacaed | /classloader-pitfalls/src/test/java/com/link_intersystems/publications/blog/classloader_pitfalls/ClassCastExceptionTest.java | 41b87a06465a6df831abef137e4304d60f05b457 | [
"Apache-2.0"
] | permissive | szymonleyk/blog | 3399cc17b8011aea78beed52256fc8714855710e | 24917cbba66a0b0e7def0c622020ab5ab1b94d28 | refs/heads/master | 2021-05-28T16:18:26.387061 | 2015-05-01T15:47:23 | 2015-05-01T15:51:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,813 | java | package com.link_intersystems.publications.blog.classloader_pitfalls;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.Assert;
import org.junit.Test;
public class ClassCastExceptionTest {
/**
* This test shows that a class loaded by one class loader is not equal to
* the same class loaded by another class loader.
*
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
@Test(expected = ClassCastException.class)
@SuppressWarnings("unused")
public void classCastExceptionWithDifferentClassLoaders()
throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
// Calculator is just a test class that I created
URL[] urls = getClassLoaderClasspath(Calculator.class);
URLClassLoader classLoader1 = new URLClassLoader(urls, null);
URLClassLoader classLoader2 = new URLClassLoader(urls, null);
String canonicalName = Calculator.class.getCanonicalName();
Class<?> calcClass1 = classLoader1.loadClass(canonicalName);
Class<?> calcClass2 = classLoader2.loadClass(canonicalName);
// The classes are not equal, because they are loaded by different class
// loaders.
Assert.assertFalse(calcClass1.equals(calcClass2));
Object calcInstance1 = calcClass1.newInstance();
Object calcInstance2 = calcClass2.newInstance();
// As the test defines we expect a ClassCastException, because an
// instance of calcClass2 can not be casted to calcClass1
calcClass1.cast(calcInstance2);
}
private URL[] getClassLoaderClasspath(Class<?> clazz) {
ClassLoader classLoader = clazz.getClassLoader();
Assert.assertTrue(classLoader instanceof URLClassLoader);
URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
URL[] urls = urlClassLoader.getURLs();
return urls;
}
}
| [
"rene.link@link-intersystems.com"
] | rene.link@link-intersystems.com |
e8b2e60e02c8d309eacb6c69b6c0735025ab5ad3 | 02f4c29726cec69f5923bb70e2eb2c91a9635fb5 | /src/main/java/com/iceq/springdata/controller/MemService.java | c5c82edd3eeb5ce5764f7609dd8bb755493268e9 | [] | no_license | ikrix32/IceQAI | f40cd40899d24ce61320327adb283811ae433543 | 77283f6205daebffa41ad3cc4a4a68d2578fb226 | refs/heads/master | 2020-05-20T23:07:50.346486 | 2017-06-01T14:52:55 | 2017-06-01T14:52:55 | 84,542,376 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package com.iceq.springdata.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.iceq.natural.language.Sequence;
import com.iceq.springdata.repository.NodeRepository;
@Service
public class MemService {
@Autowired
NodeRepository nodeRepository;
@Transactional
public void saveStatement(Sequence seq){
}
}
| [
"cristianserrban@yahoo.com"
] | cristianserrban@yahoo.com |
3b4c6934886ed36abbaa883b6f6f6ea3204b7229 | e048a05c4eb2a1686ec3c7efde287e56023d076a | /src/controller/src/launchingGame/SearchBar.java | 4cb1016f7bafed2f5e3a53c913a437bb2ad2b43a | [
"MIT"
] | permissive | yk154/voogasalad_PrintStackTrace | 66b80e8e1bd8dd9f147ceba68acbb4fc3c893055 | 47e82b3401270e81681f8fef11691a3878b26a82 | refs/heads/master | 2020-04-23T11:39:05.466768 | 2019-02-17T19:24:35 | 2019-02-17T19:24:35 | 171,143,365 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,538 | java | package launchingGame;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import social.EngineEvent;
import social.EventBus;
public class SearchBar {
public static final String PROMPT_MESSAGE = "Game Name";
public static final String CROSS_PATH = "/graphics/black-cross.png";
public static final double BAR_WIDTH = 400;
public static final double MIN_WIDTH = 200;
public static final double ICON_WIDTH = 10;
public static final double ICON_HEIGHT = 10;
private HBox myBox;
private TextField myTextField;
private Button myCloseButton;
private Searchable mySearchable;
public SearchBar(Searchable searchable) {
mySearchable = searchable;
initField();
initButton();
initBox();
myBox.getChildren().add(myCloseButton);
myBox.getChildren().add(myTextField);
EventBus.getInstance().register(EngineEvent.SWITCH_SEARCHABLE, this::switchSearchable);
}
private void initBox() {
myBox = new HBox();
myBox.setAlignment(Pos.CENTER_LEFT);
}
private void initField() {
myTextField = new TextField();
myTextField.setPromptText(PROMPT_MESSAGE);
myTextField.getStyleClass().add("search-bar");
myTextField.setPrefWidth(BAR_WIDTH);
myTextField.setMinWidth(MIN_WIDTH);
myTextField.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
String txt = myTextField.getCharacters().toString();
mySearchable.showByTag(txt);
myTextField.clear();
}
});
}
private void initButton() {
Image image = new Image(getClass().getResourceAsStream(CROSS_PATH));
ImageView imageView = new ImageView(image);
imageView.setFitWidth(ICON_WIDTH);
imageView.setFitHeight(ICON_HEIGHT);
myCloseButton = new Button();
myCloseButton.setGraphic(imageView);
myCloseButton.getStyleClass().add("closebutton");
myCloseButton.setOnAction(event -> {
myTextField.clear();
mySearchable.showAll();
});
}
public void switchSearchable(Object ...args){
Searchable searchable = (Searchable) args[0];
mySearchable = searchable;
}
public HBox getView() {
return myBox;
}
}
| [
"yk154@duke.edu"
] | yk154@duke.edu |
f903837662cdbf55a54334f22ecbd6d5905d1083 | f64893d16ab13919cf4bf6695dc6fa7256a382ae | /jvm-core/src/main/java/jvm/allocate/MinorGC.java | b435c45afe14a2b020cb3ced2cf2c471554d6973 | [] | no_license | JadeLuo/JVM | 816f77e67ac4f00fcb43ba1c5903fbd32fac3346 | 2b599b2a07c9135a6e310bff3fd46d2ceaec870d | refs/heads/master | 2020-06-10T16:24:00.507089 | 2019-01-22T14:56:44 | 2019-01-22T14:56:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,379 | java | package jvm.allocate;
/**
* MinorGC 新生代垃圾收集动作
* VM params : -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8
*
* @author LightMingMing
*/
public class MinorGC {
private static final int _1M = 1024 * 1024;
public static void main(String[] args) {
byte[] alloc1, alloc2, alloc3, alloc4;
alloc1 = new byte[2 * _1M];
alloc2 = new byte[2 * _1M];
alloc3 = new byte[2 * _1M];
alloc4 = new byte[4 * _1M]; // Minor GC
}
}
/*
JDK 8
[GC (Allocation Failure) [PSYoungGen: 8192K->624K(9216K)] 12288K->4728K(19456K), 0.0009462 secs] [Times: user=0.01 sys=0.00, real=0.00 secs]
Heap
PSYoungGen total 9216K, used 872K [0x00000007bf600000, 0x00000007c0000000, 0x00000007c0000000)
eden space 8192K, 3% used [0x00000007bf600000,0x00000007bf63e0d0,0x00000007bfe00000)
from space 1024K, 60% used [0x00000007bfe00000,0x00000007bfe9c010,0x00000007bff00000)
to space 1024K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007c0000000)
ParOldGen total 10240K, used 4104K [0x00000007bec00000, 0x00000007bf600000, 0x00000007bf600000)
object space 10240K, 40% used [0x00000007bec00000,0x00000007bf002010,0x00000007bf600000)
Metaspace used 3277K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 360K, capacity 388K, committed 512K, reserved 1048576K
*/ | [
"1849901944@qq.com"
] | 1849901944@qq.com |
3614a22a2885fc384ca4452c80bf50bd0b8f2f0a | ea82c0ea88234f282a148d73d1743fa81cf38232 | /src.application/desmoj/extensions/applicationDomains/production/PartsList.java | 28a52c7dea4b2047180cf9d9d9273b955698bf54 | [] | no_license | PriyWerry/desmoj | 64008d40ff9ea2722ceed6bd153f4747c4b304e8 | 683489d9a885c12f8ef4c22db7bdf3c3048fe102 | refs/heads/master | 2021-06-13T14:12:34.750043 | 2016-10-04T13:51:33 | 2016-10-04T13:51:33 | 72,842,185 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 11,922 | java | package desmoj.extensions.applicationDomains.production;
import desmoj.core.simulator.Model;
import desmoj.core.simulator.ModelComponent;
/**
* A PartsList is a listing of all the different kinds of parts and the number
* (quantity) of them needed to produce a new part (or product). It is used in
* conjunction with a <code>WorkStation</code> in order to tell the work
* station how many and of which kind of parts should be assembled there. The
* user can instantiate a PartsList either by providing to arrays of the same
* length, one with all the different kinds of parts and one with the respective
* number of each different part, or by instantiating a PartsList with the
* number of different kinds of parts and then adding pairs of [kindOfPart,
* number of this kind of parts] using the <code>addPart</code> method.
*
* @version DESMO-J, Ver. 2.5.1d copyright (c) 2015
* @author Soenke Claassen
*
* 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.
*
*/
public class PartsList extends ModelComponent {
/**
* The number of different kinds of parts, needed for the assembly.
*/
private int numberOfDiffParts;
/**
* An array of the different kinds of the parts, needed for the assembly.
*/
private java.lang.Class[] kindOfParts;
/**
* An array of the number of each different kind of part, needed for the
* assembly.
*/
private int[] numberOfParts;
/**
* Constructs a PartsList with the given arrays of different kinds of parts
* and the quantities of that kind of part. Both arrays must be of the same
* size, of course. The PartsList leaves no messages in the trace.
*
* @param ownerModel
* desmoj.Model : The model this PartsList is associated to.
* @param name
* java.lang.String : The name of this PartsList.
* @param kindsOfParts
* java.lang.Class[] : The array containing the different kinds
* of parts.
* @param numOfParts
* int[] : The array constaining the number of each kind of part.
*/
public PartsList(Model ownerModel, String name, Class[] kindsOfParts,
int[] numOfParts) {
super(ownerModel, name, false); // make a ModelComponent with no trace
// output
// check if the given arrays have the same length
if (kindsOfParts.length != numOfParts.length) {
sendWarning(
"The given number of different kinds of parts is not the "
+ "same like the number of quantities of each kind. No PartsList will "
+ "be created!",
getClass().getName()
+ ": "
+ getQuotedName()
+ ", Constructor: "
+ "PartsList(Model ownerModel, String name, Class[] kindsOfParts, "
+ "int[] numOfParts)",
"Both arrays (kindsOfParts, numOfParts) must have the same length.",
"Make sure to provide two arrays with the same length to construct a "
+ "valid PartsList.");
return; // ignore that rubbish and just return
} else {
this.numberOfDiffParts = kindsOfParts.length;
}
// save both arrays
this.kindOfParts = kindsOfParts;
this.numberOfParts = numOfParts;
}
/**
* Constructs a PartsList with enough space to store a number of different
* kinds of parts with the respective quantity needed of each kind. Use the
* method <code>addPart</code> to add a pair of [kind of part, quantity of
* that kind of part]. The PartsList leaves no messages in the trace.
*
* @param ownerModel
* desmoj.Model : The model this PartsList is associated to.
* @param name
* java.lang.String : The name of this PartsList.
* @param numberOfDifferentParts
* int : The number of different kinds of parts. Should not be
* zero or negative!
*/
public PartsList(Model ownerModel, String name, int numberOfDifferentParts) {
super(ownerModel, name, false); // make a ModelComponent with no trace
// output
// check the number of different kinds of parts
if (numberOfDifferentParts < 1) {
sendWarning(
"The given number of different kinds of parts is zero or "
+ "negative. No PartsList will be created!",
getClass().getName()
+ ": "
+ getQuotedName()
+ ", Constructor: "
+ "PartsList(Model ownerModel, String name, int numberOfDifferentParts)",
"A PartsList with no parts does not make sense.",
"Make sure to provide a positive valid number of parts to create a "
+ "PartsList.");
return; // ignore that rubbish and just return
} else {
this.numberOfDiffParts = numberOfDifferentParts;
}
// create the arrays of the given size
kindOfParts = new Class[numberOfDiffParts];
numberOfParts = new int[numberOfDiffParts];
}
/**
* Adds a pair of [kind of part, quantity of that kind of part] to the
* PartsList. There can not be added more pairs than the PartsList can hold.
* To check how many pairs a PartList can hold use the method
* <code>getNumberOfDiffParts()<code>.
* @param kindOfPart java.lang.Class : The kind of part as a Class object.
* @param numberOfParts int : The number of that kind of part.
*/
public void addPart(Class kindOfPart, int numberOfParts) {
// check the number of parts
if (numberOfParts < 1) {
sendWarning(
"The number of parts is zero or negative. The attempted "
+ "insertion of a new pair into the PartsList will be ignored!",
getClass().getName()
+ ": "
+ getQuotedName()
+ ", Method: "
+ "void addPart(Class kindOfPart, int numberOfParts)",
"A negative or zero quantity of parts does not make sense.",
"Make sure to provide a positive valid quantity of parts when adding "
+ "it to the PartsList.");
return; // do nothing, just return
}
// flag, if the insertion of the pair was successful
boolean successful = false;
// loop through the arrays
for (int i = 0; i < numberOfDiffParts; i++) {
// check for a free space
if (kindOfParts[i] == null) {
this.kindOfParts[i] = kindOfPart;
this.numberOfParts[i] = numberOfParts;
successful = true; // sucessfully added to the arrays
break; // leave the loop
}
}
// if no place was found
if (!successful) {
sendWarning(
"The PartsList is full already. No more elements can be added "
+ "to the list. The attempted insertion of a new pair will be ignored!",
getClass().getName()
+ ": "
+ getQuotedName()
+ ", Method: "
+ "void addPart(Class kindOfPart, int numberOfParts)",
"The size of this PartsList is not big enough to hold another pair.",
"Make sure that the PartList is not full already before trying to add "
+ "another pair.");
// do nothing
}
}
/**
* Returns the index of the given kind of part (
* <code>java.lang.Class</code>). The index is indicating the position in
* the array of kindOfParts. If the given kind of part is not found in this
* PartsList, undefinded (-1) will be returned.
*
* @return int : The index of the given kind of part (
* <code>java.lang.Class</code>). That is the position in the
* array of kindOfParts. Or undefined (-1) if no such kind of part
* can be found in this PartsList.
* @param kind
* java.lang.Class : The kind of part given as an object of
* <code>java.lang.Class</code>.
*/
public int getIndexOfKind(Class kind) {
// check kind
if (kind == null) {
sendWarning("The given kind of the part is only a null pointer. "
+ "No index can be returned for that kind of part!",
getClass().getName() + ": " + getQuotedName()
+ ", Method: " + "int getIndexOfKind(Class kind)",
"The given parameter is only a null pointer.",
"Make sure to provide a valid Class variable for the kind of part you "
+ "are looking for.");
return -1; // ignore that rubbish and just return (-1) undefined
}
// search the whole array
for (int i = 0; i < numberOfDiffParts; i++) {
if (kind == kindOfParts[i]) {
return i;
}
}
// nothing found -> return undefined
return -1;
}
/**
* Returns the kind of the part at index i as a Class object.
*
* @return java.lang.Class : The Class object identifying the kind of the
* part. If there is no entry at this index position in the
* PartsList <code>null</code> will be returned.
* @param index
* int : The index in the PartsList for which the kind of the
* part will be returned. The index runs from zero to
* (numberOfDiffParts - 1).
*/
public Class getKindOfPart(int index) {
// check the index
if (index >= numberOfDiffParts || index < 0) {
sendWarning(
"The given index is negative or greater than the number of "
+ "different parts in the PartsList. No kind of part can be returned for "
+ "that index!", getClass().getName() + ": "
+ getQuotedName() + ", Method: "
+ "Class getkindOfPart(int index)",
"The given index is out of bounds.",
"Make sure to provide a positive valid index when trying to retrieve "
+ "the kind of part for that index.");
}
return kindOfParts[index];
}
/**
* Returns the whole array of all kinds of parts listed in this PartsList.
*
* @return java.lang.Class[] : the whole array of all kinds of parts listed
* in this PartsList.
*/
public java.lang.Class[] getKindOfParts() {
return kindOfParts.clone();
}
/**
* Returns the number of different parts (that is the number of entries) in
* this PartsList.
*
* @return int : The number of different parts (that is the number of
* entries) in this PartsList.
*/
public int getNumberOfDiffParts() {
return numberOfDiffParts;
}
/**
* Returns the whole array of all the different quantities of all different
* kinds of parts listed in this PartsList.
*
* @return int[] : The whole array of all the different quantities of all
* different kinds of parts listed in this PartsList.
*/
public int[] getNumberOfParts() {
return numberOfParts.clone();
}
/**
* Returns the quantity of the part at the index i of this PartsList.
*
* @return int : The quantity of the kind of part at index i of this
* PartsList.
* @param index
* int : The index in the PartsList for which the quantity of the
* part will be returned. The index runs from zero to
* (numberOfDiffParts - 1).
*/
public int getQuantityOfPart(int index) {
// check the index
if (index >= numberOfDiffParts || index < 0) {
sendWarning(
"The given index is negative or greater than the number of "
+ "different parts in the PartsList. No kind of part can be returned for "
+ "that index!", getClass().getName() + ": "
+ getQuotedName() + ", Method: "
+ "int getQuantityOfPart(int index)",
"The given index is out of bounds.",
"Make sure to provide a positive valid index when trying to retrieve "
+ "the quantity of part for that index.");
}
return numberOfParts[index];
}
} | [
"goebel_j@86b4f37d-0b98-42f3-ae9f-20825ac9f6ca"
] | goebel_j@86b4f37d-0b98-42f3-ae9f-20825ac9f6ca |
10280738626a98002c7f4502d8e1bbec56bb47ba | 109064e4b2d480e28f35148e715e687e1185e473 | /dictionary-core/src/main/java/org/tveki/dictionary/api/TranslateRequest.java | e6c129114a5ac7ebd01f002dc747c17ae0e5a9cb | [] | no_license | tveki/dictionary-api | 6ad44075e340d8949670762388112dfdc47f1efe | ffd278c8095961104c08be6e1fc908ee652d07d2 | refs/heads/master | 2021-01-22T06:58:54.688880 | 2019-02-24T07:56:22 | 2019-02-24T07:56:22 | 31,650,504 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.tveki.dictionary.api;
/**
*
* @author tveki
*/
public class TranslateRequest extends TranslationTask {
}
| [
"tveki@webstar.hu"
] | tveki@webstar.hu |
035c753e3dd075878393c277e2ac18a7d563d09a | b111b77f2729c030ce78096ea2273691b9b63749 | /db-example-large-multi-project/project27/src/main/java/org/gradle/test/performance/mediumjavamultiproject/project27/p135/Production2700.java | 4755e1fd96dd5afd1e2efe5fff200bd7704670a2 | [] | no_license | WeilerWebServices/Gradle | a1a55bdb0dd39240787adf9241289e52f593ccc1 | 6ab6192439f891256a10d9b60f3073cab110b2be | refs/heads/master | 2023-01-19T16:48:09.415529 | 2020-11-28T13:28:40 | 2020-11-28T13:28:40 | 256,249,773 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,896 | java | package org.gradle.test.performance.mediumjavamultiproject.project27.p135;
public class Production2700 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
8630f6579311b98b701350c6ebf7ce60f7ebfe8a | ae464c2aa556d002e2b69e4936f10dd392ff1c9a | /src/EngineFrame.java | f4f05c79e7d13c174d29ffdd41cdcc8886d6d7c7 | [] | no_license | ducttapecrown/raycaster | 8fcdecac03ea88a61e2c08e2b41a40f9b9d126d2 | ae9207767441e912aa8594381fc9a41508313384 | refs/heads/master | 2020-06-24T20:34:59.132384 | 2016-11-24T07:14:29 | 2016-11-24T07:14:29 | 74,622,777 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,544 | java | /**
* Frame to display the engine.
*
* @author Tim Stoddard, Sam Lindbloom-Airey
* @version program007
*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Image;
import java.text.DecimalFormat;
import java.util.Arrays;
/**
* Frame to display the engine.
*
* @author Tim Stoddard, Sam Lindbloom-Airey
* @version program007
*/
public class EngineFrame extends JFrame {
// double buffering
private Image dbImage;
private Graphics dbg;
// stuff
public Map map;
public Player player;
public Keyboard keyboard;
public Mouse mouse;
private int currLevel;
private long startTime;
private double[] distances;
/**
* Creates a new EngineFrame to display and render the game.
*/
public EngineFrame() {
super("CPE Quest");
add(new JPanel() {
public void paint(Graphics window) {
/* don't edit this */
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
window.drawImage(dbImage, 0, 0, this);
/* end don't edit this */
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (distances != null) {
draw3D(g2);
}
drawMiniMap(g2, 520, 0);
}
});
init();
setSize(865, 480);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void draw3D(Graphics2D g2) {
int height = 480;
for (int x = 0; x < distances.length; x++) {
int lineHeight = (int) (height / distances[x]);
int drawStart = - lineHeight / 2 + height / 2;
drawStart = drawStart < 0 ? 0 : drawStart;
int drawEnd = lineHeight / 2 + height / 2;
drawEnd = drawEnd >= height ? height - 1 : drawEnd;
g2.drawLine(x, drawStart, x, drawEnd);
}
}
private void drawMiniMap(Graphics2D g2, int dx, int dy) {
// draw stats
double scale = 1;
dy += scale * map.getHeight();
g2.setColor(Color.black);
DecimalFormat dec = new DecimalFormat("##.00");
g2.setFont(new Font("Helvetica", Font.PLAIN, 30));
g2.drawString("Position: " + dec.format(player.position[0]) + ", "
+ dec.format(player.position[1]), 10 + dx, 50 + dy);
g2.drawString("Direction: " + dec.format(player.direction[0]) + ", "
+ dec.format(player.direction[1]), 10 + dx, 150 + dy);
g2.drawString(
"Time: " + new DecimalFormat("##.00")
.format((System.currentTimeMillis() - startTime) / 1000.0),
145 + dx, 250 + dy);
}
/**
* Starts the game at level1.
*/
public void init() {
currLevel = 1;
updateMap(currLevel);
startTime = System.currentTimeMillis();
}
/**
* Setter method for the field of vision, set by Engine.
*
* @param fieldOfVision a double array of rectangle heights that
* has length equal to number of rays cast by the engine.
*/
public void sendDistances(double[] distances) {
this.distances = Arrays.copyOf(distances, distances.length);
}
private String stripNonAlpha(String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isAlphabetic(chars[i]) && !Character.isDigit(chars[i])
&& chars[i] != 32) {
chars[i] = '.';
}
}
String temp = new String(chars).replace(".", "");
return temp.length() > 20 ? temp.substring(0, 20) : temp;
}
/**
* Returns the current map.
*
* @return The current map
*/
public Map getMap() {
return map;
}
/**
* Returns the player.
*
* @return the player
*/
public Player getPlayer() {
return player;
}
private void updateMap(int level) {
map = new Map(level);
player = new Player(map);
keyboard = new Keyboard(player);
mouse = new Mouse(player);
addKeyListener(keyboard);
addMouseMotionListener(mouse);
}
}
| [
"sam@Sams-MacBook-Air.local"
] | sam@Sams-MacBook-Air.local |
92b309cbff408cfc2cf463fa134473ec16e5d3e9 | c6e6496e2fa9f3c971e868eee86561d51dc87c0b | /sts-provider/src/main/java/org/jboss/sts/provider/RoleClaimHandler.java | bd58dbe07cffb118f7f9b18962722b281ea15298 | [] | no_license | jurakp/reproducers | 5718ebf9cd179f61bfa029fa5893402191a3214b | f9df32ed36780d142ed6b5a168403d9528eaf4fd | refs/heads/master | 2021-01-21T09:59:30.385219 | 2019-04-03T12:36:39 | 2019-04-03T12:36:39 | 91,675,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,321 | java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.sts.provider;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import javax.xml.ws.WebServiceContext;
import org.apache.cxf.sts.claims.Claim;
import org.apache.cxf.sts.claims.ClaimCollection;
import org.apache.cxf.sts.claims.ClaimsHandler;
import org.apache.cxf.sts.claims.ClaimsParameters;
import org.apache.cxf.sts.claims.RequestClaim;
import org.apache.cxf.sts.claims.RequestClaimCollection;
import org.apache.ws.security.saml.ext.bean.AttributeBean;
/**
* @author pjurak
*
*/
public class RoleClaimHandler implements ClaimsHandler {
/*
* (non-Javadoc)
*
* @see org.apache.cxf.sts.claims.ClaimsHandler#getSupportedClaimTypes()
*/
@Override
public List<URI> getSupportedClaimTypes() {
try {
return Arrays.asList(new URI[] { new URI("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role") });
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.apache.cxf.sts.claims.ClaimsHandler#retrieveClaimValues(org.apache.cxf.sts.claims.RequestClaimCollection,
* org.apache.cxf.sts.claims.ClaimsParameters)
*/
@Override
public ClaimCollection retrieveClaimValues(RequestClaimCollection claims, ClaimsParameters parameters) {
ClaimCollection claimsColl = new ClaimCollection();
for (RequestClaim claim : claims) {
if ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role".equals(claim.getClaimType().toString())) {
Claim c = new Claim();
c.setClaimType(claim.getClaimType());
c.setPrincipal(parameters.getPrincipal());
// add roles (hardcoded)
if ("alice".equalsIgnoreCase(parameters.getPrincipal().getName())) {
c.addValue("friend");
} else {
c.addValue("");
}
claimsColl.add(c);
} else {
System.out.println("Unsupported claim " + claim.getClaimType() + " " + claim.getClaimValue());
}
}
return claimsColl;
}
}
| [
"pjurak@redhat.com"
] | pjurak@redhat.com |
83d6ac3d494e37470218a78fe98b5313cf0f249c | b86f8c9282857e7507d1c06552089ced3ccf48e9 | /11-Timer/examples/ScheduleTimer/ScheduleTimer-ejb/src/java/com/example/TimerServiceLocal.java | 932903c9da0a7d0110c737c15075d7b3f8a2b055 | [] | no_license | sidlors/CursoEJB | 3b45662a0ae221fcbf5059271383b36e2de4bbf5 | 14246c28dcbbe9636fd7839a7d1448b4c2be97aa | refs/heads/master | 2022-11-25T05:27:23.349044 | 2020-04-06T13:20:46 | 2020-04-06T13:20:46 | 31,856,155 | 3 | 9 | null | 2022-11-24T02:15:06 | 2015-03-08T16:12:25 | Java | UTF-8 | Java | false | false | 251 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example;
import javax.ejb.Local;
/**
*
* @author anshenoy
*/
@Local
public interface TimerServiceLocal {
public void doWork();
}
| [
"sidlors@gmail.com"
] | sidlors@gmail.com |
54ee8591caeef7a296506e063843b0282ed4ea5a | 913977dba09d712f51923229fb10860fd08cf5a1 | /src/leetcode/Lee792.java | daa174006f92758b21e1501e231f996ffb9257ab | [] | no_license | zsjwish/algorithm | 17e5bbcef780c30e0b9ab415551a3e642bf001b8 | 4e21ef7398a418ea6358e67b1923ac60c98a6e4e | refs/heads/master | 2021-06-21T06:37:18.566962 | 2019-08-17T15:27:20 | 2019-08-17T15:27:35 | 130,315,973 | 0 | 0 | null | 2018-04-23T09:26:15 | 2018-04-20T06:00:52 | Java | UTF-8 | Java | false | false | 1,748 | java | package leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* created by zsj in 15:58 2018/9/25
* description:给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。
* 示例:
* 输入:
* S = "abcde"
* words = ["a", "bb", "acd", "ace"]
* 输出: 3
* 解释: 有三个是 S 的子序列的单词: "a", "acd", "ace"。
**/
public class Lee792 {
public static void main(String[] args) {
System.out.println(isSubsequence("abc","ahbgdc"));
}
public static int numMatchingSubseq(String S, String[] words) {
int res = 0;
Set<String> pass = new HashSet<>();
Set<String> out = new HashSet<>();
for (String tmp : words) {
if (pass.contains(tmp) || out.contains(tmp)) {
if (pass.contains(tmp)) {
res++;
}
continue;
}
else {
if (isSubsequence(tmp, S)) {
pass.add(tmp);
res++;
}
else {
out.add(tmp);
}
}
}
return res;
}
/**
* s 是 t 的子序列
* @param s
* @param t
* @return
*/
public static boolean isSubsequence(String s, String t) {
if (s.length() == 0) {
return true;
}
if (t.length() == 0) {
return false;
}
int pos = 0;
for (int i = 0; i < t.length() && pos < s.length(); i++) {
if (s.charAt(pos) == t.charAt(i)) {
pos++;
}
}
if (pos == s.length()) {
return true;
}
return false;
}
}
| [
"zsjwish@126.com"
] | zsjwish@126.com |
6836d8ef430627b4815b3d21796c8ba781a62ccc | 40d95f0cc0ed7ad2052a3d4ab2bcf0fa2fad950f | /src/main/java/com/recruitment/common/MD5.java | adc5f4fc9a9de1d40aed362ddf8141b79e4b8e54 | [] | no_license | mcholka/recruitment | f394f00b13b20c13498f52492984416fd06e1613 | bf0517b17eb893be09bf7cabf876c840ad49ed1b | refs/heads/master | 2016-09-06T09:53:45.968595 | 2014-07-02T19:13:41 | 2014-07-02T19:13:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 742 | java | package com.recruitment.common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by mcholka on 2014-05-22. Enjoy!
*/
public class MD5 {
public String getMd5(String value){
try {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(value.getBytes());
StringBuilder sb = new StringBuilder();
for (byte anArray : array) {
sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
| [
"michal.cholka@bluemedia.pl"
] | michal.cholka@bluemedia.pl |
1592e0eb92a1284a3cb410ca0d4ee1821ac79ffa | 195a49ea5bbfc2706fd4440bd061bbae17af714f | /src/main/java/exception/ParamException.java | 62a0b977e00b282d3e87c11dfdf9dc320c7e3979 | [] | no_license | xiaoxixi0314/use-java-thread | 1d282353cf66b5f503d909178db8679db161e35f | c3f373d927e8056e81985873b787c6948d387a5c | refs/heads/master | 2022-07-14T12:18:54.138748 | 2020-06-15T03:21:29 | 2020-06-15T03:21:29 | 225,623,694 | 0 | 0 | null | 2022-06-17T02:41:46 | 2019-12-03T13:14:11 | Java | UTF-8 | Java | false | false | 152 | java | package exception;
public class ParamException extends RuntimeException {
public ParamException(String message) {
super(message);
}
}
| [
"xiaoxixi@caibaopay.com"
] | xiaoxixi@caibaopay.com |
ff7e432d2ea94749d81b570be1af0e5eb11df0bf | cd449c17b5cf6ec7080079dcd62f5e0567fd6b1e | /app/src/main/java/com/linghao/mychattest/controller/adapter/GroupDetailAdapter.java | bc696cd982144708c0f10ab22b384cd8b8ef0569 | [] | no_license | duanxian123/MyChatTest | a145c86785aa15f543fec087c00fe2ecade8bd90 | e4fa379a7c58d7796c59de77178c6932253bebee | refs/heads/master | 2021-01-01T19:40:27.629337 | 2017-09-05T02:10:54 | 2017-09-05T02:10:56 | 98,643,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,578 | java | package com.linghao.mychattest.controller.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.linghao.mychattest.R;
import com.linghao.mychattest.model.bean.UserInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/9/26.
*/
public class GroupDetailAdapter extends BaseAdapter {
private Context mContext;
private boolean mIsCanModify;// 是否允许添加和删除群成员
private List<UserInfo> mUsers = new ArrayList<>();
private boolean mIsDeleteModel;// 删除模式 true:表示可以删除; false:表示不可以删除
private OnGroupDetailListener mOnGroupDetailListener;
public GroupDetailAdapter(Context context, boolean isCanModify, OnGroupDetailListener onGroupDetailListener) {
mContext = context;
mIsCanModify = isCanModify;
mOnGroupDetailListener = onGroupDetailListener;
}
// 获取当前的删除模式
public boolean ismIsDeleteModel() {
return mIsDeleteModel;
}
// 设置当前的删除模式
public void setmIsDeleteModel(boolean mIsDeleteModel) {
this.mIsDeleteModel = mIsDeleteModel;
}
// 刷新数据
public void refresh(List<UserInfo> users) {
if (users != null && users.size() >= 0) {
mUsers.clear();
// 添加加号和减号
initUsers();
mUsers.addAll(0, users);
}
notifyDataSetChanged();
}
private void initUsers() {
UserInfo add = new UserInfo("add");
UserInfo delete = new UserInfo("delete");
mUsers.add(delete);
mUsers.add(0, add);
}
@Override
public int getCount() {
return mUsers == null ? 0 : mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 获取或创建viewholder
ViewHolder holder = null;
if(convertView == null) {
holder = new ViewHolder();
convertView = View.inflate(mContext, R.layout.item_groupdetail,null);
holder.photo = (ImageView) convertView.findViewById(R.id.iv_group_detail_photo);
holder.delete = (ImageView) convertView.findViewById(R.id.iv_group_detail_delete);
holder.name = (TextView) convertView.findViewById(R.id.tv_group_detail_name);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
// 获取当前item数据
final UserInfo userInfo = mUsers.get(position);
// 显示数据
if(mIsCanModify) {// 群主或开放了群权限
// 布局的处理
if(position == getCount() - 1) {// 减号处理
// 删除模式判断
if(mIsDeleteModel) {
convertView.setVisibility(View.INVISIBLE);
}else {
convertView.setVisibility(View.VISIBLE);
holder.photo.setImageResource(R.drawable.em_smiley_minus_btn_pressed);
holder.delete.setVisibility(View.GONE);
holder.name.setVisibility(View.INVISIBLE);
}
}else if(position == getCount() - 2) {// 加号的处理
// 删除模式判断
if(mIsDeleteModel) {
convertView.setVisibility(View.INVISIBLE);
}else {
convertView.setVisibility(View.VISIBLE);
holder.photo.setImageResource(R.drawable.em_smiley_add_btn_pressed);
holder.delete.setVisibility(View.GONE);
holder.name.setVisibility(View.INVISIBLE);
}
}else {// 群成员
convertView.setVisibility(View.VISIBLE);
holder.name.setVisibility(View.VISIBLE);
holder.name.setText(userInfo.getName());
holder.photo.setImageResource(R.drawable.em_default_avatar);
if(mIsDeleteModel) {
holder.delete.setVisibility(View.VISIBLE);
}else {
holder.delete.setVisibility(View.GONE);
}
}
// 点击事件的处理
if(position == getCount() - 1) {// 减号
holder.photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!mIsDeleteModel) {
mIsDeleteModel = true;
notifyDataSetChanged();
}
}
});
}else if(position == getCount() - 2) {// 加号的位置
holder.photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnGroupDetailListener.onAddMembers();
}
});
}else {
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnGroupDetailListener.onDeleteMember(userInfo);
}
});
}
}else {// 普通的群成员
if(position == getCount() - 1 || position == getCount() - 2) {
convertView.setVisibility(View.GONE);
}else {
convertView.setVisibility(View.VISIBLE);
// 名称
holder.name.setText(userInfo.getName());
// 头像
holder.photo.setImageResource(R.drawable.em_default_avatar);
// 删除
holder.delete.setVisibility(View.GONE);
}
}
// 返回view
return convertView;
}
private class ViewHolder{
private ImageView photo;
private ImageView delete;
private TextView name;
}
public interface OnGroupDetailListener{
// 添加群成员方法
void onAddMembers();
// 删除群成员方法
void onDeleteMember(UserInfo user);
}
}
| [
"782695971@qq.com"
] | 782695971@qq.com |
c170f4352912203c41f309320e2c23e9ff942b09 | e01dc5993b7ac310c346763d46e900f3b2d5db5e | /jasperserver-dto/src/test/java/com/jaspersoft/jasperserver/dto/logcapture/CollectorSettingsTest.java | 3946abf995d6374768b048d1fb34993a4f6da103 | [] | no_license | yohnniebabe/jasperreports-server-ce | ed56548a2ee18d37511c5243ffd8e0caff2be8f7 | e65ce85a5dfca8d9002fcabc172242f418104453 | refs/heads/master | 2023-08-26T00:01:23.634829 | 2021-10-22T14:15:32 | 2021-10-22T14:15:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,228 | java | /*
* Copyright (C) 2005 - 2020 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.dto.logcapture;
import com.jaspersoft.jasperserver.dto.basetests.BaseDTOPresentableTest;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
/**
* @author Andriy Tivodar <ativodar@tibco>
*/
public class CollectorSettingsTest extends BaseDTOPresentableTest<CollectorSettings> {
@Override
protected List<CollectorSettings> prepareInstancesWithAlternativeParameters() {
return Arrays.asList(
createFullyConfiguredInstance().setId("id2"),
createFullyConfiguredInstance().setName("name2"),
createFullyConfiguredInstance().setStatus("status2"),
createFullyConfiguredInstance().setVerbosity("verbosity2"),
createFullyConfiguredInstance().setLogFilterParameters(new LogFilterParameters().setUserId("userId2")),
// with null values
createFullyConfiguredInstance().setId(null),
createFullyConfiguredInstance().setName(null),
createFullyConfiguredInstance().setStatus(null),
createFullyConfiguredInstance().setVerbosity(null),
createFullyConfiguredInstance().setLogFilterParameters(null)
);
}
@Override
protected CollectorSettings createFullyConfiguredInstance() {
CollectorSettings collectorSettings = new CollectorSettings();
collectorSettings.setId("id");
collectorSettings.setName("name");
collectorSettings.setStatus("status");
collectorSettings.setVerbosity("verbosity");
collectorSettings.setLogFilterParameters(new LogFilterParameters().setUserId("userId"));
return collectorSettings;
}
@Override
protected CollectorSettings createInstanceWithDefaultParameters() {
return new CollectorSettings();
}
@Override
protected CollectorSettings createInstanceFromOther(CollectorSettings other) {
return new CollectorSettings(other);
}
@Override
protected void assertFieldsHaveUniqueReferences(CollectorSettings expected, CollectorSettings actual) {
assertNotSame(expected.getLogFilterParameters(), actual.getLogFilterParameters());
}
@Test
public void exportIsNotEnabledForNullLogFilterParameters() {
fullyConfiguredTestInstance.setLogFilterParameters(null);
boolean result = fullyConfiguredTestInstance.exportEnabled();
assertEquals(false, result);
}
@Test
public void exportIsEnabledWhenExportDataSnapshotDisabled() {
boolean result = fullyConfiguredTestInstance.exportEnabled();
assertEquals(false, result);
}
@Test
public void exportIsEnabledWhenExportDataSnapshotEnabled() {
ResourceAndSnapshotFilter resourceAndSnapshotFilter = new ResourceAndSnapshotFilter()
.setResourceUri("uri")
.setIncludeDataSnapshots(true);
fullyConfiguredTestInstance.setLogFilterParameters(new LogFilterParameters()
.setResourceAndSnapshotFilter(resourceAndSnapshotFilter));
boolean result = fullyConfiguredTestInstance.exportEnabled();
assertEquals(true, result);
}
}
| [
"hguntupa@tibco.com"
] | hguntupa@tibco.com |
6cecae5f8151dfcb660747f6d249ebea59d15da6 | 53d677a55e4ece8883526738f1c9d00fa6560ff7 | /com/tencent/mm/plugin/product/ui/HtmlTextView.java | 8c433257e505e1b90526d79128d15538b1d679fb | [] | no_license | 0jinxing/wechat-apk-source | 544c2d79bfc10261eb36389c1edfdf553d8f312a | f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d | refs/heads/master | 2020-06-07T20:06:03.580028 | 2019-06-21T09:17:26 | 2019-06-21T09:17:26 | 193,069,132 | 9 | 4 | null | null | null | null | UTF-8 | Java | false | false | 1,417 | java | package com.tencent.mm.plugin.product.ui;
import android.content.Context;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.util.AttributeSet;
import android.widget.TextView;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.kernel.g;
import com.tencent.mm.sdk.platformtools.al;
public class HtmlTextView extends TextView
{
Html.ImageGetter pib;
Html.TagHandler pic;
public HtmlTextView(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
AppMethodBeat.i(44016);
this.pib = new HtmlTextView.2(this);
this.pic = new HtmlTextView.3(this);
AppMethodBeat.o(44016);
}
public HtmlTextView(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
AppMethodBeat.i(44015);
this.pib = new HtmlTextView.2(this);
this.pic = new HtmlTextView.3(this);
AppMethodBeat.o(44015);
}
public void setText(String paramString)
{
AppMethodBeat.i(44017);
g.RS().a(new HtmlTextView.1(this, paramString));
AppMethodBeat.o(44017);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes8-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.product.ui.HtmlTextView
* JD-Core Version: 0.6.2
*/ | [
"172601673@qq.com"
] | 172601673@qq.com |
546cdb7f735355ddda42ca2ddce4ca0523b6203d | 5052c8597ddd6d29568355df2037588ce88834f0 | /src/modulo-01-java-OO/modulo-01/DataTerceiraEraTest.java | 67f63a3346ad5ba4a78b16d3eed196f587dc350f | [] | no_license | OtavioBubans/crescer-2016-2 | 4a13b6f96daf40d48bd716113e64500b321ae06a | 914417e17a51ff892116398dd44e9b0c5feeade2 | refs/heads/master | 2021-05-03T11:47:28.690962 | 2016-12-07T19:46:49 | 2016-12-07T19:46:49 | 69,389,931 | 0 | 0 | null | 2016-11-01T22:39:25 | 2016-09-27T19:12:08 | JavaScript | UTF-8 | Java | false | false | 1,732 | java |
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DataTerceiraEraTest{
@Test
public void testaData(){
DataTerceiraEra data = new DataTerceiraEra(1,5,2005);
assertEquals(1,data.getDia());
assertEquals(5,data.getMes());
assertEquals(2005,data.getAno());
}
@Test
public void testaDataInexistente(){
DataTerceiraEra data = new DataTerceiraEra(40,15,403);
assertEquals(40,data.getDia());
assertEquals(15,data.getMes());
assertEquals(403,data.getAno());
}
@Test
public void criarAno3019QueNaoEhBissexto() {
// Arrange
DataTerceiraEra data = new DataTerceiraEra(1, 10, 3019);
// Act
boolean obtido = data.ehBissexto();
// Assert
assertFalse(obtido);
}
@Test
public void criarAno2000QueEhBissexto() {
// Arrange
DataTerceiraEra data = new DataTerceiraEra(1, 1, 2000);
// Act
boolean obtido = data.ehBissexto();
// Assert
assertTrue(obtido);
}
@Test
public void criarAno1900NaoEhBissexto() {
assertFalse(new DataTerceiraEra(1,1,1900).ehBissexto());
}
@Test
public void criarAno2012QueEhBissexto() {
assertTrue(new DataTerceiraEra(04, 05, 2012).ehBissexto());
}
@Test
public void criarAno2200QueNaoEhBissexto() {
assertFalse(new DataTerceiraEra(04, 05, 2200).ehBissexto());
}
@Test
public void criarAno2015QueNaoEhBissexto() {
assertFalse(new DataTerceiraEra(04, 05, 2015).ehBissexto());
}
}
| [
"otaviobubans@hotmail.com"
] | otaviobubans@hotmail.com |
c688d5ee34e2483b1391ac308a163e2717f3ad87 | aab2c74d9a58a7dcd3b6c45d822c0207d71ce8a3 | /07-Inner-And-Abstract-Classes-&-Interfaces/Abstraction/src/com/rahul/Dog.java | 7e5b88e9529ebe445114f01bc1bef203eb3b3d13 | [] | no_license | Rowlptk/java_tutorial | 0bf098718bc1b166f0e83fd500dbaf94b4ecff69 | 40292275d77cac9e6891ae9fee5cb15ccc5a92a0 | refs/heads/master | 2022-12-05T05:53:58.045538 | 2020-08-13T12:09:41 | 2020-08-13T12:09:41 | 277,821,346 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java |
package com.rahul;
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(getName() + " is eating");
}
@Override
public void breathe() {
System.out.println("Breathe in, breathe out, repeat");
}
}
| [
"rahulzha93@gmail.com"
] | rahulzha93@gmail.com |
34f625a193366b40e841d5eb546642655892200f | 095d00a66a4f646e8ce9d42753579a468f94fbd7 | /src/main/java/com/rfa/employee/repository/EnterpriseOrgStructureRepository.java | c651b13462df6a64a34ee7a719393654d7170965 | [] | no_license | jinggasella/employee | 4e83193dd580dc576ac0959d4a9d60939d354d7f | 0d1d5c69988a17128d15c086e0e665e76d86a208 | refs/heads/master | 2020-06-22T10:32:03.635769 | 2019-07-19T04:06:53 | 2019-07-19T04:06:53 | 197,699,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package com.rfa.employee.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.rfa.employee.model.EnterpriseOrgStructure;
public interface EnterpriseOrgStructureRepository extends JpaRepository<EnterpriseOrgStructure, Long>{
}
| [
"jinggasella22@gmail.com"
] | jinggasella22@gmail.com |
ced4c95e9c0ce9640c0bc77718b0f1d8f4a338e9 | 3cf86285483513fb0a34f21650bd551fc0d56474 | /src/main/java/br/com/campanate/orders/entity/Type.java | 4194f89809575dfe7a2b23513c164f873e9fb457 | [] | no_license | FernandoCamp/service-order | 5504b97e75069b972e3be6005c24b4946056a0ee | c7f2c22bcfdb85f07f037e11fe17a5a6d33e4870 | refs/heads/master | 2021-06-24T20:25:30.772156 | 2019-10-19T23:57:34 | 2019-10-19T23:57:34 | 216,283,582 | 1 | 0 | null | 2021-04-26T19:35:59 | 2019-10-19T23:39:30 | Java | UTF-8 | Java | false | false | 685 | java | package br.com.campanate.orders.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import lombok.Getter;
import lombok.Setter;
@Entity(name = "types")
@Getter
@Setter
public class Type {
@Id
@Column(insertable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String description;
private boolean active;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "type")
private List<Order> order;
}
| [
"fernando@fernando-H81M-S1"
] | fernando@fernando-H81M-S1 |
71070893238bbdcf0cc9b6507b9602fc68efa6fe | 44292c4e6bce26b2209061664f344075ed983595 | /loveouapprate/src/main/java/br/com/kikomesquita/loveouapprate/LoveOurAppRate.java | 9eda2175a338b844122965351f9c5cef32192de1 | [
"MIT"
] | permissive | kikomesquita/LoveOurAppRate-Android | 065b98ca59415f262b3bddbcf23a352a50dbe2d0 | 1af4bcbc4d57e3fed91de33efc446dc792467716 | refs/heads/master | 2022-07-29T22:24:32.426762 | 2020-05-22T02:27:58 | 2020-05-22T02:27:58 | 265,997,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,974 | java | package br.com.kikomesquita.loveouapprate;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
public class LoveOurAppRate {
private static final String TAG = LoveOurAppRate.class.getSimpleName();
private static final String PREF_NAME = "LoveOurAppRate";
private static final String KEY_INSTALL_DATE = "loar_install_date";
private static final String KEY_LAUNCH_TIMES = "loar_launch_times";
private static final String KEY_OPT_OUT = "loar_opt_out";
private static final String KEY_ASK_LATER_DATE = "loar_ask_later_date";
private static Date mInstallDate = new Date();
private static int mLaunchTimes = 0;
private static boolean mOptOut = false;
private static Date mAskLaterDate = new Date();
private static Config sConfig = new Config();
/**
* Initialize configuration.
* @param config Configuration object.
*/
public static void init(Config config) {
sConfig = config;
}
/**
* Call this API when the launcher activity is launched.<br>
* It is better to call this API in onCreate() of the launcher activity.
* @param context Context
*/
public static void onCreate(Context context) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = pref.edit();
// If it is the first launch, save the date in shared preference.
if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) {
storeInstallDate(context, editor);
}
// Increment launch times
int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
launchTimes++;
editor.putInt(KEY_LAUNCH_TIMES, launchTimes);
log("Launch times; " + launchTimes);
editor.apply();
mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0));
mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
mOptOut = pref.getBoolean(KEY_OPT_OUT, false);
mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0));
printStatus(context);
}
/**
* Check whether the rate dialog should be shown or not.
* Developers may call this method directly if they want to show their own view instead of
* dialog provided by this library.
* @return
*/
public static boolean shouldShowRateRequest() {
if (mOptOut) {
return false;
} else {
if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) {
return true;
}
long threshold = TimeUnit.DAYS.toMillis(sConfig.mCriteriaInstallDays); // msec
if (new Date().getTime() - mInstallDate.getTime() >= threshold &&
new Date().getTime() - mAskLaterDate.getTime() >= threshold) {
return true;
}
return false;
}
}
/**
* Stop showing the rate request
* @param context
*/
public static void stopRateRequest(final Context context){
setOptOut(context, true);
}
/**
* Get count number of rate request launches
* @return
*/
public static int getLaunchCount(final Context context){
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
return pref.getInt(KEY_LAUNCH_TIMES, 0);
}
/**
* Show the rate dialog if the criteria is satisfied.
* @param context Context
* @return true if shown, false otherwise.
*/
public static boolean showRateRequestIfNeeded(final Context context) {
if (shouldShowRateRequest()) {
showRateRequest(context);
return true;
} else {
return false;
}
}
protected static void clearSharedPreferences(Context context) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.remove(KEY_INSTALL_DATE);
editor.remove(KEY_LAUNCH_TIMES);
editor.apply();
}
/**
* Set opt out flag.
* If it is true, the rate dialog will never shown unless app data is cleared.
* This method is called when Yes or No is pressed.
* @param context
* @param optOut
*/
protected static void setOptOut(final Context context, boolean optOut) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean(KEY_OPT_OUT, optOut);
editor.apply();
mOptOut = optOut;
}
/**
* Store install date.
* Install date is retrieved from package manager if possible.
* @param context
* @param editor
*/
private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) {
Date installDate = new Date();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
PackageManager packMan = context.getPackageManager();
try {
PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0);
installDate = new Date(pkgInfo.firstInstallTime);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
editor.putLong(KEY_INSTALL_DATE, installDate.getTime());
log("First install: " + installDate.toString());
}
/**
* Store the date the user asked for being asked again later.
* @param context
*/
protected static void storeAskLaterDate(final Context context) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis());
editor.apply();
}
/**
* Print values in SharedPreferences (used for debug)
* @param context
*/
private static void printStatus(final Context context) {
SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
log("*** LoveOuAppStatus Status ***");
log("Install Date: " + new Date(pref.getLong(KEY_INSTALL_DATE, 0)));
log("Launch Times: " + pref.getInt(KEY_LAUNCH_TIMES, 0));
log("Opt out: " + pref.getBoolean(KEY_OPT_OUT, false));
}
/**
* Print log
* @param message
*/
private static void log(String message) {
Log.v(TAG, message);
}
public static void showRateRequest(Context context){
Intent i = new Intent(context, LoveOurAppRateActivity.class);
i.putExtra("appPackageName", context.getPackageName() );
context.startActivity(i);
}
/**
* configuration.
*/
public static class Config {
public static final int CANCEL_MODE_BACK_KEY_OR_TOUCH_OUTSIDE = 0;
public static final int CANCEL_MODE_BACK_KEY = 1;
public static final int CANCEL_MODE_NONE = 2;
private String mUrl = null;
private int mCriteriaInstallDays;
private int mCriteriaLaunchTimes;
private int mCancelMode = CANCEL_MODE_BACK_KEY_OR_TOUCH_OUTSIDE;
/**
* Constructor with default criteria.
*/
public Config() {
this(7, 10);
}
/**
* Constructor.
*
* @param criteriaInstallDays
* @param criteriaLaunchTimes
*/
public Config(int criteriaInstallDays, int criteriaLaunchTimes) {
this.mCriteriaInstallDays = criteriaInstallDays;
this.mCriteriaLaunchTimes = criteriaLaunchTimes;
}
}
}
| [
"kiko-lp@hotmail.com"
] | kiko-lp@hotmail.com |
36e63d244630353e06e8008eb19ce01d4c3ae422 | 91121d7f4f5f83aa82eff29669c721b57d0e1361 | /src/main/java/com/squirrel/smsfapi/exception/BadRequestException.java | c462d9b194f081999fba473171518186dcdca623 | [] | no_license | RonildoBragaJunior/smsf-api | 1b311cdcf21e4ddb23b1e89b262de2c2287222fc | 939001bb6d145d4b6c6b5accf2e63ef453034db2 | refs/heads/master | 2021-10-28T13:00:19.217979 | 2019-03-11T23:00:18 | 2019-03-11T23:00:18 | 166,924,506 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 435 | java | package com.squirrel.smsfapi.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
}
| [
"ronildo@Ronildos-MacBook-Pro.local"
] | ronildo@Ronildos-MacBook-Pro.local |
b8b180ca0645a3a6e496b3f384701a54d1d9a0ca | 3c2990adae62effb525da0406c22d75d7a6f387c | /src/com/cloudgarden/jigloo/actions/ToggleEditorsAction.java | b0ea3be41344c413a0ab1c2db83de9ca463af31b | [] | no_license | orb1t/jigloo | 567840b2cd5311e3b4169c2f950fee13bac6751b | 0f885e336665562a23f3de17e06608bff29d00c8 | refs/heads/master | 2021-07-14T13:47:01.787942 | 2017-10-20T20:50:25 | 2017-10-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,480 | java | /*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.cloudgarden.jigloo.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import com.cloudgarden.jigloo.editors.FormEditor;
/**
* Our sample action implements workbench action delegate.
* The action proxy will be created by the workbench and
* shown in the UI. When the user tries to use the action,
* this delegate will be created and execution will be
* delegated to it.
* @see IWorkbenchWindowActionDelegate
*/
public class ToggleEditorsAction
extends Action
implements IEditorActionDelegate {
private IEditorPart editor;
/**
* The constructor.
*/
public ToggleEditorsAction() {
}
/**
* The action has been activated. The argument of the
* method represents the 'real' action sitting
* in the workbench UI.
* @see IWorkbenchWindowActionDelegate#run
*/
public void run(IAction action) {
if(editor instanceof FormEditor) {
FormEditor fed = (FormEditor)editor;
fed.toggleEditors();
}
}
/**
* Selection in the workbench has been changed. We
* can change the state of the 'real' action here
* if we want, but this can only happen after
* the delegate has been created.
* @see IWorkbenchWindowActionDelegate#selectionChanged
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/**
* We can use this method to dispose of any system
* resources we previously allocated.
* @see IWorkbenchWindowActionDelegate#dispose
*/
public void dispose() {
editor = null;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart)
*/
public void setActiveEditor(IAction action, IEditorPart targetEditor) {
editor = targetEditor;
}
} | [
"jskinnersley@hotmail.com"
] | jskinnersley@hotmail.com |
916aa06539c6bd41493816a1c600ed3cd438c1df | f7e3116d6cd5d717c230c9a630b902bf299ae309 | /code/java/test/qam/pat/PilotSequenceTest.java | 1b3f819ff28b1c4542986653f574dd3ba76a38bf | [] | no_license | robbymckilliam/FastOptimalQAM | e11e743a5b79891cea1e5e71657fd32be0add683 | d45c4f79153b6afaf5b0cf50c2a37517470486c1 | refs/heads/master | 2020-08-07T06:32:42.110230 | 2014-04-14T05:44:13 | 2014-04-14T05:44:13 | 18,748,923 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,507 | java | package qam.pat;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import pubsim.Complex;
/**
*
* @author Robby
*/
public class PilotSequenceTest {
public PilotSequenceTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of next method, of class PilotSequence.
*/
@Test
public void next() {
System.out.println("next");
Complex[] ca = { new Complex(1,2), new Complex(3,4), new Complex(5,6) };
PilotSequence instance = new PilotSequence(ca);
assertEquals(true, instance.next().equals(new Complex(3,4)));
assertEquals(true, instance.next().equals(new Complex(5,6)));
assertEquals(true, instance.next().equals(new Complex(1,2)));
assertEquals(true, instance.next().equals(new Complex(3,4)));
double[] da = { 1,2, 3,4, 5,6 };
instance = new PilotSequence(da);
assertEquals(true, instance.next().equals(new Complex(3,4)));
assertEquals(true, instance.next().equals(new Complex(5,6)));
assertEquals(true, instance.next().equals(new Complex(1,2)));
assertEquals(true, instance.next().equals(new Complex(3,4)));
}
/**
* Test of current method, of class PilotSequence.
*/
@Test
public void current() {
System.out.println("current");
Complex[] ca = { new Complex(1,2), new Complex(3,4), new Complex(5,6) };
PilotSequence instance = new PilotSequence(ca);
assertEquals(true, instance.current().equals(new Complex(1,2)));
assertEquals(true, instance.next().equals(new Complex(3,4)));
assertEquals(true, instance.current().equals(new Complex(3,4)));
assertEquals(true, instance.next().equals(new Complex(5,6)));
assertEquals(true, instance.current().equals(new Complex(5,6)));
assertEquals(true, instance.next().equals(new Complex(1,2)));
assertEquals(true, instance.current().equals(new Complex(1,2)));
assertEquals(true, instance.next().equals(new Complex(3,4)));
assertEquals(true, instance.current().equals(new Complex(3,4)));
}
} | [
"robby.mckilliam@gmail.com"
] | robby.mckilliam@gmail.com |
a2d2e348c1aa9a14c0722981284bf2cd200cc60f | 68047d2f520ab586f16faa8fd3e4287ea478b26d | /android/src/main/java/com/facebook/flipper/plugins/sandbox/SandboxFlipperPlugin.java | 881affcd0b5105196f7a98dbd20a9f36b1a79fe8 | [
"MIT"
] | permissive | s1rius/flipper | 34bf8523af1bee09a8bd28fcb61c4cf3981692ab | 082daa57eadb05f9455bf62cdd832974e54348b3 | refs/heads/master | 2020-08-05T14:56:44.613410 | 2019-10-03T14:10:37 | 2019-10-03T14:10:37 | 186,237,175 | 3 | 0 | MIT | 2019-05-12T09:50:23 | 2019-05-12T09:50:22 | null | UTF-8 | Java | false | false | 2,436 | java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.sandbox;
import com.facebook.flipper.core.FlipperArray;
import com.facebook.flipper.core.FlipperConnection;
import com.facebook.flipper.core.FlipperObject;
import com.facebook.flipper.core.FlipperPlugin;
import com.facebook.flipper.core.FlipperReceiver;
import com.facebook.flipper.core.FlipperResponder;
import java.util.Map;
public class SandboxFlipperPlugin implements FlipperPlugin {
public static final String ID = "Sandbox";
private static final String SET_METHOD_NAME = "setSandbox";
private static final String GET_METHOD_NAME = "getSandbox";
private final SandboxFlipperPluginStrategy mStrategy;
public SandboxFlipperPlugin(SandboxFlipperPluginStrategy strategy) {
mStrategy = strategy;
}
@Override
public String getId() {
return ID;
}
@Override
public void onConnect(FlipperConnection connection) {
connection.receive(
GET_METHOD_NAME,
new FlipperReceiver() {
@Override
public void onReceive(FlipperObject params, final FlipperResponder responder) {
final FlipperArray.Builder sandboxes = new FlipperArray.Builder();
Map<String, String> knownSandboxes = mStrategy.getKnownSandboxes();
if (knownSandboxes == null) {
responder.success(sandboxes.build());
return;
}
for (String sandboxName : knownSandboxes.keySet()) {
sandboxes.put(
new FlipperObject.Builder()
.put("name", sandboxName)
.put("value", knownSandboxes.get(sandboxName)));
}
responder.success(sandboxes.build());
}
});
connection.receive(
SET_METHOD_NAME,
new FlipperReceiver() {
@Override
public void onReceive(FlipperObject params, FlipperResponder responder) throws Exception {
String sandbox = params.getString("sandbox");
mStrategy.setSandbox(sandbox);
responder.success(new FlipperObject.Builder().put("result", true).build());
}
});
}
@Override
public void onDisconnect() {}
@Override
public boolean runInBackground() {
return false;
}
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
0f13a24e34febbd990c1e6cf87ebbea78792c65b | 78eb1491c0c7ca6c9561647e375c2633043b5eb8 | /src/main/java/nl/stefankohler/stash/badgr/achievements/extension/StyleIsEternal.java | af3c1cedaab0425d0ff09d8a3a8269a12f5db29e | [] | no_license | ofir123/Badgr | 0e157661697e2cc4779ab3d19867463322f1934e | dfbe55ca64bb9be2ebe49ee5d59dbaeae607da8d | refs/heads/master | 2021-01-13T02:22:36.770445 | 2014-09-24T16:00:34 | 2014-09-24T16:00:34 | 20,454,086 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 654 | java | package nl.stefankohler.stash.badgr.achievements.extension;
import nl.stefankohler.stash.badgr.Achievement;
/**
* The Style Is Eternal Achievement.
* Granted after adding an X number of CSS files
* to Stash.
*
* @author Stefan Kohler
* @since 1.1
*/
@Achievement
public class StyleIsEternal extends ExtensionBasedAchievement {
private static final Integer COUNTING_LIMIT = 71;
@Override
public String getExtension() {
return "css";
}
@Override
public String getBadge() {
return "styleiseternal.png";
}
@Override
public Integer getCountingLimit() {
return COUNTING_LIMIT;
}
}
| [
"ofirbrukner@gmail.com"
] | ofirbrukner@gmail.com |
b630ea3baee045dba7b033a17cd2b4b7ea54fe2d | ab2080016e068c60118870ce7f89466dc2dd9abe | /app/src/main/java/com/huske/sharedexample/AdminPreferenceConfig.java | a4fbb1e6d260a62eb24b37861319d92227403484 | [] | no_license | Samul333/NotifyMe | db2410c112df0a2448f09373cbfb6d19ed4e5358 | 1619859c6e88c98e2326cd99cea9db5997142fbc | refs/heads/master | 2020-05-17T06:37:50.974335 | 2019-08-01T07:17:40 | 2019-08-01T07:17:40 | 183,563,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 955 | java | package com.huske.sharedexample;
import android.content.Context;
import android.content.SharedPreferences;
public class AdminPreferenceConfig {
private SharedPreferences sharedPreferences;
private Context context;
public AdminPreferenceConfig(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.admin_login_preference),Context.MODE_PRIVATE);
}
public void writeLoginStatus(Boolean status){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(context.getResources().getString(R.string.admin_login_status_preference),status);
editor.commit();
}
public boolean readLoginstatus (){
boolean status = false;
status = sharedPreferences.getBoolean(context.getResources().getString(R.string.admin_login_status_preference),false);
return status;
}
}
| [
"samulshrestha101@gmail.com"
] | samulshrestha101@gmail.com |
6ca4a7366c83dbebf17f830aea3e01f2f089ee46 | cdeb9c129a8bccbd56c5cfa0fcc5f443ce21889a | /src/EditingArrays/AddElement.java | 921a92ea10bf29e1dbbab05da1470605d2c3a92c | [] | no_license | RayNjire/The-Complete-Arrays-Study | 8c6392f27a740fb089235ca27cbd86d2162c6fcd | 829f9760dcbfc0f69d7478dd5efa7ec356c2e34e | refs/heads/master | 2023-03-01T03:17:44.091974 | 2021-02-03T09:44:36 | 2021-02-03T09:44:36 | 265,082,657 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,660 | java | package EditingArrays;
import java.util.Arrays;
/**Author and License
*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*
* @author ray njire
*/
public class AddElement
{
public static void AddString()
{
String allSubjects[] = {"Maths", "Science", "English", "Kiswahili", "S.S.T.", "C.R.E.", "P.E.", "Swimming"};
System.out.println("Original Array -> " + Arrays.toString(allSubjects) + "\n\n");
//Copy the array into itself but declare it with a larger array size
allSubjects = Arrays.copyOf(allSubjects, allSubjects.length + 1);
//Enter the number 4 into the last index of the array
allSubjects[allSubjects.length - 1] = "Arts and Crafts";
System.out.println("New Array -> " + Arrays.toString(allSubjects) + "\n\n");
}
public static void AddInt()
{
int allNumbers[] = {600, 50, 98, 65, 78, 95, 111, 521};
System.out.println("Original Array -> " + Arrays.toString(allNumbers) + "\n\n");
//Copy the array into itself but declare it with a larger array size
allNumbers = Arrays.copyOf(allNumbers, allNumbers.length + 1);
//Enter the number 4 into the last index of the array
allNumbers[allNumbers.length - 1] = 123456;
System.out.println("New Array -> " + Arrays.toString(allNumbers) + "\n\n");
}
public static void main(String args[])
{
//AddString();
//AddInt();
}
}
| [
"ray.njire23@gmail.com"
] | ray.njire23@gmail.com |
363176ff48ac84293f2d486f37aabdc5654dde27 | 6e6905e5f32d803d8d5edb591210fd0e78dd20a0 | /src/main/java/site/higgs/limiter/semaphore/SemaphoreManager.java | 9578ae44045d52a9cd02a0897579f52b3eefb73a | [
"Apache-2.0"
] | permissive | 986510453/SpringLimiter | 247da439f9f3980f4137b89ada3b2f9a21733e1d | 5b9474e71c3293033ab611829e59e02e4c32cf72 | refs/heads/master | 2020-04-11T11:53:35.062816 | 2018-12-02T06:33:37 | 2018-12-02T06:33:37 | 161,762,697 | 2 | 0 | Apache-2.0 | 2018-12-14T09:33:34 | 2018-12-14T09:33:34 | null | UTF-8 | Java | false | false | 562 | java | package site.higgs.limiter.semaphore;
import site.higgs.limiter.LimiterManager;
import java.util.Collection;
/**
* Created by caocg on 2018/9/23.
*/
public abstract class SemaphoreManager implements LimiterManager<Semaphore> {
public abstract Semaphore getSemaphore(String name);
public abstract Collection<String> getSemaphoreNames();
@Override
public Semaphore getLimiter(String name) {
return getSemaphore(name);
}
@Override
public Collection<String> getLimiterNames() {
return getSemaphoreNames();
}
}
| [
"241939300@qq.com"
] | 241939300@qq.com |
05cfdee226f02819ca1b076ebfe319c67a80a8e7 | ae124491d41fd9bbe79b982f689fd7d255061d9b | /modules/core/src/main/java/org/mycontroller/standalone/offheap/MessageQueueSleepImpl.java | c61aa01175384c4674b8c14ec2a1de1a81e3bfe9 | [
"Apache-2.0"
] | permissive | nino21/mycontroller | 8d1a56256fdff04c16732a00873dac73ed3f31f1 | 1f162e269175980d243aeaab19d34c07a31a57b1 | refs/heads/development | 2021-01-25T14:49:16.492198 | 2018-10-29T14:50:06 | 2018-10-29T14:50:06 | 123,730,094 | 0 | 0 | Apache-2.0 | 2019-03-11T20:25:32 | 2018-03-03T20:48:42 | Java | UTF-8 | Java | false | false | 2,819 | java | /*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* 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.mycontroller.standalone.offheap;
import java.util.ArrayList;
import org.mapdb.HTreeMap;
import org.mycontroller.standalone.AppProperties;
import org.mycontroller.standalone.message.IMessage;
import lombok.extern.slf4j.Slf4j;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 1.2.0
*/
@Slf4j
public class MessageQueueSleepImpl {
private String _nameMap;
HTreeMap<String, ArrayList<IMessage>> _map;
public MessageQueueSleepImpl(String name) {
_nameMap = IMap.MAP_PREFIX + "_msg_sleep_" + name;
_map = OffHeapFactory.store().getHashMap(_nameMap);
if (AppProperties.getInstance().getClearMessagesQueueOnStart()) {
_map.clear();
} else {
_logger.debug("Continuing with offline messages in the map:[{}]", _nameMap);
}
}
public synchronized void clear() {
_map.clear();
}
public synchronized void delete() {
OffHeapFactory.store().delete(_nameMap);
}
public synchronized void put(IMessage message) {
// no need to handle broadcast messages
if (message.getNodeEui().equalsIgnoreCase(IMessage.NODE_BROADCAST_ID)) {
return;
}
updateEmpty(message.getNodeEui());
ArrayList<IMessage> _queue = _map.get(message.getNodeEui());
_queue.add(message);
_logger.debug("Adding [key:{}, size:{}, {}] in to the map", message.getNodeEui(), _queue.size(), message);
}
public synchronized ArrayList<IMessage> get(String key) {
updateEmpty(key);
return _map.get(key);
}
public synchronized ArrayList<IMessage> remove(String key) {
updateEmpty(key);
ArrayList<IMessage> _queue = _map.remove(key);
_logger.debug("Removing[key:{}, size:{}] in to the map", key, _queue.size());
return _queue;
}
public synchronized boolean isEmpty(String key) {
updateEmpty(key);
return _map.get(key).isEmpty();
}
private synchronized void updateEmpty(String key) {
if (_map.get(key) == null) {
_map.put(key, new ArrayList<IMessage>());
}
}
}
| [
"jkandasa@gmail.com"
] | jkandasa@gmail.com |
7f486e2d27e503f80d8fc66d05b339c5bc24a44d | 5b62981e0a3b016c6e32aef3a5d829f3b5ca5c88 | /src/test_Suite/lib/eForms/EForm.java | ea4a32fae4f00e218b88f4e9e60a9d5be9799b7d | [] | no_license | kamaltechnocrat/JMeter | c1f61416fb832d97ad4f09e022a80a2a74c2f01b | cd36cf4185949e8516c446f6705f4144eb6bfb19 | refs/heads/master | 2020-03-15T13:40:43.682421 | 2018-05-04T18:03:34 | 2018-05-04T18:03:34 | 132,172,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,637 | java | /*
* FormsHelper.java
*
* Created on February 1, 2007, 457 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package test_Suite.lib.eForms;
/**
*
* @author mshakshouki
*/
import static watij.finders.SymbolFactory.*;
import java.util.ArrayList;
import java.util.List;
import watij.runtime.ie.IE;
import test_Suite.constants.eForms.*;
import test_Suite.constants.ui.*;
import test_Suite.utils.cases.GeneralUtil;
import test_Suite.utils.ui.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.RandomStringUtils;
//import org.apache.commons.
public class EForm {
private static Log log = LogFactory.getLog(EForm.class);
protected String eFormType = null;
protected String eFormName = null;
protected String eFormSubType = null;
protected String eFormId = null;
protected String eFormFullId = null;
protected String eFormTitle = null;
private String eFormTitles[] = null;
protected String scrumble = null;
protected String preFix = null;
protected String postFix = null;
protected Integer formletCounter = 0;
protected boolean retValue;
protected String primaryOrg = null;
protected String orgAccess = null;
protected String defaultFormlet;
protected String displayProjInfo = "Never";
protected List<Formlet> lstFormlets;
static ArrayList<String> errorSmall;
/************* Constructors ****/
public EForm(String preFix, String eFormName, String postFix, boolean isNew) {
this.preFix = preFix;
this.eFormName = eFormName;
this.postFix = postFix;
this.setEFormFullId(preFix + eFormName + postFix);
this.setEFormId(preFix + eFormName);
}
public EForm() {
this.setScrumble(RandomStringUtils.randomAlphabetic(5));
this.setFormletCounter(0);
// TODO: may change and be set in the test case
this.setPrimaryOrg("G3");
this.setOrgAccess("Public");
}
public EForm(String eFormType, String preFix) {
this.eFormType = eFormType;
this.setScrumble(RandomStringUtils.randomAlphabetic(5));
this.setEFormId(preFix + eFormType);
this.setEFormFullId(this.getEFormId() + "-" + this.getScrumble());
this.setFormletCounter(0);
this.preFix = preFix;
// TODO: may change and be set in the test case
this.setPrimaryOrg("G3");
this.setOrgAccess("Public");
}
public EForm(String eFormType, String eFormSubType, String preFix) {
this.eFormType = eFormType;
this.eFormSubType = eFormSubType;
this.setScrumble(RandomStringUtils.randomAlphabetic(5));
this.setEFormId(preFix + eFormSubType);
this.setEFormFullId(this.getEFormId() + "-" + this.getScrumble());
this.setFormletCounter(0);
this.preFix = preFix;
// TODO: may change and be set in the test case
this.setPrimaryOrg("G3");
this.setOrgAccess("Public");
}
public EForm(String eFormType, String eFormSubType, String preFix,
String postFix) {
this.eFormType = eFormType;
this.eFormSubType = eFormSubType;
this.preFix = preFix;
this.postFix = postFix;
this.setScrumble(RandomStringUtils.randomAlphabetic(5));
this.setEFormId(this.getPreFix() + this.getEFormSubType());
this.setEFormFullId(this.getEFormId() + this.getPostFix());
this.setFormletCounter(0);
// TODO: may change and be set in the test case
this.setPrimaryOrg("G3");
this.setOrgAccess("Public");
}
public boolean createEForm() throws Exception {
log.info("Start Creating eForm Type " + this.eFormType);
retValue = false;
IE ie = IEUtil.getActiveIE();
log.info("Opening Forms List");
ClicksUtil.clickLinks(IClicksConst.openFormsListLnk);
FiltersUtil.filterListByLabel(IFiltersConst.gpa_FormIdent_Lbl, this.eFormFullId,"Exact");
ClicksUtil.clickImage(IClicksConst.newImg);
ie.textField(id, IEFormsConst.formIdentifier_TextField_Id).set(
this.getEFormFullId());
ie.selectList(id, IEFormsConst.formType_SelectList_Id).select(
this.eFormType);
GeneralUtil.takeANap(0.5);
ie.selectList(id, IEFormsConst.formSubType_SelectList_Id).select(
this.eFormSubType);
ie.selectList(id, IEFormsConst.formPrimaryOrg_DropdownField_Id).select(
this.getPrimaryOrg());
ie.selectList(id, IEFormsConst.formOrgAccess_DropdownField_Id).select(
this.getOrgAccess());
if (ie.selectList(id,IEFormsConst.formDeisplyProjectInfo_DropdwonField_Id).exists())
{
ie.selectList(id,IEFormsConst.formDeisplyProjectInfo_DropdwonField_Id).select(this.displayProjInfo);
}
ie.textField(id, "/0:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
if (ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
ClicksUtil.clickButtons(IClicksConst.saveBtn);
GeneralUtil.takeANap(0.5);
if (ClicksUtil.clickButtons(IClicksConst.openFormPlannerBtn)){
retValue = true;
}
return retValue;
}
public void editEFormDetails() throws Exception {
IE ie = IEUtil.getActiveIE();
ie.textField(id, IEFormsConst.formIdentifier_TextField_Id).set(
this.getEFormFullId());
if(ie.selectList(id, IEFormsConst.formType_SelectList_Id).exists()) {
ie.selectList(id, IEFormsConst.formType_SelectList_Id).select(
this.eFormType);
GeneralUtil.takeANap(0.5);
ie.selectList(id, IEFormsConst.formSubType_SelectList_Id).select(
this.eFormSubType);
}
ie.selectList(id, IEFormsConst.formPrimaryOrg_DropdownField_Id).select(
this.getPrimaryOrg());
ie.selectList(id, IEFormsConst.formOrgAccess_DropdownField_Id).select(
this.getOrgAccess());
ie.selectList(id,IEFormsConst.formDeisplyProjectInfo_DropdwonField_Id).select(this.displayProjInfo);
ie.textField(id, "/0:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
if (ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
ClicksUtil.clickButtons(IClicksConst.saveBtn);
GeneralUtil.takeANap(0.5);
ClicksUtil.clickButtons(IClicksConst.saveBtn);
}
/**
* Simplified method to create or update Form
*
* @throws Exception
* Added by Alex Pankov
*/
public void createOrUpdateForm() throws Exception {
IE ie = IEUtil.getActiveIE();
if (GeneralUtil.isButtonExists(IClicksConst.unPublishFormBtn))
ClicksUtil.clickButtons(IClicksConst.unPublishFormBtn);
ie.textField(id, IEFormsConst.formIdentifier_TextField_Id).set(
this.eFormId);
ie.selectList(id, IEFormsConst.formType_SelectList_Id).select(
this.eFormType);
ie.selectList(id, IEFormsConst.formPrimaryOrg_DropdownField_Id).select(
this.primaryOrg);
ie.selectList(id, IEFormsConst.formOrgAccess_DropdownField_Id).select(
this.orgAccess);
ie.textField(id, "/0:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
if (ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/1:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/2:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.exists()) {
ie.textField(id, "/3:" + IEFormsConst.formTitle_TextField_Id + "/")
.set(this.getEFormTitle());
}
if (GeneralUtil.isButtonExists(IClicksConst.publishFormBtn)){
ClicksUtil.clickButtons(IClicksConst.publishFormBtn);
GeneralUtil.takeANap(0.5);
ClicksUtil.clickButtons(IClicksConst.publishFormBtn);
}
else {
ClicksUtil.clickButtons(IClicksConst.saveBtn);
GeneralUtil.takeANap(0.5);
ClicksUtil.clickButtons(IClicksConst.saveBtn);
}
}
public boolean publishForm(String defaultFormlet) throws Exception {
retValue = false;
IE ie = IEUtil.getActiveIE();
// are you still in the Form planner?
if (ie.link(title, IClicksConst.eForm_eFormDetails_Title_lnk).exists()
|| ie.htmlElement(title,
IClicksConst.eForm_eFormDetails_Title_lnk).exists()) {
ClicksUtil
.clickLinksByTitle(IClicksConst.eForm_eFormDetails_Title_lnk);
retValue = true;
} else {
// Start from the Forms List
ClicksUtil.clickLinks(IClicksConst.openFormsListLnk);
FiltersUtil.filterListByLabel(IFiltersConst.gpa_FormIdent_Lbl,
this.eFormId,"Exact");
// IF there is More pages
for (Integer x = 2; x == 20; x++) {
if (TablesUtil.findInTable(ITablesConst.formsTableId,
this.eFormId)) {
ClicksUtil.clickLinks(this.eFormId);
ClicksUtil
.clickLinksByTitle(IClicksConst.eForm_eFormDetails_Title_lnk);
retValue = true;
break;
} else {
if (ie.link(text, x.toString()).exists()) {
ClicksUtil.clickLinks(x.toString());
} else {
log.debug("could not find Form");
break;
}
}
}
}
if (retValue) {
ie.selectList(id, IEFormsConst.formDefaultFormlet_SelectList_Id)
.select(defaultFormlet);
if (!ClicksUtil.clickButtons(IClicksConst.publishFormBtn)){
log.error("Form cannot be published");
return false;
}
log.info("Form has been published");
}
return retValue;
}
public boolean publishEFormAndCheckErrors(String defaultFormlet)
throws Exception {
IE ie = IEUtil.getActiveIE();
errorSmall = null;
ClicksUtil.clickLinksByTitle(IClicksConst.eForm_eFormDetails_Title_lnk);
ie.selectList(id, IEFormsConst.formDefaultFormlet_SelectList_Id)
.select(defaultFormlet);
ClicksUtil.clickButtons(IClicksConst.publishFormBtn);
if (GeneralUtil.isButtonExistsByValue(IClicksConst.unPublishFormBtn)) {
return true;
}
errorSmall = GeneralUtil.checkForErrorMessages();
if (errorSmall != null && !errorSmall.isEmpty()) {
for (String string : errorSmall) {
log.error("Validation error: " + string);
}
}
return false;
}
public boolean unPublishForm() throws Exception {
ClicksUtil.clickLinksByTitle("e.Form Details");
if (GeneralUtil.isButtonExistsByValue(IClicksConst.unPublishFormBtn)) {
ClicksUtil.clickButtons(IClicksConst.unPublishFormBtn);
if (GeneralUtil.isButtonExistsByValue(IClicksConst.publishFormBtn)) {
ClicksUtil.clickButtons(IClicksConst.backBtn);
return true;
}
}
ClicksUtil.clickButtons(IClicksConst.backBtn);
return false;
}
// #####*************End of etc****************************
/**
* @return the eFormFullId
*/
public String getEFormFullId() {
return eFormFullId;
}
/**
* @param formFullId
* the eFormFullId to set
*/
public void setEFormFullId(String formFullId) {
eFormFullId = formFullId;
}
public String getEFormName(){
return eFormName;
}
// public void setEFormName(String eFormName){
//
// eFormName = eFormName;
// }
/**
* @return the defaultFormlet
*/
public String getDefaultFormlet() {
return defaultFormlet;
}
/**
* @param defaultFormlet
* the defaultFormlet to set
*/
public void setDefaultFormlet(String defaultFormlet) {
this.defaultFormlet = defaultFormlet;
}
/**
* @return the formletCounter
*/
public Integer getFormletCounter() {
return formletCounter;
}
/**
* @param formletCounter
* the formletCounter to set
*/
public void setFormletCounter(Integer formletCounter) {
this.formletCounter = formletCounter;
}
public String getEFormId() {
return eFormId;
}
public void setEFormId(String formId) {
eFormId = formId;
}
public String getEFormType() {
return eFormType;
}
public void setEFormType(String formType) {
eFormType = formType;
}
public String getEFormTitle() {
return eFormTitle;
}
public void setEFormTitle(String formTitle) {
eFormTitle = formTitle;
}
public String getOrgAccess() {
return orgAccess;
}
public void setOrgAccess(String orgAccess) {
this.orgAccess = orgAccess;
}
public String getPrimaryOrg() {
return primaryOrg;
}
public void setPrimaryOrg(String primaryOrg) {
this.primaryOrg = primaryOrg;
}
public String[] getEFormTitles() {
return eFormTitles;
}
public void setEFormTitles(String[] formTitles) {
eFormTitles = formTitles;
}
/**
* @return the eFormSubType
*/
public String getEFormSubType() {
return eFormSubType;
}
/**
* @param formSubType
* the eFormSubType to set
*/
public void setEFormSubType(String formSubType) {
eFormSubType = formSubType;
}
/**
* @return the scrumble
*/
public String getScrumble() {
return scrumble;
}
/**
* @param scrumble
* the scrumble to set
*/
public void setScrumble(String scrumble) {
this.scrumble = scrumble;
}
/**
* @return the postFix
*/
public String getPostFix() {
return postFix;
}
/**
* @param postFix
* the postFix to set
*/
public void setPostFix(String postFix) {
this.postFix = postFix;
}
/**
* @return the preFix
*/
public String getPreFix() {
return preFix;
}
/**
* @param preFix
* the preFix to set
*/
public void setPreFix(String preFix) {
this.preFix = preFix;
}
/**
* @return the lstFormlets
*/
public List<Formlet> getLstFormlets() {
return lstFormlets;
}
/**
* @param lstFormlets the lstFormlets to set
*/
public void setLstFormlets(List<Formlet> lstFormlets) {
this.lstFormlets = lstFormlets;
}
/**
* @return the displayProjInfo
*/
public String getDisplayProjInfo() {
return displayProjInfo;
}
/**
* @param displayProjInfo the displayProjInfo to set
*/
public void setDisplayProjInfo(String displayProjInfo) {
this.displayProjInfo = displayProjInfo;
}
}
| [
"k.sharma@csdc-lan.csdcsystems.com"
] | k.sharma@csdc-lan.csdcsystems.com |
629b7746a804e7a105eda5c6830d3077299e5fb3 | c941a61f445e41627319d190719abab521a96174 | /vetclinic/src/main/java/ua/iot/lviv/Main.java | 908176d47034e53b36f4fbb096dfac84c41d3d9d | [] | no_license | smallpoxlviv/3s_db_lab_5 | 49102cddad162671801427fac6a036fb1f5f5207 | 8c3ad34734a379152c50eaa48999c0e84521ddae | refs/heads/main | 2023-02-01T16:07:17.266978 | 2020-12-11T17:32:01 | 2020-12-11T17:32:01 | 317,036,060 | 0 | 0 | null | 2020-12-11T17:28:15 | 2020-11-29T20:22:02 | null | UTF-8 | Java | false | false | 570 | java | package ua.iot.lviv;
import ua.iot.lviv.persistence.ConnectionManager;
import ua.iot.lviv.view.MyView;
public class Main {
public static void main(final String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
new MyView().show();
} catch (ClassNotFoundException ex) {
System.out.println("MySql Driver is not loaded");
} finally {
ConnectionManager.closeSession();
ConnectionManager.closeSessionFactory();
System.out.println("Good Bye!");
}
}
}
| [
"bogdan.bedrylo@gmail.com"
] | bogdan.bedrylo@gmail.com |
7df80ad9d32f2613a4e8417d82934367780216c1 | 447698e4348550abed6a8732e42cf163d43b78e8 | /app/src/main/java/KotlinAgency/XiaomingFather.java | f9b7c44e1db8750fde25a6f869fe9d6677063ffc | [] | no_license | aWhalefall/andoridkotlin | c747003e231df45f95d15063b8f4bd1d03d3110a | 50eead1f5f71fe71df92782b9b09aef2ba7bdba8 | refs/heads/master | 2021-08-14T17:26:31.544003 | 2017-11-16T10:13:27 | 2017-11-16T10:13:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 128 | java | package KotlinAgency;
/**
* Created by weichyang on 2017/11/2.
*/
public interface XiaomingFather {
void payMoney();
}
| [
"279642707@qq.com"
] | 279642707@qq.com |
7e81e8dc45496bb72a5af01be01e0cb347483a19 | fbdb3a00076e895c190919081822feebc539db1e | /src/java/minhtn/tblCar/TblCarDTO.java | e7694ada675dd96714316d4f3bb53d4973da25a8 | [] | no_license | minh2ws/J3LP0015_CarRental | c4cac9dee1c31339b60c6af18d7fd0d7fe277504 | 80ab8a8a0fdcf8791bdd3350cb59753ac3f4c17d | refs/heads/main | 2023-04-03T02:46:28.868032 | 2021-04-11T07:39:06 | 2021-04-11T07:39:06 | 356,799,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,260 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minhtn.tblCar;
import java.io.Serializable;
import java.sql.Date;
/**
*
* @author minhv
*/
public class TblCarDTO implements Serializable {
private String carID;
private String carName;
private String image;
private String color;
private Date year;
private double price;
private int quantity;
private String description;
private String categoryId;
public TblCarDTO() {
}
public TblCarDTO(String carID, String carName, String image, String color, Date year, double price, int quantity, String description, String categoryId) {
this.carID = carID;
this.carName = carName;
this.image = image;
this.color = color;
this.year = year;
this.price = price;
this.quantity = quantity;
this.description = description;
this.categoryId = categoryId;
}
/**
* @return the carID
*/
public String getCarID() {
return carID;
}
/**
* @param carID the carID to set
*/
public void setCarID(String carID) {
this.carID = carID;
}
/**
* @return the carName
*/
public String getCarName() {
return carName;
}
/**
* @param carName the carName to set
*/
public void setCarName(String carName) {
this.carName = carName;
}
/**
* @return the image
*/
public String getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return the year
*/
public Date getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(Date year) {
this.year = year;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the categoryId
*/
public String getCategoryId() {
return categoryId;
}
/**
* @param categoryId the categoryId to set
*/
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}
| [
"trnnhtminht1709@gmail.com"
] | trnnhtminht1709@gmail.com |
aee01637bddc291a5cb2698e8640cedb6e0cf2d7 | d7c5f605608eb9b31a733b85eb7a24ddac3ca736 | /Java 2 Projects/tellepet_Assignment08/src/SerializableObjectsPackage/ProgrammerMon.java | 5393ca59960ae508a4dc52aef55fef0b4ea9324f | [] | no_license | navett52/Java-Repo | 590ecaa79e813b5b9210cf32e3d4c2bdb6559407 | 4c3e915f8f907af26edb3cd3bd2215db84bab31e | refs/heads/master | 2021-01-01T18:21:21.436951 | 2017-07-25T17:59:59 | 2017-07-25T17:59:59 | 98,320,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,544 | java | /******************************************************
* Evan Tellep *
* Assignment 08 *
* 03/10/2016 *
* IT2045C (Computer Programming 2) *
* Class used to define a programmer monster *
* Ref: Friendship bread from Bill(what was posted) *
******************************************************/
package SerializableObjectsPackage;
import java.io.Serializable;
import java.util.ArrayList;
public class ProgrammerMon implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3054587322009948232L;
// the list of languages the monster knows
private ArrayList<String> Languages = new ArrayList<String>();
//The monster's given name
private String name;
//The monster's height in inches
private int heightInches;
//The monster's weight in pounds
private int weightPounds;
//How much the monster makes every hour
private double hourlyRate;
//The highest degree the monster has earned
private String highestDegreeEarned;
//Whether or not the monster wears glasses
private Boolean wearsGlasses;
/**
* Constructs a monster based on parameters entered
* @param name Name of the monster
* @param heightInches Height of the monster in inches
* @param weightPounds Weight of the monster in pounds
* @param hourlyRate How much the monster makes every hour
* @param highestDegreeEarned The highest degree the monster has earned
* @param wearsGlasses Whether the monster wears glasses or not
*/
public ProgrammerMon(String name, int heightInches, int weightPounds, double hourlyRate, String highestDegreeEarned, Boolean wearsGlasses ) {
this.name = name;
this.heightInches = heightInches;
this.weightPounds = weightPounds;
this.hourlyRate = hourlyRate;
this.highestDegreeEarned = highestDegreeEarned;
this.wearsGlasses = wearsGlasses;
}
/**
* Logic that compares the attributes of the monsters and determines if one is better than the other
* @param opponent The monster to fight the current monster
* @return True if the current object wins, false if the opponent wins
*/
public boolean Fight(ProgrammerMon opponent) {
//Default battleForce for each programmer starts at 100
int thisBattleForce = 100;
int opponentBattleForce = 100;
//If the current object's name contains any of these "cool letters" making their name cool the current object gets +1 battle force for each "cool letter"
for (int i = 0; i < this.name.length(); i++) {
if (this.name.charAt(i) == 'x' || this.name.charAt(i) == 'z' || this.name.charAt(i) == 'v' || this.name.charAt(i) == 'q' ||
this.name.charAt(i) == 'n' || this.name.charAt(i) == 'j' || this.name.charAt(i) == 'e' || this.name.charAt(i) == 'X' ||
this.name.charAt(i) == 'Z' || this.name.charAt(i) == 'V' || this.name.charAt(i) == 'Q' || this.name.charAt(i) == 'N' ||
this.name.charAt(i) == 'J' || this.name.charAt(i) == 'E')
{
thisBattleForce ++;
}
thisBattleForce ++;
}
//If the opponent's name contains any of these "cool letters" making their name cool the opponent gets +1 battle force for each "cool letter"
for (int i = 0; i < opponent.name.length(); i++) {
if (opponent.name.charAt(i) == 'x' || opponent.name.charAt(i) == 'z' || opponent.name.charAt(i) == 'v' || opponent.name.charAt(i) == 'q' ||
opponent.name.charAt(i) == 'n' || opponent.name.charAt(i) == 'j' || opponent.name.charAt(i) == 'e' || opponent.name.charAt(i) == 'X' ||
opponent.name.charAt(i) == 'Z' || opponent.name.charAt(i) == 'V' || opponent.name.charAt(i) == 'Q' || opponent.name.charAt(i) == 'N' ||
opponent.name.charAt(i) == 'J' || opponent.name.charAt(i) == 'E')
{
opponentBattleForce ++;
}
opponentBattleForce ++;
}
//Whichever object is taller receives +5 to their battleForce
if (this.heightInches > opponent.heightInches) {
thisBattleForce += 5;
} else {
opponentBattleForce += 5;
}
//Whichever object weighs more receives +5 to their battleForce
if (this.weightPounds > opponent.weightPounds) {
thisBattleForce += 5;
} else {
opponentBattleForce += 5;
}
//Takes whichever object's hourly rate is higher and adds the difference in hourlyRates to that object's battleForce
if (this.hourlyRate > opponent.hourlyRate) {
thisBattleForce = thisBattleForce + ((int)this.hourlyRate - (int)opponent.hourlyRate);
} else {
opponentBattleForce = opponentBattleForce + ((int)opponent.hourlyRate - (int)this.hourlyRate);
}
//Adds more to this object's battleForce depending on what that highest degree earned is
if (this.highestDegreeEarned == "High School Diploma") {
thisBattleForce += 1;
} else if (this.highestDegreeEarned == "Associates Degree") {
thisBattleForce += 3;
} else if (this.highestDegreeEarned == "Bachelor's Degree") {
thisBattleForce += 5;
} else if (this.highestDegreeEarned == "Master's Degree") {
thisBattleForce += 8;
} else if (this.highestDegreeEarned == "Doctorate" || this.highestDegreeEarned == "PhD") {
thisBattleForce += 10;
}
//Adds more to the opponent's battleForce depending on what that highest degree earned is
if (opponent.highestDegreeEarned == "High School Diploma") {
opponentBattleForce += 1;
} else if (opponent.highestDegreeEarned == "Associates Degree") {
opponentBattleForce += 3;
} else if (opponent.highestDegreeEarned == "Bachelor's Degree") {
opponentBattleForce += 5;
} else if (opponent.highestDegreeEarned == "Master's Degree") {
opponentBattleForce += 8;
} else if (opponent.highestDegreeEarned == "Doctorate" || this.highestDegreeEarned == "PhD") {
opponentBattleForce += 10;
}
//If either object wears glasses they get +5 to their battleForce
if (this.wearsGlasses == true) {
thisBattleForce += 5;
} else if (opponent.wearsGlasses == true) {
opponentBattleForce += 5;
}
if (this.getLanguages() != null) {
//Adds one to this object's battleForce for every language known, and adds +3 to it's battleForce for every popular* language it knows
//* http://www.codingdojo.com/blog/9-most-in-demand-programming-languages-of-2016/
for (int i = 0; i < this.Languages.size(); i++) {
if (this.Languages.get(i) == "Java" || this.Languages.get(i) == "SQL" || this.Languages.get(i) == "Javascript" ||
this.Languages.get(i) == "C#" || this.Languages.get(i) == "Python" || this.Languages.get(i) == "C++" ||
this.Languages.get(i) == "PHP" || this.Languages.get(i) == "IOS" || this.Languages.get(i) == "Ruby")
{
thisBattleForce += 3;
}
thisBattleForce ++;
}
}
if (opponent.getLanguages() != null) {
//Adds one to the opponent's battleForce for every language known, and adds +3 to the opponent's battleForce for every popular* language it knows
//* http://www.codingdojo.com/blog/9-most-in-demand-programming-languages-of-2016/
for (int i = 0; i < opponent.Languages.size(); i++) {
if (opponent.Languages.get(i) == "Java" || opponent.Languages.get(i) == "SQL" || opponent.Languages.get(i) == "Javascript" ||
opponent.Languages.get(i) == "C#" || opponent.Languages.get(i) == "Python" || opponent.Languages.get(i) == "C++" ||
opponent.Languages.get(i) == "PHP" || opponent.Languages.get(i) == "IOS" || opponent.Languages.get(i) == "Ruby")
{
opponentBattleForce += 3;
}
opponentBattleForce ++;
}
}
System.out.println(this.name + "'s Battle Force is " + thisBattleForce);
System.out.println(opponent.name + "'s Battle Force is " + opponentBattleForce);
//Determines the winner by comparing battleForces
if (thisBattleForce < opponentBattleForce) {
return false;
}
return true;
}
// Todo write gets and sets for private members of the class.
/**
* Get languages list
* @return list of languages
*/
public ArrayList<String> getLanguages() {
return Languages;
}
/**
* Get the amount of money the monster makes hourly
* @return The amount of money the monster makes hourly
*/
public double getHourlyRate() {
return hourlyRate;
}
/**
* Get the highest degree the monster has earned
* @return The highest degree earned
*/
public String getHighestDegreeEarned() {
return highestDegreeEarned;
}
/**
* Get whether or not the monster wears glasses
* @return true if the monster wears glasses, false otherwise
*/
public Boolean getWearsGlasses() {
return wearsGlasses;
}
/**
* Get the name of the monster
* @return The name of the monster
*/
public String getName() {
return name;
}
/**
* Get the height of the monster in inches
* @return The height of the monster
*/
public int getHeightInches() {
return heightInches;
}
/**
* Get the weight of the monster in pounds
* @return The weight of the monster
*/
public int getWeightPounds() {
return weightPounds;
}
}
| [
"evantellep@yahoo.com"
] | evantellep@yahoo.com |
9ace2ec8bdca0d3172282b168d8097f1dfb26500 | b0a3f31816ad429c075c28d4f5e30d7ab42452a7 | /backend/src/main/java/com/devsuperior/dscatalog/resources/exceptions/ValidationError.java | 0b6ac5bdeb4f39090f12656ee75ee6468be28e3d | [] | no_license | Geraldo-git/dscatalog-devsuperior-aula | 790c997b933a1660679591abd72b4de19d990062 | 0412292d60b1e1f25ed5250e6f4d8ef9d4257afa | refs/heads/main | 2023-08-24T14:39:22.036893 | 2021-10-06T13:48:56 | 2021-10-06T13:48:56 | 406,493,760 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 451 | java | package com.devsuperior.dscatalog.resources.exceptions;
import java.util.ArrayList;
import java.util.List;
public class ValidationError extends StandardError {
private static final long serialVersionUID = 1L;
private List<FieldMessage> errors = new ArrayList<>();
public List<FieldMessage> getErrors() {
return errors;
}
public void addError(String fieldName, String message) {
errors.add(new FieldMessage (fieldName,message));
}
}
| [
"laboratorio.inicial@gmail.com"
] | laboratorio.inicial@gmail.com |
1cb4ed333b563cc35bb0586e359896bfe723426f | 1c31b9ec95619aa5573221614902cc2f9eeceb32 | /koreaweather4j/src/kr/ac/chungbuk/bigdata/weather/main/DailyScrapSimpleWeatherData.java | 615d517fb2dd94a3905a95ea3f1d83602b646ed0 | [] | no_license | SuperMartin/KoreaWeather4j | 030e243458bc88d172b0b6583365ae2dbcda9613 | 340fb3bd5389d3179eaef5454050f28f664df010 | refs/heads/master | 2021-01-01T18:37:46.168393 | 2016-10-26T14:04:42 | 2016-10-26T14:04:42 | 20,653,089 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,957 | java | package kr.ac.chungbuk.bigdata.weather.main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kr.ac.chungbuk.bigdata.weather.manager.DatabaseConnectionPoolManager2;
import kr.ac.chungbuk.bigdata.weather.manager.HttpProtocolManager2;
import kr.ac.chungbuk.bigdata.weather.model.KoreaWeatherSimpleModel;
import kr.ac.chungbuk.bigdata.weather.util.ConfigUtil;
import kr.ac.chungbuk.bigdata.weather.util.DateGenerator;
import kr.ac.chungbuk.bigdata.weather.util.GeoLocationManager;
import kr.ac.chungbuk.bigdata.weather.util.MarioService;
/**
* 어제 00시부터 23시 날씨데이터를 가져옴
*
* @author HYUNA,Chihwan Choi(charisma0629@gmail.com)
*
*/
public class DailyScrapSimpleWeatherData {
public void getData() throws FileNotFoundException, IOException, ParseException, InterruptedException {
Properties prop = ConfigUtil.getXMLProperties("koreaweather4j.xml");
// CLI APACHE PR OJECT
Logger logger = LoggerFactory.getLogger(DailyScrapSimpleWeatherData.class);
logger.info("{}", "starting application");
logger.info("{}", "Initializing GeoLocationManager");
GeoLocationManager.initialize();
logger.info("{}", "Initializing GeoLocationManager...OK");
// AWS Data를 받아올 날짜 입력 (YYYYMMDDHHMM). null = 현재.
// 추가해야 할 사항 : 1.과거 데이터 수집 시, From~To 기능 추가 / 2.일정 간격으로 계속 수집하는 기능 추가
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH");
long yesterday = System.currentTimeMillis() - 1000 * 60 * 60 * 24;
Date date = new Date(yesterday);
String dateString = sdf.format(date);
// System.out.println(dateString);
dateString = dateString.subSequence(0, 11) + "00.00.00";
Date fromDate = sdf.parse(dateString);
Date toDate = new Date((fromDate.getTime() + 1000 * 60 * 60 * 24));
// System.out.println(sdf.format(fromDate));
// System.out.println(sdf.format(toDate));
List<Date> dateList = DateGenerator.doDateGenerateYYYYMMDDHH(sdf.format(fromDate), sdf.format(toDate), true);
for (Date inputDate : dateList) {
//
HttpProtocolManager2 httpMgr = new HttpProtocolManager2();
String httpRequest = httpMgr.getHttpURL(sdf.format(inputDate));
String responseHtml = httpMgr.getWeatherData(httpRequest);
List<KoreaWeatherSimpleModel> koreaWeatherDataList = httpMgr.getKoreaSimpleWeatherDataList(responseHtml);
// db에 저장. 현재 MySQL로 저장 가능한 상태.
// 추가해야 할 사항 : 1.Create, Update 기능 추가 / 2.MS_SQL 연동 추가
DatabaseConnectionPoolManager2 database = new DatabaseConnectionPoolManager2(false,
prop.getProperty("IPADDRESS"), prop.getProperty("PORT"), prop.getProperty("DATABASENAME"),
prop.getProperty("USER"), prop.getProperty("PASSWORD"), prop.getProperty("TABLENAME"));
long start = System.currentTimeMillis();
database.persistSimpleWeatherData(koreaWeatherDataList);
long end = System.currentTimeMillis();
System.out.println("** Inserted Recoreds : " + koreaWeatherDataList.size() + " Working Time : "
+ (end - start) + " ms ");
try {
Thread.sleep(3000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
System.exit(0);
// String inputDate = "201406201800"; // ex = "201405201800"
}
public static void main(String[] args) {
MarioService.printMarioAsciiPictureR2();
DailyScrapSimpleWeatherData crawler = new DailyScrapSimpleWeatherData();
try {
crawler.getData();
} catch (IOException | ParseException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"ruserive@gmail.com"
] | ruserive@gmail.com |
7a4244fc6870d7c493f66bde2aaecee07bf925d2 | d905c9cad548390506661bfc5cb57695c271b320 | /app/src/main/java/tr/edu/ufuk/siberguvenlikegitimi/genericList/GirisGenericList.java | 5206008b15588f699ba3781bb08085694e7c0071 | [] | no_license | mustafaergan/Siber-Guvenlik-Egitimi | 9e068b1a7b06653b9af0e0bfe7ce0a9005b449a7 | 24bb26dc665a387ec7c4e14f023c7eb31b73535b | refs/heads/master | 2020-05-30T15:52:16.625031 | 2019-06-02T10:09:10 | 2019-06-02T10:09:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,222 | java | package tr.edu.ufuk.siberguvenlikegitimi.genericList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import tr.edu.ufuk.siberguvenlikegitimi.R;
import tr.edu.ufuk.siberguvenlikegitimi.entity.ImageGenericList;
/**
* Created by mustafaergan.
*/
public class GirisGenericList extends BaseAdapter {
private LayoutInflater layoutInflater;
List<ImageGenericList> imageGenericListList;
public GirisGenericList(Activity activity, List<ImageGenericList> imageGenericListList) {
this.layoutInflater = (LayoutInflater)
activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageGenericListList = imageGenericListList;
}
@Override
public int getCount() {
return imageGenericListList.size();
}
@Override
public Object getItem(int position) {
return imageGenericListList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView;
myView = layoutInflater.inflate(R.layout.generic_liste_image,null);
TextView textViewName =
(TextView) myView.findViewById(R.id.girisListName);
ImageView ımageView =
(ImageView)myView.findViewById(R.id.girisListImage);
ImageGenericList person = this.imageGenericListList.get(position);
textViewName.setText(person.getName());
for (ImageGenericList imageGenericList : imageGenericListList) {
if (imageGenericList.getImageNumber() == 0) {
ımageView.setImageResource(R.drawable.giris0);
} else if (imageGenericList.getImageNumber() == 1) {
ımageView.setImageResource(R.drawable.giris1);
} else if (imageGenericList.getImageNumber() == 2) {
ımageView.setImageResource(R.drawable.giris2);
}
}
return myView;
}
}
| [
"mustafaergan@gmail.com"
] | mustafaergan@gmail.com |
0e35b87ca8d929540a5900d81ff25643da743e5e | 7f9fa8221b7bc975beb5abc6c8add3028a6240f6 | /java-demo-blahblah/src/main/java/com/zhangshixu/java/demo/blahblah/reflection/TestFields.java | 4ccfde92e5081e4c74aa6f60193467db7384f95f | [] | no_license | darkhorsezsx/java-demo | 9c9f3a7a8f0c8dc54fdb2a9db9e534a0ece64718 | e43f5c5c91a85cc40de7d1d114fcec7e246183a6 | refs/heads/master | 2021-05-03T17:25:37.727847 | 2018-02-06T11:30:09 | 2018-02-06T11:30:09 | 120,444,707 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,926 | java | package com.zhangshixu.java.demo.blahblah.reflection;
import com.zhangshixu.java.demo.blahblah.reflection.entity.Animal;
import com.zhangshixu.java.demo.blahblah.reflection.entity.Person;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.*;
/**
* This is {@link TestFields}.
*
* @author Zhang Shixu
* @since 0.0.1
*/
public class TestFields {
public static void main(String[] args) {
Animal animal = new Animal("dog", 12, "zsx");
Animal animal2 = new Animal("cat", 12, "sss");
Person person = new Person("Jack", animal);
Person person2 = new Person("Jack", animal);
// System.out.println(contrastObj(animal, animal2));
System.out.println(compareFieldsV3(person, person2, new String[]{}));
}
/**
* demo1
* @param obj1
* @param obj2
* @return
*/
public static boolean contrastObj(Object obj1, Object obj2) {
boolean isEquals = true;
if (obj1 instanceof Animal && obj2 instanceof Animal ) {
Animal pojo1 = (Animal) obj1;
Animal pojo2 = (Animal) obj2;
List textList = new ArrayList<String>();
try {
Class clazz = pojo1.getClass();
Field[] fields = pojo1.getClass().getDeclaredFields();
for (Field field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = getMethod.invoke(pojo2);
if (!o1.toString().equals(o2.toString())) {
isEquals = false;
textList.add(getMethod.getName() + ":" + "false");
} else {
textList.add(getMethod.getName() + ":" + "true");
}
}
} catch (Exception e) {
}
for (Object object : textList) {
System.out.println(object);
}
}
return isEquals;
}
/**
* demo2
* @param obj1
* @param obj2
* @param ignoreArr
* @return
*/
public static Map<String, List<Object>> compareFields(Object obj1, Object obj2, String[] ignoreArr) {
try{
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
List<String> ignoreList = null;
if(ignoreArr != null && ignoreArr.length > 0){
ignoreList = Arrays.asList(ignoreArr);
}
if (obj1.getClass() == obj2.getClass()) {// 只有两个对象都是同一类型的才有可比性
Class clazz = obj1.getClass();
// 获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {// 这里就是所有的属性了
String name = pd.getName();// 属性名
if(ignoreList != null && ignoreList.contains(name)){// 如果当前属性选择忽略比较,跳到下一次循环
continue;
}
Method readMethod = pd.getReadMethod();// get方法
// 在obj1上调用get方法等同于获得obj1的属性值
Object o1 = readMethod.invoke(obj1);
// 在obj2上调用get方法等同于获得obj2的属性值
Object o2 = readMethod.invoke(obj2);
if(o1 == null && o2 == null){
continue;
}else if(o1 == null && o2 != null){
List<Object> list = new ArrayList<Object>();
list.add(o1);
list.add(o2);
map.put(name, list);
continue;
}
if (!o1.equals(o2)) {// 比较这两个值是否相等,不等就可以放入map了
List<Object> list = new ArrayList<Object>();
list.add(o1);
list.add(o2);
map.put(name, list);
}
}
}
return map;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* demo3
* @param obj1
* @param obj2
* @param ignoreArr
* @return
*/
public static Map<String, Map<String,Object>> compareFieldsV3(Object obj1, Object obj2, String[] ignoreArr) {
try{
Map<String, Map<String,Object>> map = new HashMap<>();
Map<String, Object> objMap1 = new HashMap<>();
Map<String, Object> objMap2 = new HashMap<>();
map.put("former", objMap1);
map.put("latter", objMap2);
List<String> ignoreList = null;
if(ignoreArr != null && ignoreArr.length > 0){
ignoreList = Arrays.asList(ignoreArr);
}
if (obj1.getClass() == obj2.getClass()) {// 只有两个对象都是同一类型的才有可比性
Class clazz = obj1.getClass();
// 获取object的属性描述
PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {// 这里就是所有的属性了
String name = pd.getName();// 属性名
if(ignoreList != null && ignoreList.contains(name)){// 如果当前属性选择忽略比较,跳到下一次循环
continue;
}
Method readMethod = pd.getReadMethod();// get方法
// 在obj1上调用get方法等同于获得obj1的属性值
Object o1 = readMethod.invoke(obj1);
// 在obj2上调用get方法等同于获得obj2的属性值
Object o2 = readMethod.invoke(obj2);
if(o1 == null && o2 == null){
continue;
}else if(o1 == null && o2 != null){
objMap1.put(name, o1);
objMap2.put(name, o2);
continue;
}
if (!o1.equals(o2)) {// 比较这两个值是否相等,不等就可以放入map了
objMap1.put(name, o1);
objMap2.put(name, o2);
}
}
}
return map;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
| [
"zhangshixu@inspur.com"
] | zhangshixu@inspur.com |
53f8b643034c2460225882b66733b3acb2caa6a3 | 4f55eb5487c62936502153e799b9ab21687d265b | /hihsoft-sso/JavaSource/com/hihframework/core/utils/StringHelpers.java | 007ee36d01885fa527326392f0539d202cad8b2c | [
"Apache-2.0"
] | permissive | qinglinGG/sso | 00edd3ac8723a1c60039b3e4d3b87531baa9a18f | d5867b6eab25015e146431f1c5927160652e7a08 | refs/heads/master | 2021-01-20T01:35:18.900427 | 2017-04-26T02:35:48 | 2017-04-26T02:35:48 | 89,302,895 | 0 | 0 | null | 2017-04-25T01:21:29 | 2017-04-25T01:21:29 | null | UTF-8 | Java | false | false | 26,668 | java | /**
* Copyright (c) 2013-2015 www.javahih.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.hihframework.core.utils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang.RandomStringUtils;
/**
* <p> Title: 字符处理辅助类:主要处理字符的各种操作</p>
* <p> Description:字符追加、字符替换、字符编码转换、各种类型的转化</p>
* <p> Copyright: Copyright (c) 2013 </p>
* <p> Company:hihsoft.co.,ltd </p>
*
* @author hihsoft.co.,ltd
* @version 1.0
*/
public class StringHelpers
{
/** The Constant chr. */
public final static char[] chr = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
// 将字符串转换成BigDecimal类型
/**
* To big decimal.
*
* @param bigdecimal the bigdecimal
* @return the big decimal
*/
public static BigDecimal toBigDecimal(final String bigdecimal)
{
if (bigdecimal == null)
{
return null;
}
if (bigdecimal.length() < 1)
{
return null;
}
try
{
return new BigDecimal(bigdecimal);
}
catch (final Exception e)
{
return null;
}
}
// 1 -> '0001'
/**
* Gets the number string.
*
* @param i the i
* @param length the length
* @return the number string
*/
public static String getNumberString(final int i, final int length)
{
String sret = String.valueOf(i);
final int lack = length - sret.length();
if (lack == 0)
{
return sret;
}
if (lack > 0)
{
for (int x = 0; x < lack; x++)
sret = "0" + sret;
}
else
{
sret = sret.substring(0 - lack, sret.length());
}
return sret;
}
// 1 -> '0001'
/**
* Gets the number string.
*
* @param i the i
* @param length the length
* @return the number string
*/
public static String getNumberString(final long i, final int length)
{
String sret = String.valueOf(i);
final int lack = length - sret.length();
if (lack == 0)
{
return sret;
}
if (lack > 0)
{
for (int x = 0; x < lack; x++)
sret = "0" + sret;
}
else
{
sret = sret.substring(0 - lack, sret.length());
}
return sret;
}
// 将字符串转换成符合HTML页面以及其表单显示的字符串
/**
* To form input.
*
* @param oldValue the old value
* @return the string
*/
public static String toFormInput(final String oldValue)
{
if (oldValue == null)
{
return null;
}
String szTemp = "";
final int len = oldValue.length();
for (int i = 0; i < len; i++)
switch (oldValue.charAt(i))
{
case 34: // '"'
szTemp = szTemp + """;
break;
default:
szTemp = szTemp + oldValue.charAt(i);
break;
}
return szTemp;
}
// 将字符串中的oldtext用newtext来替换掉
// 如:"hello world"中的" "用"_"替换,就成了:"hello_world"
/**
* Replace.
*
* @param source the source
* @param oldtext the oldtext
* @param newtext the newtext
* @return the string
*/
public static String Replace(final String source, final String oldtext, final String newtext)
{
if ((source == null) || (oldtext == null) || (newtext == null))
{
return null;
}
String temp1 = source;
String temp = "";
for (int index = temp1.indexOf(oldtext); index >= 0; index = temp1.indexOf(oldtext))
{
temp = temp + temp1.substring(0, index) + newtext;
temp1 = temp1.substring(index + oldtext.length(), temp1.length());
}
temp = temp + temp1;
return temp;
}
// 将字符串形式的浮点数值转换成浮点数,如:"234.7"-->234.7
// 可以处理象"12,345.7"的形式
/**
* To float.
*
* @param value the value
* @return the float
*/
public static float toFloat(final String value)
{
if (value == null)
{
return 0.0F;
}
String szTemp = "";
for (int i = 0; i < value.length(); i++)
if (value.charAt(i) != ',')
{
szTemp = szTemp + value.charAt(i);
}
try
{
final float f = Float.parseFloat(szTemp);
return f;
}
catch (final NumberFormatException e)
{
final float f1 = 0.0F;
return f1;
}
}
// 将字符串形式的浮点数值转换成浮点数,如:"234.7"-->234.7
// 可以处理象"12,345.7"的形式
/**
* To double.
*
* @param value the value
* @return the double
*/
public static double toDouble(final String value)
{
if (value == null)
{
return 0.0D;
}
String szTemp = "";
for (int i = 0; i < value.length(); i++)
if (value.charAt(i) != ',')
{
szTemp = szTemp + value.charAt(i);
}
try
{
final double d = Double.parseDouble(szTemp);
return d;
}
catch (final NumberFormatException e)
{
final double d1 = 0.0D;
return d1;
}
}
// 将字符串形式的长整型值转换成长整数,如:"234"-->234
// 可以处理象"12,345"的形式
/**
* To long.
*
* @param value the value
* @return the long
*/
public static long toLong(final String value)
{
if (value == null)
{
return 0L;
}
String szTemp = "";
for (int i = 0; i < value.length(); i++)
if (value.charAt(i) != ',')
{
szTemp = szTemp + value.charAt(i);
}
try
{
final double dd = Double.parseDouble(szTemp);
final long l1 = (long) dd;
return l1;
}
catch (final NumberFormatException e)
{
final long l = 0L;
return l;
}
}
// 将字符串形式的整型值转换成整数,如:"234"-->234
// 可以处理象"12,345"的形式
/**
* To int.
*
* @param value the value
* @return the int
*/
public static int toInt(final String value)
{
return (int) toLong(value);
}
// 将对象转换成字符串
/**
* To string.
*
* @param obj the obj
* @return the string
*/
public static String toString(final Object obj)
{
if (obj == null)
{
return "";
}
else
{
return obj.toString();
}
}
/**
* 将数字转换成用'a'-'z'表示的字符串;1='a'...26='z',27='aa'...52='zz'等
* 等于将十进制转换成二十六进制
*
* @param num the num
* @return the string
*/
public static String toAbcNumber(final int num)
{
int i = num;
final StringBuffer str = new StringBuffer();
if (i <= 0)
{
return "";
}
do
{
str.insert(0, chr[(i - 1) % chr.length]);
i = i / chr.length;
if ((i > 0) && (i < chr.length))
{
str.insert(0, chr[i - 1]);
}
}
while (i > chr.length);
return str.toString();
}
/**
* 缩简字符串的函数
* 例如:"abcdef,akd;adf" 变成 "abcdef,a..."
* 可以指定长度和最后的字符串
*
* @param source the source
* @param lststr the lststr
* @param length the length
* @param iscodelen the iscodelen
* @return the string
*/
public static String trimString(final String source, final String lststr, final int length, final boolean iscodelen)
{
if ((source == null) || (source.trim().length() == 0) || (length <= 0))
{
return source;
}
final String endStr = (lststr != null) ? lststr : "...";
String result = source.trim();
final int len = (endStr.length() < length) ? (length - endStr.length()) : 2;
final byte[] sbytes = result.getBytes();
if (length < (iscodelen ? sbytes.length : result.length()))
{
if (iscodelen)
{
if (new String(sbytes, 0, len).length() == 0)
{
result = new String(sbytes, 0, len - 1) + endStr;
}
else
{
result = new String(sbytes, 0, len) + endStr;
}
}
else
{
result = source.substring(0, len) + endStr;
}
}
return result;
}
/**
* 将字符串转换成垂直显示的HTML格式代码
* 在每一个字符的后面加上一个<br>.
*
* @param source the source
* @param lstline the lstline
* @param length the length
* @param iscodelen the iscodelen
* @return the string
*/
public static String toTrimHtmlVerticalString(final String source, final String lstline, final int length, final boolean iscodelen)
{
if ((source == null) || (source.trim().length() == 0) || (length <= 0))
{
return source;
}
String dst = source.trim();
final byte[] sbytes = dst.getBytes();
boolean istrim = false;
if (length < (iscodelen ? sbytes.length : dst.length()))
{
istrim = true;
if (iscodelen)
{
if (new String(sbytes, 0, length).length() == 0)
{
dst = new String(sbytes, 0, length - 1);
}
else
{
dst = new String(sbytes, 0, length);
}
}
else
{
dst = dst.substring(0, length);
}
}
final int len = dst.length();
final StringBuffer result = new StringBuffer();
for (int i = 0; i < (len - 1); i++)
{
result.append(dst.charAt(i)).append("<br>");
}
if (istrim && (lstline != null) && (lstline.trim().length() > 0))
{
result.append(lstline.trim());
}
else
{
result.append(dst.charAt(len - 1));
}
return result.toString();
}
/**
* 将字符串转换成垂直显示的HTML格式代码
* 在每一个字符的后面加上一个<br>.
*
* @param source the source
* @return the string
*/
public static String toHtmlVerticalString(final String source)
{
if ((source == null) || (source.trim().length() == 0))
{
return source;
}
final String tmp = source.trim();
final int len = tmp.length();
final StringBuffer result = new StringBuffer();
for (int i = 0; i < (len - 1); i++)
{
result.append(tmp.charAt(i)).append("<br>");
}
result.append(tmp.charAt(len - 1));
return result.toString();
}
/**
* 缩简字符串的函数
* 例如:"abcdef,akd;adf" 变成 "abcdef,a..."
* 可以指定长度和最后的字符串
*
* @param source the source
* @return the short string
*/
// 无参数,取缺省参数
public static String getShortString(final String source)
{
final int len = 10;
final String endStr = "...";
String result = source;
if ((source != null) && (source.length() > len))
{
result = source.substring(0, len) + endStr;
}
return result;
}
// 指定长度
/**
* Gets the short string.
*
* @param source the source
* @param length the length
* @return the short string
*/
public static String getShortString(final String source, final int length)
{
final int len = (length > 0) ? length : 10;
final String endStr = "...";
String result = source;
if ((source != null) && (source.length() > len))
{
result = source.substring(0, len) + endStr;
}
return result;
}
// 指定长度与最后字符串
/**
* Gets the short string.
*
* @param source the source
* @param length the length
* @param lastStr the last str
* @return the short string
*/
public static String getShortString(final String source, final int length, final String lastStr)
{
final int len = (length > 0) ? length : 10;
final String endStr = (lastStr != null) ? lastStr : "...";
String result = source;
if ((source != null) && (source.length() > len))
{
result = source.substring(0, len) + endStr;
}
return result;
}
// 计算次方
/**
* P.
*
* @param a the a
* @param b the b
* @return the double
*/
public static double P(final int a, final int b)
{
int result = 1;
for (int i = 0; i < b; i++)
result = result * a;
return result;
}
/**
* P.
*
* @param a the a
* @param b the b
* @return the double
*/
public static double P(final float a, final int b)
{
float result = 1;
for (int i = 0; i < b; i++)
result = result * a;
return result;
}
// 将整数值转换成二进制数组,如 13(10)=1101(2),即1,3,4位为真,第2位为假(假设第一位为1)
// 输入参数:整数数值value,数组长度length
/**
* Gets the bin array.
*
* @param value the value
* @param length the length
* @return the bin array
*/
public static int[] getBinArray(final int value, final int length)
{
if ((value < 0) || (length <= 0))
{
return null;
}
final int len = (length > 32) ? 32 : length; // 限定最多32位长度
int val = value;
final int[] binbit = new int[len];
for (int i = 0; i < len; i++)
{
if ((val % 2) == 1)
{
binbit[i] = 1;
}
else
{
binbit[i] = 0;
}
val = val >> 1;
}
return binbit;
}
/**
* 换行,空格字符的替换操作.
*
* @param in 要进行转换的字符串
* @return 替换后的字符串
*/
public static String replaceNewLine(final String in)
{
if (in == null)
{
return null;
}
char ch;
final char[] input = in.toCharArray();
final int len = input.length;
final StringBuffer out = new StringBuffer((int) (len * 1.3));
for (int index = 0; index < len; index++)
{
ch = input[index];
if (ch == '\n')
{
out.append("<br>");
}
else if (ch == ' ')
{
out.append(" ");
}
else
{
out.append(ch);
}
}
return out.toString();
}
/**
* 把字符串的字符集从ISO转换为gb2312.
*
* @param in 输入的ISO字符串
* @return GB2312字符串
*/
public static String convertIso8859ToGb2312(final String in)
{
String out = null;
byte[] ins = null;
try
{
ins = in.getBytes("iso-8859-1");
}
catch (final UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
out = new String(ins, "gb2312");
}
catch (final UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
}
/**
* 把字符串的字符集从GB2312转换为ISO.
*
* @param in 输入的GB2312字符串
* @return ISO字符串
*/
public static String convertGb2312ToIso8859(final String in)
{
String out = null;
try
{
final byte[] ins = in.getBytes("gb2312");
out = new String(ins, "iso-8859-1");
}
catch (final Exception e)
{
}
return out;
}
/**
* Convert utf to gbk.
*
* @param in the in
* @return the string
*/
public static String convertUtfToGBK(final String in)
{
String out = null;
try
{
final byte[] ins = in.getBytes("UTF-8");
out = new String(ins, "ISO-8859-1");
}
catch (final Exception e)
{
}
return out;
}
/**
* 去掉字符串两头的空格.
*
* @param str 待处理的字符串
* @return 处理后的字符串
*/
public static String convertNullToString(final String str)
{
if (str == null)
{
return "";
}
else
{
final int len = str.length();
for (int i = 0; i < len; i++)
{
if (str.charAt(i) != ' ')
break;
}
return str.trim();
}
}
/**
* 检查电子邮件合法性.
*
* @param email 带验证的电子邮件地址
* @return true表示合法 false表示非法
*/
public static boolean checkEmailIsValid(final String email)
{
boolean isok = false;
if (email.equals("") || email == "" || email == null)
isok = false;
for (int i = 1; i < email.length(); i++)
{
final char s = email.charAt(i);
if (s == '@')
{
isok = true;
break;
}
}
return isok;
}
/**
* 替换字符串某些字符操作.
*
* @param str 原始的字符串 例如:bluesunny
* @param pattern 配备的字符 例如:blue
* @param replace 替换为的字符 例如:green
* @return 返回处理结果 例如:greensunny
*/
public static String replace(final String str, final String pattern, String replace)
{
if (replace == null)
{
replace = "";
}
int s = 0, e = 0;
final StringBuffer result = new StringBuffer(str.length() * 2);
while ((e = str.indexOf(pattern, s)) >= 0)
{
result.append(str.substring(s, e));
result.append(replace);
s = e + pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
/**
* 判断字符串是否为数字类型.
*
* @param str 待处理的字符串
* @return true表示为数字类型 false表示为非数字类型
*/
public static boolean isNumber(final String str)
{
if (str == null || str.equals(""))
{
return false;
}
String sStr = "";
int m = 0;
m = str.indexOf(".");
for (int j = 0; j < str.length(); j++)
{
if (m != j)
sStr = sStr + str.charAt(j);
}
final byte[] btyeStr = sStr.getBytes();
for (int i = 0; i < btyeStr.length; i++)
{
if ((btyeStr[i] < 48) || (btyeStr[i] > 57))
{
return false;
}
}
return true;
}
/**
* 把string型字符串转为整型.
*
* @param str 待处理的字符串
* @return 整数
*/
public static int strToInt(final String str)
{
int i = 0;
if (str != null && str.length() != 0)
{
try
{
i = Integer.parseInt(str.trim());
}
catch (final NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
return i;
}
/**
* 把string型字符串转为Double.
*
* @param str 待处理的字符串
* @return double
*/
public static double strToDouble(final String str)
{
double i = 0;
if (str != null && str.length() != 0)
{
try
{
i = Double.parseDouble(str.trim());
}
catch (final NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
return i;
}
/**
* 产生随机字符串.
*
* @return the string
*/
public static String createRandomString()
{
String random = null;
// 产生随机字符串
random = RandomStringUtils.randomAlphabetic(10);
// 随机字符串再加上当前的日期时间 long
random += DateUtils.getNowDateTimeToLong();
return random;
}
/**
* 将Id数组转换成逗号分隔的字符串.
*
* @param fid the fid
* @return the string
*/
public static final String comboIdStr(final String[] fid)
{
String IdStr = "";
for (int i = 0; i < fid.length; i++)
{
IdStr += fid[i];
if (i != fid.length - 1)
IdStr += ",";
}
return IdStr;
}
/**
* 将带特殊分隔符的字符串转换为按照指定替换符的字符串.
*
* @param oldValue the old value
* @param separateChar the separate char
* @param replaceStr the replace str
* @return the tree level value
*/
public static final String getTreeLevelValue(final String oldValue, final String separateChar, final String replaceStr)
{
final String[] spStr = oldValue.split(separateChar);
String tmp = "";
for (int i = 0; i < spStr.length - 1; i++)
{
tmp += replaceStr;
}
return tmp;
}
/**
* 2006-1.11zhujw add
* 把数组字符串转化成'1','2','3'格式
*
* @param fid the fid
* @return the string
*/
public static final String StrComboId(final String[] fid)
{
final StringBuffer str = new StringBuffer("");
for (int i = 0; i < fid.length; i++)
{
str.append("'").append(fid[i]).append('\'');
if (i != fid.length - 1)
str.append(',');
}
return str.toString();
}
/**
* String >> char[] >> byte[] >> String
* 解决JSP中的中文问题.
*
* @param source the source
* @return the string
*/
public static String toByteString(final String source)
{
if (source == null)
{
return null;
}
if (source.length() == 0)
{
return "";
}
final char[] chars = source.toCharArray();
final byte[] bytes = new byte[source.length() * 2];
int index = 0;
for (int i = 0, charValue = 0; (i < chars.length) && (index < (chars.length * 2)); i++)
{
charValue = chars[i];
if (charValue > 255)
{
try
{
final byte[] tmp = (new Character(chars[i])).toString().getBytes("GB2312");
for (int j = 0; j < tmp.length; j++)
{
bytes[index] = tmp[j];
index++;
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
else
{
bytes[index] = (byte) chars[i];
index++;
}
}
return new String(bytes, 0, index);
}
// unicode -> 8859-1 charset
/**
* To_iso_8859_1.
*
* @param source the source
* @return the string
*/
public static String to_iso_8859_1(final String source)
{
if (source == null)
{
return null;
}
try
{
final String s = new String(source.getBytes(), "iso-8859-1");
return s;
}
catch (final Exception uee)
{
final String s1 = null;
return s1;
}
}
// 8859-1 -> unicode charset
/**
* From_iso_8859_1.
*
* @param source the source
* @return the string
*/
public static String from_iso_8859_1(final String source)
{
if (source == null)
{
return null;
}
try
{
final String s = new String(source.getBytes("iso-8859-1"));
return s;
}
catch (final Exception uee)
{
final String s1 = null;
return s1;
}
}
/**
* 首字母大写.
*
* @param arg the arg
* @return the string
*/
public static String fistCapital(String arg)
{
if (arg != null && !arg.trim().equals(""))
{
arg = arg.replaceFirst(String.valueOf(arg.charAt(0)), String.valueOf(arg.charAt(0)).toUpperCase());
}
return arg;
}
/**
* Index of ignore case.
*
* @param src the src
* @param subS the sub s
* @param startIndex the start index
* @return the int
*/
public static int indexOfIgnoreCase(final String src, final String subS, final int startIndex)
{
final String sub = subS.toLowerCase();
final int sublen = sub.length();
final int total = src.length() - sublen + 1;
for (int i = startIndex; i < total; i++)
{
int j = 0;
while (j < sublen)
{
final char source = Character.toLowerCase(src.charAt(i + j));
if (sub.charAt(j) != source)
{
break;
}
j++;
}
if (j == sublen)
{
return i;
}
}
return -1;
}
/**
* Equals.
*
* @param obj1 the obj1
* @param obj2 the obj2
* @return true, if successful
*/
public static boolean equals(final Object obj1, final Object obj2)
{
if (obj1 == null && obj2 == null)
{
return true;
}
else if (obj1 != null)
{
return obj1.equals(obj2);
}
else
{
return obj2.equals(obj1);
}
}
/**
* 是否为空
* @param obj
* @return
* @author Xiaojf
* @since 2011-5-24
*/
public static boolean isNull(Object obj) {
return obj == null || "".equals(obj);
}
/**
* 是否非空
* @param obj
* @return
* @author Xiaojf
* @since 2011-5-24
*/
public static boolean notNull(Object obj) {
return !isNull(obj);
}
/**
* 将字符患的首字母大写
* @param source
* @return
* @author Xiaojf
* @since 2011-6-24
*/
public static String upperFirst(String source) {
if (isNull(source)) return "";
return source.substring(0, 1).toUpperCase() + source.substring(1);
}
/**
* 首字母小写
* @param source
* @return
* @author Xiaojf
* @since 2011-9-14
*/
public static String lowerFirst(String source) {
if (isNull(source)) return source;
return source.substring(0, 1).toLowerCase() + source.substring(1);
}
/**
* 把集合中的某一字段用逗号连接起来,用来拼装SQL语句
* @param datas
* @param field
* @return
* @author Xiaojf
* @since 2011-9-14
*/
public static String join(List<?> datas, String field) {
return join(datas, ",", "'", field);
}
/**
* 把集合中的某一字段用指定的符号连接起来,用来拼装SQL语句
* @param datas
* @param field
* @return
* @author Xiaojf
* @since 2011-9-14
*/
public static String join(List<?> datas, String parttern, String wrapChar, String field) {
if (datas == null || datas.isEmpty()) return wrapChar + wrapChar;
String[] strs = new String[datas.size()];
Method getter = null;
int index = 0;
for (Object t : datas) {
if (getter == null) {
try {
getter = t.getClass().getDeclaredMethod("get"+ upperFirst(field));
} catch (Exception e) {}
}
if (getter != null) {
Object o = null;
try {
o = getter.invoke(t);
} catch (Exception e) {}
if (o == null) continue;
strs[index++] = o.toString();
}
}
return join(strs, parttern, wrapChar);
}
/**
* 把数组中的某一字段用逗号连接起来,用来拼装SQL语句
* @param ts
* @return
* @author Xiaojf
* @since 2011-9-14
*/
public static String join(Object[] ts) {
return join(ts, ",", "'");
}
/**
* 把数组中的某一字段用指定的符号连接起来,用来拼装SQL语句
* @param ts
* @param parttern
* @param wrapChar
* @return
* @author Xiaojf
* @since 2011-9-14
*/
public static String join(Object[] ts, String parttern, String wrapChar) {
StringBuffer s = new StringBuffer();
if (ts == null) return s.toString();
if (isNull(parttern)) parttern = "";
if (isNull(wrapChar)) wrapChar = "";
for (Object obj : ts) {
if (isNull(obj)) continue;
s.append(wrapChar + obj + wrapChar + parttern);
}
if (s.length() > 0) s.setLength(s.length() - 1);
return s.toString();
}
/**
* 获取对象对应的表名,如对象名为TsysOrg,则转换的表名为:T_SYS_ORG
* @param obj
* @return
* @author xjf721
* @since 2011-10-18
*/
public static String getTableName(Class<?> clazz) {
String root = ReflectUtil.getRootClassName(clazz);
StringBuffer sb = new StringBuffer();
int count = 0;
for (int i = 0; i < root.length(); i++) {
char c = root.charAt(i);
if (c >= 65 && c <=90) {
if (count > 0) sb.append("_");
count++;
}
sb.append(c);
}
return sb.toString().toUpperCase();
}
public static String encodeToUrl(String value) {
try {
String v = java.net.URLEncoder.encode(value, "UTF-8");
return v.replaceAll("\\+", "%20");
} catch (Exception e) {}
return value;
}
}
| [
"hihsoft@gmail.com"
] | hihsoft@gmail.com |
d1fcd901e55ea7666640f1b580e4b494842c869d | 6bddfe245aefa4591d18c20c61407b215349ba2b | /src/main/java/lilypuree/forest_tree/datagen/Languages.java | 94cc55ba7aa3ef7d902083205a53522e15375921 | [] | no_license | lilypuree/ForestTree | 53bcc9f5a8156439695fb96ca7141a9a78d667eb | e23ba0b28d232fe37fa778bde8acd4ea9539c578 | refs/heads/master | 2020-12-28T17:33:39.915847 | 2020-08-28T16:01:39 | 2020-08-28T16:01:39 | 238,422,214 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,244 | java | package lilypuree.forest_tree.datagen;
import lilypuree.forest_tree.ForestTree;
import lilypuree.forest_tree.Registration;
import lilypuree.forest_tree.common.world.trees.gen.feature.parametric.Module;
import lilypuree.forest_tree.common.world.trees.gen.feature.parametric.Parameter;
import net.minecraft.data.DataGenerator;
import net.minecraftforge.common.data.LanguageProvider;
public class Languages extends LanguageProvider {
public Languages(DataGenerator gen, String locale) {
super(gen, ForestTree.MODID, locale);
}
@Override
protected void addTranslations() {
add(Registration.TREE_DESIGNER_BLOCK.get(), "Tree Designer");
add(Registration.CUSTOM_SAPLING.get(), "Custom Sapling");
add(Registration.GRAFTING_TOOL.get(), "Grafting Tool");
for (Module module : Module.values()){
for (Parameter parameter : Parameter.parameters[module.index]){
add("forest_tree.treedesignergui.parameters."+parameter.name, parameter.name);
add("forest_tree.treedesignergui.descriptions."+parameter.name, "description here");
}
add("forest_tree.treedesignergui.modules."+module.name(), module.name());
}
}
}
| [
"000abczyx@naver.com"
] | 000abczyx@naver.com |
1af8d157e7c5ca3e56008824a4672e92f61c3072 | f260eced97f135f743e855f50fb197c1af26e1ab | /src/main/java/com/wspa/mpkmanager/model/AbstractUniqueEntity.java | 6e3eea0b03b2125ef8c5359dd6b27de98271d69d | [] | no_license | Palii-Meshchanynets-Tiupa/MpkManager | a4f71deced76cfcaaee0acbc876b11d62d1ce584 | 8137c1367cc5955e12815bd6a1d61df10de1ba54 | refs/heads/master | 2021-01-24T09:55:54.761065 | 2018-06-03T17:10:41 | 2018-06-03T17:10:41 | 123,028,665 | 1 | 0 | null | 2018-05-20T19:09:52 | 2018-02-26T20:49:26 | TypeScript | UTF-8 | Java | false | false | 557 | java | package com.wspa.mpkmanager.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;
import java.util.UUID;
@MappedSuperclass
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = true)
public abstract class AbstractUniqueEntity extends AbstractEntity {
@Getter
@Setter
@NotNull
@Column(columnDefinition = "UUID")
private UUID uuid = UUID.randomUUID();
}
| [
"mrexidex@gmail.com"
] | mrexidex@gmail.com |
7c2fc35737f1b833731830e2cad6b46269afc255 | 59d50c6c2b093c68c877eaee2877537438562987 | /app/src/main/java/com/bringin/iak/giziremaja/Kategori.java | c9e99269144a9f432de2f61db1dbe9daf264f204 | [] | no_license | yogiyulianto/GiziRemaja | bef71ec4990d646bad377091c09711f8fd3d09f8 | 1d803ba99bd8d10d79774be975030c9fe8417136 | refs/heads/master | 2021-04-09T15:39:35.967497 | 2018-03-20T04:11:51 | 2018-03-20T04:11:51 | 125,723,609 | 0 | 1 | null | 2018-03-20T04:52:44 | 2018-03-18T12:40:51 | Java | UTF-8 | Java | false | false | 770 | java | package com.bringin.iak.giziremaja;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Kategori extends AppCompatActivity {
Button btnNexti;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kategori);
btnNexti = findViewById(R.id.btn_next_faktor);
btnNexti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent pindahActivity = new Intent(getApplicationContext(), indeks.class);
startActivity(pindahActivity);
}
});
}
}
| [
"yogi.yulianto@students.amikom.ac.id"
] | yogi.yulianto@students.amikom.ac.id |
581233f28337484b74d0a27670d146c096183d0e | 9211886c9631c072d3aa6e8dfe642af0a3e78919 | /src/main/java/com/brian/config/BrianTypeFilter.java | 419a7d31289ff148d32e7a76e2b5722ff29e2cf8 | [] | no_license | showkawa/spring-annotation | ee3e286e9a1c2c7706e527caf56d9f1e499db60f | 1a04b7d5a32bcfb2e074dba5ea3362643a3d6d30 | refs/heads/master | 2022-08-09T16:47:20.174817 | 2022-07-06T09:57:44 | 2022-07-06T09:57:44 | 150,225,788 | 30 | 5 | null | 2022-06-28T06:15:10 | 2018-09-25T07:38:05 | Java | UTF-8 | Java | false | false | 853 | java | package com.brian.config;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
public class BrianTypeFilter implements TypeFilter {
/*
*
* metadataReader:读取到的当前正在扫描类的信息
* metadataReaderFactory: 可以获取到其他类的任何信息
* */
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
System.out.println("getClassMetadata--:" + metadataReader.getClassMetadata().getClassName());
if(metadataReader.getClassMetadata().getClassName().contains("BrianBeanFactory"))
{
return true;
}
return false;
}
}
| [
"szhuangl@cn.ibm.com"
] | szhuangl@cn.ibm.com |
c276ffeccf38ed176b45123d6365d2b8e7e48a4a | 0d8f2002f045a92f44569732fdd5ba202f514b02 | /72/Solution.java | 9ff76d4718a881880fc016ddaeb6c36af583de16 | [] | no_license | LunaMing/LeetCodeRepo | 5184fd7695e7502cb9e73affbba477ff7c3c258f | 700fbc06c40daffa1bf306c0fabb86fe8f535bca | refs/heads/master | 2021-05-24T09:07:58.271049 | 2020-05-07T11:01:11 | 2020-05-07T11:01:11 | 253,487,087 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,697 | java | import static java.lang.Math.max;
import static java.lang.Math.min;
public class Solution {
public int minDistance(String word1, String word2) {
return this.MyLeetcodeTry(word1, word2);
}
public int MyLeetcodeTry(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
for (int i = 0; i <= len2; i++) {
dp[0][i] = i;
}
int a, b, c;
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
a = dp[i - 1][j - 1];
b = dp[i][j - 1];
c = dp[i - 1][j];
if (word1.charAt(i - 1) != word2.charAt(j - 1))
dp[i][j] = Math.min(a, Math.min(b, c)) + 1;
else
dp[i][j] = a;
}
}
return dp[len1][len2];
}
public int LeetcodeMinDis(String word1, String word2) {
int n = word1.length();
int m = word2.length();
// 有一个字符串为空串
if (n * m == 0)
return n + m;
// DP 数组
int[][] D = new int[n + 1][m + 1];
// 边界状态初始化
for (int i = 0; i < n + 1; i++) {
D[i][0] = i;
}
for (int j = 0; j < m + 1; j++) {
D[0][j] = j;
}
// 计算所有 DP 值
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
int left = D[i - 1][j] + 1;
int down = D[i][j - 1] + 1;
int left_down = D[i - 1][j - 1];
if (word1.charAt(i - 1) != word2.charAt(j - 1))
left_down += 1;
D[i][j] = Math.min(left, Math.min(down, left_down));
}
}
return D[n][m];
}
public int MyMinDis(String word1, String word2) {
if (word1.length() == 0)
return word2.length();
if (word2.length() == 0)
return word1.length();
if (word1.equals(word2))
return 0;
int maxLength = Math.max(word1.length(), word2.length());
int lengthOfSubS = word1.length();
int start, end, indexContain;
int distance = 0, minDis = maxLength;
while (lengthOfSubS > 0) {
start = 0;
end = lengthOfSubS;
for (int i = 0; i < word1.length() - lengthOfSubS + 1; i++) {
String tempSubString = word1.substring(start, end);
indexContain = word2.indexOf(tempSubString, 0);
//有某一位相同,进入子串分支求和
if (indexContain >= 0) {
distance = 0;//清空改动计数器
//前半部分
String tempWord1 = word1.substring(0, start);
String tempWord2 = word2.substring(0, indexContain);
distance += this.MyMinDis(tempWord1, tempWord2);
//后半部分
tempWord1 = word1.substring(end);
tempWord2 = word2.substring(indexContain + lengthOfSubS);
distance += this.MyMinDis(tempWord1, tempWord2);
//比较是不是最小改动
minDis = Math.min(minDis, distance);
}
while (indexContain > 0) {
//查看剩余位是否相同
indexContain = word2.indexOf(tempSubString, indexContain + 1);
//有某一位相同,进入子串分支求和
if (indexContain >= 0) {
distance = 0;//清空改动计数器
//前半部分
String tempWord1 = word1.substring(0, start);
String tempWord2 = word2.substring(0, indexContain);
distance += this.MyMinDis(tempWord1, tempWord2);
//后半部分
tempWord1 = word1.substring(end);
tempWord2 = word2.substring(indexContain + lengthOfSubS);
distance += this.MyMinDis(tempWord1, tempWord2);
//比较是不是最小改动
minDis = Math.min(minDis, distance);
}
}
//word1换一个子串查
start++;
end++;
}
lengthOfSubS--;
if (distance > 0 && lengthOfSubS > 3) {
//如果在这个位数下面已经有结果了,还继续嘛?
//试一下少一位,最多也就是差一位吧??
//嗯 个位就不用试了 没意义
start = 0;
end = lengthOfSubS;
for (int i = 0; i < word1.length() - lengthOfSubS + 1; i++) {
String tempSubString = word1.substring(start, end);
indexContain = word2.indexOf(tempSubString, 0);
//有某一位相同,进入子串分支求和
if (indexContain >= 0) {
distance = 0;//清空改动计数器
//前半部分
String tempWord1 = word1.substring(0, start);
String tempWord2 = word2.substring(0, indexContain);
distance += this.MyMinDis(tempWord1, tempWord2);
//后半部分
tempWord1 = word1.substring(end);
tempWord2 = word2.substring(indexContain + lengthOfSubS);
distance += this.MyMinDis(tempWord1, tempWord2);
//比较是不是最小改动
minDis = Math.min(minDis, distance);
}
//查看剩余位是否相同
while (indexContain > 0) {
indexContain = word2.indexOf(tempSubString, indexContain + 1);
//有某一位相同,进入子串分支求和
if (indexContain >= 0) {
distance = 0;//清空改动计数器
//前半部分
String tempWord1 = word1.substring(0, start);
String tempWord2 = word2.substring(0, indexContain);
distance += this.MyMinDis(tempWord1, tempWord2);
//后半部分
tempWord1 = word1.substring(end);
tempWord2 = word2.substring(indexContain + lengthOfSubS);
distance += this.MyMinDis(tempWord1, tempWord2);
//比较是不是最小改动
minDis = Math.min(minDis, distance);
}
}
//word1换一个子串查
start++;
end++;
}
break;
}
}
if (distance == 0) {
//说明没有任意一位相同
return maxLength;
}
return minDis;
}
public int minDisWrong(String word1, String word2) {
if (word1.length() == 0)
return word2.length();
if (word2.length() == 0)
return word1.length();
char chCompare;
int index1 = 0, index2 = 0;
int indexSame = 0, indexStart2 = 0;
int dis2 = 0, dis1 = 0;
int distance = 0;//按照本次长度比较得到的改动数
int minDis = Math.max(word1.length(), word2.length());//最终
while (indexStart2 < word2.length()) {
//从头开始比较
index1 = 0;
index2 = indexStart2;
dis2 = indexStart2;//从第几位开始比较,之前的所有都算2的改动
distance = 0;//清空之前的dis
while (index1 < word1.length() && index2 < word2.length()) {
chCompare = word2.charAt(index2);
indexSame = word1.indexOf(chCompare, index1);
if (indexSame == -1) {
dis2++;//如果没有相同字符,计入字符串2的改动
} else {
//如果有相同,标记改动,计数
dis1 = indexSame - index1;//字符串1的改动数,是相同的字符之间的间隔
distance += Math.max(dis1, dis2);//计算总改动
dis1 = 0;//清空计数器
dis2 = 0;//清空计数器
index1 = indexSame + 1;//字符串1的指针移到字符相同的位置,的下一个位置
}
index2++;
if (index2 >= word2.length()) {
//如果2比较结束,就结束整段比较
distance += Math.max(dis2, word1.length() - index1);
}
if (index1 >= word1.length()) {
//如果1比较结束,就结束整段比较
distance += word2.length() - index2;
}
}
minDis = Math.min(distance, minDis);//验证是最小的方案
indexStart2++;//每一轮比较都向后找一位word2
}
return minDis;
}
public static void main(String[] args) {
Solution s = new Solution();
int n;
n = s.minDistance("horse", "ros");//3
System.out.println(n);
n = s.minDistance("mart", "karma");//3
System.out.println(n);
n = s.minDistance("intention", "execution");//5
System.out.println(n);
n = s.minDistance("execution", "intention");//5
System.out.println(n);
n = s.minDistance("", "a");//1
System.out.println(n);
n = s.minDistance("a", "ab");//1
System.out.println(n);
n = s.minDistance("ab", "bc");//2
System.out.println(n);
n = s.minDistance("sea", "ate");//3
System.out.println(n);
n = s.minDistance("industry", "interest");//6
System.out.println(n);
n = s.minDistance("prosperity", "properties");//4
System.out.println(n);
n = s.minDistance("a", "a");//0
System.out.println(n);
n = s.minDistance("abcdxabcde", "abcdeabcdx");//2
System.out.println(n);
n = s.minDistance("dinitrophenylhydrazine", "acetylphenylhydrazine");//6
System.out.println(n);
}
}
| [
"44162157+LunaMing@users.noreply.github.com"
] | 44162157+LunaMing@users.noreply.github.com |
7b56eb22fa6f801e5470e3df9d60f7e2a8f711e8 | cbdd81e6b9cf00859ce7169df36cf566417e4c8b | /3.JavaMultithreading/src/com/javarush/task/task28/task2805/MyThread_01.java | d2068ea5685aa846aa8af943ed5a1b35624daa45 | [] | no_license | id2k1149/JavaRushTasks | 3f13cd5d37977e38e8933e581f17fd48597f90d8 | 450a432649aa20608e6e9a46ada35123056480cf | refs/heads/master | 2023-03-31T21:03:06.944109 | 2021-03-19T00:58:45 | 2021-03-19T00:58:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,156 | java | package com.javarush.task.task28.task2805;
import java.util.concurrent.atomic.AtomicInteger;
public class MyThread_01 extends Thread {
private static final AtomicInteger number = new AtomicInteger(1);
public MyThread_01() {
if (number.get() == 11) {
number.set(1);
}
setPriority(number.getAndIncrement());
}
public MyThread_01(ThreadGroup group, String name) {
if (number.get() == group.getMaxPriority() + 1) {
number.set(1);
}
setPriority(number.getAndIncrement());
}
public MyThread_01(Runnable target) {
super(target);
}
public MyThread_01(ThreadGroup group, Runnable target) {
super(group, target);
}
public MyThread_01(String name) {
super(name);
}
public MyThread_01(Runnable target, String name) {
super(target, name);
}
public MyThread_01(ThreadGroup group, Runnable target, String name) {
super(group, target, name);
}
public MyThread_01(ThreadGroup group, Runnable target, String name, long stackSize) {
super(group, target, name, stackSize);
}
}
| [
"id2k1149@gmail.com"
] | id2k1149@gmail.com |
7363d939f7739815fa2a1200ae893b9fc2197049 | 90a5ff8513bfcb29117dd96054ed4379879400ea | /PetClinicSpring05c/src/com/coder/form/OwnerRegisterForm.java | 3234fccf1b7cc1615e7966f8ed531e2446566c8a | [] | no_license | MinPyaeHein/Pet-Clinic-Management-System | 5a39a651066fb26b8d1a9d3733a67dc8460dd71c | aab6417a423dfec73bbbd3b0d5b517ee60a7b069 | refs/heads/main | 2023-08-23T06:19:14.615536 | 2021-10-20T04:06:23 | 2021-10-20T04:06:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package com.coder.form;
import java.util.Map;
import org.apache.commons.collections4.map.HashedMap;
public class OwnerRegisterForm {
private OwnerForm ownerForm;
public OwnerForm getOwnerForm() {
return ownerForm;
}
public void setOwnerForm(OwnerForm ownerForm) {
this.ownerForm = ownerForm;
}
}
| [
"92769828+MinPyaeHein@users.noreply.github.com"
] | 92769828+MinPyaeHein@users.noreply.github.com |
dadf6bd0b846550d23122ac33f3c2248781d20c6 | 467d91329c0047a2c9eda3fd07d6c3cad05def5c | /src/test/java/com/qa/capturefailedscreenshot/CaptureFailedScreenShot.java | 87170895970b9d40c9f28390f60dd7a718b55e23 | [] | no_license | wilsonfernandes1991/TestngRetryLogic | 0a50512a2e3cf1c12f3cd16fb1c07a3780f302ab | 9d5a0078a6b245a524eff387aebb23e4143e5a34 | refs/heads/master | 2021-04-06T13:44:44.091485 | 2018-03-10T18:21:15 | 2018-03-10T18:21:15 | 124,650,954 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,220 | java | package com.qa.capturefailedscreenshot;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class CaptureFailedScreenShot {
@Test
public void sample1Test()
{
Assert.assertTrue(false);
}
@Test
public void sample2Test()
{
Assert.assertTrue(true);
}
@AfterMethod
public void afterMethod(ITestResult t) throws Exception
{
if(!t.isSuccess())
{
System.out.println(""+t.getName());
captureScreenShot(t.getName());
}
}
public void captureScreenShot(String methodName) throws Exception
{
System.out.println("Capturing Screenshot for failed test '"+methodName+"'...");
String screenshotFilePath = "Resources\\Screenshot\\"+methodName+".png";
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, "png", new File(screenshotFilePath));
}
}
| [
"fernandes.wilson57@gmail.com"
] | fernandes.wilson57@gmail.com |
b6543ce9cdc35c206dde8e3e71dfc3d8f7b57091 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/com/ali/user/mobile/external/InSideService/LoginUserInfoService.java | a37a2d9c47faafd44ae8ca55f2b638cc4268198f | [] | no_license | shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391040 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,966 | java | package com.ali.user.mobile.external.InSideService;
import android.os.Bundle;
import com.ali.user.mobile.account.bean.UserInfo;
import com.ali.user.mobile.accountbiz.extservice.AuthService;
import com.ali.user.mobile.accountbiz.extservice.manager.AntExtServiceManager;
import com.ali.user.mobile.accountbiz.sp.SecurityShareStore;
import com.ali.user.mobile.log.AliUserLog;
import com.alipay.android.phone.inside.framework.LauncherApplication;
import com.alipay.android.phone.inside.framework.service.IInsideService;
import com.alipay.android.phone.inside.framework.service.IInsideServiceCallback;
public class LoginUserInfoService implements IInsideService<Void, Bundle> {
public void start(Void voidR) throws Exception {
throw new UnsupportedOperationException();
}
public void start(IInsideServiceCallback<Bundle> iInsideServiceCallback, Void voidR) throws Exception {
if (iInsideServiceCallback != null) {
iInsideServiceCallback.onComplted(startForResult((Void) null));
}
}
public Bundle startForResult(Void voidR) throws Exception {
Bundle bundle = new Bundle();
try {
bundle.putString("loginId", SecurityShareStore.a(LauncherApplication.a(), "currentLogonId"));
AuthService authService = AntExtServiceManager.getAuthService(LauncherApplication.a());
if (authService != null) {
bundle.putBoolean("isLogin", authService.isLogin());
UserInfo userInfo = authService.getUserInfo();
if (userInfo != null) {
bundle.putString("userId", userInfo.getUserId());
bundle.putString("nickName", userInfo.getNick());
bundle.putString("userAvatar", userInfo.getUserAvatar());
}
}
} catch (Throwable th) {
AliUserLog.b("LoginUserInfoService", "getUserInfo error ", th);
}
return bundle;
}
}
| [
"hubert.yang@nf-3.com"
] | hubert.yang@nf-3.com |
89cf6d98b0043472cef4ba67ff2feb9ccebd408f | 86cd1090b1182f2832f0c6b2ccf28fb0b345610e | /AdvancedProgramming/Pattern/src/pattern/factorymethod/factorymethod/impl/ProductAFactory.java | 1bd3fa16e92cc960d6e0082ae415dce7e58c7ec5 | [] | no_license | wanglei949758173/study | a7ada3fd81d706a518e7470b4a8aa3ddc497c0e2 | d54b7e6da9bc0baaea6d7590732ba2e77a663a69 | refs/heads/master | 2022-10-12T17:55:07.486651 | 2021-04-21T14:08:26 | 2021-04-21T14:08:26 | 174,473,949 | 0 | 0 | null | 2022-10-04T23:56:36 | 2019-03-08T05:20:26 | C# | UTF-8 | Java | false | false | 553 | java | /**
* 模块编号
* 功能描述
* 文件名 ProductAFactory.java
* 作者 王磊
* 编写日期 2018年8月24日
*/
package pattern.factorymethod.factorymethod.impl;
import pattern.factorymethod.Product.Product;
import pattern.factorymethod.Product.impl.ProductImplA;
import pattern.factorymethod.factorymethod.FactoryMethod;
/**
* 产品A的工厂实现
*
* @version
* @author 王磊
*/
public class ProductAFactory extends FactoryMethod{
@Override
protected Product getProduct() {
return new ProductImplA();
}
}
| [
"949758173@qq.com"
] | 949758173@qq.com |
b3268a214cb56b5cebdf11931138e054dd9e0560 | 80866c63d983d51ae94bfd7683b051e6e152f1d8 | /src/main/java/guru/springframework/spring5recipeapp/Repositories/UnitOfMeasureRepository.java | 27c79e9d964d47814480ffab019d4ea41b6a95cc | [] | no_license | golnooshte/spring5-recipe-app | d753f3332e884df1be3c2cb2b16b3bf451bc8e8e | 13f8387d499137f94941ba990d6462d0f854b99e | refs/heads/master | 2022-12-27T19:43:33.356806 | 2020-10-16T09:46:54 | 2020-10-16T09:46:54 | 294,718,690 | 0 | 0 | null | 2020-09-11T14:33:58 | 2020-09-11T14:33:57 | null | UTF-8 | Java | false | false | 435 | java | package guru.springframework.spring5recipeapp.Repositories;
import guru.springframework.spring5recipeapp.domain.Category;
import guru.springframework.spring5recipeapp.domain.UnitOfMeasure;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UnitOfMeasureRepository extends CrudRepository<UnitOfMeasure,Long> {
Optional<UnitOfMeasure> findByDescription(String description);
}
| [
"golnoush.teimouri@gmail.com"
] | golnoush.teimouri@gmail.com |
8f48ad65637ef31b7637795c8d742d9a22c2e498 | 2a10efb07af2a6faa70cb5596103c224a739e6cd | /spring-boot-validation/src/main/java/org/schhx/springbootlearn/validation/BeanNotEmptyValidator.java | b04794c103fb2611abf9d31fd737e3601f16e06f | [
"Apache-2.0"
] | permissive | schhx/spring-boot-learn | 9a1243b92f9728d9bde8734408fef23bd39675f4 | a935daaae71e0c7cf07077cefcd40efa4d345464 | refs/heads/master | 2022-07-10T10:53:36.141471 | 2020-01-17T08:20:57 | 2020-01-17T08:20:57 | 117,394,622 | 0 | 0 | Apache-2.0 | 2022-06-20T23:31:46 | 2018-01-14T02:12:17 | Java | UTF-8 | Java | false | false | 521 | java | package org.schhx.springbootlearn.validation;
import org.schhx.springbootlearn.utils.MyBeanUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class BeanNotEmptyValidator implements ConstraintValidator<BeanNotEmpty, Object> {
@Override
public void initialize(BeanNotEmpty constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return MyBeanUtils.isNotEmpty(value);
}
}
| [
"shanchao@wosai-inc.com"
] | shanchao@wosai-inc.com |
09ea35f56a4fc820407e81235705ab1a4d85dce1 | 2fa04f21cbb7203b468f7598df6696a88b05a286 | /bus-office/src/main/java/org/aoju/bus/office/provider/AbstractSourceProvider.java | 5bf5e42905e2a5b758724e34378fa8827881967f | [
"MIT"
] | permissive | jingshuai5213/bus | 17bb475fd76592682123488608a559abec788f81 | f3ec545617acffaf2668ea78e974a05be268cfd1 | refs/heads/master | 2022-11-16T00:35:46.037858 | 2020-07-02T09:35:10 | 2020-07-02T09:35:10 | 254,873,385 | 0 | 0 | MIT | 2020-07-02T09:35:11 | 2020-04-11T13:26:50 | null | UTF-8 | Java | false | false | 2,371 | java | /*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
********************************************************************************/
package org.aoju.bus.office.provider;
import java.io.File;
/**
* 所有源文档规范实现的基类.
*
* @author Kimi Liu
* @version 6.0.1
* @since JDK 1.8+
*/
public abstract class AbstractSourceProvider extends AbstractDocumentProvider
implements SourceDocumentProvider {
protected AbstractSourceProvider(final File file) {
super(file);
}
}
| [
"839536@qq.com"
] | 839536@qq.com |
850b7d2f285d3a97f1c305c0c1c971400e041bcc | dedc17171b13676d801aa75a07414be6f71088bf | /src/main/java/uk/ac/uos/week6/CollectionDescription.java | e377be93cdb7b9e2841ddc86a3356fb7396cb015 | [] | no_license | BrenMen/MinnsBrennan-Repository-For-Java | ee7b951fe3e997e1a52822aec15dde8e4f6262f7 | f7264137b1f5d624f61119afafdc20d7350788d6 | refs/heads/master | 2021-09-28T22:00:08.586658 | 2018-11-20T19:23:10 | 2018-11-20T19:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 597 | java | package uk.ac.uos.week6;
import java.util.ArrayList;
import java.util.List;
public class CollectionDescription implements Describe {
private List<Describe> mylist = new ArrayList<Describe>();
@Override
public String describe() {
String result = "[";
for (Describe value : mylist) {
result = result + value.describe() + ", ";
}
if (result.substring(result.length() - 1).equals(" ")) {
result = result.substring(0, result.length() - 2);
}
result = result + "]";
return result;
}
public void add(Describe value) {
mylist.add(value);
}
} | [
"s195215@uos.ac.uk"
] | s195215@uos.ac.uk |
2c118fe1075ccb1c09d66e644a8f29ad19747e93 | 606a53102e1c26c7422af6da8d28633ec2056267 | /weevent-processor/src/main/java/com/webank/weevent/processor/utils/CommonUtil.java | c59aa0d861b73718e74ce845fce154b842c81b98 | [
"Apache-2.0"
] | permissive | jevyma/WeEvent | 3e3e08a36cc6a20ec79474c02f06f4ac9e00e5eb | 76a39814e91c70f0e4fc271c1337e803981b9044 | refs/heads/master | 2020-08-27T16:15:25.402748 | 2019-10-25T03:08:31 | 2019-10-25T03:08:31 | 216,731,534 | 1 | 0 | Apache-2.0 | 2019-10-22T05:40:06 | 2019-10-22T05:40:03 | null | UTF-8 | Java | false | false | 4,812 | java | package com.webank.weevent.processor.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
@Slf4j
public class CommonUtil {
/**
* check the database url
*
* @param databaseUrl data bae url
* @return connection
*/
public static Connection getConnection(String databaseUrl) {
String driver = "com.mysql.jdbc.Driver";
try {
Class.forName(driver);
return DriverManager.getConnection(databaseUrl);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static String urlPage(String url) {
String page = null;
String[] arrSplit;
String urlTemp = url.trim().toLowerCase();
arrSplit = urlTemp.split("[?]");
if ((urlTemp.length()) > 0 && (arrSplit.length >=1) && (arrSplit[0] != null)) {
page = arrSplit[0];
}
return page;
}
private static String truncateUrlPage(String strURL) {
String strAllParam = null;
String url = strURL.trim().toLowerCase();
String[] arrSplit = url.split("[?]");
if ((url.length() > 1) && (arrSplit.length) > 1 && (arrSplit[1] != null)) {
strAllParam = arrSplit[1];
}
return strAllParam;
}
public static Map<String, String> uRLRequest(String URL) {
Map<String, String> mapRequest = new HashMap<String, String>();
String[] arrSplit = null;
String strUrlParam = truncateUrlPage(URL);
if (strUrlParam == null) {
return mapRequest;
}
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
if (arrSplitEqual.length > 1) {
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (!arrSplitEqual[0].equals("")) {
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
public static List<String> getKeys(String objJson) {
List<String> keys = new ArrayList<>();
try {
if (checkValidJson(objJson)) {
for (Map.Entry<String, Object> entry : JSONObject.parseObject(objJson).entrySet()) {
keys.add(entry.getKey());
}
} else {
keys = null;
}
} catch (JSONException e) {
keys = null;
log.info("json get key error");
}
return keys;
}
/**
* check valid json string
*
* @param test json string
* @return true or false
*/
public final static boolean checkValidJson(String test) {
try {
JSONObject.parseObject(test);
} catch (JSONException ex) {
try {
JSONObject.parseArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
public static boolean checkJson(String content, String objJson) {
boolean tag = true;
//parsing and match
if (!StringUtils.isEmpty(content)
&& !StringUtils.isEmpty(objJson)) {
List<String> contentKeys = getKeys(content);
List<String> objJsonKeys = getKeys(objJson);
// objJsonKeys must longer than the contentKeys
if (contentKeys.size() > objJsonKeys.size()) {
tag = false;
} else {
for (String contentKey : contentKeys) {
if (!objJsonKeys.contains(contentKey)) {
tag = false;
}
}
}
}
log.info("checkJson tag:{}", tag);
return tag;
}
public static Map<String, Integer> contactsql(String content, String objJson) {
Map<String, Integer> sql = new HashMap<>();
if (!StringUtils.isEmpty(content)
&& !StringUtils.isEmpty(objJson)) {
List<String> objJsonKeys = getKeys(objJson);
for (String key : objJsonKeys) {
sql.put(key, 0);
if (!content.contains(key)) {
sql.put(key, 1);
}
}
}
return sql;
}
}
| [
"saintping@gmail.com"
] | saintping@gmail.com |
7d6f8df38fd440236e4d764f881f30b27e842ffc | 9d755877a025b2a5b201c21439c88ba164f4ef83 | /src/test/java/de/vandermeer/skb/interfaces/transformers/textformat/Test_Text_To_WrappedFormat.java | 109fe60e4cf84a223a1a41ee66dd49f604d55d89 | [
"Apache-2.0",
"MIT"
] | permissive | andy176631/skb-java-interfaces | 3caf33daaa44af4d312e60de51dc53afbbd93fd0 | 0ed5aafaccdf1d7203f92ee00d1eb53876f7a0eb | refs/heads/master | 2021-08-31T21:31:13.097599 | 2017-05-02T14:07:59 | 2017-05-02T14:07:59 | 114,078,539 | 0 | 0 | null | 2017-12-13T05:36:09 | 2017-12-13T05:36:08 | null | UTF-8 | Java | false | false | 2,269 | java | /* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.skb.interfaces.transformers.textformat;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import de.svenjacobs.loremipsum.LoremIpsum;
/**
* Tests for {@link Text_To_WrappedFormat}.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.0.2 build 170502 (02-May-17) for Java 1.8
* @since v0.0.1
*/
public class Test_Text_To_WrappedFormat {
static String LINEBREAK = "<br />";
@Test
public void test_Simple(){
String words = new LoremIpsum().getWords(30);
String text = words;
text = StringUtils.replace(words, "dolor ", "dolor " + LINEBREAK);
text = StringUtils.replace(text, "dolore ", "dolore " + LINEBREAK);
Pair<ArrayList<String>, ArrayList<String>> textPair;
textPair = Text_To_WrappedFormat.convert(text, 20, null);
assertEquals(0, textPair.getLeft().size());
assertEquals(11, textPair.getRight().size());
assertEquals(words, StringUtils.join(textPair.getRight(), ' '));
textPair= Text_To_WrappedFormat.convert(text, 30, Pair.of(6, 10));
System.err.println(words);
System.err.println(text);
System.err.println("\n----[ top ]----");
System.err.println("123456789012345678901234567890");
for(String s : textPair.getLeft()){
System.err.println(s);
}
System.err.println("\n----[ bottom ]----");
System.err.println("123456789012345678901234567890");
for(String s : textPair.getRight()){
System.err.println(s);
}
}
}
| [
"sven@vandermeer.de"
] | sven@vandermeer.de |
f6c7eaabe94c08c64328faf58e8f02ade6c4b9a7 | 32d8fb2eabcdd3f29bf68e98182b4a966e989bc8 | /src/main/java/by/gsu/dl/usaco/resultsupload/HTMLResults.java | 3cb2b9cd154b021adbd1caceda0394e9e99e9388 | [] | no_license | zshamrock/usaco-results-upload | 8d43dae160b50be7b034e023d692f02838f094b0 | 01ff094f31a1bb4690c8e8ed22a80e55345c8352 | refs/heads/master | 2022-09-07T14:16:27.138001 | 2019-12-24T07:26:03 | 2019-12-24T07:26:03 | 31,831,735 | 2 | 0 | null | 2022-09-01T22:44:55 | 2015-03-07T23:34:35 | Groovy | UTF-8 | Java | false | false | 12,324 | java | package by.gsu.dl.usaco.resultsupload;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import org.apache.log4j.Logger;
import org.jsoup.HttpStatusException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import by.gsu.dl.usaco.resultsupload.domain.Contest;
import by.gsu.dl.usaco.resultsupload.domain.Division;
import by.gsu.dl.usaco.resultsupload.domain.Participant;
import by.gsu.dl.usaco.resultsupload.domain.Problem;
import by.gsu.dl.usaco.resultsupload.domain.Submission;
import by.gsu.dl.usaco.resultsupload.exception.HTMLResultsCreationException;
import by.gsu.dl.usaco.resultsupload.trace.BaseTraceable;
import by.gsu.dl.usaco.resultsupload.trace.Trace;
import by.gsu.dl.usaco.resultsupload.trace.Traceable;
/**
* <p>
* <pre>
* <tr><td>USA</td><td> 2017 </td><td>Peter Wu</td><td>515</td><td> </td><td>*</td><td>x</td><td>x</td><td>x</td><td>x</td><td>x</td><td>x</td><td>x</td><td>x</td><td>x</td><td> </td><td> </td><td>*</td>...</tr>
* ^ ^ ^ ^ ^ ^ ^
* [0] [1] | [2] [3] [5] |
* | | NON_BREAKING_SPACE_UNICODE | | | EMPTY_CELLS_COUNT_BETWEEN_PROBLEMS_SUBMISSIONS
* PARTICIPANT_COUNTRY_INDEX PARTICIPANT_NAME_INDEX PARTICIPANT_NAME_INDEX PARTICIPANT_SCORE_INDEX PARTICIPANT_SUBMISSIONS_START_INDEX
* </pre>
* </p>
* <p>
* For Observers we shift index one to the left, as there is no year for Observers,
* except country as it comes before year.
* </p>
*
* @checkstyle JavadocVariable
*/
public class HTMLResults extends BaseTraceable implements Traceable {
private static final Logger LOGGER = Logger.getLogger(HTMLResults.class);
public static final int OBSERVER_YEAR = 9999;
enum ParticipantType {
PRE_COLLEGE,
OBSERVER
}
// see http://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)
// unicode value for HTML (is part of LATIN_1_SUPPLEMENT)
private static final String NON_BREAKING_SPACE_UNICODE = "\u00a0";
private static final int PARTICIPANT_COUNTRY_INDEX = 0;
private static final int PARTICIPANT_YEAR_INDEX = 1;
private static final int PARTICIPANT_NAME_INDEX = 2;
private static final int PARTICIPANT_SCORE_INDEX = 3;
private static final int PARTICIPANT_SUBMISSIONS_START_INDEX = 5;
// <td>x</td><td> </td><td> </td><td>*</td> <-- extra empty cells between problems submissions
private static final int EMPTY_CELLS_COUNT_BETWEEN_PROBLEMS_SUBMISSIONS = 2;
private Element body;
private Document document;
private Contest contest;
private List<Problem> problems;
private List<Participant> preCollegeParticipants;
private List<Participant> observers;
/**
* @checkstyle IllegalCatch
*/
public HTMLResults(final SourceData source, final Optional<Trace> trace, final Locale locale) {
super(trace, locale);
try {
LOGGER.info("Getting a document");
this.document = source.document();
this.body = this.document.body();
this.collectData();
trace("summary.results", this.year(), this.month(), this.division(), this.preCollegeParticipants().size(),
this.observers().size());
} catch (final Exception ex) {
if (ex instanceof HttpStatusException) {
final HttpStatusException httpStatusException = (HttpStatusException) ex;
trace("error.http", httpStatusException.getStatusCode(), httpStatusException.getUrl());
} else {
trace("error.processing");
}
LOGGER.error("Failed processing HTML results", ex);
throw new HTMLResultsCreationException(ex);
}
}
private void collectData() {
// Order of calls is important!
// We could pragmatically enforce and check it via internal state machine, but is it worth it?
// Could be done as an improvement.
this.collectContest();
this.collectProblems();
this.collectPreCollegeParticipants();
this.collectObservers();
}
private void collectContest() {
this.trace("collecting.contest");
this.contest = Patterns.matchesContest(this.body.select("h1").first().text());
}
private void collectProblems() {
this.trace("collecting.problems");
final List<Element> headerCells = this.preCollegeParticipantsTable().select("tbody tr").first().select("th[colspan]");
this.problems = Collections.unmodifiableList(
Lists.transform(headerCells, new Function<Element, Problem>() {
@Override
public Problem apply(final Element headerCell) {
return new Problem(headerCell.text(), Integer.parseInt(headerCell.attr("colspan")) - 1); // one cell is used for spacing
}
}));
}
private void collectPreCollegeParticipants() {
this.trace("collecting.precollegeparticipants");
this.preCollegeParticipants = this.collectParticipants(this.preCollegeParticipantsTable(),
ParticipantType.PRE_COLLEGE);
}
private Element preCollegeParticipantsTable() {
return this.body.select("table").first();
}
private void collectObservers() {
this.trace("collecting.observers");
this.observers = this.collectParticipants(this.observersTable(), ParticipantType.OBSERVER);
}
private Element observersTable() {
return this.body.select("table").last();
}
private List<Participant> collectParticipants(final Element participantsTable,
final ParticipantType participantType) {
final Elements participantsRows = participantsTable.select("tbody tr:gt(0)");
return Collections.unmodifiableList(
Lists.transform(participantsRows, new Function<Element, Participant>() {
@Override
public Participant apply(final Element participantRow) {
final Elements participantCells = HTMLResults.this.selectParticipantCellsFrom(participantRow);
return Participant.builder()
.country(HTMLResults.this.getParticipantCountryFrom(participantCells))
.year(HTMLResults.this.getParticipantYearFrom(participantCells, participantType))
.name(HTMLResults.this.getParticipantNameFrom(participantCells, participantType))
.score(HTMLResults.this.getParticipantScoreFrom(participantCells, participantType))
.submissions(HTMLResults.this.collectSubmissions(participantCells, participantType))
.build();
}
}));
}
private Elements selectParticipantCellsFrom(final Element participantRow) {
return participantRow.select("td");
}
private String getParticipantCountryFrom(final Elements participantCells) {
return participantCells.get(PARTICIPANT_COUNTRY_INDEX).text();
}
private int getParticipantYearFrom(final Elements participantCells, final ParticipantType participantType) {
return participantType == ParticipantType.PRE_COLLEGE
? Integer.parseInt(participantCells.get(PARTICIPANT_YEAR_INDEX).text()
.replaceAll(NON_BREAKING_SPACE_UNICODE, "").trim())
: OBSERVER_YEAR;
}
private String getParticipantNameFrom(final Elements participantCells, final ParticipantType participantType) {
return participantCells.get(participantNameIndex(participantType)).text();
}
private int getParticipantScoreFrom(final Elements participantCells, final ParticipantType participantType) {
return Integer.parseInt(participantCells.get(participantScoreIndex(participantType)).text());
}
private static int participantNameIndex(final ParticipantType participantType) {
return participantType == ParticipantType.PRE_COLLEGE
? PARTICIPANT_NAME_INDEX
: PARTICIPANT_NAME_INDEX - 1;
}
private static int participantScoreIndex(final ParticipantType participantType) {
return participantType == ParticipantType.PRE_COLLEGE
? PARTICIPANT_SCORE_INDEX
: PARTICIPANT_SCORE_INDEX - 1;
}
private List<Submission> collectSubmissions(
final Elements participantCells, final ParticipantType participantType) {
final List<Submission> submissions = new ArrayList<Submission>(this.problems.size());
final Deque<int[]> submissionsFromTo = new ArrayDeque<int[]>(this.problems.size());
submissionsFromTo.push(new int[]{
participantSubmissionsStartIndex(participantType),
participantSubmissionsStartIndex(participantType) + this.problems.get(0).getTestsCount()});
for (int i = 1; i < this.problems.size(); i++) {
if (i == 0) {
continue; // skip first
}
final int lastTo = submissionsFromTo.getLast()[1];
final int newFrom = lastTo + EMPTY_CELLS_COUNT_BETWEEN_PROBLEMS_SUBMISSIONS; // skipping extra empty cells
submissionsFromTo.addLast(new int[]{newFrom, newFrom + this.problems.get(i).getTestsCount()});
}
final Queue<Problem> problemsQueue = new LinkedList<Problem>(this.problems);
final Collection<List<Element>> participantSubCells = Collections2.transform(submissionsFromTo, new Function<int[], List<Element>>() {
@Override
public List<Element> apply(final int[] fromTo) {
return participantCells.subList(fromTo[0], fromTo[1]);
}
});
for (final List<Element> cells : participantSubCells) {
String submission = "";
for (final Element cell : cells) {
final String text = cell.text();
submission += text.isEmpty() ? " " : text;
}
submissions.add(new Submission(problemsQueue.poll().getName(), submission));
}
return Collections.unmodifiableList(submissions);
}
private static int participantSubmissionsStartIndex(final ParticipantType participantType) {
return participantType == ParticipantType.PRE_COLLEGE
? PARTICIPANT_SUBMISSIONS_START_INDEX
: PARTICIPANT_SUBMISSIONS_START_INDEX - 1;
}
public int year() {
return this.contest.getYear();
}
/**
* @return either month as it is (like January), or US Open (which is usually April)
*/
public String month() {
return this.contest.getMonth();
}
public Division division() {
return this.contest.getDivision();
}
public List<Problem> problems() {
return this.problems;
}
public List<Participant> preCollegeParticipants() {
return this.preCollegeParticipants;
}
public List<Participant> observers() {
return this.observers;
}
public void saveTo(final String path) throws IOException {
final PrintWriter out = new PrintWriter(path);
try {
out.println(this.document.outerHtml());
} finally {
out.close();
}
}
}
| [
"aliaksandr.kazlou@gmail.com"
] | aliaksandr.kazlou@gmail.com |
d8d68695030e9f3fb2cae1568e8ed2c2a5e2d5ba | 1d15f8f60b8b76778f4f2316dab43f3a9c4b2d91 | /app/src/main/java/tasmi/rouf/com/json/MyJSON.java | ebb057cced792424637834af718ecdd59ec1979f | [] | no_license | fajaralmu/android001-simple-scoring-app | 5eaea1ec89002c2598be283225907e59dd6ab3d1 | 1386e7ed0fde3712b3f79ca619c47d09ab49f714 | refs/heads/master | 2020-04-25T15:40:27.270643 | 2019-08-19T04:29:55 | 2019-08-19T04:29:55 | 172,886,368 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,604 | java | package tasmi.rouf.com.json;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import tasmi.rouf.com.util.Constant;
public class MyJSON {
public static String[] getObjFromArray2(String arrayJSON) {
String[] objs = {};
arrayJSON = arrayJSON.replace("},{", "ڑ");
System.out.println(arrayJSON);
if (arrayJSON.charAt(0) == '['
&& arrayJSON.charAt(arrayJSON.length() - 2) == ']') {
objs = arrayJSON.split("ڑ");
}
return objs;
}
public static int lastCharOfProp(int mulai, String s) {
int x = 0;
int y = 0;
for (int i = mulai; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '{') {
x++;
}
if (c == '}' && x > 0) {
x--;
}
if (c == '[') {
y++;
}
if (c == ']' && y > 0) {
y--;
}
if (x == 0 && y == 0) {
return i;
}
}
return mulai;
}
public static List<String> getObjFromArray(String json) {
List<String> obj_list = new ArrayList<String>();
boolean inobj = false;
String nowObj = "";
for (int i = 0; i < json.length() - 1; i++) {
char c = json.charAt(i);
if (c == '{') {
nowObj = "";
int nextI = lastCharOfProp(i, json);
for (int y = i + 2; y < nextI - 1; y++) {
nowObj += json.charAt(y);
}
i = nextI++;
obj_list.add(nowObj);
continue;
}
}
return obj_list;
}
public static List<String> getObjFromArra3y(String json) {
List<String> obj_list = new ArrayList<>();
boolean inobj = false;
String nowObj = "";
for (int i = 0; i < json.length() - 1; i++) {
char c = json.charAt(i);
if (c == '{' && !inobj) {
inobj = true;
continue;
}
if (inobj) {
if (c == '}'
&& (json.charAt(i + 1) == ']' || (json.charAt(i + 1) == ',' && json
.charAt(i + 2) == '{'))) {
inobj = false;
obj_list.add(nowObj);
nowObj = "";
continue;
}
nowObj += c;
}
}
return obj_list;
}
public static List<String> extractObj(String obj) {
boolean inproperty = false;
String nowProp = "";
String cleanQuotes = "";
StringBuilder sb = new StringBuilder(obj);
if (sb.charAt(0) == '{') {
sb.deleteCharAt(0);
if (sb.charAt(sb.length() - 1) == '}') {
sb.deleteCharAt(sb.length() - 1);
}
}
// Log.i(Constant.tag,sb.toString());
obj = sb.toString();
Log.i(Constant.tag,"OBJ"+obj);
for (int i = 0; i < obj.length(); i++) {
char c = obj.charAt(i);
if (c == '"') {
if (i > 0 && obj.charAt(i - 1) == '\\') {
cleanQuotes += c;
} else {
}
} else {
cleanQuotes += c;
}
}
List<String> listProp = new ArrayList<String>();
inproperty = true;
for (int i = 0; i < cleanQuotes.length(); i++) {
char c = cleanQuotes.charAt(i);
if (c == '{' || c == '[') {
i = lastCharOfProp(i, cleanQuotes);
continue;
}
if (c == ',') {
listProp.add(nowProp);
nowProp = "";
} else {
nowProp += c;
}
if (i == cleanQuotes.length() - 1) {
listProp.add(nowProp);
}
}
return listProp;
}
public static String[] propVal(String s) {
String[] cc = new String[]{"0", "0"};
String prop = "";
String val = "";
boolean nowPropName = true;
if (s.contains(":")) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ':') {
nowPropName = false;
continue;
}
if (nowPropName) {
prop += c;
} else {
val += c;
}
}
}
cc[0] = prop;
cc[1] = val;
// if(cc[0].equals("nilai"))
// Log.i(Constant.tag,"NILAI_PROP: "+ cc[1]);
return cc;
}
private static String eliminateGet(String s) {
s = s.substring(3);
s = s.toLowerCase();
return s;
}
private static String eliminateSet(String s) {
s = s.substring(3);
s = s.toLowerCase();
return s;
}
private static boolean validate(String function) {
if (function.contains("_")) {
return false;
}
return true;
}
private static String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
public static Object getObj(Object o, List<String[]> props) {
Class<? extends Object> c = o.getClass();
Object obj = null;
try {
obj = c.newInstance();
Method[] methods = c.getDeclaredMethods();
for (String[] s : props) {
String propName = capitalize(s[0]);
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
if (!validate(methodName))
continue;
if (methodName.startsWith("get")) {
String prop = eliminateGet(methodName);
Class<?> returnType = methods[i].getReturnType();
final String functionName = "set" + capitalize(prop);
Method set = c.getMethod(functionName,
returnType);
if(prop.equals("namakelas"))
Log.i(Constant.tag,"RETURN TYPE:"+ returnType.getName());
if (prop.toLowerCase().equals(propName.toLowerCase())) {
String propToSet = s[1];
// System.out.println(prop+":"+s[1]);
if (prop.toLowerCase().equals("nilai"))
Log.i(Constant.tag, "NILAI: " + s[1]);
if (returnType.equals(Integer.class)) {
Integer val = !propToSet.matches("-?\\d+") ? 0 : Integer.parseInt(propToSet);
set.invoke(obj, val);
} else
set.invoke(obj, propToSet);
}
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return obj;
}
}
| [
"fajaralmunawwar@yahoo.com"
] | fajaralmunawwar@yahoo.com |
b7652cb3fd00eeb46bd4474d03cadc877ad06cf9 | 46eab0873cb1b1a5d434703d1043f3c4b169178d | /tob6/src/main/java/com/tob/global/DatabaseFactory.java | 11d6f55e3c69f8059d1b6a548426a006cde827b8 | [] | no_license | YeonWooSeong/set18 | 0ed515a51a1c74c7419ebcc7bc913fcadf340652 | 841c1440e9b6a44f3cc9fbc41bd48a06b6d80799 | refs/heads/master | 2021-05-31T09:51:59.415451 | 2016-02-19T01:00:49 | 2016-02-19T01:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | package com.tob.global;
public class DatabaseFactory {
public static Database getDatabase(Vendor vendor, String id,String pass ){
String driver = null, url = null;
switch (vendor) {
case ORACLE:
driver = Constants.ORACLE_DRIVER;
url = Constants.ORACLE_URL;
break;
default:
break;
}
return new DatabaseImpl(driver, url, id, pass);
}
}
| [
"pheonix0717@naver.com"
] | pheonix0717@naver.com |
8dd1ee82aac1780d83fa4159c7703c6e5fa2b32e | d1abc236e76cc385ba235b3815b4bf73e859989c | /DeamonApp/app/src/main/java/com/example/mustufa/deamonapp/BroadcastReceivers/CallReceiver.java | cb8f2783beee666e1470ecefbb9ab6a291562c76 | [] | no_license | Mustufa786/locationAndCallTrackingApp | 529185e438027d9a0a8fe98a790e6f9b26d67666 | 47e3fde35202a3ad2998eddd220aa831cccbee52 | refs/heads/master | 2021-05-04T16:53:53.435671 | 2018-02-22T12:24:38 | 2018-02-22T12:24:38 | 120,261,160 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 5,487 | java | package com.example.mustufa.deamonapp.BroadcastReceivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.example.mustufa.deamonapp.Activities.MainActivity;
import com.example.mustufa.deamonapp.BackgroundTasks.CallingDataUploadingTask;
import com.example.mustufa.deamonapp.Services.LocationUpdateService;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static android.content.ContentValues.TAG;
public class CallReceiver extends BroadcastReceiver {
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static String callStartTime;
private static boolean isIncoming;
private static String savedNumber;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
Log.d(TAG, "onReceive: outgoing Number " + savedNumber);
}else {
String extraState = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
savedNumber = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
state = TelephonyManager.CALL_STATE_RINGING;
}else if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
state = TelephonyManager.CALL_STATE_OFFHOOK;
}else if (extraState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
state = TelephonyManager.CALL_STATE_IDLE;
}
onCallStateChanged(context,state,savedNumber);
}
}
private void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
callStartTime = df.format(date);
savedNumber = number;
Toast.makeText(context, "Incoming Call Ringing" , Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
DateFormat df_ = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date_ = new Date();
callStartTime = df_.format(date_);
Toast.makeText(context, "Outgoing Call Started" , Toast.LENGTH_SHORT).show();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
Log.d(TAG, "onCallStateChanged: Missed Call " + savedNumber + "Call time" + callStartTime);
Toast.makeText(context, "Ringing but no pickup" + savedNumber + " Call time " + callStartTime +
" Date " + new Date() , Toast.LENGTH_SHORT).show();
CallingDataUploadingTask task = new CallingDataUploadingTask(context);
task.execute(MainActivity.deviceID,"Missed Call",savedNumber,
LocationUpdateService.lati,LocationUpdateService.longi,
LocationUpdateService.addr,callStartTime);
}
else if(isIncoming){
Log.d(TAG, "onCallStateChanged: incomming " + savedNumber + "Call Time" + callStartTime);
Toast.makeText(context, "Incoming " + savedNumber + " Call time " + callStartTime , Toast.LENGTH_SHORT).show();
CallingDataUploadingTask task = new CallingDataUploadingTask(context);
task.execute(MainActivity.deviceID,"Incoming Call",savedNumber,
LocationUpdateService.lati,LocationUpdateService.longi,
LocationUpdateService.addr,callStartTime);
}
else{
Log.d(TAG, "onCallStateChanged: outgoing " + savedNumber + "Call Time " + callStartTime);
Toast.makeText(context, "outgoing " + savedNumber + " Call time "
+ callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();
CallingDataUploadingTask task = new CallingDataUploadingTask(context);
task.execute(MainActivity.deviceID,"Outgoing Call",savedNumber,
LocationUpdateService.lati,LocationUpdateService.longi,
LocationUpdateService.addr,callStartTime);
}
break;
}
lastState = state;
}
}
| [
"mustufa_ayub@hotmail.com"
] | mustufa_ayub@hotmail.com |
c7cde12af97235bb10d45a42eb4919894c6915fd | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /eclipsejdt_cluster/58768/tar_0.java | 472c540a48288c1eac078e8ac148ed2ecd4c22bc | [] | no_license | martinezmatias/GenPat-data-C3 | 63cfe27efee2946831139747e6c20cf952f1d6f6 | b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4 | refs/heads/master | 2022-04-25T17:59:03.905613 | 2020-04-15T14:41:34 | 2020-04-15T14:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,227 | java | /*******************************************************************************
* Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.core;
import java.util.Map;
import org.eclipse.core.resources.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
import org.eclipse.jdt.internal.compiler.parser.*;
import org.eclipse.jdt.internal.core.*;
/**
* This class is the entry point for source corrections.
*
* This class is not intended to be subclassed by clients. This class is intended to be instantiated by clients.
*
* @since 2.0
*/
public class CorrectionEngine implements ProblemReasons {
/**
* This field is not intended to be used by client.
*/
protected int correctionStart;
/**
* This field is not intended to be used by client.
*/
protected int correctionEnd;
/**
* This field is not intended to be used by client.
*/
protected int prefixLength;
/**
* This field is not intended to be used by client.
*/
protected ICompilationUnit unit;
/**
* This field is not intended to be used by client.
*/
protected ICorrectionRequestor requestor;
/**
* This field is not intended to be used by client.
*/
protected static final int CLASSES = 0x00000001;
/**
* This field is not intended to be used by client.
*/
protected static final int INTERFACES = 0x00000002;
/**
* This field is not intended to be used by client.
*/
protected static final int IMPORT = 0x00000004;
/**
* This field is not intended to be used by client.
*/
protected static final int METHOD = 0x00000008;
/**
* This field is not intended to be used by client.
*/
protected static final int FIELD = 0x00000010;
/**
* This field is not intended to be used by client.
*/
protected static final int LOCAL = 0x00000020;
/**
* This field is not intended to be used by client.
*/
protected int filter;
/**
* The CorrectionEngine is responsible for computing problem corrections.
*
* @param setting java.util.Map
* set of options used to configure the code correction engine.
* CURRENTLY THERE IS NO CORRECTION SPECIFIC SETTINGS.
*/
public CorrectionEngine(Map setting) {
}
/**
* Performs code correction for the given marker,
* reporting results to the given correction requestor.
*
* Correction results are answered through a requestor.
*
* @param marker
* the marker which describe the problem to correct.
*
* @param targetUnit
* replace the compilation unit given by the marker. Ignored if null.
*
* @param positionOffset
* the offset of position given by the marker.
*
* @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
* @exception JavaModelException currently this exception is never thrown, but the opportunity to thrown an exception
* when the correction failed is kept for later.
* @since 2.0
*/
public void computeCorrections(IMarker marker, ICompilationUnit targetUnit, int positionOffset, ICorrectionRequestor requestor) throws JavaModelException {
IJavaElement element = targetUnit == null ? JavaCore.create(marker.getResource()) : targetUnit;
if(!(element instanceof ICompilationUnit))
return;
ICompilationUnit unit = (ICompilationUnit) element;
int id = marker.getAttribute(IJavaModelMarker.ID, -1);
String[] args = Util.getProblemArgumentsFromMarker(marker.getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$
int start = marker.getAttribute(IMarker.CHAR_START, -1);
int end = marker.getAttribute(IMarker.CHAR_END, -1);
computeCorrections(unit, id, start + positionOffset, end + positionOffset, args, requestor);
}
/**
* Performs code correction for the given IProblem,
* reporting results to the given correction requestor.
*
* Correction results are answered through a requestor.
*
* @param problem
* the problem which describe the problem to correct.
*
* @param targetUnit
* denote the compilation unit in which correction occurs. Cannot be null.
*
* @exception IllegalArgumentException if <code>targetUnit</code> or <code>requestor</code> is <code>null</code>
* @exception JavaModelException currently this exception is never thrown, but the opportunity to thrown an exception
* when the correction failed is kept for later.
* @since 2.0
*/
public void computeCorrections(IProblem problem, ICompilationUnit targetUnit, ICorrectionRequestor requestor) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException(Util.bind("correction.nullUnit")); //$NON-NLS-1$
}
this.computeCorrections(
targetUnit, problem.getID(),
problem.getSourceStart(),
problem.getSourceEnd(),
problem.getArguments(),
requestor);
}
/**
* Ask the engine to compute a correction for the specified problem
* of the given compilation unit.
* Correction results are answered through a requestor.
*
* @param unit org.eclipse.jdt.internal.core.ICompilationUnit
* the compilation unit.
*
* @param id int
* the id of the problem.
*
* @param start int
* a position in the source where the error begin.
*
* @param end int
* a position in the source where the error finish.
*
* @param arguments String[]
* arguments of the problem.
*
* @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
* @exception JavaModelException currently this exception is never thrown, but the opportunity to thrown an exception
* when the correction failed is kept for later.
* @since 2.0
*/
private void computeCorrections(ICompilationUnit unit, int id, int start, int end, String[] arguments, ICorrectionRequestor requestor) throws JavaModelException{
if(id == -1 || arguments == null || start == -1 || end == -1)
return;
if (requestor == null) {
throw new IllegalArgumentException(Util.bind("correction.nullRequestor")); //$NON-NLS-1$
}
this.requestor = requestor;
this.correctionStart = start;
this.correctionEnd = end;
this.unit = unit;
String argument = null;
try {
switch (id) {
// Type correction
case IProblem.FieldTypeNotFound :
case IProblem.ArgumentTypeNotFound :
filter = CLASSES | INTERFACES;
argument = arguments[2];
break;
case IProblem.SuperclassNotFound :
filter = CLASSES;
argument = arguments[0];
break;
case IProblem.InterfaceNotFound :
filter = INTERFACES;
argument = arguments[0];
break;
case IProblem.ExceptionTypeNotFound :
filter = CLASSES;
argument = arguments[1];
break;
case IProblem.ReturnTypeNotFound :
filter = CLASSES | INTERFACES;
argument = arguments[1];
break;
case IProblem.ImportNotFound :
filter = IMPORT;
argument = arguments[0];
break;
case IProblem.UndefinedType :
filter = CLASSES | INTERFACES;
argument = arguments[0];
break;
// Method correction
case IProblem.UndefinedMethod :
filter = METHOD;
argument = arguments[1];
break;
// Field and local variable correction
case IProblem.UndefinedField :
filter = FIELD;
argument = arguments[0];
break;
case IProblem.UndefinedName :
filter = FIELD | LOCAL;
argument = arguments[0];
break;
}
} catch (ArrayIndexOutOfBoundsException e) {
return;
}
if(argument != null) {
correct(argument.toCharArray());
}
}
private void correct(char[] argument) throws JavaModelException {
try {
String source = unit.getSource();
Scanner scanner = new Scanner();
scanner.setSource(source.toCharArray());
scanner.resetTo(correctionStart, correctionEnd);
int token = 0;
char[] argumentSource = CharOperation.NO_CHAR;
// search last segment position
while(true) {
token = scanner.getNextToken();
if (token == TerminalTokens.TokenNameEOF) return;
char[] tokenSource = scanner.getCurrentTokenSource();
argumentSource = CharOperation.concat(argumentSource, tokenSource);
if(!CharOperation.startsWith(argument, argumentSource))
return;
if(CharOperation.equals(argument, argumentSource)) {
correctionStart = scanner.startPosition;
correctionEnd = scanner.currentPosition;
prefixLength = CharOperation.lastIndexOf('.', argument) + 1;
break;
}
}
// search completion position
int completionPosition = correctionStart;
scanner.resetTo(completionPosition, correctionEnd);
int position = completionPosition;
for (int i = 0; i < 4; i++) {
if(scanner.getNextCharAsJavaIdentifierPart()) {
completionPosition = position;
position = scanner.currentPosition;
} else {
break;
}
}
unit.codeComplete(
completionPosition,
completionRequestor
);
} catch (JavaModelException e) {
return;
} catch (InvalidInputException e) {
return;
}
}
/**
* This field is not intended to be used by client.
*/
protected ICompletionRequestor completionRequestor = new ICompletionRequestor() {
public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {}
public void acceptClass(char[] packageName,char[] className,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
if((filter & (CLASSES | INTERFACES)) != 0) {
requestor.acceptClass(
packageName,
className,
CharOperation.subarray(completionName, prefixLength, completionName.length),
modifiers,
correctionStart,
correctionEnd);
} else if((filter & IMPORT) != 0) {
char[] fullName = CharOperation.concat(packageName, className, '.');
requestor.acceptClass(
packageName,
className,
CharOperation.subarray(fullName, prefixLength, fullName.length),
modifiers,
correctionStart,
correctionEnd);
}
}
public void acceptError(IProblem error) {}
public void acceptField(char[] declaringTypePackageName,char[] declaringTypeName,char[] name,char[] typePackageName,char[] typeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
if((filter & FIELD) != 0) {
requestor.acceptField(
declaringTypePackageName,
declaringTypeName,
name,
typePackageName,
typeName,
name,
modifiers,
correctionStart,
correctionEnd);
}
}
public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
if((filter & (CLASSES | INTERFACES)) != 0) {
requestor.acceptInterface(
packageName,
interfaceName,
CharOperation.subarray(completionName, prefixLength, completionName.length),
modifiers,
correctionStart,
correctionEnd);
} else if((filter & IMPORT) != 0) {
char[] fullName = CharOperation.concat(packageName, interfaceName, '.');
requestor.acceptInterface(
packageName,
interfaceName,
CharOperation.subarray(fullName, prefixLength, fullName.length),
modifiers,
correctionStart,
correctionEnd);
}
}
public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance) {}
public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance) {}
public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance) {
if((filter & LOCAL) != 0) {
requestor.acceptLocalVariable(
name,
typePackageName,
typeName,
modifiers,
correctionStart,
correctionEnd);
}
}
public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
if((filter & METHOD) != 0) {
requestor.acceptMethod(
declaringTypePackageName,
declaringTypeName,
selector,
parameterPackageNames,
parameterTypeNames,
parameterNames,
returnTypePackageName,
returnTypeName,
selector,
modifiers,
correctionStart,
correctionEnd);
}
}
public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {}
public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance) {}
public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance) {
if((filter & (CLASSES | INTERFACES | IMPORT)) != 0) {
requestor.acceptPackage(
packageName,
CharOperation.subarray(packageName, prefixLength, packageName.length),
correctionStart,
correctionEnd);
}
}
public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance) {}
public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance) {}
};
} | [
"375833274@qq.com"
] | 375833274@qq.com |
39812fde467d21957b0bfa80ec7729af96100e44 | 2daea301eb04493a0192ae1fe4672c23a79447b9 | /ssm/src/main/java/com/smc/pojo/Book.java | e897208d936b08fddfa74fcd59bdb29c0960dc62 | [] | no_license | Song-Mc/ssm012 | d9c7f200ed3c3787225f02cff5df7ad20bf16dec | fe1a46be68117b6e06f61dcc5a13ad4980e405a5 | refs/heads/master | 2023-01-24T08:16:40.249863 | 2020-12-10T10:32:17 | 2020-12-10T10:32:17 | 319,951,690 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,811 | java | package com.smc.pojo;
import java.math.BigDecimal;
/**
* @author : SongMc
* @date : 2020/11/12 22:15
* className : Book
* package: com.smc.pojo
* version : 1.0
* Description
*/
public class Book {
private Integer id;
private String name;
private String author;
private BigDecimal price;
private Integer sales;
private Integer stock;
public Book(Integer id, String name, String author, BigDecimal price, Integer sales, Integer stock) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
this.sales = sales;
this.stock = stock;
}
public Book() {
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", sales=" + sales +
", stock=" + stock +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
}
| [
"SongMc@163.com"
] | SongMc@163.com |
6f8bdceaf8c637cb588ad29591531f37895c7cdf | 0704ceb2d2d6c5dad7b6e3b97c689fbdc0477bc7 | /Project4/src/main/java/com/revature/servlets/AuthServlet.java | 873787d81692ceb82da3cb872c1536ed16cdd90e | [] | no_license | David-Quillen9826/QMS | 2fcf5a3074b27bec433ae2e644723776a2b23fc5 | 8e02a42a187709b4d55a5c852e5df70b25603d15 | refs/heads/master | 2022-12-07T16:52:16.689191 | 2020-01-08T14:13:39 | 2020-01-08T14:13:39 | 232,559,626 | 0 | 0 | null | 2022-11-15T23:33:57 | 2020-01-08T12:35:00 | TypeScript | UTF-8 | Java | false | false | 1,807 | java | package com.revature.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.daos.UserDao;
import com.revature.models.User;
public class AuthServlet extends HttpServlet {
private UserDao userDao = UserDao.currentImplementation;
ObjectMapper om = new ObjectMapper();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("uri = " + req.getRequestURI());
if ("/project4/auth/login".equals(req.getRequestURI())) {
User credentials = (User) om.readValue(req.getReader(), User.class);
System.out.println(credentials.toString());
User loggedInUser = userDao.findByUsernameAndPassword(credentials.getUsername(), credentials.getPassword());
if (loggedInUser == null) {
System.out.println(401);
resp.setStatus(401); // Unauthorized status code
return;
} else {
System.out.println(201);
resp.setStatus(201);
req.getSession().setAttribute("User", loggedInUser);
resp.getWriter().write(om.writeValueAsString(loggedInUser));
return;
}
} else if ("/project4/auth/logout".equals(req.getRequestURI())) {
System.out.println("logged out");
resp.setStatus(201); // success code
req.getSession().invalidate();
return;
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if ("/project1/auth/session-user".equals(req.getRequestURI())) {
String json = om.writeValueAsString(req.getSession().getAttribute("user"));
resp.getWriter().write(json);
}
}
}
| [
"david.quillen@revature.net"
] | david.quillen@revature.net |
d7abe4f7f682cae9f4ce2189cf4e29bf7cba7e39 | 607aa170f1ab6070b047a9f9693e34fee280a423 | /src/main/java/molab/ApplicationStartup.java | 837b856cc064ae5f8caae2691ac519d92cdf1f1a | [] | no_license | cocoy2006/ibc | 6b7090f43e33752c76c2e602b7dc065f156888c4 | 003bcb9acb62db3d7e93512adee98162c57d7236 | refs/heads/master | 2021-05-06T20:14:28.193724 | 2017-11-27T08:32:13 | 2017-11-27T08:32:13 | 111,658,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 622 | java | package molab;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import molab.properties.WxProperties;
import weixin.popular.support.TokenManager;
@Component
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private WxProperties wp;
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
TokenManager.init(wp.getId(), wp.getSecret());
}
}
| [
"yekk@molab.com"
] | yekk@molab.com |
4976df3b9b77682456782c477bf3f0e7713772bd | cc289d8473c60e9cfab34937875d3f2f5488da69 | /uk/me/alexhaig/FooCompile/NodeStmt.java | 33e8846f1b26bd8e20056c04d05aaf68d2d3969a | [] | no_license | apparentlymart/FooCompile | a1986fd439e6d0873329d71fc6878ced2d0f483b | eb66765d9210e9ba91f7ddafdfd863af44178b4b | refs/heads/master | 2023-08-30T21:19:53.027902 | 2005-05-02T07:00:00 | 2012-01-09T04:06:18 | 3,133,952 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,044 | java |
package uk.me.alexhaig.FooCompile;
public class NodeStmt extends Node {
public static boolean canStart(Tokeniser t) {
return NodeCodeBlock.canStart(t)
|| NodeExprStmt.canStart(t)
|| NodeIfStmt.canStart(t)
|| NodeSelectStmt.canStart(t)
|| NodeVariableDecStmt.canStart(t)
|| NodeForStmt.canStart(t)
|| NodeDeleteStmt.canStart(t)
|| NodeReturnStmt.canStart(t)
|| NodeDelegateAssignStmt.canStart(t)
|| NodeWhileStmt.canStart(t);
}
public static Node parse(Tokeniser t) {
int startline = t.getLine(), startcolumn = t.getColumn();
if (NodeIfStmt.canStart(t)) return setPos(NodeIfStmt.parse(t), startline, startcolumn);
if (NodeWhileStmt.canStart(t)) return setPos(NodeWhileStmt.parse(t), startline, startcolumn);
if (NodeSelectStmt.canStart(t)) return setPos(NodeSelectStmt.parse(t), startline, startcolumn);
if (NodeVariableDecStmt.canStart(t)) return setPos(NodeVariableDecStmt.parse(t), startline, startcolumn);
if (NodeForStmt.canStart(t)) return setPos(NodeForStmt.parse(t), startline, startcolumn);
if (NodeDeleteStmt.canStart(t)) return setPos(NodeDeleteStmt.parse(t), startline, startcolumn);
if (NodeReturnStmt.canStart(t)) return setPos(NodeReturnStmt.parse(t), startline, startcolumn);
if (NodeDelegateAssignStmt.canStart(t)) return setPos(NodeDelegateAssignStmt.parse(t), startline, startcolumn);
if (NodeCodeBlock.canStart(t)) return setPos(NodeCodeBlock.parse(t), startline, startcolumn);
if (NodeExprStmt.canStart(t)) return setPos(NodeExprStmt.parse(t), startline, startcolumn);
throw new InternalErrorException("Can't parse statement");
}
public void printSelf(IndentingWriter w) {
w.println(getClassName() + " (printSelf not implemented);");
}
public String toString() {
return "NodeStmt()";
}
}
| [
"mart@degeneration.co.uk"
] | mart@degeneration.co.uk |
3277c7f92558f0b4b8e1f8901fb6a542905a0fe5 | ca57c3651db75069fcbbb7c5190e6a328331660e | /src/com/siwuxie095/forme/designpattern/category/chapter12th/example6th/Quackologist.java | acecb9ca576f794339ba9898434445fc2e63e457 | [] | no_license | gouyanzhan/HelloWorld | f915ec8eabf8878b0c01fb8ec29b869e6fd68c5f | 8cd9dc117d301d10207690052f2f27de2d9b9e2c | refs/heads/master | 2022-03-25T07:31:52.842092 | 2022-03-11T07:08:30 | 2022-03-11T07:08:30 | 164,224,001 | 1 | 1 | null | 2019-01-07T14:18:44 | 2019-01-05T14:52:23 | Java | UTF-8 | Java | false | false | 378 | java | package com.siwuxie095.forme.designpattern.category.chapter12th.example6th;
/**
* 呱呱叫学家(观察者)
*
* @author Jiajing Li
* @date 2019-11-10 11:42:22
*/
class Quackologist implements Observer {
@Override
public void update(Observable duck) {
System.out.println("Quackologist: " + duck.getClass().getSimpleName() + " just quacked.");
}
}
| [
"834879583@qq.com"
] | 834879583@qq.com |
cef709f66e70c697fefc4d8542f80cb5bff08303 | a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb | /dm-20170622/src/main/java/com/aliyun/dm20170622/models/CreateDomainResponse.java | cbf4203840da09ba0d9726d00604e13cc121aa45 | [
"Apache-2.0"
] | permissive | aliyun/alibabacloud-java-sdk | 83a6036a33c7278bca6f1bafccb0180940d58b0b | 008923f156adf2e4f4785a0419f60640273854ec | refs/heads/master | 2023-09-01T04:10:33.640756 | 2023-09-01T02:40:45 | 2023-09-01T02:40:45 | 288,968,318 | 40 | 45 | null | 2023-06-13T02:47:13 | 2020-08-20T09:51:08 | Java | UTF-8 | Java | false | false | 1,336 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.dm20170622.models;
import com.aliyun.tea.*;
public class CreateDomainResponse extends TeaModel {
@NameInMap("headers")
@Validation(required = true)
public java.util.Map<String, String> headers;
@NameInMap("statusCode")
@Validation(required = true)
public Integer statusCode;
@NameInMap("body")
@Validation(required = true)
public CreateDomainResponseBody body;
public static CreateDomainResponse build(java.util.Map<String, ?> map) throws Exception {
CreateDomainResponse self = new CreateDomainResponse();
return TeaModel.build(map, self);
}
public CreateDomainResponse setHeaders(java.util.Map<String, String> headers) {
this.headers = headers;
return this;
}
public java.util.Map<String, String> getHeaders() {
return this.headers;
}
public CreateDomainResponse setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
return this;
}
public Integer getStatusCode() {
return this.statusCode;
}
public CreateDomainResponse setBody(CreateDomainResponseBody body) {
this.body = body;
return this;
}
public CreateDomainResponseBody getBody() {
return this.body;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
bfb515caabb66628c1e22b9e809aa5b51f2a2025 | e42275f69adb0e68139db9cf54d13d054cbba0db | /src/main/java/com/odero/reddit/model/VerificationToken.java | bb82b935e2a036822ce45d7b81ddfe0601d44950 | [] | no_license | OderoOluoch/RedditSpringBoot | 7a59bb72ce49de8ee24580b1da1c9a9a73e18505 | 517d3d0e3bd4454539adcf1cec008c600a673cf5 | refs/heads/master | 2023-07-01T06:45:10.670908 | 2021-08-08T19:49:45 | 2021-08-08T19:49:45 | 391,583,911 | 0 | 0 | null | 2021-08-08T19:49:46 | 2021-08-01T09:30:50 | Java | UTF-8 | Java | false | false | 573 | java | package com.odero.reddit.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.Instant;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.GenerationType.IDENTITY;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "token")
public class VerificationToken {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String token;
@OneToOne(fetch = LAZY)
private User user;
private Instant expiryDate;
}
| [
"oderoluoch@gmail.com"
] | oderoluoch@gmail.com |
cb4ccad8651a524edeacbb97f50f82df9ab901cd | 2b8acfd16cd45e99f270c799ffb8f310860f6848 | /app/src/main/java/ir/sadjadtalakoob/tarebar_shop/RetrofitClientInstance2.java | 9e239a88d589d75d79789875965090794b7c0187 | [] | no_license | sadjadtalakoob74/TareBar-Shop | bf2f4bbb84a6776b21486f2daace8da638761514 | 514aa9bf58b3a704e5fb3400bb9d7be02221999b | refs/heads/master | 2023-03-21T05:37:42.345435 | 2021-03-07T20:32:50 | 2021-03-07T20:32:50 | 345,446,858 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package ir.sadjadtalakoob.tarebar_shop;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by praka on 12/24/2017.
*/
public class RetrofitClientInstance2 {
private static Retrofit retrofit;
//private static final String BASE_URL = "https://drive.google.com";
//private static final String BASE_URL = "https://raw.githubusercontent.com/";
private static final String BASE_URL = "https://torchofknowledge.ir";
public static Retrofit getRetrofitInstance2() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
| [
"sadjadtalakob74@gmail.com"
] | sadjadtalakob74@gmail.com |
2d0b7664d72b9ef2650572365de89c201820043b | 6d66a9a1e32183d874909912dfe73fa35a9027bd | /app/src/main/java/com/catatanasad/navigationdrawer/fragment/TrainingFragment.java | b5ba77b468ab0affc0d3da339a3291aafce805ed | [] | no_license | RahmahNajiyah/web-view-with-nav-draw | cae818d352417f50a647faab3a242dc6c4b9183d | a0344c789a5147e29f83ab22c317153b2f5ba65f | refs/heads/master | 2020-03-27T15:49:57.372672 | 2018-08-29T14:06:39 | 2018-08-29T14:06:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,521 | java | package com.catatanasad.navigationdrawer.fragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
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.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.catatanasad.navigationdrawer.R;
/**
* A simple {@link Fragment} subclass.
*/
public class TrainingFragment extends Fragment {
public TrainingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_training, container, false);
}
// todo panggil method onViewCreated
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// todo id webviewnya
WebView webView = view.findViewById(R.id.web_view);
// todo set url
String url = "http://idn.id/training/";
// todo load url
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
final ProgressDialog dialog = ProgressDialog.show(getContext(), "", "Loading");
webView.setWebViewClient(new WebViewClient(){
// todo ketika url error
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(getContext(), "URL Error", Toast.LENGTH_SHORT).show();
}
// todo ketika halaman web loading
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
dialog.show();
}
// todo ketika halaman web finish loading
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
}
}
| [
"asadhamasy@gmail.com"
] | asadhamasy@gmail.com |
b95216524a82f080a424c4655f4cb9cac0852ad0 | 6092bc62be290c65c3fab5976a5f7029265b920b | /ProjecteHelloWordApp/src/demo/Persona.java | cd34ca59df991f222d95f02a4a1e7e7affc0bd06 | [] | no_license | infomila/GitTesting | 187aa9859469e7f6f596c770885dda15496460aa | 895f5555596069e022316f66e22b6fb11599627e | refs/heads/master | 2021-01-10T09:47:42.206694 | 2016-01-21T12:28:37 | 2016-01-21T12:28:37 | 48,172,913 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 810 | java | package demo;
/**
*
* @author bernat
*/
public class Persona {
private int id;
private String nom;
private String cognom;
public Persona(int id, String nom, String cognom) {
this.id = id;
this.nom = nom;
setCognom(cognom);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getCognom() {
return cognom;
}
public void setCognomX(String cognom) {
this.cognom = cognom;
}
public void funcioNova3_0(){
System.out.println("YYYYY");
}
private branca(){
// Més canvis
System.out.println("XXXXX");
}
}
| [
"bernat.orellana@gmail.com"
] | bernat.orellana@gmail.com |
ec59ce6d397c13a6093c19b3beb362d983c33c34 | a666c798a28223f97d74d21786f9a4f4000d5acb | /edu.harvard.i2b2.ontology/gensrc/edu/harvard/i2b2/ontology/datavo/i2b2message/ConditionsType.java | 4fe610adde65cc8fc42583a23c8e6df8fe535557 | [] | no_license | gmacdonnell/i2b2-fsu-1704 | d65239edf95aa3b25844a6ed9af599e06dcaa185 | 12638996fe46a7014ac827e359c40e5b0e8c1d3e | refs/heads/master | 2021-01-23T07:02:31.537241 | 2015-01-27T15:09:33 | 2015-01-27T15:09:33 | 29,916,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,289 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-558
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.26 at 12:47:09 PM EST
//
package edu.harvard.i2b2.ontology.datavo.i2b2message;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for conditionsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="conditionsType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="condition" maxOccurs="unbounded">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ERROR"/>
* <enumeration value="FATAL_ERROR"/>
* <enumeration value="WARNING"/>
* <enumeration value="INFO"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="coding_system" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "conditionsType", propOrder = {
"condition"
})
public class ConditionsType {
@XmlElement(required = true)
protected List<ConditionsType.Condition> condition;
/**
* Gets the value of the condition property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the condition property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCondition().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ConditionsType.Condition }
*
*
*/
public List<ConditionsType.Condition> getCondition() {
if (condition == null) {
condition = new ArrayList<ConditionsType.Condition>();
}
return this.condition;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ERROR"/>
* <enumeration value="FATAL_ERROR"/>
* <enumeration value="WARNING"/>
* <enumeration value="INFO"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="coding_system" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class Condition {
@XmlValue
protected String value;
@XmlAttribute(required = true)
protected String type;
@XmlAttribute(name = "coding_system", required = true)
protected String codingSystem;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the codingSystem property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingSystem() {
return codingSystem;
}
/**
* Sets the value of the codingSystem property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingSystem(String value) {
this.codingSystem = value;
}
}
}
| [
"gmacdonnell@fsu.edu"
] | gmacdonnell@fsu.edu |
46ba299ec05fd87924751f965c0885736ab70227 | 892ce164a91e473d808aedd0873bb911711a0120 | /src/main/java/com/szcxsl/oa/modules/sys/utils/LogUtils.java | 9bfc7b1f991e868135d1f61800e1aa00f0140ee1 | [
"Apache-2.0"
] | permissive | TinLLara/kserp | 96e7a4e30e975a595fc5a6fb86e8e46b75a79158 | c02c3813889d5b1dcf4350e7ef44204aa99a4ce4 | refs/heads/master | 2020-05-06T13:59:46.163793 | 2019-05-21T14:26:55 | 2019-05-21T14:26:55 | 180,167,390 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,982 | java | /**
* Copyright © 2012-2014 <a href="http://www.kszhineng.cn">OA</a> All rights reserved.
*/
package com.szcxsl.oa.modules.sys.utils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.method.HandlerMethod;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.szcxsl.oa.common.config.Global;
import com.szcxsl.oa.common.utils.CacheUtils;
import com.szcxsl.oa.common.utils.Exceptions;
import com.szcxsl.oa.common.utils.SpringContextHolder;
import com.szcxsl.oa.common.utils.StringUtils;
import com.szcxsl.oa.modules.sys.dao.LogDao;
import com.szcxsl.oa.modules.sys.dao.MenuDao;
import com.szcxsl.oa.modules.sys.entity.Log;
import com.szcxsl.oa.modules.sys.entity.Menu;
import com.szcxsl.oa.modules.sys.entity.User;
/**
* 字典工具类
* @author Shi Lei
* @version 2014-11-7
*/
public class LogUtils {
public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
private static LogDao logDao = SpringContextHolder.getBean(LogDao.class);
private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
/**
* 保存日志
*/
public static void saveLog(HttpServletRequest request, String title){
saveLog(request, null, null, title);
}
/**
* 保存日志
*/
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
User user = UserUtils.getUser();
if (user != null && user.getId() != null){
Log log = new Log();
log.setTitle(title);
log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
log.setRemoteAddr(StringUtils.getRemoteAddr(request));
log.setUserAgent(request.getHeader("user-agent"));
log.setRequestUri(request.getRequestURI());
log.setParams(request.getParameterMap());
log.setMethod(request.getMethod());
// 异步保存日志
new SaveLogThread(log, handler, ex).start();
}
}
/**
* 保存日志线程
*/
public static class SaveLogThread extends Thread{
private Log log;
private Object handler;
private Exception ex;
public SaveLogThread(Log log, Object handler, Exception ex){
super(SaveLogThread.class.getSimpleName());
this.log = log;
this.handler = handler;
this.ex = ex;
}
@Override
public void run() {
// 获取日志标题
if (StringUtils.isBlank(log.getTitle())){
String permission = "";
if (handler instanceof HandlerMethod){
Method m = ((HandlerMethod)handler).getMethod();
RequiresPermissions rp = m.getAnnotation(RequiresPermissions.class);
permission = (rp != null ? StringUtils.join(rp.value(), ",") : "");
}
log.setTitle(getMenuNamePath(log.getRequestUri(), permission));
}
// 如果有异常,设置异常信息
log.setException(Exceptions.getStackTraceAsString(ex));
// 如果无标题并无异常日志,则不保存信息
if (StringUtils.isBlank(log.getTitle()) && StringUtils.isBlank(log.getException())){
return;
}
// 保存日志信息
log.preInsert();
logDao.insert(log);
}
}
/**
* 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
*/
public static String getMenuNamePath(String requestUri, String permission){
String href = StringUtils.substringAfter(requestUri, Global.getAdminPath());
@SuppressWarnings("unchecked")
Map<String, String> menuMap = (Map<String, String>)CacheUtils.get(CACHE_MENU_NAME_PATH_MAP);
if (menuMap == null){
menuMap = Maps.newHashMap();
List<Menu> menuList = menuDao.findAllList(new Menu());
for (Menu menu : menuList){
// 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
String namePath = "";
if (menu.getParentIds() != null){
List<String> namePathList = Lists.newArrayList();
for (String id : StringUtils.split(menu.getParentIds(), ",")){
if (Menu.getRootId().equals(id)){
continue; // 过滤跟节点
}
for (Menu m : menuList){
if (m.getId().equals(id)){
namePathList.add(m.getName());
break;
}
}
}
namePathList.add(menu.getName());
namePath = StringUtils.join(namePathList, "-");
}
// 设置菜单名称路径
if (StringUtils.isNotBlank(menu.getHref())){
menuMap.put(menu.getHref(), namePath);
}else if (StringUtils.isNotBlank(menu.getPermission())){
for (String p : StringUtils.split(menu.getPermission())){
menuMap.put(p, namePath);
}
}
}
CacheUtils.put(CACHE_MENU_NAME_PATH_MAP, menuMap);
}
String menuNamePath = menuMap.get(href);
if (menuNamePath == null){
for (String p : StringUtils.split(permission)){
menuNamePath = menuMap.get(p);
if (StringUtils.isNotBlank(menuNamePath)){
break;
}
}
if (menuNamePath == null){
return "";
}
}
return menuNamePath;
}
}
| [
"286185834@qq.com"
] | 286185834@qq.com |
f67a2aee871cdacfa814607f38f96983a56dd91e | 79ccbacdb00e883ed2efb9d629bdd5c9cae46c61 | /src/main/java/kr/or/ddit/user/repository/UserDao.java | 8ff92b22d897ef48ff7303cff65825b7e3304298 | [] | no_license | ParkCheaeeun/jsp | 9cad1b311d314be3e6d4bd5d045dba032b02f79d | a575f1a11e192c4a8a0d0031da6c0178614aa1d0 | refs/heads/master | 2021-06-19T00:00:40.206760 | 2019-09-06T02:29:57 | 2019-09-06T02:29:57 | 199,800,156 | 0 | 0 | null | 2021-04-22T18:30:37 | 2019-07-31T07:09:18 | JavaScript | UTF-8 | Java | false | false | 2,460 | java | package kr.or.ddit.user.repository;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.common.model.Page;
import kr.or.ddit.user.model.User;
import kr.or.ddit.util.mybatis;
public class UserDao implements IUserDao{
@Override
public List<User> getUserList(SqlSession sqlSession) {
//db에서 조회가 되었다고 가정하고 가짜 객체를 리턴
// List<UserVo> userList = new ArrayList<UserVo>();
// userList.add(new UserVo("brown"));
// userList.add(new UserVo("Sally"));
// userList.add(new UserVo("cony"));
// userList.add(new UserVo("moon"));
// userList.add(new UserVo("james"));
return sqlSession.selectList("user.getUserList");
}
/**
* Method : getUser
* 작성자 : PC-09
* 변경이력 :
* @param userId
* @return
* Method 설명 : userId를 갖는 사용자 조회
*/
@Override
public User getUser(SqlSession sqlSession, String userId) {
User userVo = sqlSession.selectOne("user.getUser", userId);
sqlSession.close();
return userVo;
}
@Override
public List<User> getUserHalfList(SqlSession sqlSession) {
List<User> list = sqlSession.selectList("user.getUserListOnlyHalf");
return list;
}
@Override
public List<User> getUserPagingList(SqlSession sqlSession, Page page) {
List<User> list = sqlSession.selectList("user.getUserPagingList", page);
return list;
}
/**
* Method : getUserTotalCount
* 작성자 : PC-09
* 변경이력 :
* @param sqlSession
* @return
* Method 설명 : 전체 사용자 건수 조회
*/
public int getUserTotalCount(SqlSession sqlSession) {
return sqlSession.selectOne("user.getUserTotalCnt");
}
/**
* Method : insertUser
* 작성자 : SEM-PC
* 변경이력 :
* @param sqlSession
* @param user
* @return
* Method 설명 : 사용자 등록
*/
@Override
public int insertUser(SqlSession sqlSession, User user) {
return sqlSession.insert("user.insertUser", user);
}
/**
* Method : deleteUser
* 작성자 : SEM-PC
* 변경이력 :
* @param sqlSession
* @param userId
* @return
* Method 설명 : 사용자 삭제
*/
@Override
public int deleteUser(SqlSession sqlSession, String userId) {
return sqlSession.delete("user.deleteUser", userId);
}
@Override
public int updateUser(SqlSession sqlSession, User user) {
return sqlSession.update("user.updateUser", user);
}
}
| [
"ParkCheaeeun.codms121@gmail.com"
] | ParkCheaeeun.codms121@gmail.com |
8252e7b7536870e9573ed70d7a8349b65a752a8a | beb573fe2d9ceb06f0e203b1ca4c8760c3e2685b | /src/main/java/me/antonle/telegrambot/itbot/disruptor/UpdateDisruptor.java | 4a431c4fef76cbfbf4dfb9e79328aef65572c87a | [
"MIT"
] | permissive | gherolyants/itbot | f10a5a17011e68e2b55be82c78592088454bbf28 | 73dd2b5c0dc046ab115b84a114ae192eff0248d5 | refs/heads/develop | 2021-01-11T09:44:25.298673 | 2015-09-22T17:50:52 | 2015-09-22T17:50:52 | 48,324,694 | 0 | 0 | null | 2015-12-20T14:44:37 | 2015-12-20T14:44:36 | Java | UTF-8 | Java | false | false | 1,971 | java | package me.antonle.telegrambot.itbot.disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import me.antonle.telegrambot.itbot.properties.UpdateDisruptorProperties;
import me.antonle.telegrambot.itbot.service.MessageHandlerService;
import me.antonle.telegrambot.itbot.telegram.model.Update;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@Service
public class UpdateDisruptor {
@Autowired
private MessageHandlerService messageHandler;
private Executor executor = Executors.newCachedThreadPool();
private Disruptor<UpdateEvent> disruptor;
@Autowired
private UpdateDisruptorProperties disruptorProperties;
public UpdateDisruptor() {
}
private void handleEvent(UpdateEvent event, long sequence, boolean endOfBatch) {
Update update = event.getUpdate();
messageHandler.handle(update);
}
private void translate(UpdateEvent event, long sequence, Update update) {
event.setUpdate(update);
}
@SuppressWarnings("unchecked")
@PostConstruct
public void init() {
disruptor = new Disruptor<>(UpdateEvent::new, disruptorProperties.getBufferSize(), executor);
disruptor.handleEventsWith(this::handleEvent);
disruptor.start();
}
public void processEvent(Update update) {
RingBuffer<UpdateEvent> ringBuffer = disruptor.getRingBuffer();
ringBuffer.publishEvent(this::translate, update);
}
public void setMessageHandler(MessageHandlerService messageHandler) {
this.messageHandler = messageHandler;
}
public void setDisruptorProperties(UpdateDisruptorProperties disruptorProperties) {
this.disruptorProperties = disruptorProperties;
}
}
| [
"le@physics.msu.ru"
] | le@physics.msu.ru |
a3f4a32b5bfc9f1a9c8339e5ecfbde81bfdb50b3 | d00af6c547e629983ff777abe35fc9c36b3b2371 | /jboss-all/testsuite/src/main/org/jboss/test/cmp2/commerce/ManyToManyBiTest.java | a52d96f27854438a235e47f1d0f09f4a20a9ebb2 | [] | no_license | aosm/JBoss | e4afad3e0d6a50685a55a45209e99e7a92f974ea | 75a042bd25dd995392f3dbc05ddf4bbf9bdc8cd7 | refs/heads/master | 2023-07-08T21:50:23.795023 | 2013-03-20T07:43:51 | 2013-03-20T07:43:51 | 8,898,416 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 10,258 | java | package org.jboss.test.cmp2.commerce;
import java.util.Collection;
import java.util.Iterator;
import javax.naming.InitialContext;
import junit.framework.TestCase;
import net.sourceforge.junitejb.EJBTestCase;
public class ManyToManyBiTest extends EJBTestCase {
public ManyToManyBiTest(String name) {
super(name);
}
private ProductHome getProductHome() {
try {
InitialContext jndiContext = new InitialContext();
return (ProductHome) jndiContext.lookup("commerce/Product");
} catch(Exception e) {
e.printStackTrace();
fail("Exception in getProduct: " + e.getMessage());
}
return null;
}
private ProductCategoryHome getProductCategoryHome() {
try {
InitialContext jndiContext = new InitialContext();
return (ProductCategoryHome)
jndiContext.lookup("commerce/ProductCategory");
} catch(Exception e) {
e.printStackTrace();
fail("Exception in getProductCategory: " + e.getMessage());
}
return null;
}
private Product a1;
private Product a2;
private Product a3;
private Product a4;
private Product a5;
private ProductCategory b1;
private ProductCategory b2;
private ProductCategory b3;
private ProductCategory b4;
private ProductCategory b5;
public void setUpEJB() throws Exception {
ProductHome productHome = getProductHome();
ProductCategoryHome productCategoryHome = getProductCategoryHome();
// clean out the db
deleteAllProducts(productHome);
deleteAllProductCategories(productCategoryHome);
// setup the before change part of the test
beforeChange(productHome, productCategoryHome);
}
private void beforeChange(
ProductHome productHome,
ProductCategoryHome productCategoryHome) throws Exception {
// Before change:
a1 = productHome.create();
a2 = productHome.create();
a3 = productHome.create();
a4 = productHome.create();
a5 = productHome.create();
b1 = productCategoryHome.create();
b2 = productCategoryHome.create();
b3 = productCategoryHome.create();
b4 = productCategoryHome.create();
b5 = productCategoryHome.create();
a1.getProductCategories().add(b1);
a1.getProductCategories().add(b2);
a2.getProductCategories().add(b1);
a2.getProductCategories().add(b2);
a2.getProductCategories().add(b3);
a3.getProductCategories().add(b2);
a3.getProductCategories().add(b3);
a3.getProductCategories().add(b4);
a4.getProductCategories().add(b3);
a4.getProductCategories().add(b4);
a4.getProductCategories().add(b5);
a5.getProductCategories().add(b4);
a5.getProductCategories().add(b5);
assertTrue(a1.getProductCategories().contains(b1));
assertTrue(a1.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b1));
assertTrue(a2.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b2));
assertTrue(a3.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b3));
assertTrue(a4.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b5));
assertTrue(a5.getProductCategories().contains(b4));
assertTrue(a5.getProductCategories().contains(b5));
assertTrue(b1.getProducts().contains(a1));
assertTrue(b1.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a1));
assertTrue(b2.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a2));
assertTrue(b3.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a3));
assertTrue(b4.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a5));
assertTrue(b5.getProducts().contains(a4));
assertTrue(b5.getProducts().contains(a5));
}
// a1.setB(a3.getB());
public void test_a1SetB_a3GetB() {
// Change:
a1.setProductCategories(a3.getProductCategories());
// Expected result:
assertTrue(!a1.getProductCategories().contains(b1));
assertTrue(a1.getProductCategories().contains(b2));
assertTrue(a1.getProductCategories().contains(b3));
assertTrue(a1.getProductCategories().contains(b4));
assertTrue(a2.getProductCategories().contains(b1));
assertTrue(a2.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b2));
assertTrue(a3.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b3));
assertTrue(a4.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b5));
assertTrue(a5.getProductCategories().contains(b4));
assertTrue(a5.getProductCategories().contains(b5));
assertTrue(!b1.getProducts().contains(a1));
assertTrue(b1.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a1));
assertTrue(b2.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a1));
assertTrue(b3.getProducts().contains(a2));
assertTrue(b3.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a1));
assertTrue(b4.getProducts().contains(a3));
assertTrue(b4.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a5));
assertTrue(b5.getProducts().contains(a4));
assertTrue(b5.getProducts().contains(a5));
}
// a1.getB().add(b3);
public void test_a1GetB_addB3() {
// Change:
a1.getProductCategories().add(b3);
// Expected result:
assertTrue(a1.getProductCategories().contains(b1));
assertTrue(a1.getProductCategories().contains(b2));
assertTrue(a1.getProductCategories().contains(b3));
assertTrue(a2.getProductCategories().contains(b1));
assertTrue(a2.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b2));
assertTrue(a3.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b3));
assertTrue(a4.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b5));
assertTrue(a5.getProductCategories().contains(b4));
assertTrue(a5.getProductCategories().contains(b5));
assertTrue(b1.getProducts().contains(a1));
assertTrue(b1.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a1));
assertTrue(b2.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a1));
assertTrue(b3.getProducts().contains(a2));
assertTrue(b3.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a3));
assertTrue(b4.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a5));
assertTrue(b5.getProducts().contains(a4));
assertTrue(b5.getProducts().contains(a5));
}
// a2.getB().remove(b2);
public void test_a2GetB_removeB2() {
// Change:
a2.getProductCategories().remove(b2);
// Expected result:
assertTrue(a1.getProductCategories().contains(b1));
assertTrue(a1.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b1));
assertTrue(!a2.getProductCategories().contains(b2));
assertTrue(a2.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b2));
assertTrue(a3.getProductCategories().contains(b3));
assertTrue(a3.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b3));
assertTrue(a4.getProductCategories().contains(b4));
assertTrue(a4.getProductCategories().contains(b5));
assertTrue(a5.getProductCategories().contains(b4));
assertTrue(a5.getProductCategories().contains(b5));
assertTrue(b1.getProducts().contains(a1));
assertTrue(b1.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a1));
assertTrue(!b2.getProducts().contains(a2));
assertTrue(b2.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a2));
assertTrue(b3.getProducts().contains(a3));
assertTrue(b3.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a3));
assertTrue(b4.getProducts().contains(a4));
assertTrue(b4.getProducts().contains(a5));
assertTrue(b5.getProducts().contains(a4));
assertTrue(b5.getProducts().contains(a5));
}
public void tearDownEJB() throws Exception {
}
public void deleteAllProducts(ProductHome productHome) throws Exception {
// delete all Products
Iterator currentProducts = productHome.findAll().iterator();
while(currentProducts.hasNext()) {
Product p = (Product)currentProducts.next();
p.remove();
}
}
public void deleteAllProductCategories(ProductCategoryHome productCategoryHome) throws Exception {
// delete all ProductCategories
Iterator currentProductCategories = productCategoryHome.findAll().iterator();
while(currentProductCategories.hasNext()) {
ProductCategory pc = (ProductCategory)currentProductCategories.next();
pc.remove();
}
}
}
| [
"rasmus@dll.nu"
] | rasmus@dll.nu |
ce6bc729b2d87e300ffaf8591ddf69c1f5ee63f1 | 85add549bdaa78108fbfad28f7f8d0bc1d0981e3 | /src/main/java/com/ning/hfind/primary/ExpressionFactory.java | 1dadd38e33bc0730209409ba486f76bb7a9b72e1 | [
"Apache-2.0"
] | permissive | deltaprojects/hfind | afba5161049260e9b32747183a0aac8877c2849a | 49558bfafa8eefa98234cc74321bc69e7343a5fa | refs/heads/master | 2020-12-31T01:02:36.214593 | 2014-10-29T11:14:19 | 2014-10-29T11:14:19 | 25,916,249 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,559 | java | /*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.hfind.primary;
import com.ning.hfind.util.PushbackIterator;
import org.apache.commons.cli.Option;
import org.apache.oro.text.regex.MalformedPatternException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class ExpressionFactory
{
public static Expression buildExpressionFromCommandLine(PushbackIterator<Option> iterator)
{
if (!iterator.hasNext()) {
return Expression.TRUE;
}
else {
try {
return build(iterator);
}
catch (MalformedPatternException e) { // from -name
throw new IllegalArgumentException(e);
}
}
}
private static Expression build(PushbackIterator<Option> iterator) throws MalformedPatternException
{
// Extract leftmost primary from the expression
Primary leftPrimary = PrimaryFactory.primaryFromOption(iterator.next());
// We ignore certain primaries
if (leftPrimary == null) {
return build(iterator);
}
if (!iterator.hasNext()) {
return new Expression(leftPrimary, Primary.ALWAYS_MATCH, new AndOperand());
}
// Extract operand
Operand operand = OperandFactory.operandFromOption(iterator);
// If it's an OR, compute
// leftPrimary OR (rest of the command line)
if (operand.getClass().equals(OrOperand.class)) {
return new Expression(leftPrimary, build(iterator), operand);
}
// It's an AND, regardless if -a was explicitly specified
if (!iterator.hasNext()) {
throw new IllegalArgumentException("Invalid expression");
}
// Extract right primary
Primary rightPrimary = PrimaryFactory.primaryFromOption(iterator.next());
Expression andExpression = new Expression(leftPrimary, rightPrimary, new AndOperand());
if (!iterator.hasNext()) {
return andExpression;
}
else {
// Extract next operand
operand = OperandFactory.operandFromOption(iterator);
return new Expression(andExpression, build(iterator), operand);
}
}
public static Iterator<Option> sanitizeCommandLine(Option[] options)
{
ArrayList<Option> optionsList = new ArrayList<Option>(Arrays.asList(options));
Iterator<Option> optionIterator = (Iterator<Option>) optionsList.iterator();
while (optionIterator.hasNext()) {
Option option = optionIterator.next();
try {
if (PrimaryFactory.primaryFromOption(option) == null) {
optionIterator.remove();
}
}
catch (MalformedPatternException ignored) {
}
catch (IllegalArgumentException ignored) {
}
}
return optionsList.iterator();
}
}
| [
"pierre@mouraf.org"
] | pierre@mouraf.org |
5d3f224967748da58b634a478a7864b375c9a1ad | 097d439cafff15a54152379895c14395d05f9b96 | /SMS.java | 0e818c73e935090060fb1e41bc77ee4cd45e580c | [] | no_license | quinnbabe/EPIC | baeaf731170132380966179778a65a28119a9617 | 7962d6f0e65a07e6dad619ce14fbd7cba9978c78 | refs/heads/master | 2021-01-10T04:52:04.669274 | 2015-10-18T19:50:05 | 2015-10-18T19:50:05 | 44,493,617 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,510 | java | /*
* You are given a telephone keymap
* 0-0, 1-1, 2-ABC2, 3-DEF3, 4-GHI4, 5-JKL5,
* 6-MNO6,7-PQRS7, 8-TUV8, 9-WXYZ9, *-<space>, #-char separator
* if you type "2", you will get 'A', that is "2"-'A',
* "22"-'B' ,"222"-'C', "2222"-'D'
* However, the digits can repeated many times
* "22222"-you get 'A' again -google 1point3acres
* You can use "#" to separate characters, for example
* "2#22", you get "AB". However, you may also have
* consecutive different digits without separator:"23"-'AD'
* If you type "*", it means space. You a given a
* sequence of digits, translate it into a text message
*/
public class SMS{
//Be careful about the wrong input.
private static String[] map = {"0","1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV8","WXYZ9"," "};
public static void main(String[] args){
translate("2233444");
}
public static void translate(String digits){
StringBuilder sb = new StringBuilder();
for(int i=0;i<digits.length();i++){
if(digits.charAt(i) == '#'){
continue;
}
if(digits.charAt(i) == '*'){
sb.append(" ");
}else{
if(digits.charAt(i) >= '0' && digits.charAt(i) <= '9'){
String curr = map[digits.charAt(i)-'0'];
int select = 0;
while(i+1<digits.length() && digits.charAt(i) == digits.charAt(i+1)){
i++;
select++;
}
sb.append(curr.charAt(select%curr.length()));
}
else{
System.out.println("Wrong Input!");
System.exit(1);
}
}
}
System.out.println(sb.toString());
}
} | [
"quyingcrystal@gmail.com"
] | quyingcrystal@gmail.com |
a6b11c7d322325173545d418d230d90cd79a9328 | 7569f9a68ea0ad651b39086ee549119de6d8af36 | /cocoon-2.1.9/src/blocks/databases/java/org/apache/cocoon/components/language/markup/xsp/PostgresEsqlQuery.java | 8d35f6317511f127d2ef9cf208ffeac015a755cf | [
"Apache-2.0"
] | permissive | tpso-src/cocoon | 844357890f8565c4e7852d2459668ab875c3be39 | f590cca695fd9930fbb98d86ae5f40afe399c6c2 | refs/heads/master | 2021-01-10T02:45:37.533684 | 2015-07-29T18:47:11 | 2015-07-29T18:47:11 | 44,549,791 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,961 | java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.apache.cocoon.components.language.markup.xsp;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
/**
* @author <a href="mailto:haul@apache.org">Christian Haul</a>
* @author <a href="mailto:tcurdt@apache.org">Torsten Curdt</a>
* @version CVS $Id: PostgresEsqlQuery.java 30932 2004-07-29 17:35:38Z vgritsenko $
*/
final public class PostgresEsqlQuery extends AbstractEsqlQuery {
public PostgresEsqlQuery(Connection connection, String query) {
super(connection, query);
}
/**
* Only newInstance may use this contructor
* @param resultSet
*/
private PostgresEsqlQuery(ResultSet resultSet) {
super(resultSet);
}
/**
* Create a EsqlQuery of the same type
* @param resultSet
*/
public AbstractEsqlQuery newInstance(final ResultSet resultSet) {
return(new PostgresEsqlQuery(resultSet));
}
public String getQueryString() throws SQLException {
StringBuffer sb = new StringBuffer(super.getQueryString());
if (getMaxRows() > -1) sb.append(" LIMIT ").append(getMaxRows()+1);
if (getSkipRows() > 0) sb.append(" OFFSET ").append(getSkipRows());
return(sb.toString());
}
public void getResultRows() throws SQLException {
setPosition(getSkipRows());
}
}
| [
"ms@tpso.com"
] | ms@tpso.com |
1bf5dc9c4a9246c3f42fe4f06b534ae594f5553f | 6a8673a21468e11f53dda53696d680835b3d17ee | /Zoos_v8_1222/app/src/main/java/com/chanb/zoos/Main_act.java | 40a2f71663125e12298fd59e1947a2440d5aba38 | [] | no_license | HotKano/Zoos | 12e250453ae7c0786aae00c8092f4bd52545d22a | 2dd5743c3758638a228db0299a9c5a27c5c0d14d | refs/heads/master | 2021-01-16T09:09:58.350694 | 2020-03-11T09:07:24 | 2020-03-11T09:07:24 | 243,017,183 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,740 | java | package com.chanb.zoos;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.chanb.zoos.utils.Database;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Main_act extends AppCompatActivity {
RequestQueue requestQueue;
FrameLayout frameLayout;
TabLayout tabs;
SNS_frag frag_home;
Profile_frag frag_profile;
Calendar_frag frag_diary;
MessageList_Frag frag_chat;
Save_frag save_frag;
Database database;
int page;
public static Main_act _Main_act;
public String id, type;
GlobalApplication globalApplication;
String nickname;
int backButton = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_act);
try {
_Main_act = this;
Log.d("MAIN_ACT", "active");
setting();
setFrag();
setTabs();
} catch (Exception e) {
e.printStackTrace();
}
}
//뷰 세팅
private void setting() {
requestQueue = Volley.newRequestQueue(getApplicationContext());
globalApplication = new GlobalApplication();
globalApplication.getWindow(this);
String dbName = "UserDatabase_Zoos";
int dataBaseVersion = 1;
database = new Database(this, dbName, null, dataBaseVersion);
database.init();
String[] temp = database.select("MEMBERINFO");
Intent intent = getIntent();
type = intent.getStringExtra("Type");
page = 1;
//id = intent.getStringExtra("id");
//nickname = intent.getStringExtra("nickname");
id = temp[0];
nickname = temp[2];
}
// 프레그먼트 세팅
public void setFrag() {
frameLayout = findViewById(R.id.container_main);
frag_home = new SNS_frag(); // 메인 화면
frag_profile = new Profile_frag(); // 환경설정 화면
frag_diary = new Calendar_frag(); // 캘린더 일정 화면
frag_chat = new MessageList_Frag(); // 메세지 리스트 화면
save_frag = new Save_frag(); // 세이브 화면
Intent intent = getIntent();
if (intent != null) {
frag_home.refresh_frag1(intent);
frag_profile.refresh_frag_info(intent);
frag_diary.refresh_frag_calendar(intent);
save_frag.refresh_frag_save(intent);
}
FragmentTransaction tf = getSupportFragmentManager().beginTransaction().replace(R.id.container_main, frag_home);
tf.commitNowAllowingStateLoss();
}
//하단 tabs.
public void setTabs() {
page = 0;
tabs = findViewById(R.id.tabs);
int color_blue = getResources().getColor(R.color.start_with_phone_color);
View view1 = getLayoutInflater().inflate(R.layout.custom_tab, null);
view1.findViewById(R.id.icon).setBackgroundResource(R.drawable.home_main_tab_on);
TextView title1 = view1.findViewById(R.id.title_tab);
title1.setText("홈");
title1.setTextColor(color_blue);
tabs.addTab(tabs.newTab().setCustomView(view1));
View view2 = getLayoutInflater().inflate(R.layout.custom_tab, null);
view2.findViewById(R.id.icon).setBackgroundResource(R.drawable.save_tab);
TextView title2 = view2.findViewById(R.id.title_tab);
title2.setText("저장소");
tabs.addTab(tabs.newTab().setCustomView(view2));
View view3 = getLayoutInflater().inflate(R.layout.custom_tab, null);
view3.findViewById(R.id.icon).setBackgroundResource(R.drawable.message_main_tab);
TextView title3 = view3.findViewById(R.id.title_tab);
title3.setText("메시지");
tabs.addTab(tabs.newTab().setCustomView(view3));
View view4 = getLayoutInflater().inflate(R.layout.custom_tab, null);
view4.findViewById(R.id.icon).setBackgroundResource(R.drawable.profile_tab);
TextView title4 = view4.findViewById(R.id.title_tab);
title4.setText("프로필");
tabs.addTab(tabs.newTab().setCustomView(view4));
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
int color = getResources().getColor(R.color.tab_on);
Fragment selected = null;
if (position == 0) { // 홈
selected = frag_home;
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.home_main_tab_on);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
title3.setTextColor(color);
page = 0;
backButton = 1;
} else if (position == 1) { //저장소
selected = save_frag;
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.save_tab_on);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
title3.setTextColor(color);
page = 1;
backButton = 1;
} else if (position == 2) { //메시지
selected = frag_chat;
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.message_main_tab_on);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
title3.setTextColor(color);
page = 2;
backButton = 1;
} else if (position == 3) { //프로필
//selected = frag_home;
//tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.profile_tab_on);
//TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
//title3.setTextColor(color);
petConnect();
tab = tabs.getTabAt(page);
tab.select();
backButton = 1;
}
if (position != 3) {
FragmentTransaction tf = getSupportFragmentManager().beginTransaction().replace(R.id.container_main, selected);
tf.commitNowAllowingStateLoss();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 0) { // 홈
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.home_main_tab);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
int color = getResources().getColor(R.color.sns_act_color);
title3.setTextColor(color);
} else if (position == 1) { //저장소
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.save_tab);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
int color = getResources().getColor(R.color.sns_act_color);
title3.setTextColor(color);
} else if (position == 2) { //메시지
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.message_main_tab);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
int color = getResources().getColor(R.color.sns_act_color);
title3.setTextColor(color);
} else if (position == 3) { //프로필
tabs.getTabAt(position).getCustomView().findViewById(R.id.icon).setBackgroundResource(R.drawable.profile_tab);
TextView title3 = tabs.getTabAt(position).getCustomView().findViewById(R.id.title_tab);
int color = getResources().getColor(R.color.sns_act_color);
title3.setTextColor(color);
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 0) {
frag_home.setScrollView();
} else if (position == 1) {
//frag_diary.setScrollView();
save_frag.setScrollView();
} else if (position == 2) {
frag_chat.setScrollView();
} else if (position == 3) {
}
}
});
}
//펫 정보 받아오는 부분.
public void petConnect() {
String SNSUrl = "http://133.186.135.41/zozo_edit_pet_show.php";
StringRequest request = new StringRequest(Request.Method.POST, SNSUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonOutput = JsonUtil.getJSONObjectFrom(response);
String text = JsonUtil.getStringFrom(jsonOutput, "state");
if (text.equals("fail")) {
Intent intent = new Intent(Main_act.this, Pet_edit_act.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("id", id);
intent.putExtra("kind", "0");
startActivity(intent);
} else {
Intent intent = new Intent(Main_act.this, Story_act.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("id", id);
intent.putExtra("target_id", id);
intent.putExtra("nickname", nickname);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main_act.this, "인터넷 접속 상태를 확인해주세요.", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("id", id);
parameters.put("petNo", "1");
return parameters;
}
};
requestQueue.add(request);
}
// date to frag.
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
Bundle extras = intent.getExtras();
if (extras != null) {
frag_home.requestQueue = requestQueue;
frag_diary.requestQueue = requestQueue;
frag_home.id = id;
frag_profile.id = id;
frag_diary.id = id;
String id_after = extras.getString("id");
String nickname_after = extras.getString("nickname");
if (!TextUtils.isEmpty(id_after)) {
id = id_after;
frag_home.id = id;
frag_profile.id = id;
frag_diary.id = id;
}
if (!TextUtils.isEmpty(nickname_after)) {
nickname = nickname_after;
frag_home.nickname = nickname;
}
String page = extras.getString("page");
long id_kakao_pre = extras.getLong("id", -1);
String id_naver_pre = extras.getString("id_naver");
if (id_kakao_pre != -1) {
id_after = String.valueOf(id_kakao_pre);
id = id_after;
frag_home.id = id;
Log.d("kakao_login", frag_home.id + "tttt");
} else if (id_naver_pre != null) {
id = id_naver_pre;
frag_home.id = id;
Log.d("naver_login", frag_home.id + "tttt");
}
if (page != null) {
if (page.equals("1")) {
String id = extras.getString("id");
String nickname = extras.getString("nickname");
frag_home.id = id;
frag_home.nickname = nickname;
frag_home.nickname_main.setText(nickname);
frag_home.cardConnect();
frag_home.gridConnect();
//getSupportFragmentManager().beginTransaction().replace(R.id.container_main, frag_home).commit();
} else if (page.equals("2")) {
frag_diary.id = id;
frag_diary.nickname = nickname;
frag_diary.cardConnect();
//frag_diary.monthViewAdapter.notifyDataSetChanged();
} else if (page.equals("3")) {
Log.d("frag_chat", "act");
String kind = extras.getString("kind");
frag_chat.refresh_frag_chatting(kind);
} else if (page.equals("4")) {
frag_profile.petConnect();
frag_profile.adapter_pet.notifyDataSetChanged();
}
}
} else {
Log.d("test_for_Main", "null");
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
if (backButton == 1) {
View view = findViewById(R.id.main_act);
Snackbar snackbar = Snackbar
.make(view, "한 번 더 누르시면 종료 됩니다.", Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.WHITE);
View sbView = snackbar.getView();
sbView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.start_with_phone_color));
snackbar.show();
backButton = 2;
} else {
super.onBackPressed();
}
}
}
| [
"dpsw23@naver.com"
] | dpsw23@naver.com |
33c43cb17893b14671ae026dafb2cf0ccf940cdc | 72c33f95ca7d9c0ed5c241d75d200cdcc154a5e8 | /Final Ecommerce Project/Ecommerce_Project-master/project/ecommercebackend/src/main/java/com/ecommerce2/ecommercebackend/FileUpload/UploadFile.java | 88ea8a2d711a4a4738d0b698613112621fde34c3 | [] | no_license | sumonkarmakar/Final-Ecommerce-Project | 79b97962e223ef375500a29865edd72668426fc6 | 78b145b866f103a08824dedc404cdfcbaacb2d21 | refs/heads/master | 2021-07-13T14:26:17.038791 | 2017-10-15T09:38:01 | 2017-10-15T09:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,138 | java | package com.ecommerce2.ecommercebackend.FileUpload;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
public class UploadFile {
private static final String ABS_PATH= "C:\\Users\\Koustabh\\project\\ecommerce1\\src\\main\\webapp\\resources\\images\\";
private static String REAL_PATH="";
private static final Logger logger = LoggerFactory.getLogger(UploadFile.class);
public static void uploadFile(HttpServletRequest request, MultipartFile file) {
REAL_PATH= request.getSession().getServletContext().getRealPath("/resources/images/");
logger.info(REAL_PATH);
logger.info(ABS_PATH);
if(!new File(ABS_PATH).exists()){
new File(ABS_PATH).mkdirs();
}
if(!new File(REAL_PATH).exists()){
new File(REAL_PATH).mkdirs();
}
try{
//server upload
file.transferTo(new File(REAL_PATH + file.getOriginalFilename()));
//project directory upload
file.transferTo(new File(ABS_PATH + file.getOriginalFilename()));
}catch(Exception e){
e.printStackTrace();
}
}
}
| [
"biswas.koustabh@gmail.com"
] | biswas.koustabh@gmail.com |
38c4eac1169d7c9517aa1ce632ceae7749697bb3 | ed9e143f36c05babd2f54c6143ba074f9ca07716 | /starter_code/src/main/java/com/example/demo/security/UserDetailsServiceImpl.java | 25543a9614b0817491137407037585478e2cce60 | [] | no_license | projecthub14/P04-eCommerceApplication | f9c1c319d75d43fb8b464f024ed324b2c5cab301 | ed2db1324652b7ed474b62c4d21d24ab15b6ab87 | refs/heads/master | 2021-08-07T10:28:30.470952 | 2019-12-12T00:37:45 | 2019-12-12T00:37:45 | 226,993,840 | 0 | 0 | null | 2020-10-13T18:06:19 | 2019-12-10T00:20:47 | Java | UTF-8 | Java | false | false | 1,111 | java | package com.example.demo.security;
import com.example.demo.model.persistence.User;
import com.example.demo.model.persistence.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import static java.util.Collections.emptyList;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User applicationUser = userRepository.findByUsername(username);
if (applicationUser == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(applicationUser.getUsername(), applicationUser.getPassword(), emptyList());
}
} | [
"sowmya.kol@gmail.com"
] | sowmya.kol@gmail.com |
4e2e29b61c38715c8a8d38e039cb7e750aafd5d5 | b6ea417b48402d85b6fe90299c51411b778c07cc | /spring-beans/src/main/java/org/springframework/beans/factory/config/BeanPostProcessor.java | 996daad6697f9a6307077a315495c071050809b5 | [
"Apache-2.0"
] | permissive | DevHui/spring-framework | 065f24e96eaaed38495b9d87bc322db82b6a046c | 4a2f291e26c6f78c3875dea13432be21bb1c0ed6 | refs/heads/master | 2020-12-04T21:08:18.445815 | 2020-01-15T03:54:42 | 2020-01-15T03:54:42 | 231,526,595 | 1 | 0 | Apache-2.0 | 2020-01-03T06:28:30 | 2020-01-03T06:28:29 | null | UTF-8 | Java | false | false | 4,196 | java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
import org.springframework.lang.Nullable;
/**
* Factory hook that allows for custom modification of new bean instances,
* e.g. checking for marker interfaces or wrapping them with proxies.
*
* <p>ApplicationContexts can autodetect BeanPostProcessor beans in their
* bean definitions and apply them to any beans subsequently created.
* Plain bean factories allow for programmatic registration of post-processors,
* applying to all beans created through this factory.
*
* <p>Typically, post-processors that populate beans via marker interfaces
* or the like will implement {@link #postProcessBeforeInitialization},
* while post-processors that wrap beans with proxies will normally
* implement {@link #postProcessAfterInitialization}.
*
* @author Juergen Hoeller
* @see InstantiationAwareBeanPostProcessor
* @see DestructionAwareBeanPostProcessor
* @see ConfigurableBeanFactory#addBeanPostProcessor
* @see BeanFactoryPostProcessor
* @since 10.10.2003
*/
public interface BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>The default implementation returns the given {@code bean} as-is.
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* <p>The default implementation returns the given {@code bean} as-is.
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
| [
"pengshaohui@markor.com.cn"
] | pengshaohui@markor.com.cn |
1bda35ce73547397a0b80502b57b04bddaee8e53 | dba87418d2286ce141d81deb947305a0eaf9824f | /sources/com/iaai/android/bdt/feature/account/watchlist/PreSaleListViewModel_Factory.java | 1402c7edf563d870f01ccc9d9e8999ce87d7c45e | [] | no_license | Sluckson/copyOavct | 1f73f47ce94bb08df44f2ba9f698f2e8589b5cf6 | d20597e14411e8607d1d6e93b632d0cd2e8af8cb | refs/heads/main | 2023-03-09T12:14:38.824373 | 2021-02-26T01:38:16 | 2021-02-26T01:38:16 | 341,292,450 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,431 | java | package com.iaai.android.bdt.feature.account.watchlist;
import com.iaai.android.bdt.feature.watchList.WatchRepository;
import dagger.internal.Factory;
import javax.inject.Provider;
public final class PreSaleListViewModel_Factory implements Factory<PreSaleListViewModel> {
private final Provider<PreSaleListRepository> repositoryProvider;
private final Provider<WatchRepository> watchRepositoryProvider;
public PreSaleListViewModel_Factory(Provider<PreSaleListRepository> provider, Provider<WatchRepository> provider2) {
this.repositoryProvider = provider;
this.watchRepositoryProvider = provider2;
}
public PreSaleListViewModel get() {
return provideInstance(this.repositoryProvider, this.watchRepositoryProvider);
}
public static PreSaleListViewModel provideInstance(Provider<PreSaleListRepository> provider, Provider<WatchRepository> provider2) {
return new PreSaleListViewModel(provider.get(), provider2.get());
}
public static PreSaleListViewModel_Factory create(Provider<PreSaleListRepository> provider, Provider<WatchRepository> provider2) {
return new PreSaleListViewModel_Factory(provider, provider2);
}
public static PreSaleListViewModel newPreSaleListViewModel(PreSaleListRepository preSaleListRepository, WatchRepository watchRepository) {
return new PreSaleListViewModel(preSaleListRepository, watchRepository);
}
}
| [
"lucksonsurprice94@gmail.com"
] | lucksonsurprice94@gmail.com |
1a838f716671bbe385fef8dd0744c74919673e87 | d40f8dba678b47274dd26c6a321e6a58fd6c1682 | /mr-admin/orderservice/server/src/main/java/com/hwj/server/result/ResultVo.java | e916753e8ee535aaa1c91aeaeb8df93bb7f12968 | [] | no_license | hwj01/mr | 502de9435ad06c3c7726ad5b7b0b1f88ea282fe6 | cbd7d3d7ac34e6d581a11be5955f3c2678fd2707 | refs/heads/master | 2021-05-26T01:25:14.725036 | 2020-08-25T01:16:12 | 2020-08-25T01:16:12 | 253,999,326 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 392 | java | package com.hwj.server.result;
import lombok.Data;
@Data
public class ResultVo<T> {
private Integer code;
private String msg;
private T data;
public static ResultVo success(Object data) {
ResultVo<Object> resultVo = new ResultVo<>();
resultVo.setCode(200);
resultVo.setMsg("成功");
resultVo.setData(data);
return resultVo;
}
}
| [
"44132661+hwj01@users.noreply.github.com"
] | 44132661+hwj01@users.noreply.github.com |
79f4d6ff969c7c0ab816a72570d69e700156815d | d313b09f0beda39050729d182c781ab05ca11d76 | /COMPX204/Assignment2/3.9/HttpServerSession.java | e20a08b31a89cf4cf1e34ba1a1a8227ebead177f | [] | no_license | TamahauBrown/Networking-Basics | 5d9c3e599ed85c8bf04324166b5e80579c483ecc | 40fb08cf1a9967cf2b4991db98bf1d9b1ea00977 | refs/heads/master | 2022-02-06T00:18:09.867182 | 2019-06-12T22:50:25 | 2019-06-12T22:50:25 | 191,654,628 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,239 | java | //Tamahau Brown's Assignment
import java.net.*;
import java.io.*;
import java.util.*;
class HttpServerSession extends Thread
{
//Creates a socket variable, and a printwriter variable
private Socket Client;
private PrintWriter Write;
//Creates an instance of the HttpServer class
private HttpServer h = new HttpServer();
//Declare the FileInputStream
FileInputStream fis;
//The Constructor of the HttpServerSession
public HttpServerSession(Socket s) throws Exception
{
Client = s;
Write = null;
}
//Creates a run method
public void run()
{
//Declare a String variable called filename
String filename;
File file;
//Try-Catch method
try
{
//Creates a BufferedOutputStream and a BufferedReader
BufferedOutputStream bos = new BufferedOutputStream(Client.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(Client.getInputStream()));
//Loops until 'break;' is called.
while(true)
{
//Reads each line and splits whenever there is a space
String r =reader.readLine();
String parts [] = r.split(" ");
//If the length of the parts is not 3 and its not a "GET" then it breaks the loop.
if(parts.length != 3 && parts[0].compareTo("GET") != 0)
{
break;
}
//Otherwise it reads the file and continues
else
{
//This gets the filename from parts[1] without the first letter, and it prints it //out
filename = parts[1].substring(1);
if(filename.compareTo("") != 0)
{
System.out.println(filename);
}
else
{
System.out.println("Lulu.txt (Default file when no file is put in)");
}
//If there is nothing in the readline it prints out "EOF" in the terminal
if(r == null)
{
System.out.println("EOF");
}
//Otherwise if readline is "" it breaks from the loop
if(r.compareTo("") == 0)
{
break;
}
}
if(filename.compareTo("") != 0)
{
//Creates a new file
file = new File(filename);
}
else
{
file = new File("/home/tmmb1/COMPX204/Assignment2/3.9/Lulu.txt");
}
//If the file exists it prints it out that its okay and continues
if(file.exists())
{
//Prints out the ok message to the bufferedoutputstream
println(bos, "HTTP/1.1 200 OK");
println(bos, "");
//Creates the byte size of the file
byte [] buff = new byte[1000];
//Gets the file for the fileinputstream
fis = new FileInputStream(file);
//Makes the number equal to the size of the fileinputstream reading the byte size
int num = fis.read(buff);
//Loops as long as it is not an out of bounds exception it writes the file onto //the page.
while(num != -1)
{
//Sleeps it for 1 second
sleep(1000);
//Writes the file contents
bos.write(buff, 0, num);
//Makes number equal to the fileinputstream reading the byte size.
num = fis.read(buff);
}
}
//If the file does not exist
else
{
//Prints to the bos the 404 error message and that the file is not found
println(bos, "HTTP/1.1 404 Not Found");
println(bos, "");
println(bos, "File not found");
}
//Closes the bufferedoutputstream and fileinputstream
bos.close();
fis.close();
}
}
//If an exception occurs it prints out the error message.
catch(Exception e)
{
System.err.println(e);
}
}
//The println method which takes a bufferedoutputstream and a string
public void println(BufferedOutputStream bos,String s) throws IOException
{
//Creates a news string which creates a "\r\n" message
String news = s + "\r\n";
//Gets the byte size of the array
byte [] array = news.getBytes();
//As long as i is less than the array length it runs and it increments i by 1.
for(int i= 0; i < array.length; i++)
{
//Writes the position of the array
bos.write(array[i]);
}
//Once its out of the array it returns out of the method.
return;
}
}
| [
"tmmb1@students.waikato.ac.nz"
] | tmmb1@students.waikato.ac.nz |
9e29e4fb113591250e3e14fef04334a9e065e4e3 | 94cebb0acf22633ab896eb723d4f275f80cdf5c4 | /src/innerclass/InnerInterface.java | 20c4ce981fa600023ab2b87fdafbd6700ee61356 | [] | no_license | andresfonky/Java-Technical-Questions | 0b41f885bde35a8efc593d4db7c329b16c68148c | dc8a5bd031b4f0e11ce646935b4d0e718071f3b9 | refs/heads/master | 2022-11-13T10:39:59.183211 | 2020-07-09T16:56:55 | 2020-07-09T16:56:55 | 274,883,128 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | package innerclass;
public class InnerInterface {
private int data = 15;
public static void main(String[] args) {
Anonymous inner = new Anonymous() {
int data = 5;
@Override
public int getValue() {
return data;
}
@Override
public int getData() {
return data;
}
};
InnerInterface outer = new InnerInterface();
System.out.println(inner.getValue() + inner.getData() + outer.data);
}
}
interface Anonymous {
public int getValue();
public int getData();
}
| [
"andresfonquernie@gmail.com"
] | andresfonquernie@gmail.com |
a0902870605c3503c96aab404d2e5bd4388883bf | 78cd308135a3260fcaf0ca46da01ba743f51f557 | /Tp1IngSoft/src/model/CatalogoDePaquetesJson.java | 7d94c4f96ea507e30a8ec8f7a0586f32ce4340ea | [] | no_license | josdan23/Tp1_IngSoft | 329024fd75b86ec92a479a59dd6b1f55858402b8 | 0f57d33a6491967528c00ebd75f76aec1ae07528 | refs/heads/master | 2020-06-30T21:49:04.755107 | 2016-09-02T03:11:44 | 2016-09-02T03:11:44 | 66,985,030 | 2 | 0 | null | 2016-09-02T03:11:45 | 2016-08-30T23:27:19 | Java | UTF-8 | Java | false | false | 1,332 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.util.ArrayList;
/**
*
* @author josdan
*/
public class CatalogoDePaquetesJson implements IAdaptadorCatalogoDePaquetes{
@Override
public ArrayList<Paquete> obtenerPaquetes() {
/* ArrayList<Paquete> listaPaquetes = new ArrayList<Paquete>();
listaPaquetes.add(new Paquete("p1", "paqA", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p2", "paqB", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p3", "paqC", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p4", "paqD", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p5", "paqE", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p6", "paqF", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
listaPaquetes.add(new Paquete("p7", "paqJ", "xxxx", "xxxx", " xxxx", 2, 3, new Ciudad(2,"xxxx")));
return listaPaquetes;
*/
return null;
}
} | [
"josdan@josdan_pc"
] | josdan@josdan_pc |
eb4654b30741bd03bfa38748247275c5aa43e787 | 96ca02a85d3702729076cb59ff15d069dfa8232b | /ADS1.0/src/java/com/avit/ads/xml/beans/GetAssetLocations.java | b82a2f4bb316b72f9ff82332268d86e485d92ebd | [] | no_license | Hurson/mysql | 4a1600d9f580ac086ff9472095ed6fa58fb11830 | 3db53442376485a310c76ad09d6cf71143f38274 | refs/heads/master | 2021-01-10T17:55:50.003989 | 2016-03-11T11:36:15 | 2016-03-11T11:36:15 | 54,877,514 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,040 | java | /**
* Copyright (c) AVIT LTD (2012). All Rights Reserved.
* Welcome to <a href="www.avit.com.cn">www.avit.com.cn</a>
*/
package com.avit.ads.xml.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @Description:资产定位查询请求消息
* @author lizhiwei
* @Date: 2012-5-25
* @Version: 1.0
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="GetAssetLocations")
public class GetAssetLocations {
@XmlAttribute(name="assetId", required = true)
private String assetId;
@XmlAttribute(name="providerID", required = true)
private String providerID;
public String getAssetId() {
return assetId;
}
public void setAssetId(String assetId) {
this.assetId = assetId;
}
public String getProviderID() {
return providerID;
}
public void setProviderID(String providerID) {
this.providerID = providerID;
}
}
| [
"zhengguojin@d881c268-5c81-4d69-b6ac-ed4e9099e0f2"
] | zhengguojin@d881c268-5c81-4d69-b6ac-ed4e9099e0f2 |
14330ab45f23b25c6b6b9ca490ad44690f3ec3de | 68c8ecca4ddf73f287ed9d9e4284d69b49beadd0 | /app/src/main/java/fi/iki/elonen/NanoHTTPD.java | e23b74d7e3d2d5b0ef899d41ca907077e79ec1a7 | [] | no_license | sanderbos/AndroidSimplePhotoWebServer | 347cfd482def05bb0c57dc42683a72a5e8b266f1 | 7f337ff7a96feb210c9353805d72aa7167c3770a | refs/heads/master | 2022-02-23T10:54:42.524129 | 2022-02-19T11:54:55 | 2022-02-19T11:54:55 | 31,384,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 55,180 | java | package fi.iki.elonen;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
/**
* A simple, tiny, nicely embeddable HTTP server in Java
* <p/>
* <p/>
* NanoHTTPD
* <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p>
* <p/>
* <p/>
* <b>Features + limitations: </b>
* <ul>
* <p/>
* <li>Only one Java file</li>
* <li>Java 5 compatible</li>
* <li>Released as open source, Modified BSD licence</li>
* <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li>
* <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li>
* <li>Supports both dynamic content and file serving</li>
* <li>Supports file upload (since version 1.2, 2010)</li>
* <li>Supports partial content (streaming)</li>
* <li>Supports ETags</li>
* <li>Never caches anything</li>
* <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
* <li>Default code serves files and shows all HTTP parameters and headers</li>
* <li>File server supports directory listing, index.html and index.htm</li>
* <li>File server supports partial content (streaming)</li>
* <li>File server supports ETags</li>
* <li>File server does the 301 redirection trick for directories without '/'</li>
* <li>File server supports simple skipping for files (continue download)</li>
* <li>File server serves also very long files without memory overhead</li>
* <li>Contains a built-in list of most common mime types</li>
* <li>All header names are converted lowercase so they don't vary between browsers/clients</li>
* <p/>
* </ul>
* <p/>
* <p/>
* <b>How to use: </b>
* <ul>
* <p/>
* <li>Subclass and implement serve() and embed to your own program</li>
* <p/>
* </ul>
* <p/>
* The license of NanoHTTPD in full reads:
*
* Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* * Neither the name of the NanoHttpd organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public abstract class NanoHTTPD {
/**
* Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
* This is required as the Keep-Alive HTTP connections would otherwise
* block the socket reading thread forever (or as long the browser is open).
*/
public static final int SOCKET_READ_TIMEOUT = 5000;
/**
* Common mime type for dynamic content: plain text
*/
public static final String MIME_PLAINTEXT = "text/plain";
/**
* Common mime type for dynamic content: html
*/
public static final String MIME_HTML = "text/html";
/**
* Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.
*/
private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
private final String hostname;
private final int myPort;
private ServerSocket myServerSocket;
private Set<Socket> openConnections = new HashSet<Socket>();
private Thread myThread;
/**
* Pluggable strategy for asynchronously executing requests.
*/
private AsyncRunner asyncRunner;
/**
* Pluggable strategy for creating and cleaning up temporary files.
*/
private TempFileManagerFactory tempFileManagerFactory;
/**
* Constructs an HTTP server on given port.
*/
public NanoHTTPD(int port) {
this(null, port);
}
/**
* Constructs an HTTP server on given hostname and port.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new DefaultTempFileManagerFactory());
setAsyncRunner(new DefaultAsyncRunner());
}
private static final void safeClose(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
}
}
}
private static final void safeClose(Socket closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
}
}
}
private static final void safeClose(ServerSocket closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
}
}
}
/**
* Start the server.
*
* @throws IOException if the socket is in use.
*/
public void start() throws IOException {
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
myThread = new Thread(new Runnable() {
@Override
public void run() {
do {
try {
final Socket finalAccept = myServerSocket.accept();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
asyncRunner.exec(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
/**
* Stop the server.
*/
public void stop() {
try {
safeClose(myServerSocket);
closeAllConnections();
if (myThread != null) {
myThread.join();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Registers that a new connection has been set up.
*
* @param socket the {@link Socket} for the connection.
*/
public synchronized void registerConnection(Socket socket) {
openConnections.add(socket);
}
/**
* Registers that a connection has been closed
*
* @param socket
* the {@link Socket} for the connection.
*/
public synchronized void unRegisterConnection(Socket socket) {
openConnections.remove(socket);
}
/**
* Forcibly closes all connections that are open.
*/
public synchronized void closeAllConnections() {
for (Socket socket : openConnections) {
safeClose(socket);
}
}
public final int getListeningPort() {
return myServerSocket == null ? -1 : myServerSocket.getLocalPort();
}
public final boolean wasStarted() {
return myServerSocket != null && myThread != null;
}
public final boolean isAlive() {
return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive();
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this delegates to serveFile() and allows directory listing.)
*
* @param uri Percent-decoded URI without parameters, for example "/index.cgi"
* @param method "GET", "POST" etc.
* @param parms Parsed, percent decoded parameters from URI and, in case of POST, data.
* @param headers Header entries, percent decoded
* @return HTTP response, see class Response for details
*/
@Deprecated
public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms,
Map<String, String> files) {
return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this delegates to serveFile() and allows directory listing.)
*
* @param session The HTTP session
* @return HTTP response, see class Response for details
*/
public Response serve(IHTTPSession session) {
Map<String, String> files = new HashMap<String, String>();
Method method = session.getMethod();
if (Method.PUT.equals(method) || Method.POST.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
Map<String, String> parms = session.getParms();
parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString());
return serve(session.getUri(), method, session.getHeaders(), parms, files);
}
/**
* Decode percent encoded <code>String</code> values.
*
* @param str the percent encoded <code>String</code>
* @return expanded form of the input, for example "foo%20bar" becomes "foo bar"
*/
protected String decodePercent(String str) {
String decoded = null;
try {
decoded = URLDecoder.decode(str, "UTF8");
} catch (UnsupportedEncodingException ignored) {
}
return decoded;
}
/**
* Decode parameters from a URL, handing the case where a single parameter name might have been
* supplied several times, by return lists of values. In general these lists will contain a single
* element.
*
* @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
*/
protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER));
}
/**
* Decode parameters from a URL, handing the case where a single parameter name might have been
* supplied several times, by return lists of values. In general these lists will contain a single
* element.
*
* @param queryString a query string pulled from the URL.
* @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
*/
protected Map<String, List<String>> decodeParameters(String queryString) {
Map<String, List<String>> parms = new HashMap<String, List<String>>();
if (queryString != null) {
StringTokenizer st = new StringTokenizer(queryString, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
if (!parms.containsKey(propertyName)) {
parms.put(propertyName, new ArrayList<String>());
}
String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null;
if (propertyValue != null) {
parms.get(propertyName).add(propertyValue);
}
}
}
return parms;
}
// ------------------------------------------------------------------------------- //
//
// Threading Strategy.
//
// ------------------------------------------------------------------------------- //
/**
* Pluggable strategy for asynchronously executing requests.
*
* @param asyncRunner new strategy for handling threads.
*/
public void setAsyncRunner(AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
// ------------------------------------------------------------------------------- //
//
// Temp file handling strategy.
//
// ------------------------------------------------------------------------------- //
/**
* Pluggable strategy for creating and cleaning up temporary files.
*
* @param tempFileManagerFactory new strategy for handling temp files.
*/
public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
this.tempFileManagerFactory = tempFileManagerFactory;
}
/**
* HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value.
*/
public enum Method {
GET, PUT, POST, DELETE, HEAD, OPTIONS;
static Method lookup(String method) {
for (Method m : Method.values()) {
if (m.toString().equalsIgnoreCase(method)) {
return m;
}
}
return null;
}
}
/**
* Pluggable strategy for asynchronously executing requests.
*/
public interface AsyncRunner {
void exec(Runnable code);
}
/**
* Factory to create temp file managers.
*/
public interface TempFileManagerFactory {
TempFileManager create();
}
// ------------------------------------------------------------------------------- //
/**
* Temp file manager.
* <p/>
* <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup
* temporary files created as a result of handling the request.</p>
*/
public interface TempFileManager {
TempFile createTempFile() throws Exception;
void clear();
}
/**
* A temp file.
* <p/>
* <p>Temp files are responsible for managing the actual temporary storage and cleaning
* themselves up when no longer needed.</p>
*/
public interface TempFile {
OutputStream open() throws Exception;
void delete() throws Exception;
String getName();
}
/**
* Default threading strategy for NanoHttpd.
* <p/>
* <p>By default, the server spawns a new Thread for every incoming request. These are set
* to <i>daemon</i> status, and named according to the request number. The name is
* useful when profiling the application.</p>
*/
public static class DefaultAsyncRunner implements AsyncRunner {
private long requestCount;
@Override
public void exec(Runnable code) {
++requestCount;
Thread t = new Thread(code);
t.setDaemon(true);
t.setName("NanoHttpd Request Processor (#" + requestCount + ")");
t.start();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p></p>This class stores its files in the standard location (that is,
* wherever <code>java.io.tmpdir</code> points to). Files are added
* to an internal list, and deleted when no longer needed (that is,
* when <code>clear()</code> is invoked at the end of processing a
* request).</p>
*/
public static class DefaultTempFileManager implements TempFileManager {
private final String tmpdir;
private final List<TempFile> tempFiles;
public DefaultTempFileManager() {
tmpdir = System.getProperty("java.io.tmpdir");
tempFiles = new ArrayList<TempFile>();
}
@Override
public TempFile createTempFile() throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
tempFiles.add(tempFile);
return tempFile;
}
@Override
public void clear() {
for (TempFile file : tempFiles) {
try {
file.delete();
} catch (Exception ignored) {
}
}
tempFiles.clear();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p></p></[>By default, files are created by <code>File.createTempFile()</code> in
* the directory specified.</p>
*/
public static class DefaultTempFile implements TempFile {
private File file;
private OutputStream fstream;
public DefaultTempFile(String tempdir) throws IOException {
file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
fstream = new FileOutputStream(file);
}
@Override
public OutputStream open() throws Exception {
return fstream;
}
@Override
public void delete() throws Exception {
safeClose(fstream);
file.delete();
}
@Override
public String getName() {
return file.getAbsolutePath();
}
}
/**
* HTTP response. Return one of these from serve().
*/
public static class Response {
/**
* HTTP status code after processing, e.g. "200 OK", HTTP_OK
*/
private IStatus status;
/**
* MIME type of content, e.g. "text/html"
*/
private String mimeType;
/**
* Data of the response, may be null.
*/
private InputStream data;
/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
private Map<String, String> header = new HashMap<String, String>();
/**
* The request method that spawned this response.
*/
private Method requestMethod;
/**
* Use chunkedTransfer
*/
private boolean chunkedTransfer;
/**
* Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message
*/
public Response(String msg) {
this(Status.OK, MIME_HTML, msg);
}
/**
* Basic constructor.
*/
public Response(IStatus status, String mimeType, InputStream data) {
this.status = status;
this.mimeType = mimeType;
this.data = data;
}
/**
* Convenience method that makes an InputStream out of given text.
*/
public Response(IStatus status, String mimeType, String txt) {
this.status = status;
this.mimeType = mimeType;
try {
this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null;
} catch (java.io.UnsupportedEncodingException uee) {
uee.printStackTrace();
}
}
/**
* Adds given line to the header.
*/
public void addHeader(String name, String value) {
header.put(name, value);
}
public String getHeader(String name) {
return header.get(name);
}
/**
* Sends given response to the socket.
*/
protected void send(OutputStream outputStream) {
String mime = mimeType;
SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
if (status == null) {
throw new Error("sendResponse(): Status can't be null.");
}
PrintWriter pw = new PrintWriter(outputStream);
pw.print("HTTP/1.1 " + status.getDescription() + " \r\n");
if (mime != null) {
pw.print("Content-Type: " + mime + "\r\n");
}
if (header == null || header.get("Date") == null) {
pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
}
if (header != null) {
for (String key : header.keySet()) {
String value = header.get(key);
pw.print(key + ": " + value + "\r\n");
}
}
sendConnectionHeaderIfNotAlreadyPresent(pw, header);
if (requestMethod != Method.HEAD && chunkedTransfer) {
sendAsChunked(outputStream, pw);
} else {
int pending = data != null ? data.available() : 0;
sendContentLengthHeaderIfNotAlreadyPresent(pw, header, pending);
pw.print("\r\n");
pw.flush();
sendAsFixedLength(outputStream, pending);
}
outputStream.flush();
safeClose(data);
} catch (IOException ioe) {
// Couldn't write? No can do.
}
}
protected void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) {
if (!headerAlreadySent(header, "content-length")) {
pw.print("Content-Length: "+ size +"\r\n");
}
}
protected void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) {
if (!headerAlreadySent(header, "connection")) {
pw.print("Connection: keep-alive\r\n");
}
}
private boolean headerAlreadySent(Map<String, String> header, String name) {
boolean alreadySent = false;
for (String headerName : header.keySet()) {
alreadySent |= headerName.equalsIgnoreCase(name);
}
return alreadySent;
}
private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException {
pw.print("Transfer-Encoding: chunked\r\n");
pw.print("\r\n");
pw.flush();
int BUFFER_SIZE = 16 * 1024;
byte[] CRLF = "\r\n".getBytes();
byte[] buff = new byte[BUFFER_SIZE];
int read;
while ((read = data.read(buff)) > 0) {
outputStream.write(String.format("%x\r\n", read).getBytes());
outputStream.write(buff, 0, read);
outputStream.write(CRLF);
}
outputStream.write(String.format("0\r\n\r\n").getBytes());
}
private void sendAsFixedLength(OutputStream outputStream, int pending) throws IOException {
if (requestMethod != Method.HEAD && data != null) {
int BUFFER_SIZE = 16 * 1024;
byte[] buff = new byte[BUFFER_SIZE];
while (pending > 0) {
int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending));
if (read <= 0) {
break;
}
outputStream.write(buff, 0, read);
pending -= read;
}
}
}
public IStatus getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getData() {
return data;
}
public void setData(InputStream data) {
this.data = data;
}
public Method getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(Method requestMethod) {
this.requestMethod = requestMethod;
}
public void setChunkedTransfer(boolean chunkedTransfer) {
this.chunkedTransfer = chunkedTransfer;
}
public interface IStatus {
int getRequestStatus();
String getDescription();
}
/**
* Some HTTP response status codes
*/
public enum Status implements IStatus {
SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301,
"Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401,
"Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416,
"Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
@Override
public int getRequestStatus() {
return this.requestStatus;
}
@Override
public String getDescription() {
return "" + this.requestStatus + " " + description;
}
}
}
public static final class ResponseException extends Exception {
private final Response.Status status;
public ResponseException(Response.Status status, String message) {
super(message);
this.status = status;
}
public ResponseException(Response.Status status, String message, Exception e) {
super(message, e);
this.status = status;
}
public Response.Status getStatus() {
return status;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
@Override
public TempFileManager create() {
return new DefaultTempFileManager();
}
}
/**
* Handles one session, i.e. parses the HTTP request and returns the response.
*/
public interface IHTTPSession {
void execute() throws IOException;
Map<String, String> getParms();
Map<String, String> getHeaders();
/**
* @return the path part of the URL.
*/
String getUri();
String getQueryParameterString();
Method getMethod();
InputStream getInputStream();
CookieHandler getCookies();
/**
* Adds the files in the request body to the files map.
* @arg files - map to modify
*/
void parseBody(Map<String, String> files) throws IOException, ResponseException;
}
protected class HTTPSession implements IHTTPSession {
public static final int BUFSIZE = 8192;
private final TempFileManager tempFileManager;
private final OutputStream outputStream;
private PushbackInputStream inputStream;
private int splitbyte;
private int rlen;
private String uri;
private Method method;
private Map<String, String> parms;
private Map<String, String> headers;
private CookieHandler cookies;
private String queryParameterString;
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
this.outputStream = outputStream;
}
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
this.outputStream = outputStream;
String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
headers = new HashMap<String, String>();
headers.put("remote-addr", remoteIp);
headers.put("http-client-ip", remoteIp);
}
@Override
public void execute() throws IOException {
try {
// Read the first 8192 bytes.
// The full header should fit in here.
// Apache's default header limit is 8KB.
// Do NOT assume that a single read will get the entire header at once!
byte[] buf = new byte[BUFSIZE];
splitbyte = 0;
rlen = 0;
{
int read = -1;
try {
read = inputStream.read(buf, 0, BUFSIZE);
} catch (Exception e) {
safeClose(inputStream);
safeClose(outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
if (read == -1) {
// socket was been closed
safeClose(inputStream);
safeClose(outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
while (read > 0) {
rlen += read;
splitbyte = findHeaderEnd(buf, rlen);
if (splitbyte > 0)
break;
read = inputStream.read(buf, rlen, BUFSIZE - rlen);
}
}
if (splitbyte < rlen) {
inputStream.unread(buf, splitbyte, rlen - splitbyte);
}
parms = new HashMap<String, String>();
if(null == headers) {
headers = new HashMap<String, String>();
}
// Create a BufferedReader for parsing the header.
BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen)));
// Decode the header into parms and header java properties
Map<String, String> pre = new HashMap<String, String>();
decodeHeader(hin, pre, parms, headers);
method = Method.lookup(pre.get("method"));
if (method == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
}
uri = pre.get("uri");
cookies = new CookieHandler(headers);
// Ok, now do the serve()
Response r = serve(this);
if (r == null) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
} else {
cookies.unloadQueue(r);
r.setRequestMethod(method);
r.send(outputStream);
}
} catch (SocketException e) {
// throw it out to close socket object (finalAccept)
throw e;
} catch (SocketTimeoutException ste) {
throw ste;
} catch (IOException ioe) {
Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
r.send(outputStream);
safeClose(outputStream);
} catch (ResponseException re) {
Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
r.send(outputStream);
safeClose(outputStream);
} finally {
tempFileManager.clear();
}
}
@Override
public void parseBody(Map<String, String> files) throws IOException, ResponseException {
RandomAccessFile randomAccessFile = null;
BufferedReader in = null;
try {
randomAccessFile = getTmpBucket();
long size;
if (headers.containsKey("content-length")) {
size = Integer.parseInt(headers.get("content-length"));
} else if (splitbyte < rlen) {
size = rlen - splitbyte;
} else {
size = 0;
}
// Now read all the body and write it to f
byte[] buf = new byte[512];
while (rlen >= 0 && size > 0) {
rlen = inputStream.read(buf, 0, (int)Math.min(size, 512));
size -= rlen;
if (rlen > 0) {
randomAccessFile.write(buf, 0, rlen);
}
}
// Get the raw body as a byte []
ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
// Create a BufferedReader for easily reading it as string.
InputStream bin = new FileInputStream(randomAccessFile.getFD());
in = new BufferedReader(new InputStreamReader(bin));
// If the method is POST, there may be parameters
// in data section, too, read it:
if (Method.POST.equals(method)) {
String contentType = "";
String contentTypeHeader = headers.get("content-type");
StringTokenizer st = null;
if (contentTypeHeader != null) {
st = new StringTokenizer(contentTypeHeader, ",; ");
if (st.hasMoreTokens()) {
contentType = st.nextToken();
}
}
if ("multipart/form-data".equalsIgnoreCase(contentType)) {
// Handle multipart/form-data
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
}
String boundaryStartString = "boundary=";
int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
boundary = boundary.substring(1, boundary.length() - 1);
}
decodeMultipartData(boundary, fbuf, in, parms, files);
} else {
String postLine = "";
StringBuilder postLineBuffer = new StringBuilder();
char pbuf[] = new char[512];
int read = in.read(pbuf);
while (read >= 0 && !postLine.endsWith("\r\n")) {
postLine = String.valueOf(pbuf, 0, read);
postLineBuffer.append(postLine);
read = in.read(pbuf);
}
postLine = postLineBuffer.toString().trim();
// Handle application/x-www-form-urlencoded
if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
decodeParms(postLine, parms);
} else if (postLine.length() != 0) {
// Special case for raw POST data => create a special files entry "postData" with raw content data
files.put("postData", postLine);
}
}
} else if (Method.PUT.equals(method)) {
files.put("content", saveTmpFile(fbuf, 0, fbuf.limit()));
}
} finally {
safeClose(randomAccessFile);
safeClose(in);
}
}
/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers)
throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}
// If there's another token, it's protocol version,
// followed by HTTP headers. Ignore version but parse headers.
// NOTE: this now forces header names lowercase since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
String line = in.readLine();
while (line != null && line.trim().length() > 0) {
int p = line.indexOf(':');
if (p >= 0)
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
line = in.readLine();
}
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, ";");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Find byte index separating header from body. It must be the last byte of the first two sequential new lines.
*/
private int findHeaderEnd(final byte[] buf, int rlen) {
int splitbyte = 0;
while (splitbyte + 3 < rlen) {
if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
return splitbyte + 4;
}
splitbyte++;
}
return 0;
}
/**
* Find the byte positions where multipart boundaries start.
*/
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int matchcount = 0;
int matchbyte = -1;
List<Integer> matchbytes = new ArrayList<Integer>();
for (int i = 0; i < b.limit(); i++) {
if (b.get(i) == boundary[matchcount]) {
if (matchcount == 0)
matchbyte = i;
matchcount++;
if (matchcount == boundary.length) {
matchbytes.add(matchbyte);
matchcount = 0;
matchbyte = -1;
}
} else {
i -= matchcount;
matchcount = 0;
matchbyte = -1;
}
}
int[] ret = new int[matchbytes.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = matchbytes.get(i);
}
return ret;
}
/**
* Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned.
*/
private String saveTmpFile(ByteBuffer b, int offset, int len) {
String path = "";
if (len > 0) {
FileOutputStream fileOutputStream = null;
try {
TempFile tempFile = tempFileManager.createTempFile();
ByteBuffer src = b.duplicate();
fileOutputStream = new FileOutputStream(tempFile.getName());
FileChannel dest = fileOutputStream.getChannel();
src.position(offset).limit(offset + len);
dest.write(src.slice());
path = tempFile.getName();
} catch (Exception e) { // Catch exception if any
throw new Error(e); // we won't recover, so throw an error
} finally {
safeClose(fileOutputStream);
}
}
return path;
}
private RandomAccessFile getTmpBucket() {
try {
TempFile tempFile = tempFileManager.createTempFile();
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
throw new Error(e); // we won't recover, so throw an error
}
}
/**
* It returns the offset separating multipart file headers from the file's data.
*/
private int stripMultipartHeaders(ByteBuffer b, int offset) {
int i;
for (i = offset; i < b.limit(); i++) {
if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
break;
}
}
return i + 1;
}
/**
* Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
* adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map.
*/
private void decodeParms(String parms, Map<String, String> p) {
if (parms == null) {
queryParameterString = "";
return;
}
queryParameterString = parms;
StringTokenizer st = new StringTokenizer(parms, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
if (sep >= 0) {
p.put(decodePercent(e.substring(0, sep)).trim(),
decodePercent(e.substring(sep + 1)));
} else {
p.put(decodePercent(e).trim(), "");
}
}
}
@Override
public final Map<String, String> getParms() {
return parms;
}
public String getQueryParameterString() {
return queryParameterString;
}
@Override
public final Map<String, String> getHeaders() {
return headers;
}
@Override
public final String getUri() {
return uri;
}
@Override
public final Method getMethod() {
return method;
}
@Override
public final InputStream getInputStream() {
return inputStream;
}
@Override
public CookieHandler getCookies() {
return cookies;
}
}
public static class Cookie {
private String n, v, e;
public Cookie(String name, String value, String expires) {
n = name;
v = value;
e = expires;
}
public Cookie(String name, String value) {
this(name, value, 30);
}
public Cookie(String name, String value, int numDays) {
n = name;
v = value;
e = getHTTPTime(numDays);
}
public String getHTTPHeader() {
String fmt = "%s=%s; expires=%s";
return String.format(fmt, n, v, e);
}
public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
}
/**
* Provides rudimentary support for cookies.
* Doesn't support 'path', 'secure' nor 'httpOnly'.
* Feel free to improve it and/or add unsupported features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String> {
private HashMap<String, String> cookies = new HashMap<String, String>();
private ArrayList<Cookie> queue = new ArrayList<Cookie>();
public CookieHandler(Map<String, String> httpHeaders) {
String raw = httpHeaders.get("cookie");
if (raw != null) {
String[] tokens = raw.split(";");
for (String token : tokens) {
String[] data = token.trim().split("=");
if (data.length == 2) {
cookies.put(data[0], data[1]);
}
}
}
}
@Override public Iterator<String> iterator() {
return cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name) {
return cookies.get(name);
}
/**
* Sets a cookie.
*
* @param name The cookie's name.
* @param value The cookie's value.
* @param expires How many days until the cookie expires.
*/
public void set(String name, String value, int expires) {
queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}
public void set(Cookie cookie) {
queue.add(cookie);
}
/**
* Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
*
* @param name The cookie name.
*/
public void delete(String name) {
set(name, "-delete-", -30);
}
/**
* Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
*
* @param response The Response object to which headers the queued cookies will be added.
*/
public void unloadQueue(Response response) {
for (Cookie cookie : queue) {
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
}
| [
"sander@sanderbos.com"
] | sander@sanderbos.com |
efb3b17b8a9459bf1346189196038db05a4c302a | c1b4f7e7a3b8438c810313f2ef2b730b1a950962 | /libros-project/libros-server/libros-api/src/main/java/edu/upc/eetac/dsa/arnau/libros/api/links/Link.java | 857880649ab4a4c826020a790bf38feea4118c62 | [] | no_license | arnau193/libros-project | a8488e8440c4c1cb5250d50b3bc7d12ec276f884 | b2f0675d7d3b3834ca4f25bbb2cae11ad69c73a4 | refs/heads/master | 2016-09-02T02:24:50.213359 | 2013-12-19T15:55:52 | 2013-12-19T15:55:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 699 | java | package edu.upc.eetac.dsa.arnau.libros.api.links;
public class Link {
private String uri; // URL absoluta
private String rel;
private String type; // indica el tipo de media que respone o consume la uri
private String title; // descripción legible de lo que hay en la uri
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| [
"arnau193@gmail.com"
] | arnau193@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.