blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
811562509c2898707fd238096dfd0c667423196b
16,475,494,574,938
afb6300a642ae80ff353a7a61dee14061954c41d
/sphere-java-client-core/src/main/java/io/sphere/sdk/client/TokensSupplierImpl.java
6a078d6fdbcfc4a4219d48361005fa6a782e057f
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
z0lope0z/sphere-jvm-sdk
https://github.com/z0lope0z/sphere-jvm-sdk
2b5935527114301c934722acea2796f9c4be259c
a741e0b01a2319d057ab3147191a0461e55dc46c
refs/heads/master
2021-01-17T18:51:28.803000
2015-04-28T11:31:47
2015-04-28T11:31:47
34,769,049
1
0
null
true
2015-04-29T02:56:50
2015-04-29T02:56:49
2015-04-28T11:31:48
2015-04-28T15:45:59
27,484
0
0
0
null
null
null
package io.sphere.sdk.client; import com.fasterxml.jackson.databind.JsonNode; import io.sphere.sdk.http.*; import io.sphere.sdk.json.JsonException; import io.sphere.sdk.json.JsonUtils; import io.sphere.sdk.utils.MapUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; import java.util.concurrent.CompletionStage; import static io.sphere.sdk.client.SphereAuth.AUTH_LOGGER; import static io.sphere.sdk.http.HttpMethod.POST; import static java.lang.String.format; /** * Component that can fetch SPHERE.IO access tokens. * Does not refresh them, */ final class TokensSupplierImpl extends AutoCloseableService implements TokensSupplier { private final SphereAuthConfig config; private final HttpClient httpClient; private final boolean closeHttpClient; private boolean isClosed = false; private TokensSupplierImpl(final SphereAuthConfig config, final HttpClient httpClient, final boolean closeHttpClient) { this.config = config; this.httpClient = httpClient; this.closeHttpClient = closeHttpClient; } static TokensSupplier of(final SphereAuthConfig config, final HttpClient httpClient, final boolean closeHttpClient) { return new TokensSupplierImpl(config, httpClient, closeHttpClient); } /** * Executes a http auth sphere request and fetches a new access token. * @return future of a token */ @Override public CompletionStage<Tokens> get() { AUTH_LOGGER.debug(() -> "Fetching new token."); final CompletionStage<Tokens> result = httpClient.execute(newRequest()).thenApply(this::parseResponse); logTokenResult(result); return result; } private void logTokenResult(final CompletionStage<Tokens> result) { result.whenComplete((tokens, e) -> { if (tokens != null) { AUTH_LOGGER.debug(() -> "Successfully fetched token that expires in " + tokens.getExpiresIn().map(x -> x.toString()).orElse("an unknown time") + "."); } else { AUTH_LOGGER.error(() -> "Failed to fetch token." + tokens.getExpiresIn(), e); } }); } @Override protected synchronized void internalClose() { if (!isClosed) { if (closeHttpClient) { closeQuietly(httpClient); } isClosed = true; } } private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.of(MapUtils.mapOf("grant_type", "client_credentials", "scope", format("manage_project:%s", config.getProjectKey()))); return HttpRequest.of(POST, config.getAuthUrl() + "/oauth/token", httpHeaders, Optional.of(body)); } /** Parses Tokens from a response from the backend authorization service. * @param response Response from the authorization service. */ private Tokens parseResponse(final HttpResponse response) { if (response.getStatusCode() == 401 && response.getResponseBody().isPresent()) { UnauthorizedException authorizationException = new UnauthorizedException(response.toString()); try { final JsonNode jsonNode = JsonUtils.readTree(response.getResponseBody().get()); if (jsonNode.get("error").asText().equals("invalid_client")) { authorizationException = new InvalidClientCredentialsException(config); } } catch (final JsonException e) { authorizationException = new UnauthorizedException(response.toString(), e); } authorizationException.setProjectKey(config.getProjectKey()); authorizationException.setUnderlyingHttpResponse(response); throw authorizationException; } return JsonUtils.readObject(Tokens.typeReference(), response.getResponseBody().get()); } }
UTF-8
Java
4,397
java
TokensSupplierImpl.java
Java
[]
null
[]
package io.sphere.sdk.client; import com.fasterxml.jackson.databind.JsonNode; import io.sphere.sdk.http.*; import io.sphere.sdk.json.JsonException; import io.sphere.sdk.json.JsonUtils; import io.sphere.sdk.utils.MapUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; import java.util.concurrent.CompletionStage; import static io.sphere.sdk.client.SphereAuth.AUTH_LOGGER; import static io.sphere.sdk.http.HttpMethod.POST; import static java.lang.String.format; /** * Component that can fetch SPHERE.IO access tokens. * Does not refresh them, */ final class TokensSupplierImpl extends AutoCloseableService implements TokensSupplier { private final SphereAuthConfig config; private final HttpClient httpClient; private final boolean closeHttpClient; private boolean isClosed = false; private TokensSupplierImpl(final SphereAuthConfig config, final HttpClient httpClient, final boolean closeHttpClient) { this.config = config; this.httpClient = httpClient; this.closeHttpClient = closeHttpClient; } static TokensSupplier of(final SphereAuthConfig config, final HttpClient httpClient, final boolean closeHttpClient) { return new TokensSupplierImpl(config, httpClient, closeHttpClient); } /** * Executes a http auth sphere request and fetches a new access token. * @return future of a token */ @Override public CompletionStage<Tokens> get() { AUTH_LOGGER.debug(() -> "Fetching new token."); final CompletionStage<Tokens> result = httpClient.execute(newRequest()).thenApply(this::parseResponse); logTokenResult(result); return result; } private void logTokenResult(final CompletionStage<Tokens> result) { result.whenComplete((tokens, e) -> { if (tokens != null) { AUTH_LOGGER.debug(() -> "Successfully fetched token that expires in " + tokens.getExpiresIn().map(x -> x.toString()).orElse("an unknown time") + "."); } else { AUTH_LOGGER.error(() -> "Failed to fetch token." + tokens.getExpiresIn(), e); } }); } @Override protected synchronized void internalClose() { if (!isClosed) { if (closeHttpClient) { closeQuietly(httpClient); } isClosed = true; } } private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.of(MapUtils.mapOf("grant_type", "client_credentials", "scope", format("manage_project:%s", config.getProjectKey()))); return HttpRequest.of(POST, config.getAuthUrl() + "/oauth/token", httpHeaders, Optional.of(body)); } /** Parses Tokens from a response from the backend authorization service. * @param response Response from the authorization service. */ private Tokens parseResponse(final HttpResponse response) { if (response.getStatusCode() == 401 && response.getResponseBody().isPresent()) { UnauthorizedException authorizationException = new UnauthorizedException(response.toString()); try { final JsonNode jsonNode = JsonUtils.readTree(response.getResponseBody().get()); if (jsonNode.get("error").asText().equals("invalid_client")) { authorizationException = new InvalidClientCredentialsException(config); } } catch (final JsonException e) { authorizationException = new UnauthorizedException(response.toString(), e); } authorizationException.setProjectKey(config.getProjectKey()); authorizationException.setUnderlyingHttpResponse(response); throw authorizationException; } return JsonUtils.readObject(Tokens.typeReference(), response.getResponseBody().get()); } }
4,397
0.680464
0.678645
102
42.107841
39.102154
198
false
false
0
0
0
0
0
0
0.647059
false
false
9
ecd38e2932ccae3b1da6f64b773d26cc303b12db
4,758,823,787,966
92d591a8def8592e8ead171d532e1dfecc8af6a6
/src/main/java/com/basketbandit/rizumu/stage/scene/play/scondary/PauseMenu.java
d10c753e41bf00e161c38878fb4af27f098c318c
[ "Apache-2.0" ]
permissive
BasketBandit/Rizumu
https://github.com/BasketBandit/Rizumu
20b7bbc89ee1e2d09a10a8ba9f69752809bfd7a3
29e1aa57e33b97ad576ff8347f851f0cc211fea1
refs/heads/master
2022-04-26T07:30:09.490000
2020-04-29T18:26:17
2020-04-29T18:26:17
251,297,274
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.basketbandit.rizumu.stage.scene.play.scondary; import com.basketbandit.rizumu.Configuration; import com.basketbandit.rizumu.beatmap.core.Beatmap; import com.basketbandit.rizumu.beatmap.core.Track; import com.basketbandit.rizumu.drawable.Button; import com.basketbandit.rizumu.engine.Engine; import com.basketbandit.rizumu.input.KeyAdapters; import com.basketbandit.rizumu.input.MouseAdapters; import com.basketbandit.rizumu.scheduler.ScheduleHandler; import com.basketbandit.rizumu.stage.Scenes; import com.basketbandit.rizumu.stage.object.RenderObject; import com.basketbandit.rizumu.stage.scene.Scene; import com.basketbandit.rizumu.stage.scene.play.PlayScene; import com.basketbandit.rizumu.utility.Alignment; import com.basketbandit.rizumu.utility.Colours; import com.basketbandit.rizumu.utility.Fonts; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class PauseMenu extends Scene { private PlayScene playScene; private FontMetrics metrics16; public PauseMenu() { renderObject = new PauseMenuRenderer(); tickObject = null; mouseAdapter = new PauseMenuMouseAdapter(); buttons.put("resumeButton", new com.basketbandit.rizumu.drawable.Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) - 25, 400, 75).setButtonText("Resume")); buttons.put("restartButton", new com.basketbandit.rizumu.drawable.Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) + 60, 400, 75).setButtonText("Restart")); buttons.put("quitButton", new Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) + 145, 400, 75).setButtonText("Quit")); } @Override public PauseMenu init(Object... objects) { MouseAdapters.setMouseAdapter("pause", mouseAdapter); KeyAdapters.setKeyAdapter("pause", null); playScene = (PlayScene) objects[0]; audioPlayer.pause(); return this; } private class PauseMenuRenderer implements RenderObject { @Override public void render(Graphics2D g) { if(metrics16 == null) { metrics16 = g.getFontMetrics(Fonts.default16); } g.setFont(Fonts.default16); g.setColor(Colours.DARK_GREY_90); g.fillRect(0, 0, Configuration.getWidth(), Configuration.getHeight()); // draw all the buttons buttons.forEach((key, button) -> { g.setColor(Colours.BLACK); g.fill(button); g.setColor(Colours.DARK_GREY); g.fillRect(button.x+1, button.y+1, button.width-2, button.height-2); g.setColor(Colours.WHITE); centerBoth = Alignment.centerBoth(button.getButtonText(), metrics16, button); g.drawString(button.getButtonText(), centerBoth[0], centerBoth[1]); }); } } private class PauseMenuMouseAdapter extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { // 'resume' button, close the pause menu if(buttons.get("resumeButton").isHovered()) { audioPlayer.resume(); effectPlayer.play("menu-click2"); Engine.getPrimaryScene().init(); Engine.setSecondaryScene(null); ScheduleHandler.resumeExecution(); playScene.setMenuCooldown(System.currentTimeMillis()); return; } // 'restart' button, restart the beatmap if(buttons.get("restartButton").isHovered()) { effectPlayer.play("menu-click3"); audioPlayer.stop(); Engine.setSecondaryScene(null); ScheduleHandler.cancelExecution(); Track t = Engine.getTrackParser().parseTrack(playScene.getTrack().getFile()); // forgive me for the horrible variable naming... for(Beatmap b: t.getBeatmaps()) { if(b.getName().equals(playScene.getBeatmap().getName())) { Engine.setPrimaryScene((Engine.getStaticScene(Scenes.PLAY)).init(t, b)); return; } } return; } // 'quit' button, go back to the main menu if(buttons.get("quitButton").isHovered()) { effectPlayer.play("menu-click4"); audioPlayer.stop(); ScheduleHandler.cancelExecution(); Engine.setPrimaryScene(Engine.getStaticScene(Scenes.SELECT).init()); Engine.setSecondaryScene(null); } } } } }
UTF-8
Java
4,910
java
PauseMenu.java
Java
[]
null
[]
package com.basketbandit.rizumu.stage.scene.play.scondary; import com.basketbandit.rizumu.Configuration; import com.basketbandit.rizumu.beatmap.core.Beatmap; import com.basketbandit.rizumu.beatmap.core.Track; import com.basketbandit.rizumu.drawable.Button; import com.basketbandit.rizumu.engine.Engine; import com.basketbandit.rizumu.input.KeyAdapters; import com.basketbandit.rizumu.input.MouseAdapters; import com.basketbandit.rizumu.scheduler.ScheduleHandler; import com.basketbandit.rizumu.stage.Scenes; import com.basketbandit.rizumu.stage.object.RenderObject; import com.basketbandit.rizumu.stage.scene.Scene; import com.basketbandit.rizumu.stage.scene.play.PlayScene; import com.basketbandit.rizumu.utility.Alignment; import com.basketbandit.rizumu.utility.Colours; import com.basketbandit.rizumu.utility.Fonts; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class PauseMenu extends Scene { private PlayScene playScene; private FontMetrics metrics16; public PauseMenu() { renderObject = new PauseMenuRenderer(); tickObject = null; mouseAdapter = new PauseMenuMouseAdapter(); buttons.put("resumeButton", new com.basketbandit.rizumu.drawable.Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) - 25, 400, 75).setButtonText("Resume")); buttons.put("restartButton", new com.basketbandit.rizumu.drawable.Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) + 60, 400, 75).setButtonText("Restart")); buttons.put("quitButton", new Button((Configuration.getWidth()/2) - 200, (Configuration.getHeight()/3) + 145, 400, 75).setButtonText("Quit")); } @Override public PauseMenu init(Object... objects) { MouseAdapters.setMouseAdapter("pause", mouseAdapter); KeyAdapters.setKeyAdapter("pause", null); playScene = (PlayScene) objects[0]; audioPlayer.pause(); return this; } private class PauseMenuRenderer implements RenderObject { @Override public void render(Graphics2D g) { if(metrics16 == null) { metrics16 = g.getFontMetrics(Fonts.default16); } g.setFont(Fonts.default16); g.setColor(Colours.DARK_GREY_90); g.fillRect(0, 0, Configuration.getWidth(), Configuration.getHeight()); // draw all the buttons buttons.forEach((key, button) -> { g.setColor(Colours.BLACK); g.fill(button); g.setColor(Colours.DARK_GREY); g.fillRect(button.x+1, button.y+1, button.width-2, button.height-2); g.setColor(Colours.WHITE); centerBoth = Alignment.centerBoth(button.getButtonText(), metrics16, button); g.drawString(button.getButtonText(), centerBoth[0], centerBoth[1]); }); } } private class PauseMenuMouseAdapter extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { // 'resume' button, close the pause menu if(buttons.get("resumeButton").isHovered()) { audioPlayer.resume(); effectPlayer.play("menu-click2"); Engine.getPrimaryScene().init(); Engine.setSecondaryScene(null); ScheduleHandler.resumeExecution(); playScene.setMenuCooldown(System.currentTimeMillis()); return; } // 'restart' button, restart the beatmap if(buttons.get("restartButton").isHovered()) { effectPlayer.play("menu-click3"); audioPlayer.stop(); Engine.setSecondaryScene(null); ScheduleHandler.cancelExecution(); Track t = Engine.getTrackParser().parseTrack(playScene.getTrack().getFile()); // forgive me for the horrible variable naming... for(Beatmap b: t.getBeatmaps()) { if(b.getName().equals(playScene.getBeatmap().getName())) { Engine.setPrimaryScene((Engine.getStaticScene(Scenes.PLAY)).init(t, b)); return; } } return; } // 'quit' button, go back to the main menu if(buttons.get("quitButton").isHovered()) { effectPlayer.play("menu-click4"); audioPlayer.stop(); ScheduleHandler.cancelExecution(); Engine.setPrimaryScene(Engine.getStaticScene(Scenes.SELECT).init()); Engine.setSecondaryScene(null); } } } } }
4,910
0.60835
0.595112
114
42.078949
33.873383
188
false
false
0
0
0
0
0
0
0.815789
false
false
9
2bd3a04e66751bc5bbfa8218816d456a8b319b6e
33,827,162,425,813
12d3bf9ac66b9d7a787c638344e98623ee8ae0bc
/src/main/java/ru/alexp/gc/gui/animations/GAnimation.java
0ad628034ee0110dcd14ed70d1b9a81c9ced3e84
[]
no_license
Snafy/MineProjectX
https://github.com/Snafy/MineProjectX
21d3a9cf34f4313686ca8e8355f9d955987fde25
dd53875fe63531974baa81bb3e49bfb99b1fab28
refs/heads/master
2017-12-05T14:23:50.452000
2017-01-20T21:08:32
2017-01-20T21:08:32
80,284,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.alexp.gc.gui.animations; import javafx.animation.Transition; import java.util.ArrayList; public class GAnimation extends Transition { public static AnimationFormula defaultFormula = time -> time; private AnimationFormula animationFormula = defaultFormula; private ArrayList<Attributes> attributes = new ArrayList<>(); public GAnimation() { super(); init(); setOnFinished(event -> onEnd()); } public void init() { } public void onStart() { } public void onEnd() { } @Override public void play() { onStart(); super.play(); } @Override protected void interpolate(double time) { animate(getAnimationFormula().compile(time)); } public void animate(double time) { } public AnimationFormula getAnimationFormula() { return animationFormula; } public void setAnimationFormula(AnimationFormula formula) { animationFormula = formula; } public ArrayList<Attributes> getAttributes() { return attributes; } public enum Attributes { ANIMATE_WITH } @FunctionalInterface public interface AnimationFormula { double compile(double time); } }
UTF-8
Java
1,260
java
GAnimation.java
Java
[]
null
[]
package ru.alexp.gc.gui.animations; import javafx.animation.Transition; import java.util.ArrayList; public class GAnimation extends Transition { public static AnimationFormula defaultFormula = time -> time; private AnimationFormula animationFormula = defaultFormula; private ArrayList<Attributes> attributes = new ArrayList<>(); public GAnimation() { super(); init(); setOnFinished(event -> onEnd()); } public void init() { } public void onStart() { } public void onEnd() { } @Override public void play() { onStart(); super.play(); } @Override protected void interpolate(double time) { animate(getAnimationFormula().compile(time)); } public void animate(double time) { } public AnimationFormula getAnimationFormula() { return animationFormula; } public void setAnimationFormula(AnimationFormula formula) { animationFormula = formula; } public ArrayList<Attributes> getAttributes() { return attributes; } public enum Attributes { ANIMATE_WITH } @FunctionalInterface public interface AnimationFormula { double compile(double time); } }
1,260
0.639683
0.639683
64
18.6875
19.625299
65
false
false
0
0
0
0
0
0
0.25
false
false
9
aee2a4f6441fe0969c7f6f9612ad79a4e8205189
6,992,206,787,300
6254347eaf4e96dc77e69820bef34df0eaf2d906
/pdfsam-enhanced/pdfsam-maine/tags/V_1_3_0e_sr1/src/it/pdfsam/render/JComboListItemRender.java
2002bd2c3f9d748d03e815cbaf8a3e9dce79f3e8
[]
no_license
winsonrich/pdfsam-v2
https://github.com/winsonrich/pdfsam-v2
9044913b14ec2e0c33801a77fbbc696367a8f587
0c7cc6dfeee88d1660e30ed53c7d09d40bf986aa
refs/heads/master
2020-04-02T16:20:17.751000
2018-12-07T14:52:22
2018-12-07T14:52:22
154,608,091
0
0
null
true
2018-10-25T04:03:03
2018-10-25T04:03:03
2018-10-25T04:02:58
2014-08-25T11:50:01
15,308
0
0
0
null
false
null
/* * Created on 17-Oct-2006 * Copyright (C) 2006 by Andrea Vacondio. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License. * 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 General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package it.pdfsam.render; import it.pdfsam.types.ListItem; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * Render for ListItem combo * @author Andrea Vacondio * @see it.pdfsam.types.ListItem */ public class JComboListItemRender extends JLabel implements ListCellRenderer { /** * */ private static final long serialVersionUID = 5557011327195948679L; int selectedIndex; /*Costruttore*/ public JComboListItemRender() { setOpaque(true); selectedIndex = 0; } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); selectedIndex = index; } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } if (value != null) { String text = ((ListItem)value).getValue(); setText(text); } else { setText(""); } return this; } }
UTF-8
Java
2,005
java
JComboListItemRender.java
Java
[ { "context": "* Created on 17-Oct-2006\r\n * Copyright (C) 2006 by Andrea Vacondio.\r\n *\r\n * This program is free software; you can r", "end": 71, "score": 0.9998458027839661, "start": 56, "tag": "NAME", "value": "Andrea Vacondio" }, { "context": "er;\r\n/**\r\n * Render for ListI...
null
[]
/* * Created on 17-Oct-2006 * Copyright (C) 2006 by <NAME>. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License. * 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 General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package it.pdfsam.render; import it.pdfsam.types.ListItem; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * Render for ListItem combo * @author <NAME> * @see it.pdfsam.types.ListItem */ public class JComboListItemRender extends JLabel implements ListCellRenderer { /** * */ private static final long serialVersionUID = 5557011327195948679L; int selectedIndex; /*Costruttore*/ public JComboListItemRender() { setOpaque(true); selectedIndex = 0; } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); selectedIndex = index; } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } if (value != null) { String text = ((ListItem)value).getValue(); setText(text); } else { setText(""); } return this; } }
1,987
0.662843
0.640399
64
29.296875
27.331118
98
false
false
0
0
0
0
0
0
1.78125
false
false
9
4451426f8f13ebd09f889238074b65835df2beed
19,791,209,326,258
9f24603a39851664e93bd7d9304950bda446e5b0
/SplitWise Problem/splitwise.java
312d43966653fd2845bd93dc569bfe48d91cd050
[]
no_license
singhvisha/mock-machine-coding-2
https://github.com/singhvisha/mock-machine-coding-2
622433a92ce51438dd1e5b0d2d5bf8f1b8b5e0d4
ef424ae96b4c3cf67dd66226c56b701424412e1a
refs/heads/master
2020-11-24T01:45:42.473000
2019-12-14T12:51:11
2019-12-14T12:51:11
227,910,410
0
0
null
true
2019-12-13T19:42:49
2019-12-13T19:42:48
2019-11-09T21:00:59
2019-10-31T12:17:36
534
0
0
0
null
false
false
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Application { //database that keeps track of user on the basis of their userId static HashMap<String,User> database = new HashMap<>(); public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); User u1 = new User("u1", "User1", "ramsingh@gmail.com", "8753493733"); u1.addToDatabase(database); User u2 = new User("u2", "User2", "ankitsingh@gmail.com", "8676493733"); u2.addToDatabase(database); User u3 = new User("u3", "User3", "premsingh@gmail.com", "875343433"); u3.addToDatabase(database); User u4 = new User("u4", "User4", "shyamsingh@gmail.com", "87534456733"); u4.addToDatabase(database); //variable that keeps track atleast one sharing took place. boolean sharingStarted = false; while(true) { String[] s = br1.readLine().split(" "); if(s[0].equalsIgnoreCase("SHOW")) { if(!sharingStarted) { System.out.println("No Balance"); }else { if(s.length==1) { Iterator hmIterator = database.entrySet().iterator(); while(hmIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)hmIterator.next(); User u = (User)mapElement.getValue(); u.showDebter(database); } }else if(s.length==2 && database.containsKey(s[1])) { User u = (User)database.get(s[1]); u.showDebter(database); u.showBorrower(database); }else { System.out.println("Please Enter correct format."); } } }else if(s[0].equalsIgnoreCase("EXPENSE")) { sharingStarted = true; User u = (User)database.get(s[1]); double amount = Double.parseDouble(s[2]); int number =Integer.parseInt(s[3]); String type = s[3+number+1]; String[] debtUsers = new String[number]; for(int i=0;i<number;i++) { debtUsers[i] =s[4+i]; } divideMoney(s, debtUsers, type, amount, u, number); }else { System.out.println("Error!, Please Enter the data in Correct format"); } } } //helper function that split money on the basis of type public static void divideMoney(String[] s,String[] debtUsers,String type,Double amount,User u,int number) { if(type.equals("EQUAL")) { double a = (amount*1.0)/number; for(int i=0;i<number;i++) { u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else if (type.equals("EXACT")) { int x = 3+number+2; double sum = 0; for(int i=x;i<s.length;i++) { double y = Double.parseDouble(s[i]); sum+=y; } if(amount==sum) { for(int i=0;i<number;i++) { double a = Double.parseDouble(s[x+i]); u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else { System.out.println("Error!,Sum of all distribution is not equal to Amount"); } }else if(type.equalsIgnoreCase("PERCENT")) { double sum = 0; for(int i=0;i<number;i++) { double x = Double.parseDouble(s[3+number+2+i]); sum+=x; } if(sum==100) { for(int i=0;i<number;i++) { double x = Double.parseDouble(s[3+number+2+i]); double a = amount*(x/100); u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else { System.out.println("Error!,Sum of all percentage is not equal to 100"); } } } } //User Class that has userId,name,email,mobileNo,debt,borrower as its field class User{ private String userId; private String name; private String email; private String mobileNo; private HashMap<String,Double> debt; private HashMap<String, Double> borrow; public User(String userId,String name,String email,String mobileNo) { this.userId = userId; this.name = name; this.email = email; this.mobileNo = mobileNo; debt = new HashMap<>(); borrow = new HashMap<>(); } public String getUserId() { return userId; } public String getName() { return name; } public String getEmail() { return email; } public String getMobileNo() { return mobileNo; } public HashMap<String,Double > getDebt() { return debt; } public HashMap<String, Double> getBorrow() { return borrow; } //helper function that add all the user who had borrow money public void addDebt(String debtUser,double amount) { if(!debtUser.equals(this.userId)) { if(this.debt.containsKey(debtUser)) { double a = (double)this.debt.get(debtUser); a +=amount; this.debt.put(debtUser, a); }else { this.debt.put(debtUser, amount); } } } //helper function that add the user whom current user has borrowed the money public void addBorrow(String borrower,double amount) { if(!borrower.equals(this.userId)) { if(this.borrow.containsKey(borrower)) { double a = (double)this.borrow.get(borrower); a+=amount; this.borrow.put(borrower, a); }else { this.borrow.put(borrower, amount); } } } //helper function that add the user to database public void addToDatabase(HashMap<String, User> database) { database.put(this.getUserId(),this); } //helper function list all user who has taken from him public void showDebter(HashMap<String, User> database) { Iterator debtIterator = debt.entrySet().iterator(); while(debtIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)debtIterator.next(); double value = (double)mapElement.getValue(); String userId = (String)mapElement.getKey(); String username = (String)database.get(userId).getName(); if(value>0) { System.out.println(String.format("%s owes %s : %.2f",username,this.name,value)); } } } //helper function list all user from whom this user has taken the money. public void showBorrower(HashMap<String, User> database) { Iterator borrowerIterator = borrow.entrySet().iterator(); while(borrowerIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)borrowerIterator.next(); double value = (double)mapElement.getValue(); String userId = (String)mapElement.getKey(); String username = (String)database.get(userId).getName(); if(value>0) { System.out.println(String.format("%s owes %s : %.2f",this.name,username,value)); } } } }
UTF-8
Java
6,501
java
splitwise.java
Java
[ { "context": "tem.in));\n\t\t\n\t\tUser u1 = new User(\"u1\", \"User1\", \"ramsingh@gmail.com\", \"8753493733\");\n\t\tu1.addToDatabase(database);\n\t\t", "end": 594, "score": 0.9999252557754517, "start": 576, "tag": "EMAIL", "value": "ramsingh@gmail.com" }, { "context": "e(database)...
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Application { //database that keeps track of user on the basis of their userId static HashMap<String,User> database = new HashMap<>(); public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); User u1 = new User("u1", "User1", "<EMAIL>", "8753493733"); u1.addToDatabase(database); User u2 = new User("u2", "User2", "<EMAIL>", "8676493733"); u2.addToDatabase(database); User u3 = new User("u3", "User3", "<EMAIL>", "875343433"); u3.addToDatabase(database); User u4 = new User("u4", "User4", "<EMAIL>", "87534456733"); u4.addToDatabase(database); //variable that keeps track atleast one sharing took place. boolean sharingStarted = false; while(true) { String[] s = br1.readLine().split(" "); if(s[0].equalsIgnoreCase("SHOW")) { if(!sharingStarted) { System.out.println("No Balance"); }else { if(s.length==1) { Iterator hmIterator = database.entrySet().iterator(); while(hmIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)hmIterator.next(); User u = (User)mapElement.getValue(); u.showDebter(database); } }else if(s.length==2 && database.containsKey(s[1])) { User u = (User)database.get(s[1]); u.showDebter(database); u.showBorrower(database); }else { System.out.println("Please Enter correct format."); } } }else if(s[0].equalsIgnoreCase("EXPENSE")) { sharingStarted = true; User u = (User)database.get(s[1]); double amount = Double.parseDouble(s[2]); int number =Integer.parseInt(s[3]); String type = s[3+number+1]; String[] debtUsers = new String[number]; for(int i=0;i<number;i++) { debtUsers[i] =s[4+i]; } divideMoney(s, debtUsers, type, amount, u, number); }else { System.out.println("Error!, Please Enter the data in Correct format"); } } } //helper function that split money on the basis of type public static void divideMoney(String[] s,String[] debtUsers,String type,Double amount,User u,int number) { if(type.equals("EQUAL")) { double a = (amount*1.0)/number; for(int i=0;i<number;i++) { u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else if (type.equals("EXACT")) { int x = 3+number+2; double sum = 0; for(int i=x;i<s.length;i++) { double y = Double.parseDouble(s[i]); sum+=y; } if(amount==sum) { for(int i=0;i<number;i++) { double a = Double.parseDouble(s[x+i]); u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else { System.out.println("Error!,Sum of all distribution is not equal to Amount"); } }else if(type.equalsIgnoreCase("PERCENT")) { double sum = 0; for(int i=0;i<number;i++) { double x = Double.parseDouble(s[3+number+2+i]); sum+=x; } if(sum==100) { for(int i=0;i<number;i++) { double x = Double.parseDouble(s[3+number+2+i]); double a = amount*(x/100); u.addDebt(debtUsers[i], a); User w = (User)database.get(debtUsers[i]); w.addBorrow(u.getUserId(), a); } }else { System.out.println("Error!,Sum of all percentage is not equal to 100"); } } } } //User Class that has userId,name,email,mobileNo,debt,borrower as its field class User{ private String userId; private String name; private String email; private String mobileNo; private HashMap<String,Double> debt; private HashMap<String, Double> borrow; public User(String userId,String name,String email,String mobileNo) { this.userId = userId; this.name = name; this.email = email; this.mobileNo = mobileNo; debt = new HashMap<>(); borrow = new HashMap<>(); } public String getUserId() { return userId; } public String getName() { return name; } public String getEmail() { return email; } public String getMobileNo() { return mobileNo; } public HashMap<String,Double > getDebt() { return debt; } public HashMap<String, Double> getBorrow() { return borrow; } //helper function that add all the user who had borrow money public void addDebt(String debtUser,double amount) { if(!debtUser.equals(this.userId)) { if(this.debt.containsKey(debtUser)) { double a = (double)this.debt.get(debtUser); a +=amount; this.debt.put(debtUser, a); }else { this.debt.put(debtUser, amount); } } } //helper function that add the user whom current user has borrowed the money public void addBorrow(String borrower,double amount) { if(!borrower.equals(this.userId)) { if(this.borrow.containsKey(borrower)) { double a = (double)this.borrow.get(borrower); a+=amount; this.borrow.put(borrower, a); }else { this.borrow.put(borrower, amount); } } } //helper function that add the user to database public void addToDatabase(HashMap<String, User> database) { database.put(this.getUserId(),this); } //helper function list all user who has taken from him public void showDebter(HashMap<String, User> database) { Iterator debtIterator = debt.entrySet().iterator(); while(debtIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)debtIterator.next(); double value = (double)mapElement.getValue(); String userId = (String)mapElement.getKey(); String username = (String)database.get(userId).getName(); if(value>0) { System.out.println(String.format("%s owes %s : %.2f",username,this.name,value)); } } } //helper function list all user from whom this user has taken the money. public void showBorrower(HashMap<String, User> database) { Iterator borrowerIterator = borrow.entrySet().iterator(); while(borrowerIterator.hasNext()) { Map.Entry mapElement = (Map.Entry)borrowerIterator.next(); double value = (double)mapElement.getValue(); String userId = (String)mapElement.getKey(); String username = (String)database.get(userId).getName(); if(value>0) { System.out.println(String.format("%s owes %s : %.2f",this.name,username,value)); } } } }
6,452
0.656053
0.640978
220
28.554546
24.124519
133
false
false
0
0
0
0
0
0
3.036364
false
false
9
bcddd901296de094dcf58a818e65659af395c323
22,917,945,531,434
65df20d14d5c6565ec135c9351d753436d3de0f5
/jo_plugin/JoFileMods/src/jo/sm/plugins/ship/exp/ExportImagesParameters.java
48f9f122b10883482d7bb72e204339679681a3f2
[ "Apache-2.0" ]
permissive
cadox8/SMEdit
https://github.com/cadox8/SMEdit
caf70575e27ea450e7998bf6e92f73b825cf42a1
f9bd01fc794886be71580488b656ec1c5c94afe3
refs/heads/master
2021-05-30T17:35:31.035000
2016-01-03T21:39:58
2016-01-03T21:39:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2014 * SMEdit https://github.com/StarMade/SMEdit * SMTools https://github.com/StarMade/SMTools * * 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 jo.sm.plugins.ship.exp; import jo.sm.ui.act.plugin.Description; /** * @Auther Jo Jaquinta for SMEdit Classic - version 1.0 **/ @Description(displayName = "Export Images of Object to Disk", shortDescription = "This writes fore, aft, dorsal, ventral, port, starboard, and an isometric view" + " of the object, plus a contact sheet with everything on it to the given directory.") public class ExportImagesParameters { @Description(displayName = "", shortDescription = "Directory to place images") private String mDirectory; @Description(displayName = "", shortDescription = "Prefix to use for image name") private String mName; @Description(displayName = "", shortDescription = "Width in pixels") private int mWidth; @Description(displayName = "", shortDescription = "Height in pixels") private int mHeight; public ExportImagesParameters() { mDirectory = System.getProperty("user.home"); mWidth = 1024; mHeight = 768; } public String getDirectory() { return mDirectory; } public void setDirectory(String directory) { mDirectory = directory; } public String getName() { return mName; } public void setName(String name) { mName = name; } public int getWidth() { return mWidth; } public void setWidth(int width) { mWidth = width; } public int getHeight() { return mHeight; } public void setHeight(int height) { mHeight = height; } }
UTF-8
Java
2,223
java
ExportImagesParameters.java
Java
[ { "context": "*\n * Copyright 2014 \n * SMEdit https://github.com/StarMade/SMEdit\n * SMTools https://github.com/StarMade/SMT", "end": 60, "score": 0.9994879961013794, "start": 52, "tag": "USERNAME", "value": "StarMade" }, { "context": "com/StarMade/SMEdit\n * SMTools https://github....
null
[]
/** * Copyright 2014 * SMEdit https://github.com/StarMade/SMEdit * SMTools https://github.com/StarMade/SMTools * * 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 jo.sm.plugins.ship.exp; import jo.sm.ui.act.plugin.Description; /** * @Auther <NAME> for SMEdit Classic - version 1.0 **/ @Description(displayName = "Export Images of Object to Disk", shortDescription = "This writes fore, aft, dorsal, ventral, port, starboard, and an isometric view" + " of the object, plus a contact sheet with everything on it to the given directory.") public class ExportImagesParameters { @Description(displayName = "", shortDescription = "Directory to place images") private String mDirectory; @Description(displayName = "", shortDescription = "Prefix to use for image name") private String mName; @Description(displayName = "", shortDescription = "Width in pixels") private int mWidth; @Description(displayName = "", shortDescription = "Height in pixels") private int mHeight; public ExportImagesParameters() { mDirectory = System.getProperty("user.home"); mWidth = 1024; mHeight = 768; } public String getDirectory() { return mDirectory; } public void setDirectory(String directory) { mDirectory = directory; } public String getName() { return mName; } public void setName(String name) { mName = name; } public int getWidth() { return mWidth; } public void setWidth(int width) { mWidth = width; } public int getHeight() { return mHeight; } public void setHeight(int height) { mHeight = height; } }
2,218
0.675214
0.667566
75
28.639999
30.498804
161
false
false
0
0
0
0
0
0
0.453333
false
false
9
db361b1bee99c21f8b78600b0115bb6a7a9c8764
7,739,531,127,383
382309d27cfaca0a36e6e98849e04f88631dc202
/src/com/taxiagency/dao/DriveFileDao.java
c0e074e8fae053470184641d76c870b2d2eda81f
[]
no_license
IvanBuryy/taxi-agency
https://github.com/IvanBuryy/taxi-agency
fe57150c2343a8b91e6f7070b5690edef8f8403d
aa99a49cdf1df44abf9d8145a2aa07cf910da6f1
refs/heads/master
2020-05-26T02:56:47.884000
2019-05-29T17:47:23
2019-05-29T17:47:23
188,083,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.taxiagency.dao; import com.taxiagency.domain.Driver; import com.taxiagency.domain.Entity; import java.util.List; public class DriveFileDao<T extends FileDao> implements DriveDao<RamDao> { @Override public List<Driver> findByName() { return findByName(); } @Override public String save(Entity obj) { return null; } @Override public void update(Entity obj) { } @Override public String upsert(Entity obj) { return null; } @Override public void delete(String id) { } @Override public Entity findById(String id) { return null; } @Override public List findAll() { return null; } }
UTF-8
Java
723
java
DriveFileDao.java
Java
[]
null
[]
package com.taxiagency.dao; import com.taxiagency.domain.Driver; import com.taxiagency.domain.Entity; import java.util.List; public class DriveFileDao<T extends FileDao> implements DriveDao<RamDao> { @Override public List<Driver> findByName() { return findByName(); } @Override public String save(Entity obj) { return null; } @Override public void update(Entity obj) { } @Override public String upsert(Entity obj) { return null; } @Override public void delete(String id) { } @Override public Entity findById(String id) { return null; } @Override public List findAll() { return null; } }
723
0.621024
0.621024
45
15.066667
16.130579
74
false
false
0
0
0
0
0
0
0.2
false
false
9
10f5c61651a79a0a727fd5c5caed15b8df0153d1
33,715,493,302,982
42582e0d83b106681342de39e8c041f38450f588
/Server/src/main/java/com/hapi/hapiservice/helpers/common/browserHelper.java
20cd242565943a4a3800794c571c9d0dde13a38d
[]
no_license
lesongvi/HapiApp
https://github.com/lesongvi/HapiApp
e608240d123ce3c00f2d83557eb61b92b1dd90cf
88622926caf45cf75954f264688b9af57be53610
refs/heads/main
2023-05-29T12:36:38.148000
2021-06-09T11:32:04
2021-06-09T11:32:04
347,043,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hapi.hapiservice.helpers.common; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.gson.Gson; import com.hapi.hapiservice.helpers.respository.StudentRepository; import com.hapi.hapiservice.models.schedule.*; import com.hapi.hapiservice.services.StudentService; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.*; import java.net.CookieManager; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.text.ParseException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class browserHelper extends stuffHelper { final stringHelper definedStr = new stringHelper(); final WebClient webClient = this.initial(); protected int studentId; protected String studentPassword; private StudentRepository studentRepository; private StudentService studentService; private static final SecureRandom secureRand = new SecureRandom(); private static final Base64.Encoder base64 = Base64.getUrlEncoder(); protected String token; protected EncryptHelper encryptEngine = new EncryptHelper(); Logger logger = LoggerFactory.getLogger(browserHelper.class); public browserHelper( int studentId, String studentPassword, StudentRepository studentRepository, StudentService studentService) { this.studentId = studentId; this.studentPassword = studentPassword; this.studentRepository = studentRepository; this.studentService = studentService; } public browserHelper( String token, StudentRepository studentRepository, StudentService studentService) { this(0, null, studentRepository, studentService); this.token = token; } public browserHelper() { this(null, null, null); } public String conAuth(boolean isSaved) throws MalformedURLException { Gson gson = new Gson(); authSuccess response = new authSuccess(true, "", "", "", "", "", "", ""); if ((this.studentId + "").length() != 10) return gson.toJson(new errorResponse(true, "Tài khoản sinh viên không hợp lệ", 404)); ArrayList<String> studntMP = this.getMailAndPhoneNum(); try { if (isSaved) { Students stdnt = new Students(); stdnt.setId(this.studentId); stdnt.setPwd(this.encryptEngine.pleaseHelpViSecureThis(this.studentPassword)); stdnt.setEmail(studntMP.get(0)); stdnt.setSdt(1, studntMP.get(1)); stdnt.setSdt(2, studntMP.get(2)); Students stdunt = studentService.saveAndGetStudent(stdnt); response = new authSuccess(false, stdunt.getName(), stdunt.getToken(), stdunt.getEmail(), stdunt.getSid() + "", stdunt.getSdt(1), stdunt.getSdt(2), stdunt.getAvatar()); } else { String genToken = this.generateStdntToken(); Students stdnt = new Students(); stdnt.setId(this.studentId); stdnt.setPwd(this.encryptEngine.pleaseHelpViSecureThis(this.studentPassword)); stdnt.setName(this.getSName()); stdnt.setEmail(studntMP.get(0)); stdnt.setSdt(1, studntMP.get(1)); stdnt.setSdt(2, studntMP.get(2)); stdnt.setAvatar("https://cdn.notevn.com/Lyfq3HJj9.png"); stdnt.setToken(genToken); studentRepository.save(stdnt); response = new authSuccess(false, this.getSName(), genToken, studntMP.get(0), "" + this.studentId, studntMP.get(1), studntMP.get(2), "https://cdn.notevn.com/Lyfq3HJj9.png"); } } catch (Exception e) { logger.error(e.getMessage()); return gson.toJson(new errorResponse(true, "Có lỗi đã xảy ra!", 404)); } finally { return gson.toJson(response); } } public String reAuth() throws MalformedURLException { Gson gson = new Gson(); authSuccess response = new authSuccess(true, "", "", "", "", "", "", ""); try { Students stdunt = studentService.getStudentByToken(token); response = new authSuccess(false, stdunt.getName(), stdunt.getToken(), stdunt.getEmail(), stdunt.getSid() + "", stdunt.getSdt(1), stdunt.getSdt(2), stdunt.getAvatar()); } catch (Exception e) { logger.error(e.getMessage()); return gson.toJson(new errorResponse(true, "Có lỗi đã xảy ra!", 404)); } finally { return gson.toJson(response); } } public static String generateStdntToken() { byte[] randomBytes = new byte[24]; secureRand.nextBytes(randomBytes); return base64.encodeToString(randomBytes); } public WebClient getLoginVS () { try { Matcher check = this.processingCredential(this.definedStr.invalidCredentialsPattern_PRODUCTION()); if (check.find()) { this.webClient.close(); return null; } } catch (Exception e) { logger.error(e.getMessage()); } finally { return this.webClient; } } public boolean isServerReloading() throws IOException { URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = this.requestLogin() .getPage(defaultPage); Pattern pattern = Pattern.compile(this.definedStr.serverReloadPattern_PRODUCTION()); Matcher checkReloading = pattern.matcher(page.asXml()); return checkReloading.find(); } public Matcher processingCredential(String regex) throws IOException { Object _lock = new Object(); URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); String parseBody; Pattern pattern; defaultPage = this.setAdditionalHeader(defaultPage); synchronized (_lock) { HtmlPage page = null; page = this.requestLogin() .getPage(defaultPage); parseBody = getString(page); pattern = Pattern.compile(regex); } return pattern.matcher(parseBody); } private String getString(HtmlPage page) { String parseBody; parseBody = this.passCredentials(page).asXml(); return parseBody; } private HtmlPage passCredentials(HtmlPage page) { try { HtmlInput logInput = page.getHtmlElementById(this.definedStr.loginId_PRODUCTION()); HtmlInput pwdInput = page.getHtmlElementById(this.definedStr.loginPwdId_PRODUCTION()); logInput.setValueAttribute(this.studentId + ""); pwdInput.setValueAttribute(this.studentPassword); page = page.getHtmlElementById(this.definedStr.loginBtnId_PRODUCTION()).click(); } catch (Exception e) { logger.error(e.getMessage()); } finally { return page; } } public String loginAndPattern(String regex, int groupNum) throws IOException { Matcher searchResult = this.processingCredential(regex); if (searchResult.find()) { webClient.close(); return searchResult.group(groupNum); } return ""; } public String[] getVS(String initialUrl) throws MalformedURLException { URL actionUrl = new URL(initialUrl); WebRequest defaultPage = new WebRequest(actionUrl); HtmlPage page = null; try { page = (HtmlPage) this.webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } webClient.close(); return new String[]{ page.getElementById("__VIEWSTATE").getAttribute("value"), page.getElementById("__VIEWSTATEGENERATOR").getAttribute("value") }; } public String getSName() throws MalformedURLException { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); String _studntName = null; try { HtmlPage page = (HtmlPage) this.webClient .getPage(defaultPage); DomElement helloStudnt = page.getElementById(definedStr.helloStudentId_PRODUCTION()); if (helloStudnt.getTagName().toLowerCase().equals("span")) { String _xmlDefault = this.removeTheDEGap(helloStudnt); Matcher defaultMyView = this.patternSearch(this.definedStr.studentNamePattern_PRODUCTION(), _xmlDefault); if (!defaultMyView.find()) return null; _studntName = defaultMyView.group(1); } } catch (Exception e) { logger.error(e.getMessage()); } finally { return _studntName; } } public WebClient requestLogin() throws IOException { URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page; try { page = this.webClient .getPage(defaultPage); this.passCredentials(page); } catch (IOException e) { logger.error(e.getMessage()); } return this.webClient; } private WebRequest setAdditionalHeader(WebRequest wr) { wr.setAdditionalHeader("User-Agent", this.definedStr.userAgentDefault_PRODUCTION()); wr.setAdditionalHeader("Accept-Encoding", this.definedStr.acceptEncoding_PRODUCTION()); wr.setAdditionalHeader("Accept-Language", this.definedStr.acceptLanguage_PRODUCTION()); wr.setAdditionalHeader("Accept", this.definedStr.acceptDataType_PRODUCTION()); wr.setAdditionalHeader("Origin", this.definedStr.reqOrigin_PRODUCTION()); return wr; } public ArrayList<String> getMailAndPhoneNum() throws MalformedURLException { URL actionUrl = new URL(this.definedStr.userInfoChangerUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<String> _infoBack = new ArrayList<String>(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = this.requestLogin() .getPage(defaultPage); DomElement studntMailSlct = page.getElementById(definedStr.studentEmailId_PRODUCTION()); DomElement studntSdt1Slct = page.getElementById(definedStr.studentSdt1Id_PRODUCTION()); DomElement studntSdt2Slct = page.getElementById(definedStr.studentSdt2Id_PRODUCTION()); if (studntMailSlct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntMailSlct.getAttribute("value")); } if (studntSdt1Slct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntSdt1Slct.getAttribute("value")); } if (studntSdt2Slct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntSdt2Slct.getAttribute("value")); } } catch (Exception e) { logger.error(e.getMessage()); } finally { return _infoBack; } } public static String showCookies(String websiteURL) throws IOException { CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(websiteURL); URLConnection urlConnection = url.openConnection(); urlConnection.getContent(); CookieStore cookieStore = cookieManager.getCookieStore(); return cookieStore.getCookies().get(0).getValue(); } public WebClient verifyToken() throws IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException { Students tokenInfo = this.studentService.getStudentByToken(this.token); this.studentId = tokenInfo.getSid(); this.studentPassword = this.encryptEngine.pleaseHelpViHackThis(tokenInfo.getPwd()); return this.getLoginVS(); } public String getSemesterList() throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<semesterResponse> semesterMap = new ArrayList(); Gson gson = new Gson(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement semesterOpt = page.getElementById(definedStr.semesterOptId_PRODUCTION()); semesterMap = this.semesterProcess(semesterOpt); } catch (Exception e) { logger.error(e.getMessage()); } finally { webClient.close(); return gson.toJson(semesterMap); } } public ArrayList<semesterResponse> getSemesterArr() throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<semesterResponse> semesterMap = new ArrayList(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement semesterOpt = page.getElementById(definedStr.semesterOptId_PRODUCTION()); semesterMap = this.semesterProcess(semesterOpt); } catch (Exception e) { logger.error(e.getMessage()); } finally { webClient.close(); return semesterMap; } } private ArrayList<semesterResponse> semesterProcess(DomElement semesterOpt) { String[] _semesters = new String[] {}; ArrayList<semesterResponse> semesterMap = new ArrayList<semesterResponse>(); if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlSemester = this.removeTheDEGap(semesterOpt); Matcher semesterView = this.patternSearch(this.definedStr.semesterOptPattern_PRODUCTION(), _xmlSemester); if (!semesterView.find()) return null; _semesters = semesterView .group(2) .replace("<option selected=\"selected\" value=\"", "") .replace("\"", "") .replace("</option>", "") .split("<option value=", -1); } //Thread.sleep(1500); for (String tStr : _semesters){ String singleSemester[] = tStr.split(">", -1); semesterMap.add(semesterMap.size(), new semesterResponse(singleSemester[0], singleSemester[1])); } return semesterMap; } public String getWeekList(String currSemester) throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { Gson gson = new Gson(); return gson.toJson(this.getWeekArr(currSemester)); } public ArrayList<weekResponse> getWeekArr(String currSemester) throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; if (currSemester != null) defaultPage = this.selectSemesterOpt(currSemester); else { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); defaultPage = new WebRequest(actionUrl); } defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement semesterOpt = page.getElementById(definedStr.weekOptId_PRODUCTION()); webClient.close(); return this.weekProcessing(semesterOpt); } public weekResponse findSelectedWeek() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, ParseException { WebClient webClient = this.verifyToken(); Object _lock = new Object(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement semesterOpt = page.getElementById(definedStr.weekOptId_PRODUCTION()); synchronized (_lock) { if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlWeek = this.removeTheDEGap(semesterOpt); Matcher weekView = this.patternSearch(this.definedStr.selectedMiniOptPattern_PRODUCTION(), _xmlWeek); if (weekView.find()) { String tempStr = weekView.group(1); Matcher weekNum = this.patternSearch(this.definedStr.weekNumOptPattern_PRODUCTION(), tempStr); Matcher startDate = this.patternSearch(this.definedStr.startDateOptPattern_PRODUCTION(), tempStr); Matcher endDate = this.patternSearch(this.definedStr.endDateOptPattern_PRODUCTION(), tempStr); if (weekNum.find() && startDate.find() && endDate.find()) { return new weekResponse(startDate.group(1), endDate.group(1), weekNum.group(1), tempStr); } } } } return null; } public ArrayList<weekResponse> weekProcessing(DomElement semesterOpt) { ArrayList<weekResponse> _allSWeek = new ArrayList<weekResponse>(); if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlWeek = this.removeTheDEGap(semesterOpt); Matcher weekView = this.patternSearch(this.definedStr.miniOptPattern_PRODUCTION(), _xmlWeek); while (weekView.find()) { String tempStr = weekView.group(1); Matcher weekNum = this.patternSearch(this.definedStr.weekNumOptPattern_PRODUCTION(), tempStr); Matcher startDate = this.patternSearch(this.definedStr.startDateOptPattern_PRODUCTION(), tempStr); Matcher endDate = this.patternSearch(this.definedStr.endDateOptPattern_PRODUCTION(), tempStr); if (weekNum.find() && startDate.find() && endDate.find()) { try { _allSWeek.add(new weekResponse(startDate.group(1), endDate.group(1), weekNum.group(1), tempStr)); } catch (Exception e) { logger.error(e.getMessage()); } } } } return _allSWeek; } public String getScheduleDetail(String currSemester, String currWeek) throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { Gson gson = new Gson(); return gson.toJson(this.getScheduleDetailArr(currSemester, currWeek)); } public ArrayList<scheduleReponse> getScheduleDetailArr(String currSemester, String currWeek) throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; ArrayList<scheduleReponse> _fullWSchedule = new ArrayList<scheduleReponse>(); if (currSemester != null && currWeek != null) defaultPage = this.selectWeekOpt(currSemester, currWeek); else { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); defaultPage = new WebRequest(actionUrl); } defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); if (currSemester != null && currWeek != null) page = this.getScheduleDetailByVS(webClient, page.getElementById("__VIEWSTATE").getAttribute("value"), page.getElementById("__VIEWSTATEGENERATOR").getAttribute("value"), currSemester, currWeek); DomElement scheduleTable = page.getElementById(definedStr.scheduleTableId_PRODUCTION()); if(scheduleTable.getTagName().toLowerCase().equals("table")) { String _xmlSchedule = this.removeTheDEGap(scheduleTable); Matcher scheduleView = this.patternSearch(this.definedStr.schedulePattern_PRODUCTION(), _xmlSchedule); while (scheduleView.find()) { String[] tempStr = scheduleView .group(1) //.replaceAll(this.definedStr.scheduleDescRemove_PRODUCTION(), "") .replaceAll("'", "") .split(","); _fullWSchedule.add(new scheduleReponse(tempStr[0], tempStr[1], tempStr[9], tempStr[10], tempStr[2], tempStr[5], tempStr[7], tempStr[3], tempStr[6], tempStr[4], tempStr[8], tempStr[11], tempStr[12])); } } return _fullWSchedule; } public ArrayList<ExamResponse> getExamScheArr() throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; ArrayList<ExamResponse> _fullESchedule = new ArrayList(); URL actionUrl = new URL(this.definedStr.examSchePageUrl_PRODUCTION()); defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement examTable = page.getElementById(definedStr.examTableId_PRODUCTION()); if(examTable.getTagName().toLowerCase().equals("table")) { String _xmlExamSche = this.removeTheDEGap(examTable); Matcher examView = this.patternSearch(this.definedStr.examValuPattern_PRODUCTION(), _xmlExamSche); int idx = 0; String[] incremental = {}; while (examView.find()) { String[] tempStr = examView .group(1) .split("\n"); incremental = ArrayUtils.addAll(incremental, tempStr[0]); idx++; if (idx == 10) { _fullESchedule.add(new ExamResponse(incremental[1].trim(), incremental[2].trim(), incremental[3].trim(), incremental[4].trim(), incremental[5].trim(), incremental[6].trim(), incremental[7].trim(), incremental[8].trim(), incremental[9].trim())); idx = 0; } } } return _fullESchedule; } public ArrayList<pointResponse> getCurrentPointArr() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(definedStr.studentCPointTblId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); return this.showSemesterPointArr(_xmlPTbl); } return null; } public String getCurrentPoint() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; Gson gson = new Gson(); try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } Matcher CheckMessInterrupt = this.patternSearch(this.definedStr.getMessInterrupt_PRODUCTION(), page.asXml()); if (CheckMessInterrupt.find()) { return gson.toJson(new errorResponse(true, CheckMessInterrupt.group(1).trim(), 503)); } DomElement stdntPointTbl = page.getElementById(definedStr.studentCPointTblId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); return this.showSemesterPoint(_xmlPTbl); } webClient.close(); return null; } public String showSemesterPoint(String _xmlPTbl) { Gson gson = new Gson(); return gson.toJson(this.showSemesterPointArr(_xmlPTbl)); } public ArrayList<pointResponse> showSemesterPointArr(String _xmlPTbl) { ArrayList<pointResponse> fullPointView = new ArrayList<pointResponse>(); ArrayList<String> temp = new ArrayList<String>(); int count = 0; Matcher pointView = this.patternSearch(this.definedStr.studentPointPattern_PRODUCTION(), _xmlPTbl); while (pointView.find()) { temp.add(pointView.group(1).trim()); if (!!(count == 10)) { fullPointView.add(new pointResponse(temp.get(1), temp.get(2), temp.get(3), temp.get(4), temp.get(5), temp.get(6), temp.get(7), temp.get(8), temp.get(9), temp.get(10))); count = -1; temp.clear(); } count++; } return fullPointView; } public ArrayList<PSListResponse> getPointListSemesterArr() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); Matcher pointView = null; WebRequest defaultPage = this.viewAllPoint(); ArrayList<PSListResponse> fullPointView = new ArrayList(); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(definedStr.studentPSemesterId_PRODUCTION()); String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); pointView = this.patternSearch(this.definedStr.studentPListPattern_PRODUCTION(), _xmlPTbl); while (pointView.find()) { fullPointView.add(new PSListResponse(pointView.group(5).trim(), pointView.group(6).trim())); } return fullPointView; } public ArrayList<pointResponse> getPointBySemesterArr(String semesterId) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); Matcher pointView; ArrayList<pointResponse> _empty = new ArrayList<pointResponse>(); WebRequest defaultPage = this.viewAllPoint(); defaultPage = this.setAdditionalHeader(defaultPage); Matcher firstTest = this.patternSearch(this.definedStr.cboxPointTestPattern_PRODUCTION(), semesterId); if (firstTest.find()) { semesterId = "Học kỳ " + firstTest.group(1) + " - Năm học " + firstTest.group(2) + "-" + firstTest.group(3); } HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { this.logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(this.definedStr.studentPSemesterId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); String myPattern = semesterId.trim().concat(this.definedStr.studentPRangeSelectPattern_PRODUCTION()); pointView = this.patternSearch(myPattern, _xmlPTbl); if (pointView.find()) return this.showSemesterPointArr(pointView.group(7)); else return _empty; } return _empty; } public String getPointListSemester(String semesterId) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { Gson gson = new Gson(); if (semesterId.length() == 0) return gson.toJson(this.getPointListSemesterArr()); else return gson.toJson(this.getPointBySemesterArr(semesterId)); } public Matcher patternSearch(String regex, String _test) { Pattern pattern = Pattern.compile(regex); return pattern.matcher(_test); } public String removeTheDEGap(DomElement theGap) { return theGap.asXml().replaceAll("\r\n", ""); } public HtmlPage getScheduleDetailByVS(WebClient wc, String _vs, String _vsg, String ssm, String sw) throws IOException { String _acUrl = this.definedStr.schedulePage_PRODUCTION(); URL actionUrl = new URL(_acUrl); WebRequest page = new WebRequest(actionUrl, HttpMethod.POST); page = this.setAdditionalHeader(page); page.setRequestBody("__EVENTTARGET=ctl00$ContentPlaceHolder1$ctl00$ddlTuan&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + URLEncoder.encode(_vs, StandardCharsets.UTF_8.toString()) + "&__VIEWSTATEGENERATOR=" + _vsg + "&ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK=" + URLEncoder.encode(ssm, StandardCharsets.UTF_8.toString()) + "&ctl00$ContentPlaceHolder1$ctl00$ddlLoai=0&ctl00$ContentPlaceHolder1$ctl00$ddlTuan=" + URLEncoder.encode(sw, StandardCharsets.UTF_8.toString())); return (HtmlPage) wc .getPage(page); } public WebRequest selectSemesterOpt(String selectedOpt) throws MalformedURLException, UnsupportedEncodingException { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); String _VState; Object _lock2 = new Object(); synchronized (_lock2) { _VState = this.getVS(this.definedStr.schedulePage_PRODUCTION())[0]; } schedulePage = this.setAdditionalHeader(schedulePage); schedulePage.setRequestBody(this.definedStr.requestBodySSO_PRODUCTION() .replace("{{VIEWSTATE}}", URLEncoder.encode(_VState, StandardCharsets.UTF_8.toString())) .replace("{{CHON_NHHK}}", URLEncoder.encode(selectedOpt, StandardCharsets.UTF_8.toString()))); return schedulePage; } public WebRequest selectWeekOpt(String selectedSemester, String selectedWeek) throws MalformedURLException, IllegalBlockSizeException, InvalidKeyException, NoSuchAlgorithmException, BadPaddingException, NoSuchPaddingException, ParseException, UnsupportedEncodingException { Object _lock = new Object(); Object _lock1 = new Object(); Object _lock2 = new Object(); weekResponse weekRes; String _acUrl; String _VsGet[]; synchronized (_lock) { weekRes = this.findSelectedWeek(); } synchronized (_lock1) { _acUrl = weekRes.getTenxacdinh().equals(selectedWeek) ? this.definedStr.schedulePageUrlMode1_PRODUCTION() : this.definedStr.schedulePage_PRODUCTION(); } URL actionUrl = new URL(_acUrl); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); synchronized (_lock2) { _VsGet = this.getVS(_acUrl); } schedulePage.setRequestBody("__EVENTTARGET=ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + URLEncoder.encode(_VsGet[0], StandardCharsets.UTF_8.toString()) + "&__VIEWSTATEGENERATOR=" + _VsGet[1] + "&ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK=" + URLEncoder.encode(selectedSemester, StandardCharsets.UTF_8.toString()) + "&ctl00$ContentPlaceHolder1$ctl00$ddlLoai=0"); return schedulePage; } public WebRequest viewAllPoint() throws MalformedURLException, UnsupportedEncodingException { URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); schedulePage = this.setAdditionalHeader(schedulePage); schedulePage.setRequestBody(this.definedStr.requestBodyVAP_PRODUCTION() .replace("{{VIEWSTATE}}", URLEncoder.encode(this.getVS(this.definedStr.studentPointUrl_PRODUCTION())[0], StandardCharsets.UTF_8.toString()))); return schedulePage; } public String getExamScheList() throws BadPaddingException, ParseException, NoSuchAlgorithmException, IOException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException { Gson gson = new Gson(); return gson.toJson(this.getExamScheArr()); } }
UTF-8
Java
35,456
java
browserHelper.java
Java
[ { "context": "dentId = studentId;\n this.studentPassword = studentPassword;\n this.studentRepository = studentReposito", "end": 1964, "score": 0.9985977411270142, "start": 1949, "tag": "PASSWORD", "value": "studentPassword" }, { "context": "tokenInfo.getSid();\n ...
null
[]
package com.hapi.hapiservice.helpers.common; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.gson.Gson; import com.hapi.hapiservice.helpers.respository.StudentRepository; import com.hapi.hapiservice.models.schedule.*; import com.hapi.hapiservice.services.StudentService; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.*; import java.net.CookieManager; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.text.ParseException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class browserHelper extends stuffHelper { final stringHelper definedStr = new stringHelper(); final WebClient webClient = this.initial(); protected int studentId; protected String studentPassword; private StudentRepository studentRepository; private StudentService studentService; private static final SecureRandom secureRand = new SecureRandom(); private static final Base64.Encoder base64 = Base64.getUrlEncoder(); protected String token; protected EncryptHelper encryptEngine = new EncryptHelper(); Logger logger = LoggerFactory.getLogger(browserHelper.class); public browserHelper( int studentId, String studentPassword, StudentRepository studentRepository, StudentService studentService) { this.studentId = studentId; this.studentPassword = <PASSWORD>; this.studentRepository = studentRepository; this.studentService = studentService; } public browserHelper( String token, StudentRepository studentRepository, StudentService studentService) { this(0, null, studentRepository, studentService); this.token = token; } public browserHelper() { this(null, null, null); } public String conAuth(boolean isSaved) throws MalformedURLException { Gson gson = new Gson(); authSuccess response = new authSuccess(true, "", "", "", "", "", "", ""); if ((this.studentId + "").length() != 10) return gson.toJson(new errorResponse(true, "Tài khoản sinh viên không hợp lệ", 404)); ArrayList<String> studntMP = this.getMailAndPhoneNum(); try { if (isSaved) { Students stdnt = new Students(); stdnt.setId(this.studentId); stdnt.setPwd(this.encryptEngine.pleaseHelpViSecureThis(this.studentPassword)); stdnt.setEmail(studntMP.get(0)); stdnt.setSdt(1, studntMP.get(1)); stdnt.setSdt(2, studntMP.get(2)); Students stdunt = studentService.saveAndGetStudent(stdnt); response = new authSuccess(false, stdunt.getName(), stdunt.getToken(), stdunt.getEmail(), stdunt.getSid() + "", stdunt.getSdt(1), stdunt.getSdt(2), stdunt.getAvatar()); } else { String genToken = this.generateStdntToken(); Students stdnt = new Students(); stdnt.setId(this.studentId); stdnt.setPwd(this.encryptEngine.pleaseHelpViSecureThis(this.studentPassword)); stdnt.setName(this.getSName()); stdnt.setEmail(studntMP.get(0)); stdnt.setSdt(1, studntMP.get(1)); stdnt.setSdt(2, studntMP.get(2)); stdnt.setAvatar("https://cdn.notevn.com/Lyfq3HJj9.png"); stdnt.setToken(genToken); studentRepository.save(stdnt); response = new authSuccess(false, this.getSName(), genToken, studntMP.get(0), "" + this.studentId, studntMP.get(1), studntMP.get(2), "https://cdn.notevn.com/Lyfq3HJj9.png"); } } catch (Exception e) { logger.error(e.getMessage()); return gson.toJson(new errorResponse(true, "Có lỗi đã xảy ra!", 404)); } finally { return gson.toJson(response); } } public String reAuth() throws MalformedURLException { Gson gson = new Gson(); authSuccess response = new authSuccess(true, "", "", "", "", "", "", ""); try { Students stdunt = studentService.getStudentByToken(token); response = new authSuccess(false, stdunt.getName(), stdunt.getToken(), stdunt.getEmail(), stdunt.getSid() + "", stdunt.getSdt(1), stdunt.getSdt(2), stdunt.getAvatar()); } catch (Exception e) { logger.error(e.getMessage()); return gson.toJson(new errorResponse(true, "Có lỗi đã xảy ra!", 404)); } finally { return gson.toJson(response); } } public static String generateStdntToken() { byte[] randomBytes = new byte[24]; secureRand.nextBytes(randomBytes); return base64.encodeToString(randomBytes); } public WebClient getLoginVS () { try { Matcher check = this.processingCredential(this.definedStr.invalidCredentialsPattern_PRODUCTION()); if (check.find()) { this.webClient.close(); return null; } } catch (Exception e) { logger.error(e.getMessage()); } finally { return this.webClient; } } public boolean isServerReloading() throws IOException { URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = this.requestLogin() .getPage(defaultPage); Pattern pattern = Pattern.compile(this.definedStr.serverReloadPattern_PRODUCTION()); Matcher checkReloading = pattern.matcher(page.asXml()); return checkReloading.find(); } public Matcher processingCredential(String regex) throws IOException { Object _lock = new Object(); URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); String parseBody; Pattern pattern; defaultPage = this.setAdditionalHeader(defaultPage); synchronized (_lock) { HtmlPage page = null; page = this.requestLogin() .getPage(defaultPage); parseBody = getString(page); pattern = Pattern.compile(regex); } return pattern.matcher(parseBody); } private String getString(HtmlPage page) { String parseBody; parseBody = this.passCredentials(page).asXml(); return parseBody; } private HtmlPage passCredentials(HtmlPage page) { try { HtmlInput logInput = page.getHtmlElementById(this.definedStr.loginId_PRODUCTION()); HtmlInput pwdInput = page.getHtmlElementById(this.definedStr.loginPwdId_PRODUCTION()); logInput.setValueAttribute(this.studentId + ""); pwdInput.setValueAttribute(this.studentPassword); page = page.getHtmlElementById(this.definedStr.loginBtnId_PRODUCTION()).click(); } catch (Exception e) { logger.error(e.getMessage()); } finally { return page; } } public String loginAndPattern(String regex, int groupNum) throws IOException { Matcher searchResult = this.processingCredential(regex); if (searchResult.find()) { webClient.close(); return searchResult.group(groupNum); } return ""; } public String[] getVS(String initialUrl) throws MalformedURLException { URL actionUrl = new URL(initialUrl); WebRequest defaultPage = new WebRequest(actionUrl); HtmlPage page = null; try { page = (HtmlPage) this.webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } webClient.close(); return new String[]{ page.getElementById("__VIEWSTATE").getAttribute("value"), page.getElementById("__VIEWSTATEGENERATOR").getAttribute("value") }; } public String getSName() throws MalformedURLException { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); String _studntName = null; try { HtmlPage page = (HtmlPage) this.webClient .getPage(defaultPage); DomElement helloStudnt = page.getElementById(definedStr.helloStudentId_PRODUCTION()); if (helloStudnt.getTagName().toLowerCase().equals("span")) { String _xmlDefault = this.removeTheDEGap(helloStudnt); Matcher defaultMyView = this.patternSearch(this.definedStr.studentNamePattern_PRODUCTION(), _xmlDefault); if (!defaultMyView.find()) return null; _studntName = defaultMyView.group(1); } } catch (Exception e) { logger.error(e.getMessage()); } finally { return _studntName; } } public WebClient requestLogin() throws IOException { URL actionUrl = new URL(this.definedStr.defaultPage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page; try { page = this.webClient .getPage(defaultPage); this.passCredentials(page); } catch (IOException e) { logger.error(e.getMessage()); } return this.webClient; } private WebRequest setAdditionalHeader(WebRequest wr) { wr.setAdditionalHeader("User-Agent", this.definedStr.userAgentDefault_PRODUCTION()); wr.setAdditionalHeader("Accept-Encoding", this.definedStr.acceptEncoding_PRODUCTION()); wr.setAdditionalHeader("Accept-Language", this.definedStr.acceptLanguage_PRODUCTION()); wr.setAdditionalHeader("Accept", this.definedStr.acceptDataType_PRODUCTION()); wr.setAdditionalHeader("Origin", this.definedStr.reqOrigin_PRODUCTION()); return wr; } public ArrayList<String> getMailAndPhoneNum() throws MalformedURLException { URL actionUrl = new URL(this.definedStr.userInfoChangerUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<String> _infoBack = new ArrayList<String>(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = this.requestLogin() .getPage(defaultPage); DomElement studntMailSlct = page.getElementById(definedStr.studentEmailId_PRODUCTION()); DomElement studntSdt1Slct = page.getElementById(definedStr.studentSdt1Id_PRODUCTION()); DomElement studntSdt2Slct = page.getElementById(definedStr.studentSdt2Id_PRODUCTION()); if (studntMailSlct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntMailSlct.getAttribute("value")); } if (studntSdt1Slct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntSdt1Slct.getAttribute("value")); } if (studntSdt2Slct.getTagName().toLowerCase().equals("input")) { _infoBack.add(studntSdt2Slct.getAttribute("value")); } } catch (Exception e) { logger.error(e.getMessage()); } finally { return _infoBack; } } public static String showCookies(String websiteURL) throws IOException { CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); URL url = new URL(websiteURL); URLConnection urlConnection = url.openConnection(); urlConnection.getContent(); CookieStore cookieStore = cookieManager.getCookieStore(); return cookieStore.getCookies().get(0).getValue(); } public WebClient verifyToken() throws IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException { Students tokenInfo = this.studentService.getStudentByToken(this.token); this.studentId = tokenInfo.getSid(); this.studentPassword = <PASSWORD>(tokenInfo.getPwd()); return this.getLoginVS(); } public String getSemesterList() throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<semesterResponse> semesterMap = new ArrayList(); Gson gson = new Gson(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement semesterOpt = page.getElementById(definedStr.semesterOptId_PRODUCTION()); semesterMap = this.semesterProcess(semesterOpt); } catch (Exception e) { logger.error(e.getMessage()); } finally { webClient.close(); return gson.toJson(semesterMap); } } public ArrayList<semesterResponse> getSemesterArr() throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); ArrayList<semesterResponse> semesterMap = new ArrayList(); defaultPage = this.setAdditionalHeader(defaultPage); try { HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement semesterOpt = page.getElementById(definedStr.semesterOptId_PRODUCTION()); semesterMap = this.semesterProcess(semesterOpt); } catch (Exception e) { logger.error(e.getMessage()); } finally { webClient.close(); return semesterMap; } } private ArrayList<semesterResponse> semesterProcess(DomElement semesterOpt) { String[] _semesters = new String[] {}; ArrayList<semesterResponse> semesterMap = new ArrayList<semesterResponse>(); if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlSemester = this.removeTheDEGap(semesterOpt); Matcher semesterView = this.patternSearch(this.definedStr.semesterOptPattern_PRODUCTION(), _xmlSemester); if (!semesterView.find()) return null; _semesters = semesterView .group(2) .replace("<option selected=\"selected\" value=\"", "") .replace("\"", "") .replace("</option>", "") .split("<option value=", -1); } //Thread.sleep(1500); for (String tStr : _semesters){ String singleSemester[] = tStr.split(">", -1); semesterMap.add(semesterMap.size(), new semesterResponse(singleSemester[0], singleSemester[1])); } return semesterMap; } public String getWeekList(String currSemester) throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { Gson gson = new Gson(); return gson.toJson(this.getWeekArr(currSemester)); } public ArrayList<weekResponse> getWeekArr(String currSemester) throws MalformedURLException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; if (currSemester != null) defaultPage = this.selectSemesterOpt(currSemester); else { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); defaultPage = new WebRequest(actionUrl); } defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement semesterOpt = page.getElementById(definedStr.weekOptId_PRODUCTION()); webClient.close(); return this.weekProcessing(semesterOpt); } public weekResponse findSelectedWeek() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, ParseException { WebClient webClient = this.verifyToken(); Object _lock = new Object(); URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement semesterOpt = page.getElementById(definedStr.weekOptId_PRODUCTION()); synchronized (_lock) { if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlWeek = this.removeTheDEGap(semesterOpt); Matcher weekView = this.patternSearch(this.definedStr.selectedMiniOptPattern_PRODUCTION(), _xmlWeek); if (weekView.find()) { String tempStr = weekView.group(1); Matcher weekNum = this.patternSearch(this.definedStr.weekNumOptPattern_PRODUCTION(), tempStr); Matcher startDate = this.patternSearch(this.definedStr.startDateOptPattern_PRODUCTION(), tempStr); Matcher endDate = this.patternSearch(this.definedStr.endDateOptPattern_PRODUCTION(), tempStr); if (weekNum.find() && startDate.find() && endDate.find()) { return new weekResponse(startDate.group(1), endDate.group(1), weekNum.group(1), tempStr); } } } } return null; } public ArrayList<weekResponse> weekProcessing(DomElement semesterOpt) { ArrayList<weekResponse> _allSWeek = new ArrayList<weekResponse>(); if(semesterOpt.getTagName().toLowerCase().equals("select")) { String _xmlWeek = this.removeTheDEGap(semesterOpt); Matcher weekView = this.patternSearch(this.definedStr.miniOptPattern_PRODUCTION(), _xmlWeek); while (weekView.find()) { String tempStr = weekView.group(1); Matcher weekNum = this.patternSearch(this.definedStr.weekNumOptPattern_PRODUCTION(), tempStr); Matcher startDate = this.patternSearch(this.definedStr.startDateOptPattern_PRODUCTION(), tempStr); Matcher endDate = this.patternSearch(this.definedStr.endDateOptPattern_PRODUCTION(), tempStr); if (weekNum.find() && startDate.find() && endDate.find()) { try { _allSWeek.add(new weekResponse(startDate.group(1), endDate.group(1), weekNum.group(1), tempStr)); } catch (Exception e) { logger.error(e.getMessage()); } } } } return _allSWeek; } public String getScheduleDetail(String currSemester, String currWeek) throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { Gson gson = new Gson(); return gson.toJson(this.getScheduleDetailArr(currSemester, currWeek)); } public ArrayList<scheduleReponse> getScheduleDetailArr(String currSemester, String currWeek) throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; ArrayList<scheduleReponse> _fullWSchedule = new ArrayList<scheduleReponse>(); if (currSemester != null && currWeek != null) defaultPage = this.selectWeekOpt(currSemester, currWeek); else { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); defaultPage = new WebRequest(actionUrl); } defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); if (currSemester != null && currWeek != null) page = this.getScheduleDetailByVS(webClient, page.getElementById("__VIEWSTATE").getAttribute("value"), page.getElementById("__VIEWSTATEGENERATOR").getAttribute("value"), currSemester, currWeek); DomElement scheduleTable = page.getElementById(definedStr.scheduleTableId_PRODUCTION()); if(scheduleTable.getTagName().toLowerCase().equals("table")) { String _xmlSchedule = this.removeTheDEGap(scheduleTable); Matcher scheduleView = this.patternSearch(this.definedStr.schedulePattern_PRODUCTION(), _xmlSchedule); while (scheduleView.find()) { String[] tempStr = scheduleView .group(1) //.replaceAll(this.definedStr.scheduleDescRemove_PRODUCTION(), "") .replaceAll("'", "") .split(","); _fullWSchedule.add(new scheduleReponse(tempStr[0], tempStr[1], tempStr[9], tempStr[10], tempStr[2], tempStr[5], tempStr[7], tempStr[3], tempStr[6], tempStr[4], tempStr[8], tempStr[11], tempStr[12])); } } return _fullWSchedule; } public ArrayList<ExamResponse> getExamScheArr() throws IOException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, ParseException { WebClient webClient = this.verifyToken(); WebRequest defaultPage; ArrayList<ExamResponse> _fullESchedule = new ArrayList(); URL actionUrl = new URL(this.definedStr.examSchePageUrl_PRODUCTION()); defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = (HtmlPage) webClient .getPage(defaultPage); DomElement examTable = page.getElementById(definedStr.examTableId_PRODUCTION()); if(examTable.getTagName().toLowerCase().equals("table")) { String _xmlExamSche = this.removeTheDEGap(examTable); Matcher examView = this.patternSearch(this.definedStr.examValuPattern_PRODUCTION(), _xmlExamSche); int idx = 0; String[] incremental = {}; while (examView.find()) { String[] tempStr = examView .group(1) .split("\n"); incremental = ArrayUtils.addAll(incremental, tempStr[0]); idx++; if (idx == 10) { _fullESchedule.add(new ExamResponse(incremental[1].trim(), incremental[2].trim(), incremental[3].trim(), incremental[4].trim(), incremental[5].trim(), incremental[6].trim(), incremental[7].trim(), incremental[8].trim(), incremental[9].trim())); idx = 0; } } } return _fullESchedule; } public ArrayList<pointResponse> getCurrentPointArr() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(definedStr.studentCPointTblId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); return this.showSemesterPointArr(_xmlPTbl); } return null; } public String getCurrentPoint() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException { WebClient webClient = this.verifyToken(); URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest defaultPage = new WebRequest(actionUrl); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; Gson gson = new Gson(); try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } Matcher CheckMessInterrupt = this.patternSearch(this.definedStr.getMessInterrupt_PRODUCTION(), page.asXml()); if (CheckMessInterrupt.find()) { return gson.toJson(new errorResponse(true, CheckMessInterrupt.group(1).trim(), 503)); } DomElement stdntPointTbl = page.getElementById(definedStr.studentCPointTblId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); return this.showSemesterPoint(_xmlPTbl); } webClient.close(); return null; } public String showSemesterPoint(String _xmlPTbl) { Gson gson = new Gson(); return gson.toJson(this.showSemesterPointArr(_xmlPTbl)); } public ArrayList<pointResponse> showSemesterPointArr(String _xmlPTbl) { ArrayList<pointResponse> fullPointView = new ArrayList<pointResponse>(); ArrayList<String> temp = new ArrayList<String>(); int count = 0; Matcher pointView = this.patternSearch(this.definedStr.studentPointPattern_PRODUCTION(), _xmlPTbl); while (pointView.find()) { temp.add(pointView.group(1).trim()); if (!!(count == 10)) { fullPointView.add(new pointResponse(temp.get(1), temp.get(2), temp.get(3), temp.get(4), temp.get(5), temp.get(6), temp.get(7), temp.get(8), temp.get(9), temp.get(10))); count = -1; temp.clear(); } count++; } return fullPointView; } public ArrayList<PSListResponse> getPointListSemesterArr() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); Matcher pointView = null; WebRequest defaultPage = this.viewAllPoint(); ArrayList<PSListResponse> fullPointView = new ArrayList(); defaultPage = this.setAdditionalHeader(defaultPage); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(definedStr.studentPSemesterId_PRODUCTION()); String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); pointView = this.patternSearch(this.definedStr.studentPListPattern_PRODUCTION(), _xmlPTbl); while (pointView.find()) { fullPointView.add(new PSListResponse(pointView.group(5).trim(), pointView.group(6).trim())); } return fullPointView; } public ArrayList<pointResponse> getPointBySemesterArr(String semesterId) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { WebClient webClient = this.verifyToken(); Matcher pointView; ArrayList<pointResponse> _empty = new ArrayList<pointResponse>(); WebRequest defaultPage = this.viewAllPoint(); defaultPage = this.setAdditionalHeader(defaultPage); Matcher firstTest = this.patternSearch(this.definedStr.cboxPointTestPattern_PRODUCTION(), semesterId); if (firstTest.find()) { semesterId = "Học kỳ " + firstTest.group(1) + " - Năm học " + firstTest.group(2) + "-" + firstTest.group(3); } HtmlPage page = null; try { page = (HtmlPage) webClient .getPage(defaultPage); } catch (Exception e) { this.logger.error(e.getMessage()); } DomElement stdntPointTbl = page.getElementById(this.definedStr.studentPSemesterId_PRODUCTION()); if(stdntPointTbl.getTagName().toLowerCase().equals("div")) { String _xmlPTbl = this.removeTheDEGap(stdntPointTbl); String myPattern = semesterId.trim().concat(this.definedStr.studentPRangeSelectPattern_PRODUCTION()); pointView = this.patternSearch(myPattern, _xmlPTbl); if (pointView.find()) return this.showSemesterPointArr(pointView.group(7)); else return _empty; } return _empty; } public String getPointListSemester(String semesterId) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, MalformedURLException, UnsupportedEncodingException { Gson gson = new Gson(); if (semesterId.length() == 0) return gson.toJson(this.getPointListSemesterArr()); else return gson.toJson(this.getPointBySemesterArr(semesterId)); } public Matcher patternSearch(String regex, String _test) { Pattern pattern = Pattern.compile(regex); return pattern.matcher(_test); } public String removeTheDEGap(DomElement theGap) { return theGap.asXml().replaceAll("\r\n", ""); } public HtmlPage getScheduleDetailByVS(WebClient wc, String _vs, String _vsg, String ssm, String sw) throws IOException { String _acUrl = this.definedStr.schedulePage_PRODUCTION(); URL actionUrl = new URL(_acUrl); WebRequest page = new WebRequest(actionUrl, HttpMethod.POST); page = this.setAdditionalHeader(page); page.setRequestBody("__EVENTTARGET=ctl00$ContentPlaceHolder1$ctl00$ddlTuan&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + URLEncoder.encode(_vs, StandardCharsets.UTF_8.toString()) + "&__VIEWSTATEGENERATOR=" + _vsg + "&ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK=" + URLEncoder.encode(ssm, StandardCharsets.UTF_8.toString()) + "&ctl00$ContentPlaceHolder1$ctl00$ddlLoai=0&ctl00$ContentPlaceHolder1$ctl00$ddlTuan=" + URLEncoder.encode(sw, StandardCharsets.UTF_8.toString())); return (HtmlPage) wc .getPage(page); } public WebRequest selectSemesterOpt(String selectedOpt) throws MalformedURLException, UnsupportedEncodingException { URL actionUrl = new URL(this.definedStr.schedulePage_PRODUCTION()); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); String _VState; Object _lock2 = new Object(); synchronized (_lock2) { _VState = this.getVS(this.definedStr.schedulePage_PRODUCTION())[0]; } schedulePage = this.setAdditionalHeader(schedulePage); schedulePage.setRequestBody(this.definedStr.requestBodySSO_PRODUCTION() .replace("{{VIEWSTATE}}", URLEncoder.encode(_VState, StandardCharsets.UTF_8.toString())) .replace("{{CHON_NHHK}}", URLEncoder.encode(selectedOpt, StandardCharsets.UTF_8.toString()))); return schedulePage; } public WebRequest selectWeekOpt(String selectedSemester, String selectedWeek) throws MalformedURLException, IllegalBlockSizeException, InvalidKeyException, NoSuchAlgorithmException, BadPaddingException, NoSuchPaddingException, ParseException, UnsupportedEncodingException { Object _lock = new Object(); Object _lock1 = new Object(); Object _lock2 = new Object(); weekResponse weekRes; String _acUrl; String _VsGet[]; synchronized (_lock) { weekRes = this.findSelectedWeek(); } synchronized (_lock1) { _acUrl = weekRes.getTenxacdinh().equals(selectedWeek) ? this.definedStr.schedulePageUrlMode1_PRODUCTION() : this.definedStr.schedulePage_PRODUCTION(); } URL actionUrl = new URL(_acUrl); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); synchronized (_lock2) { _VsGet = this.getVS(_acUrl); } schedulePage.setRequestBody("__EVENTTARGET=ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + URLEncoder.encode(_VsGet[0], StandardCharsets.UTF_8.toString()) + "&__VIEWSTATEGENERATOR=" + _VsGet[1] + "&ctl00$ContentPlaceHolder1$ctl00$ddlChonNHHK=" + URLEncoder.encode(selectedSemester, StandardCharsets.UTF_8.toString()) + "&ctl00$ContentPlaceHolder1$ctl00$ddlLoai=0"); return schedulePage; } public WebRequest viewAllPoint() throws MalformedURLException, UnsupportedEncodingException { URL actionUrl = new URL(this.definedStr.studentPointUrl_PRODUCTION()); WebRequest schedulePage = new WebRequest(actionUrl, HttpMethod.POST); schedulePage = this.setAdditionalHeader(schedulePage); schedulePage.setRequestBody(this.definedStr.requestBodyVAP_PRODUCTION() .replace("{{VIEWSTATE}}", URLEncoder.encode(this.getVS(this.definedStr.studentPointUrl_PRODUCTION())[0], StandardCharsets.UTF_8.toString()))); return schedulePage; } public String getExamScheList() throws BadPaddingException, ParseException, NoSuchAlgorithmException, IOException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException { Gson gson = new Gson(); return gson.toJson(this.getExamScheArr()); } }
35,422
0.650003
0.644696
836
41.375599
47.584148
479
false
false
0
0
0
0
0
0
0.769139
false
false
9
eeb84f7e1c5ffce9832325e2ba9453a6ee1e0e3a
33,715,493,307,071
67d43bf5395027100ecba4b9cac44b6ae8f32c46
/app/src/main/java/com/dlut/justeda/classnote/justpublic/fragment/NoteFragment.java
63ba511dd0f1dcf97e83a0bb9ae986a667ad5ea6
[ "Apache-2.0" ]
permissive
JiaweiZhao-git/ClassNote
https://github.com/JiaweiZhao-git/ClassNote
bfcd71e9dade35ce73d36a258a786f8804c433e0
93e1190b2348caece188ebbd309df0852a4b822c
refs/heads/master
2021-06-11T18:24:57.262000
2016-11-24T21:16:38
2016-11-24T21:16:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dlut.justeda.classnote.justpublic.fragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.dlut.justeda.classnote.R; import com.dlut.justeda.classnote.justpublic.contralwidget.SlidingMenu; import com.dlut.justeda.classnote.note.activity.NoteListActivity; import com.dlut.justeda.classnote.note.db.ClassDatabaseHelper; import com.dlut.justeda.classnote.note.noteadapter.NoteAdapter; import com.dlut.justeda.classnote.note.noteadapter.NoteItem; import com.dlut.justeda.classnote.note.util.OpenPhotoAlbum; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * 本地笔记的界面 * Created by 赵佳伟 on 2016/11/9. */ public class NoteFragment extends Fragment { private SlidingMenu slidingMenu; private ListView listView; public static NoteAdapter noteAdapter; private List<NoteItem> noteList = new ArrayList<>(); private static final int CHOOSE_PHOTO=3; private ImageButton title_button; private TextView title_text; private ClassDatabaseHelper dbHelper; private int IMAGE01 = R.drawable.note_class01; private int IMAGE02 = R.drawable.note_class02; private int IMAGE03 = R.drawable.note_class03; private int IMAGE04 = R.drawable.note_class04; private int IMAGE05 = R.drawable.note_class05; private int IMAGE[] = {IMAGE01, IMAGE02, IMAGE03, IMAGE04, IMAGE05}; private boolean isLeft = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.note_fragment_main, container,false); slidingMenu = (SlidingMenu) getActivity().findViewById(R.id.slidingmenu); listView = (ListView) view.findViewById(R.id.note_main_courselist); title_button = (ImageButton) view.findViewById(R.id.title_left_image); title_text = (TextView) view.findViewById(R.id.title_middle_text); initViews(); initEvents(); return view; } private void initViews() { title_text.setText("课堂笔记"); noteList.add(new NoteItem("相册管理", R.drawable.note_album)); noteList.add(new NoteItem("其他",R.drawable.note_item)); //需要添加其它课程信息 dbHelper = new ClassDatabaseHelper(getContext(), "Courses.db", null, 2); addFromDB(); } private void addFromDB() { SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("Courses", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex("name")); Random ran = new Random(); int index = ran.nextInt(5); noteList.add(new NoteItem(name,IMAGE[index])); } while (cursor.moveToNext()); } cursor.close(); } private void initEvents() { title_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { slidingMenu.toLeft(isLeft); isLeft = !isLeft; } }); noteAdapter = new NoteAdapter(getContext(), noteList); listView.setAdapter(noteAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { /** * 1、第一个是相册管理 * 2、第二个是qq文件管理——暂时去掉 * 3、第三个是其他文件夹 */ if (position == 0) { Intent intent=new Intent( "android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); } else{ Intent intent = new Intent(getContext(), NoteListActivity.class); intent.putExtra("name",noteList.get(position).getName()); startActivity(intent); } } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CHOOSE_PHOTO: OpenPhotoAlbum openPhotoAlbum = new OpenPhotoAlbum(getContext(), data); openPhotoAlbum.handleImageOnKitKat(); break; default: break; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } }
UTF-8
Java
5,275
java
NoteFragment.java
Java
[ { "context": "t java.util.Random;\n\n/**\n * 本地笔记的界面\n * Created by 赵佳伟 on 2016/11/9.\n */\npublic class NoteFragment exten", "end": 1067, "score": 0.9997155070304871, "start": 1064, "tag": "NAME", "value": "赵佳伟" } ]
null
[]
package com.dlut.justeda.classnote.justpublic.fragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.dlut.justeda.classnote.R; import com.dlut.justeda.classnote.justpublic.contralwidget.SlidingMenu; import com.dlut.justeda.classnote.note.activity.NoteListActivity; import com.dlut.justeda.classnote.note.db.ClassDatabaseHelper; import com.dlut.justeda.classnote.note.noteadapter.NoteAdapter; import com.dlut.justeda.classnote.note.noteadapter.NoteItem; import com.dlut.justeda.classnote.note.util.OpenPhotoAlbum; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * 本地笔记的界面 * Created by 赵佳伟 on 2016/11/9. */ public class NoteFragment extends Fragment { private SlidingMenu slidingMenu; private ListView listView; public static NoteAdapter noteAdapter; private List<NoteItem> noteList = new ArrayList<>(); private static final int CHOOSE_PHOTO=3; private ImageButton title_button; private TextView title_text; private ClassDatabaseHelper dbHelper; private int IMAGE01 = R.drawable.note_class01; private int IMAGE02 = R.drawable.note_class02; private int IMAGE03 = R.drawable.note_class03; private int IMAGE04 = R.drawable.note_class04; private int IMAGE05 = R.drawable.note_class05; private int IMAGE[] = {IMAGE01, IMAGE02, IMAGE03, IMAGE04, IMAGE05}; private boolean isLeft = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.note_fragment_main, container,false); slidingMenu = (SlidingMenu) getActivity().findViewById(R.id.slidingmenu); listView = (ListView) view.findViewById(R.id.note_main_courselist); title_button = (ImageButton) view.findViewById(R.id.title_left_image); title_text = (TextView) view.findViewById(R.id.title_middle_text); initViews(); initEvents(); return view; } private void initViews() { title_text.setText("课堂笔记"); noteList.add(new NoteItem("相册管理", R.drawable.note_album)); noteList.add(new NoteItem("其他",R.drawable.note_item)); //需要添加其它课程信息 dbHelper = new ClassDatabaseHelper(getContext(), "Courses.db", null, 2); addFromDB(); } private void addFromDB() { SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("Courses", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex("name")); Random ran = new Random(); int index = ran.nextInt(5); noteList.add(new NoteItem(name,IMAGE[index])); } while (cursor.moveToNext()); } cursor.close(); } private void initEvents() { title_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { slidingMenu.toLeft(isLeft); isLeft = !isLeft; } }); noteAdapter = new NoteAdapter(getContext(), noteList); listView.setAdapter(noteAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { /** * 1、第一个是相册管理 * 2、第二个是qq文件管理——暂时去掉 * 3、第三个是其他文件夹 */ if (position == 0) { Intent intent=new Intent( "android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); } else{ Intent intent = new Intent(getContext(), NoteListActivity.class); intent.putExtra("name",noteList.get(position).getName()); startActivity(intent); } } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CHOOSE_PHOTO: OpenPhotoAlbum openPhotoAlbum = new OpenPhotoAlbum(getContext(), data); openPhotoAlbum.handleImageOnKitKat(); break; default: break; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } }
5,275
0.639207
0.630464
159
31.371069
26.252895
123
false
false
0
0
0
0
0
0
0.685535
false
false
9
4d3b97b1654384dcb6f4e3617db684c90a0ac1a1
2,765,959,004,638
e023f95ba049cfa9cd01c8e2a495873d74a63041
/src/main/java/com/woowahan/woowahanboardservice/domain/board/dto/request/BoardEditRequestBody.java
537f5f96aea3a470c2cf2beceea98a40b4e6e64f
[]
no_license
jeongwon-p/woowahan-board-service
https://github.com/jeongwon-p/woowahan-board-service
055fbae736f7a31fd4a493319630fe3d34ed30c5
f1e9f5336e21e0e4302375d061fe0092e7016f98
refs/heads/main
2023-05-14T19:23:28.122000
2021-06-07T13:59:42
2021-06-07T13:59:42
370,028,671
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.woowahan.woowahanboardservice.domain.board.dto.request; import com.woowahan.woowahanboardservice.domain.board.entity.Board; import io.swagger.annotations.ApiModelProperty; import org.springframework.util.StringUtils; import java.util.UUID; public class BoardEditRequestBody { @ApiModelProperty(value = "첫 등록시 미입력, UUID 생성") private String boardId; private String description; private boolean hidden; private String name; private String userId; public Board toBoard() { return new Board( StringUtils.hasText(boardId) ? boardId : UUID.randomUUID().toString(), description, hidden, name ); } public String getBoardId() { return boardId; } public void setBoardId(String boardId) { this.boardId = boardId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
UTF-8
Java
1,525
java
BoardEditRequestBody.java
Java
[]
null
[]
package com.woowahan.woowahanboardservice.domain.board.dto.request; import com.woowahan.woowahanboardservice.domain.board.entity.Board; import io.swagger.annotations.ApiModelProperty; import org.springframework.util.StringUtils; import java.util.UUID; public class BoardEditRequestBody { @ApiModelProperty(value = "첫 등록시 미입력, UUID 생성") private String boardId; private String description; private boolean hidden; private String name; private String userId; public Board toBoard() { return new Board( StringUtils.hasText(boardId) ? boardId : UUID.randomUUID().toString(), description, hidden, name ); } public String getBoardId() { return boardId; } public void setBoardId(String boardId) { this.boardId = boardId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
1,525
0.606503
0.606503
72
19.930555
18.350996
67
false
false
0
0
0
0
0
0
0.347222
false
false
9
306494219b1c99d61e271fb197d2ec91741a6d51
1,829,656,086,827
9d14214cc986ae372f5511cb5d45611cc91220b6
/SQLTimeTabling/SQLTimeTabling.desktop/src/data/Timetable.java
431f193be031cc59e915590800bd186bf9872dc1
[]
no_license
una1veritas/Workspace
https://github.com/una1veritas/Workspace
6849309b908810042756640e3b02ad6716c3dc9c
32de11bec1755fdbe94885cd12688c3977c65d3a
refs/heads/master
2023-08-31T05:58:16.708000
2023-08-24T07:11:36
2023-08-24T07:11:36
5,622,781
2
0
null
false
2017-09-04T11:31:25
2012-08-31T00:31:33
2016-10-22T09:27:07
2017-09-04T11:31:25
897,886
2
2
0
C
null
null
package data; import java.sql.*; import java.util.*; import java.io.*; //import common.DBConnectionPool; public class Timetable implements Serializable { //(task, period, processor) HashSet triplets; HashMap tasks; HashMap periods; HashMap processors; HashMap taskPeriod; // opportunity HashMap processorPeriod; //availability HashMap qualifications; // qualification public Timetable(Collection lectures, Collection periods, Collection teachers, HashMap opportunities, HashMap availablities, HashMap qualifications) { Task aTask; Period aPeriod; Processor aProcessor; tasks = new HashMap(lectures.size()); for (Iterator i = lectures.iterator(); i.hasNext(); ) { aTask = (Task) i.next(); tasks.put(aTask, aTask); } processors = new HashMap(teachers.size()); for (Iterator i = teachers.iterator(); i.hasNext(); ) { aProcessor = (Processor) i.next(); processors.put(aProcessor, aProcessor); } this.periods = new HashMap(periods.size()); for (Iterator i = periods.iterator(); i.hasNext(); ) { aPeriod = (Period) i.next(); this.periods.put(aPeriod, aPeriod); } this.triplets = new HashSet(); this.taskPeriod = opportunities; this.processorPeriod = availablities; this.qualifications = qualifications; } public Timetable() { } // public Set processors() { return processors.keySet(); } public Set tasks() { return tasks.keySet(); } public Set periods() { return periods.keySet(); } // public Task getTask(Task t) { return (Task) tasks.get(t); } public Task getTask(int id) { return getTask(new Task(id)); } public Processor getProcessor(Processor p) { return (Processor) processors.get(p); } public Processor getProcessor(int id) { return getProcessor(new Processor(id)); } public Period getPeriod(Period p) { return (Period) periods.get(p); } public Period getPeriod(int id) { return getPeriod(new Period(id)); } // public HashSet taskOpportunities(Task t) { return (HashSet) taskPeriod.get(t); } // public boolean processorQualified(Processor p, Task t) { if (qualifications.containsKey(p)) { return ((HashSet) qualifications.get(p)).contains(new Integer(t.qualification_id())); } else { return false; } } // public boolean processorAvailableAtAll(Processor p, Collection c) { if (processorPeriod.containsKey(p)) { return ((HashSet) processorPeriod.get(p)).containsAll(c); } else { return false; } } // public boolean processorAvailableAt(Processor p, Period d) { if (processorPeriod.containsKey(p)) { return ((HashSet) processorPeriod.get(p)).contains(d); } else { return false; } } public boolean taskAvailableAt(Task t, Period d) { if (taskPeriod.containsKey(t)) { return ((HashSet) taskPeriod.get(t)).contains(d); } else { return false; } } public boolean taskAvailableAtAll(Task t, Collection c) { if (taskPeriod.containsKey(t)) { return ((HashSet) taskPeriod.get(t)).containsAll(c); } else { return false; } } public int getNextPeriod(int id){ Period dp = getPeriod(id); if( !(dp.next() < 0) ){ return dp.next(); } return -1; } public ArrayList getFollowingPeriodsInTheSameDay(Period startp, int max) { ArrayList result = new ArrayList(); Iterator i = periods().iterator(); Period dp = getPeriod(startp); if ( dp != null && result.size() < max ) { result.add(dp); } while ( dp != null && dp.next() < 0 && (result.size() < max) ) { Period nextp = getPeriod(dp.next()); result.add(nextp); } return result; } public ArrayList allPeriodsNecessaryFor(Triplet t) { int len = (getTask(t.task())).length(); return getFollowingPeriodsInTheSameDay(t.period(), len); } //period に task を担当している processor を返す public Set assignedProcessorsOn(Task tsk, Period prd){ HashSet result = new HashSet(); Iterator i = triplets.iterator(); while(i.hasNext()){ Triplet t = (Triplet) i.next(); if ( tsk.equals(t.task()) && prd.equals(t.period())) { result.add(t.processor()); } } return result; } public Set assignedProcessorsOn(Task tsk, Period prd, Collection c) { HashSet result = new HashSet(); Iterator i = c.iterator(); do { if(!i.hasNext()) break; Triplet t = (Triplet)i.next(); if(tsk.equals(t.task()) && prd.equals(t.period())) result.add(t.processor()); } while(true); return result; } public String toString() { StringBuffer buf = new StringBuffer("Timetable("); for(Iterator i = triplets.iterator(); i.hasNext(); buf.append(", ")) { Triplet t = (Triplet)i.next(); buf.append(t.toString()); } buf.append(") "); return buf.toString(); } public String toStoreString() { StringBuffer buf = new StringBuffer(""); Triplet t; for(Iterator i = triplets.iterator(); i.hasNext(); buf.append(t.toString() + System.getProperty("line.separator"))) t = (Triplet)i.next(); return buf.toString(); } public void clear() throws Exception { triplets.clear(); } public void insertTriplet(Task task, Period period, Processor processor) { triplets.add(new Triplet(task, period, processor)); } public void insertTriple(int taskid, int periodid, int processorid) { triplets.add(new Triplet(getTask(taskid), getPeriod(periodid), getProcessor(processorid))); } public void deleteTriplet(Task task, Period period, Processor processor) { triplets.remove(new Triplet(task, period, processor)); } public void deleteTriple(int taskid, int periodid, int processorid) { deleteTriplet(getTask(taskid), getPeriod(periodid), getProcessor(processorid)); } public HashSet triplets() { return triplets; } public boolean has(Triplet t) { return triplets.contains(t); } public int countViolations() { return countViolations(null); } public int countViolations(PrintWriter pw) { int notQualified = 0; int notAtAvailableProcessor = 0; int notAtAvailableTask = 0; int duplicatedTasks = 0; int insufficientTasks = 0; int ignoredTasks = 0; int multipleTeach = 0; ArrayList allTasks = new ArrayList(tasks()); ArrayList teacherlist = new ArrayList(processors()); HashMap counters = new HashMap(tasks().size()); Iterator i; for(i = allTasks.iterator(); i.hasNext(); counters.put((Task)i.next(), new HashSet())); Triplet tp; for(i = triplets.iterator(); i.hasNext(); ((HashSet)counters.get(tp.task())).add(tp.period())) tp = (Triplet)i.next(); i = allTasks.iterator(); do { if(!i.hasNext()) break; Task t = (Task)i.next(); int sufficientCount = 0; int insufficientCount = 0; HashSet periodByTask = (HashSet)counters.get(t); if(periodByTask.size() == 0) { ignoredTasks++; if(pw != null) pw.print("ignored: " + t + ", "); } else { for(Iterator j = periodByTask.iterator(); j.hasNext();) { Period pd = (Period)j.next(); if(assignedProcessorsOn(t, pd).size() < t.getProcessors_lb()) insufficientCount++; else sufficientCount++; } if(sufficientCount > 1) { duplicatedTasks += sufficientCount - 1; if(pw != null) pw.print("duplicating: " + t + " in " + sufficientCount + " time, "); } } } while(true); counters.clear(); counters = new HashMap(processors().size()); for(i = triplets.iterator(); i.hasNext();) { Triplet t = (Triplet)i.next(); Processor tch = t.processor(); if(counters.containsKey(tch)) { Iterator ip = allPeriodsNecessaryFor(t).iterator(); while(ip.hasNext()) { Period p = (Period)ip.next(); if(((Set)counters.get(tch)).contains(p)) { multipleTeach++; if(pw != null) pw.print("do more than one in the same time: " + t + ", "); } ((Set)counters.get(tch)).add(p); } } else { HashSet set = new HashSet(); set.addAll(allPeriodsNecessaryFor(t)); counters.put(tch, set); } } counters.clear(); i = triplets.iterator(); do { if(!i.hasNext()) break; Triplet t = (Triplet)i.next(); Processor tch = t.processor(); Task lec = t.task(); if(tch != null && lec != null) { if(!processorQualified(tch, lec)) { notQualified++; if(pw != null) pw.print("without qualification: " + t + ", "); } if(!processorAvailableAtAll(tch, allPeriodsNecessaryFor(t))) { notAtAvailableProcessor++; if(pw != null) pw.print("do not teach at: " + t + ", "); } if(!taskAvailableAtAll(lec, allPeriodsNecessaryFor(t))) { notAtAvailableTask++; if(pw != null) pw.print("cannot place lecture at: " + t + ", "); } } } while(true); return notQualified + notAtAvailableProcessor + notAtAvailableTask + ignoredTasks + duplicatedTasks + multipleTeach; } }
UTF-8
Java
10,263
java
Timetable.java
Java
[]
null
[]
package data; import java.sql.*; import java.util.*; import java.io.*; //import common.DBConnectionPool; public class Timetable implements Serializable { //(task, period, processor) HashSet triplets; HashMap tasks; HashMap periods; HashMap processors; HashMap taskPeriod; // opportunity HashMap processorPeriod; //availability HashMap qualifications; // qualification public Timetable(Collection lectures, Collection periods, Collection teachers, HashMap opportunities, HashMap availablities, HashMap qualifications) { Task aTask; Period aPeriod; Processor aProcessor; tasks = new HashMap(lectures.size()); for (Iterator i = lectures.iterator(); i.hasNext(); ) { aTask = (Task) i.next(); tasks.put(aTask, aTask); } processors = new HashMap(teachers.size()); for (Iterator i = teachers.iterator(); i.hasNext(); ) { aProcessor = (Processor) i.next(); processors.put(aProcessor, aProcessor); } this.periods = new HashMap(periods.size()); for (Iterator i = periods.iterator(); i.hasNext(); ) { aPeriod = (Period) i.next(); this.periods.put(aPeriod, aPeriod); } this.triplets = new HashSet(); this.taskPeriod = opportunities; this.processorPeriod = availablities; this.qualifications = qualifications; } public Timetable() { } // public Set processors() { return processors.keySet(); } public Set tasks() { return tasks.keySet(); } public Set periods() { return periods.keySet(); } // public Task getTask(Task t) { return (Task) tasks.get(t); } public Task getTask(int id) { return getTask(new Task(id)); } public Processor getProcessor(Processor p) { return (Processor) processors.get(p); } public Processor getProcessor(int id) { return getProcessor(new Processor(id)); } public Period getPeriod(Period p) { return (Period) periods.get(p); } public Period getPeriod(int id) { return getPeriod(new Period(id)); } // public HashSet taskOpportunities(Task t) { return (HashSet) taskPeriod.get(t); } // public boolean processorQualified(Processor p, Task t) { if (qualifications.containsKey(p)) { return ((HashSet) qualifications.get(p)).contains(new Integer(t.qualification_id())); } else { return false; } } // public boolean processorAvailableAtAll(Processor p, Collection c) { if (processorPeriod.containsKey(p)) { return ((HashSet) processorPeriod.get(p)).containsAll(c); } else { return false; } } // public boolean processorAvailableAt(Processor p, Period d) { if (processorPeriod.containsKey(p)) { return ((HashSet) processorPeriod.get(p)).contains(d); } else { return false; } } public boolean taskAvailableAt(Task t, Period d) { if (taskPeriod.containsKey(t)) { return ((HashSet) taskPeriod.get(t)).contains(d); } else { return false; } } public boolean taskAvailableAtAll(Task t, Collection c) { if (taskPeriod.containsKey(t)) { return ((HashSet) taskPeriod.get(t)).containsAll(c); } else { return false; } } public int getNextPeriod(int id){ Period dp = getPeriod(id); if( !(dp.next() < 0) ){ return dp.next(); } return -1; } public ArrayList getFollowingPeriodsInTheSameDay(Period startp, int max) { ArrayList result = new ArrayList(); Iterator i = periods().iterator(); Period dp = getPeriod(startp); if ( dp != null && result.size() < max ) { result.add(dp); } while ( dp != null && dp.next() < 0 && (result.size() < max) ) { Period nextp = getPeriod(dp.next()); result.add(nextp); } return result; } public ArrayList allPeriodsNecessaryFor(Triplet t) { int len = (getTask(t.task())).length(); return getFollowingPeriodsInTheSameDay(t.period(), len); } //period に task を担当している processor を返す public Set assignedProcessorsOn(Task tsk, Period prd){ HashSet result = new HashSet(); Iterator i = triplets.iterator(); while(i.hasNext()){ Triplet t = (Triplet) i.next(); if ( tsk.equals(t.task()) && prd.equals(t.period())) { result.add(t.processor()); } } return result; } public Set assignedProcessorsOn(Task tsk, Period prd, Collection c) { HashSet result = new HashSet(); Iterator i = c.iterator(); do { if(!i.hasNext()) break; Triplet t = (Triplet)i.next(); if(tsk.equals(t.task()) && prd.equals(t.period())) result.add(t.processor()); } while(true); return result; } public String toString() { StringBuffer buf = new StringBuffer("Timetable("); for(Iterator i = triplets.iterator(); i.hasNext(); buf.append(", ")) { Triplet t = (Triplet)i.next(); buf.append(t.toString()); } buf.append(") "); return buf.toString(); } public String toStoreString() { StringBuffer buf = new StringBuffer(""); Triplet t; for(Iterator i = triplets.iterator(); i.hasNext(); buf.append(t.toString() + System.getProperty("line.separator"))) t = (Triplet)i.next(); return buf.toString(); } public void clear() throws Exception { triplets.clear(); } public void insertTriplet(Task task, Period period, Processor processor) { triplets.add(new Triplet(task, period, processor)); } public void insertTriple(int taskid, int periodid, int processorid) { triplets.add(new Triplet(getTask(taskid), getPeriod(periodid), getProcessor(processorid))); } public void deleteTriplet(Task task, Period period, Processor processor) { triplets.remove(new Triplet(task, period, processor)); } public void deleteTriple(int taskid, int periodid, int processorid) { deleteTriplet(getTask(taskid), getPeriod(periodid), getProcessor(processorid)); } public HashSet triplets() { return triplets; } public boolean has(Triplet t) { return triplets.contains(t); } public int countViolations() { return countViolations(null); } public int countViolations(PrintWriter pw) { int notQualified = 0; int notAtAvailableProcessor = 0; int notAtAvailableTask = 0; int duplicatedTasks = 0; int insufficientTasks = 0; int ignoredTasks = 0; int multipleTeach = 0; ArrayList allTasks = new ArrayList(tasks()); ArrayList teacherlist = new ArrayList(processors()); HashMap counters = new HashMap(tasks().size()); Iterator i; for(i = allTasks.iterator(); i.hasNext(); counters.put((Task)i.next(), new HashSet())); Triplet tp; for(i = triplets.iterator(); i.hasNext(); ((HashSet)counters.get(tp.task())).add(tp.period())) tp = (Triplet)i.next(); i = allTasks.iterator(); do { if(!i.hasNext()) break; Task t = (Task)i.next(); int sufficientCount = 0; int insufficientCount = 0; HashSet periodByTask = (HashSet)counters.get(t); if(periodByTask.size() == 0) { ignoredTasks++; if(pw != null) pw.print("ignored: " + t + ", "); } else { for(Iterator j = periodByTask.iterator(); j.hasNext();) { Period pd = (Period)j.next(); if(assignedProcessorsOn(t, pd).size() < t.getProcessors_lb()) insufficientCount++; else sufficientCount++; } if(sufficientCount > 1) { duplicatedTasks += sufficientCount - 1; if(pw != null) pw.print("duplicating: " + t + " in " + sufficientCount + " time, "); } } } while(true); counters.clear(); counters = new HashMap(processors().size()); for(i = triplets.iterator(); i.hasNext();) { Triplet t = (Triplet)i.next(); Processor tch = t.processor(); if(counters.containsKey(tch)) { Iterator ip = allPeriodsNecessaryFor(t).iterator(); while(ip.hasNext()) { Period p = (Period)ip.next(); if(((Set)counters.get(tch)).contains(p)) { multipleTeach++; if(pw != null) pw.print("do more than one in the same time: " + t + ", "); } ((Set)counters.get(tch)).add(p); } } else { HashSet set = new HashSet(); set.addAll(allPeriodsNecessaryFor(t)); counters.put(tch, set); } } counters.clear(); i = triplets.iterator(); do { if(!i.hasNext()) break; Triplet t = (Triplet)i.next(); Processor tch = t.processor(); Task lec = t.task(); if(tch != null && lec != null) { if(!processorQualified(tch, lec)) { notQualified++; if(pw != null) pw.print("without qualification: " + t + ", "); } if(!processorAvailableAtAll(tch, allPeriodsNecessaryFor(t))) { notAtAvailableProcessor++; if(pw != null) pw.print("do not teach at: " + t + ", "); } if(!taskAvailableAtAll(lec, allPeriodsNecessaryFor(t))) { notAtAvailableTask++; if(pw != null) pw.print("cannot place lecture at: " + t + ", "); } } } while(true); return notQualified + notAtAvailableProcessor + notAtAvailableTask + ignoredTasks + duplicatedTasks + multipleTeach; } }
10,263
0.555414
0.55395
371
26.603773
24.33807
151
false
false
0
0
0
0
0
0
1.312668
false
false
9
c1a5e900208c989e050e98fd29b204952ba0f4be
20,916,490,764,867
e7f5346998bc1ff7382a2f185db66439809868b2
/geotk-xml-sensorML/src/main/java/org/geotoolkit/sml/xml/v100/InterfaceDefinition.java
c6d19db5ea6cd5e852c36ad77e92833c6eeeab27
[]
no_license
Geomatys/geotoolkit
https://github.com/Geomatys/geotoolkit
02f9c8fe238353150ed38619d4861ba0af075917
b9fd93908d0350b3fad0d59f74c5c9670b83db94
refs/heads/main
2023-08-16T19:43:42.347000
2023-08-14T16:15:17
2023-08-14T16:15:17
21,858,951
48
32
null
false
2023-09-14T19:36:37
2014-07-15T12:37:35
2023-09-02T22:55:53
2023-09-14T19:36:36
90,761
47
26
11
Java
false
false
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2008 - 2009, Geomatys * * This library 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 library 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. */ package org.geotoolkit.sml.xml.v100; import java.util.Objects; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlID; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.geotoolkit.sml.xml.AbstractInterfaceDefinition; import org.geotoolkit.swe.xml.v100.Category; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="serviceLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="applicationLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="presentationLayer" type="{http://www.opengis.net/sensorML/1.0}PresentationLayerPropertyType" minOccurs="0"/> * &lt;element name="sessionLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="transportLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="networkLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="dataLinkLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="physicalLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="mechanicalLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * * @module */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "serviceLayer", "applicationLayer", "presentationLayer", "sessionLayer", "transportLayer", "networkLayer", "dataLinkLayer", "physicalLayer", "mechanicalLayer" }) @XmlRootElement(name = "InterfaceDefinition") public class InterfaceDefinition implements AbstractInterfaceDefinition { private LayerPropertyType serviceLayer; private LayerPropertyType applicationLayer; private PresentationLayerPropertyType presentationLayer; private LayerPropertyType sessionLayer; private LayerPropertyType transportLayer; private LayerPropertyType networkLayer; private LayerPropertyType dataLinkLayer; private LayerPropertyType physicalLayer; private LayerPropertyType mechanicalLayer; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID private String id; public InterfaceDefinition() { } public InterfaceDefinition(final String id, final LayerPropertyType applicationLayer, final LayerPropertyType dataLinkLayer) { this.applicationLayer = applicationLayer; this.dataLinkLayer = dataLinkLayer; } public InterfaceDefinition(final AbstractInterfaceDefinition in) { if (in != null) { if (in.getServiceLayer() != null) { this.serviceLayer = new LayerPropertyType(in.getServiceLayer()); } if (in.getApplicationLayer() != null) { this.applicationLayer = new LayerPropertyType(in.getApplicationLayer()); } if (in.getDataLinkLayer() != null) { this.dataLinkLayer = new LayerPropertyType(in.getDataLinkLayer()); } this.id = in.getId(); if (in.getMechanicalLayer() != null) { this.mechanicalLayer = new LayerPropertyType(in.getMechanicalLayer()); } if (in.getNetworkLayer() != null) { this.networkLayer = new LayerPropertyType(in.getNetworkLayer()); } if (in.getPhysicalLayer() != null) { this.physicalLayer = new LayerPropertyType(in.getPhysicalLayer()); } if (in.getPresentationLayer() != null) { this.presentationLayer = new PresentationLayerPropertyType(in.getPresentationLayer()); } if (in.getServiceLayer() != null) { this.serviceLayer = new LayerPropertyType(in.getServiceLayer()); } if (in.getSessionLayer() != null) { this.sessionLayer = new LayerPropertyType(in.getSessionLayer()); } if (in.getTransportLayer() != null) { this.transportLayer = new LayerPropertyType(in.getTransportLayer()); } } } /** * Gets the value of the serviceLayer property. */ public LayerPropertyType getServiceLayer() { return serviceLayer; } /** * Sets the value of the serviceLayer property. */ public void setServiceLayer(final LayerPropertyType value) { this.serviceLayer = value; } /** * Sets the value of the serviceLayer property. */ public void setServiceLayer(final Category value) { this.serviceLayer = new LayerPropertyType(value); } /** * Gets the value of the applicationLayer property. */ public LayerPropertyType getApplicationLayer() { return applicationLayer; } /** * Sets the value of the applicationLayer property. */ public void setApplicationLayer(final LayerPropertyType value) { this.applicationLayer = value; } /** * Sets the value of the applicationLayer property. */ public void setApplicationLayer(final Category value) { this.applicationLayer = new LayerPropertyType(value); } /** * Gets the value of the presentationLayer property. */ public PresentationLayerPropertyType getPresentationLayer() { return presentationLayer; } /** * Sets the value of the presentationLayer property. */ public void setPresentationLayer(final PresentationLayerPropertyType value) { this.presentationLayer = value; } /** * Sets the value of the applicationLayer property. */ public void setPresentationLayer(final Category value) { this.presentationLayer = new PresentationLayerPropertyType(value); } /** * Gets the value of the sessionLayer property. */ public LayerPropertyType getSessionLayer() { return sessionLayer; } /** * Sets the value of the sessionLayer property. */ public void setSessionLayer(final LayerPropertyType value) { this.sessionLayer = value; } /** * Sets the value of the sessionLayer property. */ public void setSessionLayer(final Category value) { this.sessionLayer = new LayerPropertyType(value); } /** * Gets the value of the transportLayer property. */ public LayerPropertyType getTransportLayer() { return transportLayer; } /** * Sets the value of the transportLayer property. */ public void setTransportLayer(final LayerPropertyType value) { this.transportLayer = value; } /** * Sets the value of the transportLayer property. */ public void setTransportLayer(final Category value) { this.transportLayer = new LayerPropertyType(value); } /** * Gets the value of the networkLayer property. */ public LayerPropertyType getNetworkLayer() { return networkLayer; } /** * Sets the value of the networkLayer property. */ public void setNetworkLayer(final LayerPropertyType value) { this.networkLayer = value; } /** * Sets the value of the networkLayer property. */ public void setNetworkLayer(final Category value) { this.networkLayer = new LayerPropertyType(value); } /** * Gets the value of the dataLinkLayer property. */ public LayerPropertyType getDataLinkLayer() { return dataLinkLayer; } /** * Sets the value of the dataLinkLayer property. */ public void setDataLinkLayer(final LayerPropertyType value) { this.dataLinkLayer = value; } /** * Sets the value of the dataLinkLayer property. */ public void setDataLinkLayer(final Category value) { this.dataLinkLayer = new LayerPropertyType(value); } /** * Gets the value of the physicalLayer property. */ public LayerPropertyType getPhysicalLayer() { return physicalLayer; } /** * Sets the value of the physicalLayer property. */ public void setPhysicalLayer(final LayerPropertyType value) { this.physicalLayer = value; } /** * Sets the value of the physicalLayer property. */ public void setPhysicalLayer(final Category value) { this.physicalLayer = new LayerPropertyType(value); } /** * Gets the value of the mechanicalLayer property. */ public LayerPropertyType getMechanicalLayer() { return mechanicalLayer; } /** * Sets the value of the mechanicalLayer property. */ public void setMechanicalLayer(final LayerPropertyType value) { this.mechanicalLayer = value; } /** * Sets the value of the mechanicalLayer property. */ public void setMechanicalLayer(final Category value) { this.mechanicalLayer = new LayerPropertyType(value); } /** * Gets the value of the id property. */ public String getId() { return id; } /** * Sets the value of the id property. */ public void setId(final String value) { this.id = value; } /** * Verify if this entry is identical to specified object. */ @Override public boolean equals(final Object object) { if (object == this) { return true; } if (object instanceof InterfaceDefinition) { final InterfaceDefinition that = (InterfaceDefinition) object; return Objects.equals(this.applicationLayer, that.applicationLayer) && Objects.equals(this.dataLinkLayer, that.dataLinkLayer) && Objects.equals(this.id, that.id) && Objects.equals(this.mechanicalLayer, that.mechanicalLayer) && Objects.equals(this.networkLayer, that.networkLayer) && Objects.equals(this.physicalLayer, that.physicalLayer) && Objects.equals(this.presentationLayer, that.presentationLayer)&& Objects.equals(this.serviceLayer, that.serviceLayer) && Objects.equals(this.sessionLayer, that.sessionLayer) && Objects.equals(this.transportLayer, that.transportLayer); } return false; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + (this.serviceLayer != null ? this.serviceLayer.hashCode() : 0); hash = 67 * hash + (this.applicationLayer != null ? this.applicationLayer.hashCode() : 0); hash = 67 * hash + (this.presentationLayer != null ? this.presentationLayer.hashCode() : 0); hash = 67 * hash + (this.sessionLayer != null ? this.sessionLayer.hashCode() : 0); hash = 67 * hash + (this.transportLayer != null ? this.transportLayer.hashCode() : 0); hash = 67 * hash + (this.networkLayer != null ? this.networkLayer.hashCode() : 0); hash = 67 * hash + (this.dataLinkLayer != null ? this.dataLinkLayer.hashCode() : 0); hash = 67 * hash + (this.physicalLayer != null ? this.physicalLayer.hashCode() : 0); hash = 67 * hash + (this.mechanicalLayer != null ? this.mechanicalLayer.hashCode() : 0); hash = 67 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } }
UTF-8
Java
13,028
java
InterfaceDefinition.java
Java
[ { "context": "ttp://www.geotoolkit.org\n *\n * (C) 2008 - 2009, Geomatys\n *\n * This library is free software; you can r", "end": 120, "score": 0.9903479218482971, "start": 112, "tag": "NAME", "value": "Geomatys" } ]
null
[]
/* * Geotoolkit - An Open Source Java GIS Toolkit * http://www.geotoolkit.org * * (C) 2008 - 2009, Geomatys * * This library 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 library 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. */ package org.geotoolkit.sml.xml.v100; import java.util.Objects; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlID; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.geotoolkit.sml.xml.AbstractInterfaceDefinition; import org.geotoolkit.swe.xml.v100.Category; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="serviceLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="applicationLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="presentationLayer" type="{http://www.opengis.net/sensorML/1.0}PresentationLayerPropertyType" minOccurs="0"/> * &lt;element name="sessionLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="transportLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="networkLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="dataLinkLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="physicalLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;element name="mechanicalLayer" type="{http://www.opengis.net/sensorML/1.0}LayerPropertyType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * * @module */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "serviceLayer", "applicationLayer", "presentationLayer", "sessionLayer", "transportLayer", "networkLayer", "dataLinkLayer", "physicalLayer", "mechanicalLayer" }) @XmlRootElement(name = "InterfaceDefinition") public class InterfaceDefinition implements AbstractInterfaceDefinition { private LayerPropertyType serviceLayer; private LayerPropertyType applicationLayer; private PresentationLayerPropertyType presentationLayer; private LayerPropertyType sessionLayer; private LayerPropertyType transportLayer; private LayerPropertyType networkLayer; private LayerPropertyType dataLinkLayer; private LayerPropertyType physicalLayer; private LayerPropertyType mechanicalLayer; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID private String id; public InterfaceDefinition() { } public InterfaceDefinition(final String id, final LayerPropertyType applicationLayer, final LayerPropertyType dataLinkLayer) { this.applicationLayer = applicationLayer; this.dataLinkLayer = dataLinkLayer; } public InterfaceDefinition(final AbstractInterfaceDefinition in) { if (in != null) { if (in.getServiceLayer() != null) { this.serviceLayer = new LayerPropertyType(in.getServiceLayer()); } if (in.getApplicationLayer() != null) { this.applicationLayer = new LayerPropertyType(in.getApplicationLayer()); } if (in.getDataLinkLayer() != null) { this.dataLinkLayer = new LayerPropertyType(in.getDataLinkLayer()); } this.id = in.getId(); if (in.getMechanicalLayer() != null) { this.mechanicalLayer = new LayerPropertyType(in.getMechanicalLayer()); } if (in.getNetworkLayer() != null) { this.networkLayer = new LayerPropertyType(in.getNetworkLayer()); } if (in.getPhysicalLayer() != null) { this.physicalLayer = new LayerPropertyType(in.getPhysicalLayer()); } if (in.getPresentationLayer() != null) { this.presentationLayer = new PresentationLayerPropertyType(in.getPresentationLayer()); } if (in.getServiceLayer() != null) { this.serviceLayer = new LayerPropertyType(in.getServiceLayer()); } if (in.getSessionLayer() != null) { this.sessionLayer = new LayerPropertyType(in.getSessionLayer()); } if (in.getTransportLayer() != null) { this.transportLayer = new LayerPropertyType(in.getTransportLayer()); } } } /** * Gets the value of the serviceLayer property. */ public LayerPropertyType getServiceLayer() { return serviceLayer; } /** * Sets the value of the serviceLayer property. */ public void setServiceLayer(final LayerPropertyType value) { this.serviceLayer = value; } /** * Sets the value of the serviceLayer property. */ public void setServiceLayer(final Category value) { this.serviceLayer = new LayerPropertyType(value); } /** * Gets the value of the applicationLayer property. */ public LayerPropertyType getApplicationLayer() { return applicationLayer; } /** * Sets the value of the applicationLayer property. */ public void setApplicationLayer(final LayerPropertyType value) { this.applicationLayer = value; } /** * Sets the value of the applicationLayer property. */ public void setApplicationLayer(final Category value) { this.applicationLayer = new LayerPropertyType(value); } /** * Gets the value of the presentationLayer property. */ public PresentationLayerPropertyType getPresentationLayer() { return presentationLayer; } /** * Sets the value of the presentationLayer property. */ public void setPresentationLayer(final PresentationLayerPropertyType value) { this.presentationLayer = value; } /** * Sets the value of the applicationLayer property. */ public void setPresentationLayer(final Category value) { this.presentationLayer = new PresentationLayerPropertyType(value); } /** * Gets the value of the sessionLayer property. */ public LayerPropertyType getSessionLayer() { return sessionLayer; } /** * Sets the value of the sessionLayer property. */ public void setSessionLayer(final LayerPropertyType value) { this.sessionLayer = value; } /** * Sets the value of the sessionLayer property. */ public void setSessionLayer(final Category value) { this.sessionLayer = new LayerPropertyType(value); } /** * Gets the value of the transportLayer property. */ public LayerPropertyType getTransportLayer() { return transportLayer; } /** * Sets the value of the transportLayer property. */ public void setTransportLayer(final LayerPropertyType value) { this.transportLayer = value; } /** * Sets the value of the transportLayer property. */ public void setTransportLayer(final Category value) { this.transportLayer = new LayerPropertyType(value); } /** * Gets the value of the networkLayer property. */ public LayerPropertyType getNetworkLayer() { return networkLayer; } /** * Sets the value of the networkLayer property. */ public void setNetworkLayer(final LayerPropertyType value) { this.networkLayer = value; } /** * Sets the value of the networkLayer property. */ public void setNetworkLayer(final Category value) { this.networkLayer = new LayerPropertyType(value); } /** * Gets the value of the dataLinkLayer property. */ public LayerPropertyType getDataLinkLayer() { return dataLinkLayer; } /** * Sets the value of the dataLinkLayer property. */ public void setDataLinkLayer(final LayerPropertyType value) { this.dataLinkLayer = value; } /** * Sets the value of the dataLinkLayer property. */ public void setDataLinkLayer(final Category value) { this.dataLinkLayer = new LayerPropertyType(value); } /** * Gets the value of the physicalLayer property. */ public LayerPropertyType getPhysicalLayer() { return physicalLayer; } /** * Sets the value of the physicalLayer property. */ public void setPhysicalLayer(final LayerPropertyType value) { this.physicalLayer = value; } /** * Sets the value of the physicalLayer property. */ public void setPhysicalLayer(final Category value) { this.physicalLayer = new LayerPropertyType(value); } /** * Gets the value of the mechanicalLayer property. */ public LayerPropertyType getMechanicalLayer() { return mechanicalLayer; } /** * Sets the value of the mechanicalLayer property. */ public void setMechanicalLayer(final LayerPropertyType value) { this.mechanicalLayer = value; } /** * Sets the value of the mechanicalLayer property. */ public void setMechanicalLayer(final Category value) { this.mechanicalLayer = new LayerPropertyType(value); } /** * Gets the value of the id property. */ public String getId() { return id; } /** * Sets the value of the id property. */ public void setId(final String value) { this.id = value; } /** * Verify if this entry is identical to specified object. */ @Override public boolean equals(final Object object) { if (object == this) { return true; } if (object instanceof InterfaceDefinition) { final InterfaceDefinition that = (InterfaceDefinition) object; return Objects.equals(this.applicationLayer, that.applicationLayer) && Objects.equals(this.dataLinkLayer, that.dataLinkLayer) && Objects.equals(this.id, that.id) && Objects.equals(this.mechanicalLayer, that.mechanicalLayer) && Objects.equals(this.networkLayer, that.networkLayer) && Objects.equals(this.physicalLayer, that.physicalLayer) && Objects.equals(this.presentationLayer, that.presentationLayer)&& Objects.equals(this.serviceLayer, that.serviceLayer) && Objects.equals(this.sessionLayer, that.sessionLayer) && Objects.equals(this.transportLayer, that.transportLayer); } return false; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + (this.serviceLayer != null ? this.serviceLayer.hashCode() : 0); hash = 67 * hash + (this.applicationLayer != null ? this.applicationLayer.hashCode() : 0); hash = 67 * hash + (this.presentationLayer != null ? this.presentationLayer.hashCode() : 0); hash = 67 * hash + (this.sessionLayer != null ? this.sessionLayer.hashCode() : 0); hash = 67 * hash + (this.transportLayer != null ? this.transportLayer.hashCode() : 0); hash = 67 * hash + (this.networkLayer != null ? this.networkLayer.hashCode() : 0); hash = 67 * hash + (this.dataLinkLayer != null ? this.dataLinkLayer.hashCode() : 0); hash = 67 * hash + (this.physicalLayer != null ? this.physicalLayer.hashCode() : 0); hash = 67 * hash + (this.mechanicalLayer != null ? this.mechanicalLayer.hashCode() : 0); hash = 67 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } }
13,028
0.642462
0.636015
380
33.28421
31.441896
137
false
false
0
0
0
0
0
0
0.328947
false
false
9
1ac951e38509ed76938543f3859f9e5cdcbd1c69
28,046,136,501,458
73b3e19a63fb11878ddbaa2712fffc1541009372
/YingTaiDicom/branches/code/src/com/vastsoft/yingtaidicom/search/orgsearch/systems/pacs/yingtai/ver1/entity/AbstractDicomEntity.java
886d2ef747afc68d95181267ad16e5dff9385f33
[]
no_license
BellaJiangxia/Project
https://github.com/BellaJiangxia/Project
45dff645081985dd8b1cb5e5561bdf659b347d27
921bcf2f5cc81224e36a21b5c55b7a2b1416882c
refs/heads/master
2023-01-06T23:27:48.700000
2020-11-10T14:44:28
2020-11-10T14:44:28
303,154,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vastsoft.yingtaidicom.search.orgsearch.systems.pacs.yingtai.ver1.entity; import java.util.Date; public abstract class AbstractDicomEntity { private String uuid; private String udid;// 保存者的身份标识码 private int participant_type;// 身份标识类型 private Date create_time;// private byte[] thumbnail;// 缩略图 private String specific_character_set; // public void valueOf(final Attributes attrs) throws DcmStorageException { // try { // final AbstractDicomEntity entity = this; // //attrs.setSpecificCharacterSet(attrs.getString(Tag.SpecificCharacterSet)); // DicomAttribute.foreach(this.getDicomEntityClass(), new IterateRunnable<DicomAttribute>() { // public void run(DicomAttribute attribute) throws DcmStorageException { // Object value; // if (attribute.getClassType() == Integer.class) { // value = attrs.getInt(attribute.getTag().getTag(), 0); // }else if (attribute.getClassType() == String.class) { // value = attrs.getString(attribute.getTag().getTag()); // }else if (attribute.getClassType() == Long.class) { // value = attrs.getString(attribute.getTag().getTag()); // value = Long.valueOf(value.toString()); // }else if (attribute.getClassType() == Double.class) { // value = attrs.getDouble(attribute.getTag().getTag(), 0.0); // }else { // value = attrs.getString(attribute.getTag().getTag()); // } // if (value == null){ // LoggerUtils.logger.debug("获取到属性:"+attribute.getName()+" 的值为null!"); // if (attribute.isRequired()) // throw new DcmStorageException("实体:"+entity.getClass().getName()+"字段[" + attribute.getName() + "]是必须值,但当前为null!"); // return; // } // if (!ReflectTools.writeProperty(entity, attribute.getName(), value)) // throw new DcmStorageException("实体:"+entity.getClass().getName()+"字段[" + attribute.getName() + "]是写入失败!"); // } // }); // } catch (BaseException e) { // e.printStackTrace(); // throw (DcmStorageException) e; // } // } // // public Attributes toAttrs() throws DcmStorageException { // try { // final Attributes attrs = new Attributes(); // final AbstractDicomEntity entity = this; // DicomAttribute.foreach(this.getDicomEntityClass(), new IterateRunnable<DicomAttribute>() { // public void run(DicomAttribute attribute) { // Object value = ReflectTools.readProperty(entity, attribute.getName()); // attrs.setValue(attribute.getTag().getTag(), attribute.getVr(), value); // } // }); // return attrs; // } catch (BaseException e) { // e.printStackTrace(); // throw new DcmStorageException(e); // } // } // public abstract DicomEntityClass getDicomEntityClass(); // @JsonIgnore // public String getUniqueKeyValue() { // DicomAttribute attribute = DicomAttribute.takeUniqueKeyByDicomEntityClass(this.getDicomEntityClass()); // Object rr = ReflectTools.readProperty(this, attribute.getName()); // return rr==null?null:rr.toString(); // } public abstract void writeFatherUuid(String father_uuid); public abstract String readFatherUuid(); public String getUdid() { return udid; } public void setUdid(String udid) { this.udid = udid; } public int getParticipant_type() { return participant_type; } public void setParticipant_type(int participant_type) { this.participant_type = participant_type; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } // public ParticipantType getParticipantType() throws BaseException { // return ParticipantType.parseCode(this.participant_type); // } // public boolean isSameOne(AbstractDicomEntity entityTmp) throws BaseException { // if (this.getClass() != entityTmp.getClass()) // return false; // if (this.getUniqueKeyValue() != null && this.getUniqueKeyValue().equals(entityTmp.getUniqueKeyValue())) // if (!StringTools.isEmpty(this.getUdid()) && this.getUdid().equals(entityTmp.getUdid())) // if (this.getParticipantType() != null && this.participant_type == entityTmp.getParticipant_type()) // return true; // return false; // } // // /**获取判断是否相同的MAP*/ // @JsonIgnore // public Map<String, Object> getSamePropertyMap() { // DicomAttribute attribute = DicomAttribute.takeUniqueKeyByDicomEntityClass(this.getDicomEntityClass()); // return new MapBuilder<String, Object>().put(attribute.getName(), this.getUniqueKeyValue()).put("udid", udid) // .put("participant_type", participant_type).toMap(); // } public byte[] getThumbnail() { return thumbnail; } public void setThumbnail(byte[] thumbnail) { this.thumbnail = thumbnail; } // public abstract void checkEntityWholeness() throws DcmEntityUnWholenessException; public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } public String getSpecific_character_set() { return specific_character_set; } public void setSpecific_character_set(String specific_character_set) { this.specific_character_set = specific_character_set; } }
UTF-8
Java
5,143
java
AbstractDicomEntity.java
Java
[]
null
[]
package com.vastsoft.yingtaidicom.search.orgsearch.systems.pacs.yingtai.ver1.entity; import java.util.Date; public abstract class AbstractDicomEntity { private String uuid; private String udid;// 保存者的身份标识码 private int participant_type;// 身份标识类型 private Date create_time;// private byte[] thumbnail;// 缩略图 private String specific_character_set; // public void valueOf(final Attributes attrs) throws DcmStorageException { // try { // final AbstractDicomEntity entity = this; // //attrs.setSpecificCharacterSet(attrs.getString(Tag.SpecificCharacterSet)); // DicomAttribute.foreach(this.getDicomEntityClass(), new IterateRunnable<DicomAttribute>() { // public void run(DicomAttribute attribute) throws DcmStorageException { // Object value; // if (attribute.getClassType() == Integer.class) { // value = attrs.getInt(attribute.getTag().getTag(), 0); // }else if (attribute.getClassType() == String.class) { // value = attrs.getString(attribute.getTag().getTag()); // }else if (attribute.getClassType() == Long.class) { // value = attrs.getString(attribute.getTag().getTag()); // value = Long.valueOf(value.toString()); // }else if (attribute.getClassType() == Double.class) { // value = attrs.getDouble(attribute.getTag().getTag(), 0.0); // }else { // value = attrs.getString(attribute.getTag().getTag()); // } // if (value == null){ // LoggerUtils.logger.debug("获取到属性:"+attribute.getName()+" 的值为null!"); // if (attribute.isRequired()) // throw new DcmStorageException("实体:"+entity.getClass().getName()+"字段[" + attribute.getName() + "]是必须值,但当前为null!"); // return; // } // if (!ReflectTools.writeProperty(entity, attribute.getName(), value)) // throw new DcmStorageException("实体:"+entity.getClass().getName()+"字段[" + attribute.getName() + "]是写入失败!"); // } // }); // } catch (BaseException e) { // e.printStackTrace(); // throw (DcmStorageException) e; // } // } // // public Attributes toAttrs() throws DcmStorageException { // try { // final Attributes attrs = new Attributes(); // final AbstractDicomEntity entity = this; // DicomAttribute.foreach(this.getDicomEntityClass(), new IterateRunnable<DicomAttribute>() { // public void run(DicomAttribute attribute) { // Object value = ReflectTools.readProperty(entity, attribute.getName()); // attrs.setValue(attribute.getTag().getTag(), attribute.getVr(), value); // } // }); // return attrs; // } catch (BaseException e) { // e.printStackTrace(); // throw new DcmStorageException(e); // } // } // public abstract DicomEntityClass getDicomEntityClass(); // @JsonIgnore // public String getUniqueKeyValue() { // DicomAttribute attribute = DicomAttribute.takeUniqueKeyByDicomEntityClass(this.getDicomEntityClass()); // Object rr = ReflectTools.readProperty(this, attribute.getName()); // return rr==null?null:rr.toString(); // } public abstract void writeFatherUuid(String father_uuid); public abstract String readFatherUuid(); public String getUdid() { return udid; } public void setUdid(String udid) { this.udid = udid; } public int getParticipant_type() { return participant_type; } public void setParticipant_type(int participant_type) { this.participant_type = participant_type; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } // public ParticipantType getParticipantType() throws BaseException { // return ParticipantType.parseCode(this.participant_type); // } // public boolean isSameOne(AbstractDicomEntity entityTmp) throws BaseException { // if (this.getClass() != entityTmp.getClass()) // return false; // if (this.getUniqueKeyValue() != null && this.getUniqueKeyValue().equals(entityTmp.getUniqueKeyValue())) // if (!StringTools.isEmpty(this.getUdid()) && this.getUdid().equals(entityTmp.getUdid())) // if (this.getParticipantType() != null && this.participant_type == entityTmp.getParticipant_type()) // return true; // return false; // } // // /**获取判断是否相同的MAP*/ // @JsonIgnore // public Map<String, Object> getSamePropertyMap() { // DicomAttribute attribute = DicomAttribute.takeUniqueKeyByDicomEntityClass(this.getDicomEntityClass()); // return new MapBuilder<String, Object>().put(attribute.getName(), this.getUniqueKeyValue()).put("udid", udid) // .put("participant_type", participant_type).toMap(); // } public byte[] getThumbnail() { return thumbnail; } public void setThumbnail(byte[] thumbnail) { this.thumbnail = thumbnail; } // public abstract void checkEntityWholeness() throws DcmEntityUnWholenessException; public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } public String getSpecific_character_set() { return specific_character_set; } public void setSpecific_character_set(String specific_character_set) { this.specific_character_set = specific_character_set; } }
5,143
0.698625
0.697827
149
32.671143
31.273945
122
false
false
0
0
0
0
0
0
2.543624
false
false
9
90b50aa1d20a33c6894a34d98e1d379d4b4ac15b
9,723,806,002,423
dc5f24fce4e1daf71dcf2171d2ab2b206318af5a
/Server/src/blablamessenger/ConferenceEntry.java
4b37c6dc65d82c8c5e657b2b43123ccf6d59d379
[]
no_license
VladVin/BlaBlaMessenger
https://github.com/VladVin/BlaBlaMessenger
ce7d37a2f13f44bae1458e72ec21c44df364217d
347af6c89ccfdd8f5cd5dab041e43b2070a5e61f
refs/heads/master
2020-05-17T22:39:58.817000
2015-12-26T09:13:21
2015-12-26T09:13:21
32,344,682
0
1
null
false
2015-12-26T09:13:21
2015-03-16T18:27:18
2015-05-07T18:41:24
2015-12-26T09:13:21
405
0
1
1
Java
null
null
package blablamessenger; import coreutilities.Conference; import java.util.UUID; public class ConferenceEntry { public UUID contact; public Conference conference; public ConferenceEntry( UUID contact, Conference conference ) { this.contact = contact; this.conference = conference; } }
UTF-8
Java
358
java
ConferenceEntry.java
Java
[]
null
[]
package blablamessenger; import coreutilities.Conference; import java.util.UUID; public class ConferenceEntry { public UUID contact; public Conference conference; public ConferenceEntry( UUID contact, Conference conference ) { this.contact = contact; this.conference = conference; } }
358
0.648045
0.648045
21
16.047619
13.510054
37
false
false
0
0
0
0
0
0
0.380952
false
false
9
1fcb233525b98b7e198a64fd2ebb46b0e074cbf6
1,984,274,946,941
3c636571e2a03c23f83928d6157ee35669023384
/app/src/main/java/com/guohanhealth/shop/bean/Step2Info.java
5362e1ebf5e1a7562264b2ccd001bd123f095dec
[]
no_license
majicking/hhscapp
https://github.com/majicking/hhscapp
5be1c0edf538dae4bd5ac6efa87fca10dab0a1b4
4f4dbfb0e47db426fd3c4831b1e817a41ae8edb3
refs/heads/master
2020-03-17T08:45:11.052000
2018-09-05T08:19:53
2018-09-05T08:19:53
133,448,634
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guohanhealth.shop.bean; public class Step2Info extends BaseInfo{ public String pay_sn; public String payment_code; public String pay_info; }
UTF-8
Java
167
java
Step2Info.java
Java
[]
null
[]
package com.guohanhealth.shop.bean; public class Step2Info extends BaseInfo{ public String pay_sn; public String payment_code; public String pay_info; }
167
0.742515
0.736527
7
22.857143
14.951623
41
false
false
0
0
0
0
0
0
0.571429
false
false
9
25792378683da82e92956193aa68d7e484023747
22,170,621,235,750
923ab0098392a95ca1e01aa4831ed7af3efc9d31
/soapui/src/test/java/com/eviware/soapui/impl/rest/panels/resource/RestParamsTableModelUnitTest.java
764f47db085ea8f0b28ac7a323d2469b8635751e
[]
no_license
eric-stanley/soapui
https://github.com/eric-stanley/soapui
ff84477c449e7b2dd54c812f693c4b0abb678db7
dc074916b6da0e8d93568a05f157256338c30f03
refs/heads/master
2018-06-30T11:29:58.682000
2014-05-27T09:22:42
2014-05-27T09:22:42
21,195,416
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2004-2014 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.eviware.soapui.impl.rest.panels.resource; import com.eviware.soapui.impl.rest.RestMethod; import com.eviware.soapui.impl.rest.RestRequest; import com.eviware.soapui.impl.rest.RestResource; import com.eviware.soapui.impl.rest.actions.support.NewRestResourceActionBase; import com.eviware.soapui.impl.rest.support.RestParamProperty; import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder; import com.eviware.soapui.impl.rest.support.XmlBeansRestParamsTestPropertyHolder; import com.eviware.soapui.model.testsuite.TestPropertyListener; import com.eviware.soapui.support.SoapUIException; import com.eviware.soapui.utils.ModelItemFactory; import org.junit.Before; import org.junit.Test; import static com.eviware.soapui.impl.rest.actions.support.NewRestResourceActionBase.ParamLocation.METHOD; import static com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder.ParameterStyle.QUERY; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; /** * Unit tests for the RestParamsTableModel class */ public class RestParamsTableModelUnitTest { private static final int NAME_COLUMN_INDEX = 0; public static final int VALUE_COLUMN_INDEX = 1; private static final int STYLE_COLUMN_INDEX = 2; private static final int LOCATION_COLUMN_INDEX = 3; public static final String PARAM_NAME_1 = "ParamName1"; public static final String PARAM_NAME_2 = "ParamName2"; private RestParamsTableModel restParamsTableModel; private RestParamsPropertyHolder params; @Before public void setUp() throws SoapUIException { RestRequest restRequest = ModelItemFactory.makeRestRequest(); params = restRequest.getParams(); RestParamProperty param = params.addProperty( PARAM_NAME_1 ); param.setParamLocation( METHOD ); RestParamProperty param2 = params.addProperty( PARAM_NAME_2 ); param2.setParamLocation( METHOD ); restParamsTableModel = new RestParamsTableModel( params ); } @Test public void removesAndAddThePropertyListenerAgainWhenParamIsSet() { mockParams(); restParamsTableModel = new RestParamsTableModel( params ); restParamsTableModel.setParams( params ); verify( params, times( 1 ) ).removeTestPropertyListener( any( TestPropertyListener.class ) ); verify( params, times( 2 ) ).addTestPropertyListener( any( TestPropertyListener.class ) ); } @Test public void removesListenerOnRelease() { mockParams(); restParamsTableModel.setParams( params ); restParamsTableModel.release(); verify( params, times( 1 ) ).addTestPropertyListener( any( TestPropertyListener.class ) ); verify( params, times( 1 ) ).removeTestPropertyListener( any( TestPropertyListener.class ) ); } @Test public void setsValueToPropertyWhenSetValueAtIsInvoked() { String value = "New value"; restParamsTableModel.setValueAt( value, 0, VALUE_COLUMN_INDEX ); assertThat( ( String )restParamsTableModel.getValueAt( 0, VALUE_COLUMN_INDEX ), is( value ) ); } @Test public void renamesThePropertyIfSetValueIsInvokedOnFirstColumn() { String value = "New Name"; restParamsTableModel.setValueAt( value, 0, NAME_COLUMN_INDEX ); assertThat( ( String )restParamsTableModel.getValueAt( 0, NAME_COLUMN_INDEX ), is( value ) ); } @Test public void changesPropertyStyleWhenSetValueIsInvokedonStyleColumn() { restParamsTableModel.setValueAt( QUERY, 0, STYLE_COLUMN_INDEX ); assertThat( ( RestParamsPropertyHolder.ParameterStyle )restParamsTableModel.getValueAt( 0, STYLE_COLUMN_INDEX ), is( QUERY ) ); } @Test public void givenModelWithParamsWhenSetLocationAndGetLocationThenShouldReturnSameValue() { restParamsTableModel.setValueAt( METHOD, 0, LOCATION_COLUMN_INDEX ); assertThat( ( NewRestResourceActionBase.ParamLocation )restParamsTableModel.getValueAt( 0, LOCATION_COLUMN_INDEX ), is( METHOD ) ); } @Test public void retainsParameterOrderWhenChangingLocation() throws Exception { restParamsTableModel.setValueAt( METHOD, 0, LOCATION_COLUMN_INDEX ); assertThat((String)restParamsTableModel.getValueAt( 0, NAME_COLUMN_INDEX ), is(PARAM_NAME_1)); } private void mockParams() { params = mock( RestParamsPropertyHolder.class ); RestRequest restRequest = mock( RestRequest.class ); RestResource resource = mock( RestResource.class ); RestParamsPropertyHolder resourceParams = mock( XmlBeansRestParamsTestPropertyHolder.class ); when( resource.getParams() ).thenReturn( resourceParams ); when( restRequest.getResource() ).thenReturn( resource ); RestMethod restMethod = mock( RestMethod.class ); RestParamsPropertyHolder methodParams = mock( XmlBeansRestParamsTestPropertyHolder.class ); when( restMethod.getParams() ).thenReturn( methodParams ); when( restRequest.getRestMethod() ).thenReturn( restMethod ); when( params.getModelItem() ).thenReturn( restRequest ); } }
UTF-8
Java
5,520
java
RestParamsTableModelUnitTest.java
Java
[ { "context": "/*\n * Copyright 2004-2014 SmartBear Software\n *\n * Licensed under the EUPL, Versi", "end": 31, "score": 0.7636421322822571, "start": 26, "tag": "NAME", "value": "Smart" }, { "context": "/*\n * Copyright 2004-2014 SmartBear Software\n *\n * Licensed under the EUPL, Ve...
null
[]
/* * Copyright 2004-2014 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.eviware.soapui.impl.rest.panels.resource; import com.eviware.soapui.impl.rest.RestMethod; import com.eviware.soapui.impl.rest.RestRequest; import com.eviware.soapui.impl.rest.RestResource; import com.eviware.soapui.impl.rest.actions.support.NewRestResourceActionBase; import com.eviware.soapui.impl.rest.support.RestParamProperty; import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder; import com.eviware.soapui.impl.rest.support.XmlBeansRestParamsTestPropertyHolder; import com.eviware.soapui.model.testsuite.TestPropertyListener; import com.eviware.soapui.support.SoapUIException; import com.eviware.soapui.utils.ModelItemFactory; import org.junit.Before; import org.junit.Test; import static com.eviware.soapui.impl.rest.actions.support.NewRestResourceActionBase.ParamLocation.METHOD; import static com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder.ParameterStyle.QUERY; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; /** * Unit tests for the RestParamsTableModel class */ public class RestParamsTableModelUnitTest { private static final int NAME_COLUMN_INDEX = 0; public static final int VALUE_COLUMN_INDEX = 1; private static final int STYLE_COLUMN_INDEX = 2; private static final int LOCATION_COLUMN_INDEX = 3; public static final String PARAM_NAME_1 = "ParamName1"; public static final String PARAM_NAME_2 = "ParamName2"; private RestParamsTableModel restParamsTableModel; private RestParamsPropertyHolder params; @Before public void setUp() throws SoapUIException { RestRequest restRequest = ModelItemFactory.makeRestRequest(); params = restRequest.getParams(); RestParamProperty param = params.addProperty( PARAM_NAME_1 ); param.setParamLocation( METHOD ); RestParamProperty param2 = params.addProperty( PARAM_NAME_2 ); param2.setParamLocation( METHOD ); restParamsTableModel = new RestParamsTableModel( params ); } @Test public void removesAndAddThePropertyListenerAgainWhenParamIsSet() { mockParams(); restParamsTableModel = new RestParamsTableModel( params ); restParamsTableModel.setParams( params ); verify( params, times( 1 ) ).removeTestPropertyListener( any( TestPropertyListener.class ) ); verify( params, times( 2 ) ).addTestPropertyListener( any( TestPropertyListener.class ) ); } @Test public void removesListenerOnRelease() { mockParams(); restParamsTableModel.setParams( params ); restParamsTableModel.release(); verify( params, times( 1 ) ).addTestPropertyListener( any( TestPropertyListener.class ) ); verify( params, times( 1 ) ).removeTestPropertyListener( any( TestPropertyListener.class ) ); } @Test public void setsValueToPropertyWhenSetValueAtIsInvoked() { String value = "New value"; restParamsTableModel.setValueAt( value, 0, VALUE_COLUMN_INDEX ); assertThat( ( String )restParamsTableModel.getValueAt( 0, VALUE_COLUMN_INDEX ), is( value ) ); } @Test public void renamesThePropertyIfSetValueIsInvokedOnFirstColumn() { String value = "New Name"; restParamsTableModel.setValueAt( value, 0, NAME_COLUMN_INDEX ); assertThat( ( String )restParamsTableModel.getValueAt( 0, NAME_COLUMN_INDEX ), is( value ) ); } @Test public void changesPropertyStyleWhenSetValueIsInvokedonStyleColumn() { restParamsTableModel.setValueAt( QUERY, 0, STYLE_COLUMN_INDEX ); assertThat( ( RestParamsPropertyHolder.ParameterStyle )restParamsTableModel.getValueAt( 0, STYLE_COLUMN_INDEX ), is( QUERY ) ); } @Test public void givenModelWithParamsWhenSetLocationAndGetLocationThenShouldReturnSameValue() { restParamsTableModel.setValueAt( METHOD, 0, LOCATION_COLUMN_INDEX ); assertThat( ( NewRestResourceActionBase.ParamLocation )restParamsTableModel.getValueAt( 0, LOCATION_COLUMN_INDEX ), is( METHOD ) ); } @Test public void retainsParameterOrderWhenChangingLocation() throws Exception { restParamsTableModel.setValueAt( METHOD, 0, LOCATION_COLUMN_INDEX ); assertThat((String)restParamsTableModel.getValueAt( 0, NAME_COLUMN_INDEX ), is(PARAM_NAME_1)); } private void mockParams() { params = mock( RestParamsPropertyHolder.class ); RestRequest restRequest = mock( RestRequest.class ); RestResource resource = mock( RestResource.class ); RestParamsPropertyHolder resourceParams = mock( XmlBeansRestParamsTestPropertyHolder.class ); when( resource.getParams() ).thenReturn( resourceParams ); when( restRequest.getResource() ).thenReturn( resource ); RestMethod restMethod = mock( RestMethod.class ); RestParamsPropertyHolder methodParams = mock( XmlBeansRestParamsTestPropertyHolder.class ); when( restMethod.getParams() ).thenReturn( methodParams ); when( restRequest.getRestMethod() ).thenReturn( restMethod ); when( params.getModelItem() ).thenReturn( restRequest ); } }
5,520
0.780797
0.774094
146
36.80822
34.053204
117
false
false
0
0
0
0
74
0.013406
1.547945
false
false
9
41f3f03ea6a033b5b0313a864ed8958389bd352c
30,700,426,299,955
e5dc8dfd54d066e9dc414775c237addcd1cc34fd
/DailyProblems/src/dailyproblems/AUG27.java
7c3e070d1bd3e763a80e497ad0bb6ca4e7818cb3
[]
no_license
yvardha/DailyProblems
https://github.com/yvardha/DailyProblems
bc511631dd40ff5e991dc38cb7e0090bb1a6b299
a2fcfbc590127cb9485589bb2588143c55a7cde1
refs/heads/master
2020-07-13T20:45:59.916000
2019-09-11T14:05:22
2019-09-11T14:05:22
205,151,570
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dailyproblems; import java.util.Hashtable; import java.util.Iterator; import java.util.Stack; public class AUG27 { public static int solution(String str) { int len= 0; Stack<Integer> s = new Stack<Integer>(); int count = 0; int length = str.length(); Hashtable<Character,Integer> t = new Hashtable<Character, Integer>(); for(int i = 0;i<length;i++) { if(t.containsKey(str.charAt(i))) { int val=0; s.push(len); len = i+1; val = t.get(str.charAt(i)); len = len-val; t.replace(str.charAt(i),i+1); }else { t.put(str.charAt(i),i+1); len++; } } s.push(len); return len; } public static void main(String[] args) { String str = "abrkaabcdefghijjxxx"; System.out.println(solution(str)); } }
UTF-8
Java
813
java
AUG27.java
Java
[]
null
[]
package dailyproblems; import java.util.Hashtable; import java.util.Iterator; import java.util.Stack; public class AUG27 { public static int solution(String str) { int len= 0; Stack<Integer> s = new Stack<Integer>(); int count = 0; int length = str.length(); Hashtable<Character,Integer> t = new Hashtable<Character, Integer>(); for(int i = 0;i<length;i++) { if(t.containsKey(str.charAt(i))) { int val=0; s.push(len); len = i+1; val = t.get(str.charAt(i)); len = len-val; t.replace(str.charAt(i),i+1); }else { t.put(str.charAt(i),i+1); len++; } } s.push(len); return len; } public static void main(String[] args) { String str = "abrkaabcdefghijjxxx"; System.out.println(solution(str)); } }
813
0.589176
0.578106
39
18.846153
15.872147
71
false
false
0
0
0
0
0
0
2.666667
false
false
9
72603ebb194299cd9bd352ac6a2b908e4b7a71aa
12,481,174,996,121
0a7830dd92fe223fe67081b90acc2922b3127433
/src/main/java/cn/edu/seu/webPageExtractor/util/PageUtil.java
9d94e50283e2b9c5cf90406cecb7624d789daf67
[]
no_license
roketKing/webPageExtractor
https://github.com/roketKing/webPageExtractor
7572f3f5f2ae8155f344e0ba5b144eea6fec6dcb
35dbd45766728baba14b34577def26f3ee6176fe
refs/heads/master
2020-04-25T16:32:44.443000
2019-04-28T12:33:43
2019-04-28T12:33:43
172,916,255
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.seu.webPageExtractor.util; import org.openqa.selenium.WebElement; import java.util.List; public class PageUtil { public static List<WebElement> getChildElement(WebElement element){ return null; } }
UTF-8
Java
232
java
PageUtil.java
Java
[]
null
[]
package cn.edu.seu.webPageExtractor.util; import org.openqa.selenium.WebElement; import java.util.List; public class PageUtil { public static List<WebElement> getChildElement(WebElement element){ return null; } }
232
0.74569
0.74569
12
18.333334
21.472204
71
false
false
0
0
0
0
0
0
0.333333
false
false
9
43b7aaeb31d75ab3bcaeb48a2e9022d701e70a9e
26,182,120,682,202
00376b181e24618af408fa7079755034088fc1a6
/IO流的学习/M6D24/src/FileTest.java
6f35e89431051e563e98c06b777ecd680fb885e9
[]
no_license
hetianrui/JavaTest
https://github.com/hetianrui/JavaTest
22f845f83527a826771aff913a83ea16473a92ee
55e82053bdff420f785f665afb5b931caa6a1978
refs/heads/master
2021-07-14T15:39:32.738000
2020-10-13T15:34:36
2020-10-13T15:34:36
214,981,180
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.Test; import java.io.*; public class FileTest { public static void main(String[] args) { File file=new File("hello.txt"); System.out.println(file.getAbsolutePath()); } @Test public void test(){ File file=new File("hello.txt"); FileReader fr=null; try { fr=new FileReader(file); char da[]=new char[5]; int data=fr.read(da); while (data!=-1){ for (int i = 0; i <data; i++) { System.out.print(da[i]); } data=fr.read(da); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fr!=null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } //System.out.println(file.getAbsolutePath()); } @Test public void test1(){ FileWriter fw=null; try { File file=new File("world.txt"); fw=new FileWriter(file,true); fw.write("232323"); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fw!=null) fw.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void test2(){ FileReader fr=null; FileWriter fw=null; try { File file =new File("hello.txt"); File file1=new File("hello1.txt"); fr=new FileReader(file); fw=new FileWriter(file1); char c[]=new char[8]; int data; while ((data=fr.read(c))!=-1){ for (int i = 0; i <data ; i++) { fw.write(c[i]); } } } catch (IOException e) { e.printStackTrace(); } finally { if(fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if(fw!=null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test3(){ FileInputStream fi=null; FileOutputStream fo=null; long start=System.currentTimeMillis(); try { File file=new File("C:\\Users\\asus\\Desktop\\爱.死亡和机器人.Love.Death.and.Robots.S01E01.720p-官方中字.mp4"); File file1=new File("C:\\Users\\asus\\Desktop\\LDR.mp4"); fi=new FileInputStream(file); fo=new FileOutputStream(file1); byte[] bytes=new byte[1024]; int a; while ((a=fi.read(bytes))!=-1){ for (int i = 0; i <a ; i++) { fo.write(bytes[i]); } } } catch (IOException e) { e.printStackTrace(); } finally { if(fi!=null){ try { fi.close(); } catch (IOException e) { e.printStackTrace(); } } if(fo!=null){ try { fo.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(System.currentTimeMillis()-start); } }
UTF-8
Java
3,724
java
FileTest.java
Java
[ { "context": " try {\n File file=new File(\"C:\\\\Users\\\\asus\\\\Desktop\\\\爱.死亡和机器人.Love.Death.and.Robots.S01E01.7", "end": 2701, "score": 0.6219838857650757, "start": 2697, "tag": "USERNAME", "value": "asus" }, { "context": "p4\");\n File file1=new File(\"C:...
null
[]
import org.junit.Test; import java.io.*; public class FileTest { public static void main(String[] args) { File file=new File("hello.txt"); System.out.println(file.getAbsolutePath()); } @Test public void test(){ File file=new File("hello.txt"); FileReader fr=null; try { fr=new FileReader(file); char da[]=new char[5]; int data=fr.read(da); while (data!=-1){ for (int i = 0; i <data; i++) { System.out.print(da[i]); } data=fr.read(da); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fr!=null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } //System.out.println(file.getAbsolutePath()); } @Test public void test1(){ FileWriter fw=null; try { File file=new File("world.txt"); fw=new FileWriter(file,true); fw.write("232323"); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fw!=null) fw.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void test2(){ FileReader fr=null; FileWriter fw=null; try { File file =new File("hello.txt"); File file1=new File("hello1.txt"); fr=new FileReader(file); fw=new FileWriter(file1); char c[]=new char[8]; int data; while ((data=fr.read(c))!=-1){ for (int i = 0; i <data ; i++) { fw.write(c[i]); } } } catch (IOException e) { e.printStackTrace(); } finally { if(fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if(fw!=null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test3(){ FileInputStream fi=null; FileOutputStream fo=null; long start=System.currentTimeMillis(); try { File file=new File("C:\\Users\\asus\\Desktop\\爱.死亡和机器人.Love.Death.and.Robots.S01E01.720p-官方中字.mp4"); File file1=new File("C:\\Users\\asus\\Desktop\\LDR.mp4"); fi=new FileInputStream(file); fo=new FileOutputStream(file1); byte[] bytes=new byte[1024]; int a; while ((a=fi.read(bytes))!=-1){ for (int i = 0; i <a ; i++) { fo.write(bytes[i]); } } } catch (IOException e) { e.printStackTrace(); } finally { if(fi!=null){ try { fi.close(); } catch (IOException e) { e.printStackTrace(); } } if(fo!=null){ try { fo.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(System.currentTimeMillis()-start); } }
3,724
0.407888
0.398433
131
27.259542
15.661782
112
false
false
0
0
0
0
0
0
0.458015
false
false
9
21848aba89e9f83df2ccee039864429e76c86503
13,091,060,389,108
9b5bdf99c24f5597d81437e3206f2d2ccf31bc66
/app/src/main/java/com/example/newmusicplayer/bean/AlbumDetailBean.java
27c9bb2e1859beb980cea8c9c6e141ed5adbb35d
[]
no_license
sandyz987/NewMusicPlayer
https://github.com/sandyz987/NewMusicPlayer
d87087c66a85adc8633999dd03f3a29744d5dc98
e2306a7c4056c40d9e678dd2fa21e09b00f55e7c
refs/heads/master
2022-06-20T09:48:00.903000
2020-05-03T14:49:05
2020-05-03T14:49:05
260,944,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.newmusicplayer.bean; public class AlbumDetailBean { private String coverImgUrl; private String name; private Creator creator; private Tracks[] tracksList; public Tracks[] getTracksList() { return tracksList; } public void setTracksList(Tracks[] tracksList) { this.tracksList = tracksList; } public String getCoverImgUrl() { return coverImgUrl; } public void setCoverImgUrl(String coverImgUrl) { this.coverImgUrl = coverImgUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Creator getCreator() { return creator; } public void setCreator(Creator creator) { this.creator = creator; } }
UTF-8
Java
817
java
AlbumDetailBean.java
Java
[]
null
[]
package com.example.newmusicplayer.bean; public class AlbumDetailBean { private String coverImgUrl; private String name; private Creator creator; private Tracks[] tracksList; public Tracks[] getTracksList() { return tracksList; } public void setTracksList(Tracks[] tracksList) { this.tracksList = tracksList; } public String getCoverImgUrl() { return coverImgUrl; } public void setCoverImgUrl(String coverImgUrl) { this.coverImgUrl = coverImgUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Creator getCreator() { return creator; } public void setCreator(Creator creator) { this.creator = creator; } }
817
0.631579
0.631579
41
18.926828
16.84997
52
false
false
0
0
0
0
0
0
0.317073
false
false
9
4d54c4ef64dd8e03ab62f8dc6c57b1f32f5e16a5
27,221,502,788,719
bc51823698163c12b0dab18130ba43acfb0b350e
/app/src/main/java/com/cvilia/bubble/view/WeatherLineView.java
14a00cf1d419cede896633f440088277575fb23c
[]
no_license
Cvilia/Bubble
https://github.com/Cvilia/Bubble
cd17a269ad28529f3d0a1564d04f4b290e0e0f17
6be07281bf6367eddc52fa5183749675d80d8f2e
refs/heads/master
2023-02-28T13:09:49.717000
2022-08-17T22:31:38
2022-08-17T22:31:38
288,707,443
0
0
null
false
2021-03-01T06:25:09
2020-08-19T10:56:50
2021-02-26T10:53:06
2021-03-01T06:25:09
7,975
1
0
0
Java
false
false
package com.cvilia.bubble.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.annotation.Nullable; import com.cvilia.bubble.R; import com.cvilia.bubble.listener.ITempData; import com.cvilia.bubble.utils.DisplayUtil; import java.util.ArrayList; import java.util.List; /** * author: lzy * date: 2020/8/20 * describe:温度双曲线 */ public class WeatherLineView<T extends ITempData> extends View { private static final String TAG = WeatherLineView.class.getSimpleName(); private Context mContext; //温度,点,线的画笔 private Paint mTempPaint, mDotPaint, mLinePaint; private static final int TEMP2TOP = 8; private static final int TEMP2DOT = 5; private int temp2Top = -1;//表示文字距离view顶部/底部的高度 private int temp2Dot = -1;//文字和温度点的距离 private static final int DEFAULT_DOT_RADIUS = 2; private int dotRadisu = -1; //字体默认大小 private static final int TEXT_SIZE = 12; private int textSize = -1; private List<T> datas = new ArrayList<>(); //整个集合中的最高最低温度 private int maxTemp, minTemp; //当前信息在集合中的位置 private int position; private Paint.FontMetrics fontMetrics; private static final int DEFAULT_HEIGHT = 100; private static final int DEFAULT_WIDTH = 60; //整个view的宽高 private int width = -1; private int height = -1; public void setDatas(List<T> datas, int position) { this.datas = datas; this.position = position; getExtremeTemp(datas); postInvalidate(); } /** * 计算最大和最小天气 * * @param infos */ private void getExtremeTemp(List<T> infos) { int[] heigh = new int[infos.size()]; int[] low = new int[infos.size()]; for (int i = 0; i < infos.size(); i++) { heigh[i] = infos.get(i).getMaxTemp(); low[i] = infos.get(i).getMinTemp(); } int[] array = new int[heigh.length + low.length]; for (int i = 0; i < infos.size() * 2; i++) { if (i < infos.size()) { array[i] = heigh[i]; } else { array[i] = low[i - infos.size()]; } } this.maxTemp = result(array, true); this.minTemp = result(array, false); } /** * 冒泡排序求最大最小值 * * @param nums * @param needMax * @return */ private int result(int[] nums, boolean needMax) { for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - 1 - i; j++) { if (nums[j] > nums[j + 1]) { int s = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = s; } } } for (int temp : nums) { System.out.print(temp + "---"); } return needMax ? nums[nums.length - 1] : nums[0]; } public WeatherLineView(Context context) { super(context); init(context, null); } public WeatherLineView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } /** * 初始化操作 * * @param context * @param attrs */ private void init(Context context, AttributeSet attrs) { this.mContext = context; if (attrs != null) { initAttrs(attrs); } initPaints(); setAttrsPrority(); } /** * 设置属性优先级 */ private void setAttrsPrority() { if (width == -1) { width = DisplayUtil.dp2px(mContext, DEFAULT_WIDTH); } if (height == -1) { height = DisplayUtil.dp2px(mContext, DEFAULT_HEIGHT); } if (textSize == -1) { textSize = DisplayUtil.sp2px(mContext, TEXT_SIZE); } if (temp2Top == -1) { temp2Top = DisplayUtil.dp2px(mContext, TEMP2TOP); } if (temp2Dot == -1) { temp2Dot = DisplayUtil.dp2px(mContext, TEMP2DOT); } if (dotRadisu == -1) { dotRadisu = DisplayUtil.dp2px(mContext, DEFAULT_DOT_RADIUS); } } /** * 初始化画笔 */ private void initPaints() { mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDotPaint.setStyle(Paint.Style.FILL); mDotPaint.setColor(Color.WHITE); mTempPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTempPaint.setColor(Color.WHITE); mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLinePaint.setStyle(Paint.Style.FILL); mLinePaint.setStrokeWidth(DisplayUtil.dp2px(mContext, 1f)); mLinePaint.setColor(Color.WHITE); mLinePaint.setAlpha(100); } /** * 设置属性值 * * @param attrs */ private void initAttrs(AttributeSet attrs) { TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.WeatherLineView); int count = typedArray.getIndexCount(); for (int i = 0; i < count; i++) { int attr = typedArray.getIndex(i); if (attr == R.styleable.WeatherLineView_tempSize) { textSize = typedArray.getDimensionPixelSize(attr, TEXT_SIZE); } } typedArray.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 获取宽高的适配类型,UNSPECIFIED(不受约束),EXACTLY(match_parent),AT_MOST(wrap_content) */ int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthResult = getSize(widthSize, widthMode, 0); int heightResult = getSize(heightSize, heightMode, 1); setMeasuredDimension(widthResult, heightResult); } /** * @param size 宽/高大小 * @param sizeMode 测量mode * @param type 0=width 1=height * @return */ private int getSize(int size, int sizeMode, int type) { int result = -1; if (sizeMode == MeasureSpec.EXACTLY) { result = size; } else { if (type == 0) { result = width + getPaddingLeft() + getPaddingRight(); } else { result = height + getPaddingBottom() + getPaddingTop(); } if (sizeMode == MeasureSpec.AT_MOST) { result = Math.min(size, result); } } return result; } private int w, h; private int baseY; private int heightPerTemp;//温度每一度需要的高度 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (minTemp >= maxTemp) { Log.e(TAG, "maxTemp=" + maxTemp + ";minTemp=" + minTemp + ";最低温度小于或等于最高温度了,这是不允许的"); return; } mTempPaint.setTextSize(textSize); fontMetrics = mTempPaint.getFontMetrics(); //返回view的宽高 w = getWidth(); h = getHeight(); //baseY表示文字距离顶部(上面的温度)/底部(下面的温度)+文字和dot的距离以及文字本身的高度 baseY = temp2Top + temp2Dot + (int) (fontMetrics.bottom - fontMetrics.ascent); //baseHeight表示的是两个温度点的直径+两个点之间的距离,包含4各dotRadius int baseHeight = h - 2 * baseY; heightPerTemp = baseHeight / (maxTemp - minTemp); //******************************************************************************************************* T t = datas.get(position); Point[] dotPoints = getDotPoints(t); drawDots(canvas, dotPoints); Point[] tempBaseLinePoints = getTempBaseLinePoints(t, dotPoints); drawTempText(tempBaseLinePoints, canvas, t); //position>0的点都需要话左边的线 if (position > 0) { T preT = datas.get(position - 1); Point[] leftPoints = getLeftPoints(dotPoints, preT); drawLine(dotPoints, leftPoints, canvas); } //只要不是最右边的点都需要话右边的线 if (position < datas.size() - 1) { T nextT = datas.get(position + 1); Point[] rightPoints = getRightPoints(dotPoints, nextT); drawLine(dotPoints, rightPoints, canvas); } } private void drawLine(Point[] startPoints, Point[] endPoints, Canvas canvas) { canvas.drawLine(startPoints[0].x, startPoints[0].y, endPoints[0].x, endPoints[0].y, mLinePaint); canvas.drawLine(startPoints[1].x, startPoints[1].y, endPoints[1].x, endPoints[1].y, mLinePaint); } /** * 计算下一天的温度点坐标 * * @param dotPoints * @param nextT * @return */ private Point[] getRightPoints(Point[] dotPoints, T nextT) { Point[] points = new Point[2]; Point[] prePoints = getDotPoints(nextT); //这里的计算,就是连接两个点,和两个view交接相交的点的坐标,然后两边都连接到这个点,因为是计算的是当前坐标的连线点,在当前view的左边界,所以x坐标就是0 points[0] = new Point(w, (dotPoints[0].y + prePoints[0].y) / 2); points[1] = new Point(w, (dotPoints[1].y + prePoints[1].y) / 2); return points; } /** * 计算前一天的温度点的坐标 * * @param dotPoints * @param preT * @return */ private Point[] getLeftPoints(Point[] dotPoints, T preT) { Point[] points = new Point[2]; Point[] prePoints = getDotPoints(preT); //这里的计算,就是连接两个点,和两个view交接相交的点的坐标,然后两边都连接到这个点,因为是计算的是当前坐标的连线点,在当前view的左边界,所以x坐标就是0 points[0] = new Point(0, (dotPoints[0].y + prePoints[0].y) / 2); points[1] = new Point(0, (dotPoints[1].y + prePoints[1].y) / 2); return points; } /** * 画温度文本 * * @param tempBaseLinePoints * @param canvas * @param t */ private void drawTempText(Point[] tempBaseLinePoints, Canvas canvas, T t) { canvas.drawText(t.getMaxTemp() + "℃", tempBaseLinePoints[0].x, tempBaseLinePoints[0].y, mTempPaint); canvas.drawText(t.getMinTemp() + "℃", tempBaseLinePoints[1].x, tempBaseLinePoints[1].y, mTempPaint); } /** * 温度文字的起始坐标 * * @param t * @param dotPoints * @return */ private Point[] getTempBaseLinePoints(T t, Point[] dotPoints) { Point[] points = new Point[2]; //通过计算上面点的纵坐标减去点的半径再减去文字距离点的距离就是文字的纵坐标 int topY = dotPoints[0].y - dotRadisu - temp2Dot; int topX = (w - (int) mTempPaint.measureText(t.getMaxTemp() + "")) / 2; Point topTemp = new Point(topX, topY); points[0] = topTemp; int bottomTempHeight = Math.abs((int) (fontMetrics.bottom - fontMetrics.ascent)); int bottomY = dotPoints[1].y + dotRadisu + temp2Dot + bottomTempHeight / 3 * 2; int bottomX = (w - (int) mTempPaint.measureText(t.getMinTemp() + "")) / 2; Point bottomTemp = new Point(bottomX, bottomY); points[1] = bottomTemp; return points; } /** * 画温度点 * * @param canvas * @param points */ private void drawDots(Canvas canvas, Point[] points) { canvas.drawCircle(points[0].x, points[0].y, dotRadisu, mDotPaint); canvas.drawCircle(points[1].x, points[1].y, dotRadisu, mDotPaint); } /** * 计算当天(不是指今天)温度的坐标 * * @param t * @return */ private Point[] getDotPoints(T t) { Point[] points = new Point[2]; //上面的点纵坐标 int topY = baseY + dotRadisu + (maxTemp - t.getMaxTemp()) * heightPerTemp; Point topPoint = new Point(w / 2, topY); //下面点的纵坐标 int bottomY = topY + (t.getMaxTemp() - t.getMinTemp()) * heightPerTemp; Point bottomPoint = new Point(w / 2, bottomY); points[0] = topPoint; points[1] = bottomPoint; return points; } }
UTF-8
Java
12,873
java
WeatherLineView.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * author: lzy\n * date: 2020/8/20\n * describe:温度双曲线\n */\npublic c", "end": 541, "score": 0.9996075630187988, "start": 538, "tag": "USERNAME", "value": "lzy" } ]
null
[]
package com.cvilia.bubble.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.annotation.Nullable; import com.cvilia.bubble.R; import com.cvilia.bubble.listener.ITempData; import com.cvilia.bubble.utils.DisplayUtil; import java.util.ArrayList; import java.util.List; /** * author: lzy * date: 2020/8/20 * describe:温度双曲线 */ public class WeatherLineView<T extends ITempData> extends View { private static final String TAG = WeatherLineView.class.getSimpleName(); private Context mContext; //温度,点,线的画笔 private Paint mTempPaint, mDotPaint, mLinePaint; private static final int TEMP2TOP = 8; private static final int TEMP2DOT = 5; private int temp2Top = -1;//表示文字距离view顶部/底部的高度 private int temp2Dot = -1;//文字和温度点的距离 private static final int DEFAULT_DOT_RADIUS = 2; private int dotRadisu = -1; //字体默认大小 private static final int TEXT_SIZE = 12; private int textSize = -1; private List<T> datas = new ArrayList<>(); //整个集合中的最高最低温度 private int maxTemp, minTemp; //当前信息在集合中的位置 private int position; private Paint.FontMetrics fontMetrics; private static final int DEFAULT_HEIGHT = 100; private static final int DEFAULT_WIDTH = 60; //整个view的宽高 private int width = -1; private int height = -1; public void setDatas(List<T> datas, int position) { this.datas = datas; this.position = position; getExtremeTemp(datas); postInvalidate(); } /** * 计算最大和最小天气 * * @param infos */ private void getExtremeTemp(List<T> infos) { int[] heigh = new int[infos.size()]; int[] low = new int[infos.size()]; for (int i = 0; i < infos.size(); i++) { heigh[i] = infos.get(i).getMaxTemp(); low[i] = infos.get(i).getMinTemp(); } int[] array = new int[heigh.length + low.length]; for (int i = 0; i < infos.size() * 2; i++) { if (i < infos.size()) { array[i] = heigh[i]; } else { array[i] = low[i - infos.size()]; } } this.maxTemp = result(array, true); this.minTemp = result(array, false); } /** * 冒泡排序求最大最小值 * * @param nums * @param needMax * @return */ private int result(int[] nums, boolean needMax) { for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - 1 - i; j++) { if (nums[j] > nums[j + 1]) { int s = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = s; } } } for (int temp : nums) { System.out.print(temp + "---"); } return needMax ? nums[nums.length - 1] : nums[0]; } public WeatherLineView(Context context) { super(context); init(context, null); } public WeatherLineView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } /** * 初始化操作 * * @param context * @param attrs */ private void init(Context context, AttributeSet attrs) { this.mContext = context; if (attrs != null) { initAttrs(attrs); } initPaints(); setAttrsPrority(); } /** * 设置属性优先级 */ private void setAttrsPrority() { if (width == -1) { width = DisplayUtil.dp2px(mContext, DEFAULT_WIDTH); } if (height == -1) { height = DisplayUtil.dp2px(mContext, DEFAULT_HEIGHT); } if (textSize == -1) { textSize = DisplayUtil.sp2px(mContext, TEXT_SIZE); } if (temp2Top == -1) { temp2Top = DisplayUtil.dp2px(mContext, TEMP2TOP); } if (temp2Dot == -1) { temp2Dot = DisplayUtil.dp2px(mContext, TEMP2DOT); } if (dotRadisu == -1) { dotRadisu = DisplayUtil.dp2px(mContext, DEFAULT_DOT_RADIUS); } } /** * 初始化画笔 */ private void initPaints() { mDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDotPaint.setStyle(Paint.Style.FILL); mDotPaint.setColor(Color.WHITE); mTempPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTempPaint.setColor(Color.WHITE); mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLinePaint.setStyle(Paint.Style.FILL); mLinePaint.setStrokeWidth(DisplayUtil.dp2px(mContext, 1f)); mLinePaint.setColor(Color.WHITE); mLinePaint.setAlpha(100); } /** * 设置属性值 * * @param attrs */ private void initAttrs(AttributeSet attrs) { TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.WeatherLineView); int count = typedArray.getIndexCount(); for (int i = 0; i < count; i++) { int attr = typedArray.getIndex(i); if (attr == R.styleable.WeatherLineView_tempSize) { textSize = typedArray.getDimensionPixelSize(attr, TEXT_SIZE); } } typedArray.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 获取宽高的适配类型,UNSPECIFIED(不受约束),EXACTLY(match_parent),AT_MOST(wrap_content) */ int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthResult = getSize(widthSize, widthMode, 0); int heightResult = getSize(heightSize, heightMode, 1); setMeasuredDimension(widthResult, heightResult); } /** * @param size 宽/高大小 * @param sizeMode 测量mode * @param type 0=width 1=height * @return */ private int getSize(int size, int sizeMode, int type) { int result = -1; if (sizeMode == MeasureSpec.EXACTLY) { result = size; } else { if (type == 0) { result = width + getPaddingLeft() + getPaddingRight(); } else { result = height + getPaddingBottom() + getPaddingTop(); } if (sizeMode == MeasureSpec.AT_MOST) { result = Math.min(size, result); } } return result; } private int w, h; private int baseY; private int heightPerTemp;//温度每一度需要的高度 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (minTemp >= maxTemp) { Log.e(TAG, "maxTemp=" + maxTemp + ";minTemp=" + minTemp + ";最低温度小于或等于最高温度了,这是不允许的"); return; } mTempPaint.setTextSize(textSize); fontMetrics = mTempPaint.getFontMetrics(); //返回view的宽高 w = getWidth(); h = getHeight(); //baseY表示文字距离顶部(上面的温度)/底部(下面的温度)+文字和dot的距离以及文字本身的高度 baseY = temp2Top + temp2Dot + (int) (fontMetrics.bottom - fontMetrics.ascent); //baseHeight表示的是两个温度点的直径+两个点之间的距离,包含4各dotRadius int baseHeight = h - 2 * baseY; heightPerTemp = baseHeight / (maxTemp - minTemp); //******************************************************************************************************* T t = datas.get(position); Point[] dotPoints = getDotPoints(t); drawDots(canvas, dotPoints); Point[] tempBaseLinePoints = getTempBaseLinePoints(t, dotPoints); drawTempText(tempBaseLinePoints, canvas, t); //position>0的点都需要话左边的线 if (position > 0) { T preT = datas.get(position - 1); Point[] leftPoints = getLeftPoints(dotPoints, preT); drawLine(dotPoints, leftPoints, canvas); } //只要不是最右边的点都需要话右边的线 if (position < datas.size() - 1) { T nextT = datas.get(position + 1); Point[] rightPoints = getRightPoints(dotPoints, nextT); drawLine(dotPoints, rightPoints, canvas); } } private void drawLine(Point[] startPoints, Point[] endPoints, Canvas canvas) { canvas.drawLine(startPoints[0].x, startPoints[0].y, endPoints[0].x, endPoints[0].y, mLinePaint); canvas.drawLine(startPoints[1].x, startPoints[1].y, endPoints[1].x, endPoints[1].y, mLinePaint); } /** * 计算下一天的温度点坐标 * * @param dotPoints * @param nextT * @return */ private Point[] getRightPoints(Point[] dotPoints, T nextT) { Point[] points = new Point[2]; Point[] prePoints = getDotPoints(nextT); //这里的计算,就是连接两个点,和两个view交接相交的点的坐标,然后两边都连接到这个点,因为是计算的是当前坐标的连线点,在当前view的左边界,所以x坐标就是0 points[0] = new Point(w, (dotPoints[0].y + prePoints[0].y) / 2); points[1] = new Point(w, (dotPoints[1].y + prePoints[1].y) / 2); return points; } /** * 计算前一天的温度点的坐标 * * @param dotPoints * @param preT * @return */ private Point[] getLeftPoints(Point[] dotPoints, T preT) { Point[] points = new Point[2]; Point[] prePoints = getDotPoints(preT); //这里的计算,就是连接两个点,和两个view交接相交的点的坐标,然后两边都连接到这个点,因为是计算的是当前坐标的连线点,在当前view的左边界,所以x坐标就是0 points[0] = new Point(0, (dotPoints[0].y + prePoints[0].y) / 2); points[1] = new Point(0, (dotPoints[1].y + prePoints[1].y) / 2); return points; } /** * 画温度文本 * * @param tempBaseLinePoints * @param canvas * @param t */ private void drawTempText(Point[] tempBaseLinePoints, Canvas canvas, T t) { canvas.drawText(t.getMaxTemp() + "℃", tempBaseLinePoints[0].x, tempBaseLinePoints[0].y, mTempPaint); canvas.drawText(t.getMinTemp() + "℃", tempBaseLinePoints[1].x, tempBaseLinePoints[1].y, mTempPaint); } /** * 温度文字的起始坐标 * * @param t * @param dotPoints * @return */ private Point[] getTempBaseLinePoints(T t, Point[] dotPoints) { Point[] points = new Point[2]; //通过计算上面点的纵坐标减去点的半径再减去文字距离点的距离就是文字的纵坐标 int topY = dotPoints[0].y - dotRadisu - temp2Dot; int topX = (w - (int) mTempPaint.measureText(t.getMaxTemp() + "")) / 2; Point topTemp = new Point(topX, topY); points[0] = topTemp; int bottomTempHeight = Math.abs((int) (fontMetrics.bottom - fontMetrics.ascent)); int bottomY = dotPoints[1].y + dotRadisu + temp2Dot + bottomTempHeight / 3 * 2; int bottomX = (w - (int) mTempPaint.measureText(t.getMinTemp() + "")) / 2; Point bottomTemp = new Point(bottomX, bottomY); points[1] = bottomTemp; return points; } /** * 画温度点 * * @param canvas * @param points */ private void drawDots(Canvas canvas, Point[] points) { canvas.drawCircle(points[0].x, points[0].y, dotRadisu, mDotPaint); canvas.drawCircle(points[1].x, points[1].y, dotRadisu, mDotPaint); } /** * 计算当天(不是指今天)温度的坐标 * * @param t * @return */ private Point[] getDotPoints(T t) { Point[] points = new Point[2]; //上面的点纵坐标 int topY = baseY + dotRadisu + (maxTemp - t.getMaxTemp()) * heightPerTemp; Point topPoint = new Point(w / 2, topY); //下面点的纵坐标 int bottomY = topY + (t.getMaxTemp() - t.getMinTemp()) * heightPerTemp; Point bottomPoint = new Point(w / 2, bottomY); points[0] = topPoint; points[1] = bottomPoint; return points; } }
12,873
0.569549
0.558414
417
27.429256
25.357405
113
false
false
0
0
0
0
0
0
0.585132
false
false
9
57b6c89855576cd86a9779ba6c20ed844916bd5f
23,287,312,681,990
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/14/14_6eed8b498bc414ff529a3abfe0df4639f05e0278/MathUtils/14_6eed8b498bc414ff529a3abfe0df4639f05e0278_MathUtils_t.java
b3da889bb8eee5a38e4f9439583f14b7c21cca47
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/* * This file is part of Movecraft. * * Movecraft is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Movecraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Movecraft. If not, see <http://www.gnu.org/licenses/>. */ package net.countercraft.movecraft.utils; import org.bukkit.Location; public class MathUtils { public static boolean playerIsWithinBoundingPolygon( int[][][] box, int minX, int minZ, MovecraftLocation l ) { if ( l.getX() >= minX && l.getX() < ( minX + box.length ) ) { // PLayer is within correct X boundary if ( l.getZ() >= minZ && l.getZ() < ( minZ + box[l.getX() - minX].length ) ) { // Player is within valid Z boundary int minY, maxY; try { minY = box[l.getX() - minX][l.getZ() - minZ][0]; maxY = box[l.getX() - minX][l.getZ() - minZ][1]; } catch ( NullPointerException e ) { return false; } if ( l.getY() >= minY && l.getY() <= ( maxY + 2 ) ) { // Player is on board the vessel return true; } } } return false; } public static MovecraftLocation bukkit2MovecraftLoc( Location l ) { return new MovecraftLocation( l.getBlockX(), l.getBlockY(), l.getBlockZ() ); } public static MovecraftLocation rotateVec( Rotation r, MovecraftLocation l ) { MovecraftLocation newLocation = new MovecraftLocation( 0, l.getY(), 0 ); double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } int x = ( int ) Math.round( ( l.getX() * Math.cos( theta ) ) + ( l.getZ() * ( -1 * Math.sin( theta ) ) ) ); int z = ( int ) Math.round( ( l.getX() * Math.sin( theta ) ) + ( l.getZ() * Math.cos( theta ) ) ); newLocation.setX( x ); newLocation.setZ( z ); return newLocation; } public static double[] rotateVec( Rotation r, double x, double z ) { double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } double newX = Math.round( ( x * Math.cos( theta ) ) + ( z * ( -1 * Math.sin( theta ) ) ) ); double newZ = Math.round( ( x * Math.sin( theta ) ) + ( z * Math.cos( theta ) ) ); return new double[]{ newX, newZ }; } public static double[] rotateVecNoRound( Rotation r, double x, double z ) { double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } double newX = ( x * Math.cos( theta ) ) + ( z * ( -1 * Math.sin( theta ) ) ) ; double newZ = ( x * Math.sin( theta ) ) + ( z * Math.cos( theta ) ) ; return new double[]{ newX, newZ }; } public static int positiveMod( int mod, int divisor ) { if ( mod < 0 ) { mod += divisor; } return mod; } }
UTF-8
Java
3,272
java
14_6eed8b498bc414ff529a3abfe0df4639f05e0278_MathUtils_t.java
Java
[]
null
[]
/* * This file is part of Movecraft. * * Movecraft is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Movecraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Movecraft. If not, see <http://www.gnu.org/licenses/>. */ package net.countercraft.movecraft.utils; import org.bukkit.Location; public class MathUtils { public static boolean playerIsWithinBoundingPolygon( int[][][] box, int minX, int minZ, MovecraftLocation l ) { if ( l.getX() >= minX && l.getX() < ( minX + box.length ) ) { // PLayer is within correct X boundary if ( l.getZ() >= minZ && l.getZ() < ( minZ + box[l.getX() - minX].length ) ) { // Player is within valid Z boundary int minY, maxY; try { minY = box[l.getX() - minX][l.getZ() - minZ][0]; maxY = box[l.getX() - minX][l.getZ() - minZ][1]; } catch ( NullPointerException e ) { return false; } if ( l.getY() >= minY && l.getY() <= ( maxY + 2 ) ) { // Player is on board the vessel return true; } } } return false; } public static MovecraftLocation bukkit2MovecraftLoc( Location l ) { return new MovecraftLocation( l.getBlockX(), l.getBlockY(), l.getBlockZ() ); } public static MovecraftLocation rotateVec( Rotation r, MovecraftLocation l ) { MovecraftLocation newLocation = new MovecraftLocation( 0, l.getY(), 0 ); double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } int x = ( int ) Math.round( ( l.getX() * Math.cos( theta ) ) + ( l.getZ() * ( -1 * Math.sin( theta ) ) ) ); int z = ( int ) Math.round( ( l.getX() * Math.sin( theta ) ) + ( l.getZ() * Math.cos( theta ) ) ); newLocation.setX( x ); newLocation.setZ( z ); return newLocation; } public static double[] rotateVec( Rotation r, double x, double z ) { double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } double newX = Math.round( ( x * Math.cos( theta ) ) + ( z * ( -1 * Math.sin( theta ) ) ) ); double newZ = Math.round( ( x * Math.sin( theta ) ) + ( z * Math.cos( theta ) ) ); return new double[]{ newX, newZ }; } public static double[] rotateVecNoRound( Rotation r, double x, double z ) { double theta; if ( r == Rotation.CLOCKWISE ) { theta = 0.5 * Math.PI; } else { theta = -1 * 0.5 * Math.PI; } double newX = ( x * Math.cos( theta ) ) + ( z * ( -1 * Math.sin( theta ) ) ) ; double newZ = ( x * Math.sin( theta ) ) + ( z * Math.cos( theta ) ) ; return new double[]{ newX, newZ }; } public static int positiveMod( int mod, int divisor ) { if ( mod < 0 ) { mod += divisor; } return mod; } }
3,272
0.58588
0.577934
110
28.736364
30.538702
113
false
false
0
0
0
0
0
0
1.909091
false
false
9
0e0e92499fe76f98f0d3b2fdc6b42576cd5e255a
23,287,312,680,641
aa13a4f50292da99985c6d8a431ad9328f972988
/String/Convert_to_Roman_No.java
ef7ea24bb4d636e31f5ed2aa355bf87d6df34d66
[]
no_license
AkashIngole/Must-Do-Coding-Questions-for-Companies
https://github.com/AkashIngole/Must-Do-Coding-Questions-for-Companies
ad5e142ea13e759c0b88c7aee7b6348e49d3c996
0ea901c71f1cb5c3bdbcfedb04fa7e8efff17249
refs/heads/main
2023-02-12T17:46:51.948000
2021-01-08T17:02:26
2021-01-08T17:02:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class NoToRoman{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int N = sc.nextInt(); GfG g = new GfG(); System.out.println (g.convertToRoman(N)); t--; } } } class GfG{ String convertToRoman(int n){ LinkedHashMap<String, Integer> roman_numerals = new LinkedHashMap<String, Integer>(); roman_numerals.put("M", 1000); roman_numerals.put("CM", 900); roman_numerals.put("D", 500); roman_numerals.put("CD", 400); roman_numerals.put("C", 100); roman_numerals.put("XC", 90); roman_numerals.put("L", 50); roman_numerals.put("XL", 40); roman_numerals.put("X", 10); roman_numerals.put("IX", 9); roman_numerals.put("V", 5); roman_numerals.put("IV", 4); roman_numerals.put("I", 1); String roman = ""; for( Map.Entry<String, Integer> ent : roman_numerals.entrySet() ){ int match = n / ent.getValue(); roman += repeat(ent.getKey(), match); n %= ent.getValue(); } return roman; } public static String repeat(String m, int n){ if( m == null ){ return null; } final StringBuilder sb = new StringBuilder(); for(int i = 0; i<n; i++){ sb.append(m); } return sb.toString(); } }
UTF-8
Java
1,529
java
Convert_to_Roman_No.java
Java
[]
null
[]
import java.util.*; class NoToRoman{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int N = sc.nextInt(); GfG g = new GfG(); System.out.println (g.convertToRoman(N)); t--; } } } class GfG{ String convertToRoman(int n){ LinkedHashMap<String, Integer> roman_numerals = new LinkedHashMap<String, Integer>(); roman_numerals.put("M", 1000); roman_numerals.put("CM", 900); roman_numerals.put("D", 500); roman_numerals.put("CD", 400); roman_numerals.put("C", 100); roman_numerals.put("XC", 90); roman_numerals.put("L", 50); roman_numerals.put("XL", 40); roman_numerals.put("X", 10); roman_numerals.put("IX", 9); roman_numerals.put("V", 5); roman_numerals.put("IV", 4); roman_numerals.put("I", 1); String roman = ""; for( Map.Entry<String, Integer> ent : roman_numerals.entrySet() ){ int match = n / ent.getValue(); roman += repeat(ent.getKey(), match); n %= ent.getValue(); } return roman; } public static String repeat(String m, int n){ if( m == null ){ return null; } final StringBuilder sb = new StringBuilder(); for(int i = 0; i<n; i++){ sb.append(m); } return sb.toString(); } }
1,529
0.501635
0.482014
53
27.867924
18.548292
93
false
false
0
0
0
0
0
0
0.943396
false
false
9
73ce94810bfb358d563617f8ddc51807bceb9768
22,866,405,946,244
e9a3fd0783915a1f6cd1304c3dea554291153594
/app/src/main/java/com/example/sameershekhar/locationalarm/RetrofitMaps.java
fa63cced65d12825271bf951386e88d0bd5dce27
[]
no_license
sameershekhar/LocationAlarm
https://github.com/sameershekhar/LocationAlarm
edca54a0e1c51b5b38f6e1008fcbc2649a27f1e9
fc3575b0591ef5d45ff761e43eccbba69bfad3a3
refs/heads/master
2020-03-18T02:15:24.403000
2018-05-20T19:56:25
2018-05-20T19:56:25
134,181,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sameershekhar.locationalarm; /** * Created by sameershekhar on 17-Mar-18. */ import com.example.sameershekhar.locationalarm.POJO.Example; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by navneet on 17/7/16. */ public interface RetrofitMaps { /* * Retrofit get annotation with our URL * And our method that will return us details of student. */ @GET("api/directions/json?key=AIzaSyBVlKnLIjspl6T494UKmUuO74RDmf0FPD4") Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode); } /*<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/deletebutton" android:layout_below="@+id/time" android:layout_marginTop="@dimen/mg10dp" android:layout_marginRight="@dimen/mg10dp" android:layout_alignParentRight="true" android:layout_width="24dp" android:layout_height="24dp" android:src="@drawable/delete" app:civ_border_width="2dp" app:civ_border_color="#3ea416"/>*/
UTF-8
Java
1,261
java
RetrofitMaps.java
Java
[ { "context": "le.sameershekhar.locationalarm;\n\n/**\n * Created by sameershekhar on 17-Mar-18.\n */\n\nimport com.example.sameershekh", "end": 81, "score": 0.997506320476532, "start": 68, "tag": "USERNAME", "value": "sameershekhar" }, { "context": "T;\nimport retrofit2.http.Query;\n...
null
[]
package com.example.sameershekhar.locationalarm; /** * Created by sameershekhar on 17-Mar-18. */ import com.example.sameershekhar.locationalarm.POJO.Example; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by navneet on 17/7/16. */ public interface RetrofitMaps { /* * Retrofit get annotation with our URL * And our method that will return us details of student. */ @GET("api/directions/json?key=<KEY>") Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode); } /*<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/deletebutton" android:layout_below="@+id/time" android:layout_marginTop="@dimen/mg10dp" android:layout_marginRight="@dimen/mg10dp" android:layout_alignParentRight="true" android:layout_width="24dp" android:layout_height="24dp" android:src="@drawable/delete" app:civ_border_width="2dp" app:civ_border_color="#3ea416"/>*/
1,227
0.670103
0.643933
40
30.525
32.003117
170
false
false
0
0
0
0
0
0
0.225
false
false
9
28c78447c676744ae87110d4531478d9897f6974
29,927,332,120,126
5bdfc9c50a9ea9093489ff4b6c32ffcb52897fda
/fins-service-core/src/main/java/com/cgi/horizon/core/json/JsonObjectMapperAdapter.java
b855624e3d327ac41a9dd4b929ed4498d4ce4c6a
[]
no_license
vijaypolsani/fins
https://github.com/vijaypolsani/fins
59f946959b9af39f988b915dd5a225221483bf17
fd4de61dac51018c359f60384576d0a13828ee73
refs/heads/master
2015-08-10T03:51:32.954000
2014-01-21T03:00:17
2014-01-21T03:00:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cgi.horizon.core.json; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Type; /** * Simple {@linkplain JsonObjectMapper} adapter implementation, if there is no need * to provide entire operations implementation. * */ public abstract class JsonObjectMapperAdapter<P> implements JsonObjectMapper<P> { public String toJson(Object value) throws Exception { return null; } public void toJson(Object value, Writer writer) throws Exception { } public <T> T fromJson(String json, Class<T> valueType) throws Exception { return null; } public <T> T fromJson(Reader json, Class<T> valueType) throws Exception { return null; } public <T> T fromJson(P parser, Type valueType) throws Exception { return null; } }
UTF-8
Java
763
java
JsonObjectMapperAdapter.java
Java
[]
null
[]
package com.cgi.horizon.core.json; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Type; /** * Simple {@linkplain JsonObjectMapper} adapter implementation, if there is no need * to provide entire operations implementation. * */ public abstract class JsonObjectMapperAdapter<P> implements JsonObjectMapper<P> { public String toJson(Object value) throws Exception { return null; } public void toJson(Object value, Writer writer) throws Exception { } public <T> T fromJson(String json, Class<T> valueType) throws Exception { return null; } public <T> T fromJson(Reader json, Class<T> valueType) throws Exception { return null; } public <T> T fromJson(P parser, Type valueType) throws Exception { return null; } }
763
0.741809
0.741809
33
22.121212
28.180971
83
false
false
0
0
0
0
0
0
0.939394
false
false
9
1534cd06e2a7426fd6cb2db73e6bf049450b1ff1
33,028,298,527,301
7e500711df75d02a18a9f20e6dee0bdbf57c7ffe
/src/main/java/edu/bsuir/utils/ParseUtil.java
6d0cfff97368c089df2541a1338708015be706e9
[]
no_license
fast-foot/jsf-project
https://github.com/fast-foot/jsf-project
bc21c82542ab45a7ee48c6fae6e61df2279f8923
467c8693a9ce3dfd7a991967e909bf0a8ba4a488
refs/heads/master
2021-01-13T14:10:19.622000
2016-12-11T11:44:31
2016-12-11T11:44:31
76,165,995
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.bsuir.utils; import edu.bsuir.model.Film; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; /** * Created by Alesha on 01.10.2016. */ public class ParseUtil { public static boolean isNumber(String str) { return str.matches("[-+]?\\d+"); } public static void writeIntoExcel(List<Film> list) throws FileNotFoundException, IOException { File file = new File("D:\\example.xlsx"); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet(); for (int i = 0; i < list.size(); i++) { Row row = sheet.createRow(i); row.createCell(0).setCellValue(list.get(i).getName()); row.createCell(1).setCellValue(list.get(i).getCountry()); row.createCell(2).setCellValue(list.get(i).getYear().toString()); row.createCell(3).setCellValue(list.get(i).getDuration().toString()); } FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); } }
UTF-8
Java
1,195
java
ParseUtil.java
Java
[ { "context": "ception;\nimport java.util.List;\n\n/**\n * Created by Alesha on 01.10.2016.\n */\npublic class ParseUtil {\n\n ", "end": 313, "score": 0.9690894484519958, "start": 307, "tag": "NAME", "value": "Alesha" } ]
null
[]
package edu.bsuir.utils; import edu.bsuir.model.Film; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; /** * Created by Alesha on 01.10.2016. */ public class ParseUtil { public static boolean isNumber(String str) { return str.matches("[-+]?\\d+"); } public static void writeIntoExcel(List<Film> list) throws FileNotFoundException, IOException { File file = new File("D:\\example.xlsx"); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet(); for (int i = 0; i < list.size(); i++) { Row row = sheet.createRow(i); row.createCell(0).setCellValue(list.get(i).getName()); row.createCell(1).setCellValue(list.get(i).getCountry()); row.createCell(2).setCellValue(list.get(i).getYear().toString()); row.createCell(3).setCellValue(list.get(i).getDuration().toString()); } FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); } }
1,195
0.646025
0.635146
37
31.297297
25.362097
98
false
false
0
0
0
0
0
0
0.648649
false
false
9
7f671bf6ff98d7cffeaaab8ffe5292fd63344112
5,978,594,479,045
9fe2bbe7434a1c4a98500f644c324f830142853d
/miniProjects/shapes-demo/shapes/ShapeFactory.java
979d11ce9a5265582d9dfed5d1167b7f7e72a707
[]
no_license
sjoseph11236/woz-u-tutorial
https://github.com/sjoseph11236/woz-u-tutorial
7b4f612dc94ff4a92da56283137d79d1b9d46112
7f39a49716b89de8c50c344f63657123f83e5ecf
refs/heads/master
2022-12-30T22:06:00.216000
2020-06-03T04:58:39
2020-06-03T04:58:39
261,800,685
0
0
null
false
2020-10-13T22:09:16
2020-05-06T15:26:00
2020-06-03T04:51:42
2020-10-13T22:09:15
8,445
0
0
1
Java
false
false
package shapes; public class ShapeFactory { public Shape getShape(ShapeOptions shapeType) { if(ShapeOptions.CIRCLE == shapeType) { return new Circle(); } else if(ShapeOptions.RECTANGLE== shapeType) { return new Rectangle(); } else if(ShapeOptions.SQUARE == shapeType) { return new Square(); } else { return null; } } }
UTF-8
Java
387
java
ShapeFactory.java
Java
[]
null
[]
package shapes; public class ShapeFactory { public Shape getShape(ShapeOptions shapeType) { if(ShapeOptions.CIRCLE == shapeType) { return new Circle(); } else if(ShapeOptions.RECTANGLE== shapeType) { return new Rectangle(); } else if(ShapeOptions.SQUARE == shapeType) { return new Square(); } else { return null; } } }
387
0.609819
0.609819
21
17.476191
17.02832
49
false
false
0
0
0
0
0
0
0.238095
false
false
9
ba7744fcaff7882bce72a2f4c03a07cb8d849a8d
10,634,339,061,361
be1eff7c1f0e5ef30293917409a4c259f304d0dd
/app/src/main/java/com/example/xisco/missatgeria/EnviarMissatge.java
5c75e84b00b3ad3e42cb2513e2a5b02bab5d11e7
[]
no_license
iespaucasesnoves/missatgeria-FranciscoComasGomez
https://github.com/iespaucasesnoves/missatgeria-FranciscoComasGomez
ab39fd0cf194fba970a1e922cd6be0bdc2bf8b2f
5c225cfe7d4ee9c66011bd1618edf604af6e9340
refs/heads/master
2020-04-23T22:50:15.732000
2019-03-15T11:01:56
2019-03-15T11:01:56
171,515,290
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.xisco.missatgeria; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public class EnviarMissatge extends AsyncTask<String, String, String> { public static String res = ""; HashMap<String, String> missatge; Context context; public EnviarMissatge(HashMap<String, String> missatge, Context context){ this.missatge = missatge; this.context = context; } private static String montaParametres(HashMap<String, String> params) throws UnsupportedEncodingException { // A partir d'un hashmap clau-valor cream // clau1=valor1&clau2=valor2&... StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) { first = false;} else {result.append("&");} result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } @Override protected String doInBackground(String... strings) { String resultat=""; try { URL url = new URL(strings[0]); Log.i("ResSendUtils", "Connectant "+strings[0]); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setReadTimeout(15000); httpConn.setConnectTimeout(25000); httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); OutputStream os = httpConn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(montaParametres(this.missatge)); writer.flush(); writer.close(); os.close(); int resposta = httpConn.getResponseCode(); if (resposta == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(httpConn.getInputStream())); while ((line=br.readLine()) != null) { resultat+=line; } Log.i("ResSendUtils", resultat); } else { resultat=""; Log.i("sSendUtils","Errors:"+resposta); } } catch (Exception ex) { ex.printStackTrace(); } res = resultat; return resultat; } }
UTF-8
Java
3,042
java
EnviarMissatge.java
Java
[]
null
[]
package com.example.xisco.missatgeria; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public class EnviarMissatge extends AsyncTask<String, String, String> { public static String res = ""; HashMap<String, String> missatge; Context context; public EnviarMissatge(HashMap<String, String> missatge, Context context){ this.missatge = missatge; this.context = context; } private static String montaParametres(HashMap<String, String> params) throws UnsupportedEncodingException { // A partir d'un hashmap clau-valor cream // clau1=valor1&clau2=valor2&... StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) { first = false;} else {result.append("&");} result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } @Override protected String doInBackground(String... strings) { String resultat=""; try { URL url = new URL(strings[0]); Log.i("ResSendUtils", "Connectant "+strings[0]); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setReadTimeout(15000); httpConn.setConnectTimeout(25000); httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); OutputStream os = httpConn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(montaParametres(this.missatge)); writer.flush(); writer.close(); os.close(); int resposta = httpConn.getResponseCode(); if (resposta == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(httpConn.getInputStream())); while ((line=br.readLine()) != null) { resultat+=line; } Log.i("ResSendUtils", resultat); } else { resultat=""; Log.i("sSendUtils","Errors:"+resposta); } } catch (Exception ex) { ex.printStackTrace(); } res = resultat; return resultat; } }
3,042
0.609139
0.602893
87
33.965519
21.050268
82
false
false
0
0
0
0
0
0
0.781609
false
false
9
b6e141f699cfd60fcdc0cf8f0bf8092146c68836
21,869,973,488,054
d9d7bf3d0dca265c853cb58c251ecae8390135e0
/gcld/src/com/reign/gcld/blacksmith/dao/PlayerBlacksmithDao.java
51fa1157102a6095bc7fb9f3659c008c665216d3
[]
no_license
Crasader/workspace
https://github.com/Crasader/workspace
4da6bd746a3ae991a5f2457afbc44586689aa9d0
28e26c065a66b480e5e3b966be4871b44981b3d8
refs/heads/master
2020-05-04T21:08:49.911000
2018-11-19T08:14:27
2018-11-19T08:14:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reign.gcld.blacksmith.dao; import com.reign.gcld.blacksmith.domain.*; import org.springframework.stereotype.*; import java.util.*; import com.reign.framework.mybatis.*; @Component("playerBlacksmithDao") public class PlayerBlacksmithDao extends BaseDao<PlayerBlacksmith> implements IPlayerBlacksmithDao { @Override public PlayerBlacksmith read(final int vId) { return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.read", (Object)vId); } @Override public PlayerBlacksmith readForUpdate(final int vId) { return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.readForUpdate", (Object)vId); } @Override public List<PlayerBlacksmith> getModels() { return (List<PlayerBlacksmith>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getModels"); } @Override public int getModelSize() { return (int)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getModelSize"); } @Override public int create(final PlayerBlacksmith playerBlacksmith) { return this.getSqlSession().insert("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.create", playerBlacksmith); } @Override public int deleteById(final int vId) { return this.getSqlSession().delete("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.deleteById", vId); } @Override public List<PlayerBlacksmith> getListByPlayerId(final int playerId) { return (List<PlayerBlacksmith>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getListByPlayerId", (Object)playerId); } @Override public int getSizeByPlayerId(final int playerId) { return (int)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getSizeByPlayerId", (Object)playerId); } @Override public PlayerBlacksmith getByPlayerIdAndSmithId(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getByPlayerIdAndSmithId", (Object)params); } @Override public int addSmithNum(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.addSmithNum", params); } @Override public int useSmithNum(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.useSmithNum", params); } @Override public int addSmithLv(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.addSmithLv", params); } @Override public List<Integer> getPlayerIdListBySmithId(final int smithId) { return (List<Integer>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getPlayerIdListBySmithId", (Object)smithId); } @Override public int resetSmithNum() { return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.resetSmithNum"); } }
UTF-8
Java
3,841
java
PlayerBlacksmithDao.java
Java
[]
null
[]
package com.reign.gcld.blacksmith.dao; import com.reign.gcld.blacksmith.domain.*; import org.springframework.stereotype.*; import java.util.*; import com.reign.framework.mybatis.*; @Component("playerBlacksmithDao") public class PlayerBlacksmithDao extends BaseDao<PlayerBlacksmith> implements IPlayerBlacksmithDao { @Override public PlayerBlacksmith read(final int vId) { return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.read", (Object)vId); } @Override public PlayerBlacksmith readForUpdate(final int vId) { return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.readForUpdate", (Object)vId); } @Override public List<PlayerBlacksmith> getModels() { return (List<PlayerBlacksmith>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getModels"); } @Override public int getModelSize() { return (int)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getModelSize"); } @Override public int create(final PlayerBlacksmith playerBlacksmith) { return this.getSqlSession().insert("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.create", playerBlacksmith); } @Override public int deleteById(final int vId) { return this.getSqlSession().delete("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.deleteById", vId); } @Override public List<PlayerBlacksmith> getListByPlayerId(final int playerId) { return (List<PlayerBlacksmith>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getListByPlayerId", (Object)playerId); } @Override public int getSizeByPlayerId(final int playerId) { return (int)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getSizeByPlayerId", (Object)playerId); } @Override public PlayerBlacksmith getByPlayerIdAndSmithId(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return (PlayerBlacksmith)this.getSqlSession().selectOne("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getByPlayerIdAndSmithId", (Object)params); } @Override public int addSmithNum(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.addSmithNum", params); } @Override public int useSmithNum(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.useSmithNum", params); } @Override public int addSmithLv(final int playerId, final int smithId) { final Params params = new Params(); params.addParam("playerId", playerId); params.addParam("smithId", smithId); return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.addSmithLv", params); } @Override public List<Integer> getPlayerIdListBySmithId(final int smithId) { return (List<Integer>)this.getSqlSession().selectList("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.getPlayerIdListBySmithId", (Object)smithId); } @Override public int resetSmithNum() { return this.getSqlSession().update("com.reign.gcld.blacksmith.domain.PlayerBlacksmith.resetSmithNum"); } }
3,841
0.72377
0.72377
92
40.75
44.42033
160
false
false
0
0
0
0
0
0
0.73913
false
false
9
e74ec9d0800211bb16377362eb940dfee21c0f5b
18,468,359,437,604
88a4fd17e89fd3da7a7d1e286c53cbf968629e4b
/YUS/src/lt/yus/dataService/JsonClient.java
ae15dd6696f41094bcb83216b8e8f0a47762fe72
[]
no_license
sytakeris/yus
https://github.com/sytakeris/yus
04b53d6f20138303f8f4a6d5f6f4514eeba033c5
64b13f8affb255baffcb465157499b0ca083eb11
refs/heads/master
2016-09-09T12:22:42.674000
2014-12-10T22:51:55
2014-12-10T22:51:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lt.yus.dataService; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import lt.yus.data.schedule.BaseHttpClient; import lt.yus.data.schedule.ItemType; import lt.yus.data.schedule.ScheduleDay; import lt.yus.data.schedule.ScheduleItem; import lt.yus.data.schedule.Week; import lt.yus.data.schedule.WeekDays; import lt.yus.helper.FileReader; public class JsonClient extends AsyncTask<Void, Void, List<ScheduleDay>> implements BaseHttpClient { private final String SERVICE_URL = "http://178.62.119.11/getinfo.php"; //JsonScheduleItemFields private final String ITEM_GROUP = "groupName"; private final String ITEM_DAY = "day"; private final String ITEM_LECTNO = "lectNr"; private final String ITEM_WEEK = "week"; private final String ITEM_START_TIME = "startTime"; private final String ITEM_END_TIME = "endTime"; private final String ITEM_SUBGROUP = "subgroup"; private final String ITEM_CLASS = "class"; private final String ITEM_LECTNAME = "lectName"; private final String ITEM_LECTSURNAME = "lectSurname"; private final String ITEM_MODULE = "module"; private final String ITEM_TYPE = "type"; private File groupFile; private Map<String, String> info; InputStream inputStream; boolean groupsWritten; @Override public List<ScheduleDay> getSchedule() { String result = null; if (!groupsWritten) { DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httpPost = new HttpPost(SERVICE_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (Entry<String, String> infoPair : info.entrySet()) { nameValuePairs.add(new BasicNameValuePair(infoPair.getKey(), infoPair.getValue())); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null ) { sb.append(line+"\n"); } result = sb.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (!groupsWritten) { FileReader write = new FileReader(); write.save(result, groupFile); } return generateObjects(result); } @Override public List<String> getGroups(boolean all) { ArrayList<String> grp = new ArrayList<String>(); String result = null; InputStream inputStream = null; DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httpPost = new HttpPost(SERVICE_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("all", "true")); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null ) { sb.append(line+"\n"); } result = sb.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch(Exception e) { } } JSONObject groups; try { groups = new JSONObject(result); JSONArray groupList = groups.getJSONArray("groupName"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return grp; } private List<ScheduleDay> generateObjects(String result) { ArrayList<ScheduleDay> sd = new ArrayList<ScheduleDay>(); try { JSONObject jObject = new JSONObject(result); ScheduleDay tempDay = generateSCDAY(WeekDays.MONDAY, "Pirmadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.TUESDAY, "Antradienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.WEDNESDAY, "Trečiadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.THURSDAY, "Ketvirtadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.FRIDAY, "Penktadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.SATURDAY, "Šeštadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.SUNDAY, "Sekmadienis", jObject); if (tempDay != null) { sd.add(tempDay); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sd; } private ScheduleDay generateSCDAY(WeekDays day, String name, JSONObject root) throws JSONException { ScheduleDay days = null; List<ScheduleItem> items = null; JSONArray jArray = root.getJSONArray(name); if (jArray.length() > 0) { items = new ArrayList<ScheduleItem>(); days = new ScheduleDay(); days.setDay(day); for (int i = 0; i < jArray.length(); i++) { JSONObject item = jArray.getJSONObject(i); ScheduleItem itemNew = new ScheduleItem(); itemNew.setEndtime(item.getString(ITEM_END_TIME)); itemNew.setGroupName(item.getString(ITEM_GROUP)); itemNew.setLect(item.getString(ITEM_LECTNAME)+" "+item.getString(ITEM_LECTSURNAME)); itemNew.setLectNr(item.getInt(ITEM_LECTNO)); itemNew.setName(item.getString(ITEM_MODULE)); itemNew.setRoom(item.getString(ITEM_CLASS)); itemNew.setStartTime(item.getString(ITEM_START_TIME)); switch (item.getString(ITEM_TYPE)) { case "Paskaitos": itemNew.setType(ItemType.LECTURE); break; case "Pratybos": itemNew.setType(ItemType.PRACTICAL); break; case "Laboratoriniai darbai": itemNew.setType(ItemType.LAB); break; } switch (item.getString(ITEM_WEEK)) { case "0": itemNew.setWeek(Week.ALL); break; case "1": itemNew.setWeek(Week.FIRST); break; case "2": itemNew.setWeek(Week.SECOND); break; } items.add(itemNew); } days.setItems(items); } return days; } @Override protected List<ScheduleDay> doInBackground(Void... params) { return getSchedule(); } public Map<String, String> getInfo() { return info; } public void setInfo(Map<String, String> info) { this.info = info; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public boolean isGroupsWritten() { return groupsWritten; } public void setGroupsWritten(boolean groupsWritten) { this.groupsWritten = groupsWritten; } public File getGroupFile() { return groupFile; } public void setGroupFile(File groupFile) { this.groupFile = groupFile; } }
ISO-8859-13
Java
9,028
java
JsonClient.java
Java
[ { "context": "t {\r\n\tprivate final String SERVICE_URL = \"http://178.62.119.11/getinfo.php\";\r\n\r\n\t//JsonScheduleItemFields\r\n\tpriv", "end": 1328, "score": 0.9996702671051025, "start": 1315, "tag": "IP_ADDRESS", "value": "178.62.119.11" } ]
null
[]
package lt.yus.dataService; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import lt.yus.data.schedule.BaseHttpClient; import lt.yus.data.schedule.ItemType; import lt.yus.data.schedule.ScheduleDay; import lt.yus.data.schedule.ScheduleItem; import lt.yus.data.schedule.Week; import lt.yus.data.schedule.WeekDays; import lt.yus.helper.FileReader; public class JsonClient extends AsyncTask<Void, Void, List<ScheduleDay>> implements BaseHttpClient { private final String SERVICE_URL = "http://172.16.17.32/getinfo.php"; //JsonScheduleItemFields private final String ITEM_GROUP = "groupName"; private final String ITEM_DAY = "day"; private final String ITEM_LECTNO = "lectNr"; private final String ITEM_WEEK = "week"; private final String ITEM_START_TIME = "startTime"; private final String ITEM_END_TIME = "endTime"; private final String ITEM_SUBGROUP = "subgroup"; private final String ITEM_CLASS = "class"; private final String ITEM_LECTNAME = "lectName"; private final String ITEM_LECTSURNAME = "lectSurname"; private final String ITEM_MODULE = "module"; private final String ITEM_TYPE = "type"; private File groupFile; private Map<String, String> info; InputStream inputStream; boolean groupsWritten; @Override public List<ScheduleDay> getSchedule() { String result = null; if (!groupsWritten) { DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httpPost = new HttpPost(SERVICE_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (Entry<String, String> infoPair : info.entrySet()) { nameValuePairs.add(new BasicNameValuePair(infoPair.getKey(), infoPair.getValue())); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null ) { sb.append(line+"\n"); } result = sb.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (!groupsWritten) { FileReader write = new FileReader(); write.save(result, groupFile); } return generateObjects(result); } @Override public List<String> getGroups(boolean all) { ArrayList<String> grp = new ArrayList<String>(); String result = null; InputStream inputStream = null; DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httpPost = new HttpPost(SERVICE_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("all", "true")); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null ) { sb.append(line+"\n"); } result = sb.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch(Exception e) { } } JSONObject groups; try { groups = new JSONObject(result); JSONArray groupList = groups.getJSONArray("groupName"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return grp; } private List<ScheduleDay> generateObjects(String result) { ArrayList<ScheduleDay> sd = new ArrayList<ScheduleDay>(); try { JSONObject jObject = new JSONObject(result); ScheduleDay tempDay = generateSCDAY(WeekDays.MONDAY, "Pirmadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.TUESDAY, "Antradienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.WEDNESDAY, "Trečiadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.THURSDAY, "Ketvirtadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.FRIDAY, "Penktadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.SATURDAY, "Šeštadienis", jObject); if (tempDay != null) { sd.add(tempDay); } tempDay = generateSCDAY(WeekDays.SUNDAY, "Sekmadienis", jObject); if (tempDay != null) { sd.add(tempDay); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sd; } private ScheduleDay generateSCDAY(WeekDays day, String name, JSONObject root) throws JSONException { ScheduleDay days = null; List<ScheduleItem> items = null; JSONArray jArray = root.getJSONArray(name); if (jArray.length() > 0) { items = new ArrayList<ScheduleItem>(); days = new ScheduleDay(); days.setDay(day); for (int i = 0; i < jArray.length(); i++) { JSONObject item = jArray.getJSONObject(i); ScheduleItem itemNew = new ScheduleItem(); itemNew.setEndtime(item.getString(ITEM_END_TIME)); itemNew.setGroupName(item.getString(ITEM_GROUP)); itemNew.setLect(item.getString(ITEM_LECTNAME)+" "+item.getString(ITEM_LECTSURNAME)); itemNew.setLectNr(item.getInt(ITEM_LECTNO)); itemNew.setName(item.getString(ITEM_MODULE)); itemNew.setRoom(item.getString(ITEM_CLASS)); itemNew.setStartTime(item.getString(ITEM_START_TIME)); switch (item.getString(ITEM_TYPE)) { case "Paskaitos": itemNew.setType(ItemType.LECTURE); break; case "Pratybos": itemNew.setType(ItemType.PRACTICAL); break; case "Laboratoriniai darbai": itemNew.setType(ItemType.LAB); break; } switch (item.getString(ITEM_WEEK)) { case "0": itemNew.setWeek(Week.ALL); break; case "1": itemNew.setWeek(Week.FIRST); break; case "2": itemNew.setWeek(Week.SECOND); break; } items.add(itemNew); } days.setItems(items); } return days; } @Override protected List<ScheduleDay> doInBackground(Void... params) { return getSchedule(); } public Map<String, String> getInfo() { return info; } public void setInfo(Map<String, String> info) { this.info = info; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public boolean isGroupsWritten() { return groupsWritten; } public void setGroupsWritten(boolean groupsWritten) { this.groupsWritten = groupsWritten; } public File getGroupFile() { return groupFile; } public void setGroupFile(File groupFile) { this.groupFile = groupFile; } }
9,027
0.681662
0.679557
318
26.380503
22.102318
101
false
false
0
0
0
0
0
0
2.581761
false
false
9
c30f9a8de03a545fb11da551e77fd45a30cb4f2a
20,856,361,222,737
f17186b43c5a22e5317dacab6709466ae7ae832b
/Students/Cudrici Carina/Laboratoare/LAB4/4.2,4.3, 4.4, 4.5/src/Sofer.java
1f00d968f5f05ad276bd30d47ae52f61acfc958c
[]
no_license
carinaa28/POO2019-30223
https://github.com/carinaa28/POO2019-30223
e67dfc1dca2e4ffb9089d4f7cf01a8c6574312bb
93d9e58cce781c0198eadf8f11f4275cc44663df
refs/heads/master
2020-08-12T15:15:27.981000
2020-01-15T17:55:12
2020-01-15T17:55:12
214,789,759
0
0
null
true
2019-10-13T09:00:10
2019-10-13T09:00:10
2019-10-11T13:21:15
2019-10-13T08:01:57
11,867
0
0
0
null
false
false
public class Sofer { String nume; String prenume; int varsta; int numarPermis; public Sofer(String nume, String prenume, int varsta, int numarPermis) { this.nume = nume; this.prenume = prenume; this.varsta = varsta; this.numarPermis = numarPermis; } public Sofer() { } }
UTF-8
Java
290
java
Sofer.java
Java
[]
null
[]
public class Sofer { String nume; String prenume; int varsta; int numarPermis; public Sofer(String nume, String prenume, int varsta, int numarPermis) { this.nume = nume; this.prenume = prenume; this.varsta = varsta; this.numarPermis = numarPermis; } public Sofer() { } }
290
0.696552
0.696552
15
18.333334
17.226595
73
false
false
0
0
0
0
0
0
1.933333
false
false
9
babd02feb831337beac646ea86c52f31550f9cba
2,027,224,620,515
add1f7845ac16b188142a87a0cf720faef7415b9
/ReactiveExample-main/ReactiveExample-main/fepdirect-ms-edge-server/src/test/java/com/fepoc/ms/server/edge/FepdirectMsEdgeServerApplicationTests.java
b857481e20748668b70c5fe8f5cb0529e1f34be2
[]
no_license
arunbhamajumdar/redisUseCases
https://github.com/arunbhamajumdar/redisUseCases
9a2db6f2a2a67a481f124df89b3f987a8fc336af
b413f34e2203ff0b23f970572c0162542bd396b1
refs/heads/master
2023-07-24T06:33:48.749000
2023-06-21T01:03:14
2023-06-21T01:03:14
249,989,796
0
0
null
false
2023-07-05T20:46:50
2020-03-25T13:45:11
2023-06-21T01:18:22
2023-07-05T20:46:49
1,260
0
0
4
Java
false
false
package com.fepoc.ms.server.edge; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class FepdirectMsEdgeServerApplicationTests { @Test void contextLoads() { } }
UTF-8
Java
231
java
FepdirectMsEdgeServerApplicationTests.java
Java
[]
null
[]
package com.fepoc.ms.server.edge; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class FepdirectMsEdgeServerApplicationTests { @Test void contextLoads() { } }
231
0.796537
0.796537
13
16.76923
19.541491
60
false
false
0
0
0
0
0
0
0.461538
false
false
9
257554a4641ad448e065abece1e5428024b299d5
25,890,062,861,737
9f54168b92a75c972af378da2a41f1bb190ea9b8
/NPCWarehouse/src/me/jeremytrains/npcwh/WaypointFile.java
1981f28a54d1f0ced18b3abec6d99530b93befff
[]
no_license
zsscooby/NPCWarehouse
https://github.com/zsscooby/NPCWarehouse
b0561de297de739e2ec494b1b7c32652d67c574b
db3507b0e1e52e0bad74c890ebfc42f482fcabf5
refs/heads/master
2021-01-19T16:23:42.408000
2012-09-15T14:09:34
2012-09-15T14:09:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.jeremytrains.npcwh; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class WaypointFile { private static final File file = new File("plugins/NPCWarehouse/waypoints.bin"); public static void saveToFile() { if (file.exists() == false) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(NPCWarehouse.npcwypts); oos.flush(); oos.close(); }catch(Exception e){ e.printStackTrace(); } } public static void loadFromFile() throws Exception { if (file.exists() == false) { NPCWarehouse.npcwypts = new NPCWaypoint[1000]; return; } ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); Object result = ois.readObject(); ois.close(); NPCWarehouse.npcwypts = (NPCWaypoint[])result; } public static void removeWaypointFromList(NPCWaypoint w) { for (int i = 0; i < NPCWarehouse.npcwypts.length; i++) { if (NPCWarehouse.npcwypts[i] != null) { if (NPCWarehouse.npcwypts[i].equals(w)) { NPCWarehouse.npcwypts[i] = null; } } } } }
UTF-8
Java
1,368
java
WaypointFile.java
Java
[]
null
[]
package me.jeremytrains.npcwh; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class WaypointFile { private static final File file = new File("plugins/NPCWarehouse/waypoints.bin"); public static void saveToFile() { if (file.exists() == false) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(NPCWarehouse.npcwypts); oos.flush(); oos.close(); }catch(Exception e){ e.printStackTrace(); } } public static void loadFromFile() throws Exception { if (file.exists() == false) { NPCWarehouse.npcwypts = new NPCWaypoint[1000]; return; } ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); Object result = ois.readObject(); ois.close(); NPCWarehouse.npcwypts = (NPCWaypoint[])result; } public static void removeWaypointFromList(NPCWaypoint w) { for (int i = 0; i < NPCWarehouse.npcwypts.length; i++) { if (NPCWarehouse.npcwypts[i] != null) { if (NPCWarehouse.npcwypts[i].equals(w)) { NPCWarehouse.npcwypts[i] = null; } } } } }
1,368
0.66886
0.665205
53
23.811321
21.679533
81
false
false
0
0
0
0
0
0
2.283019
false
false
9
66c53cdc8d784ecb03331d8b0bd496e3f3211334
5,506,148,089,283
d2fc24cb1d0e5dae4d8cb2adc56c0c738b300a03
/backend/src/main/java/com/example/hrms/business/concretes/CandidateExperienceManager.java
c0c1b8929725987698bc1a6a8496234d53013b58
[]
no_license
vnknt/hrms_java
https://github.com/vnknt/hrms_java
0dfd1989af04401d333483c95d17c87ec87fa605
d9a428982954ec1cee4c7561c5e8535e3d7421f3
refs/heads/main
2023-05-31T13:04:44.340000
2021-12-19T15:36:39
2021-12-19T15:36:39
371,049,252
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hrms.business.concretes; import org.springframework.stereotype.Service; import com.example.hrms.business.abstracts.CandidateExperienceService; import com.example.hrms.core.concretes.utilities.results.Result; import com.example.hrms.core.concretes.utilities.results.SuccessResult; import com.example.hrms.dataAccess.abstracts.CandidateExperienceDao; import com.example.hrms.entities.concretes.CandidateExperience; @Service public class CandidateExperienceManager implements CandidateExperienceService { private CandidateExperienceDao candidateExperienceDao; public CandidateExperienceManager(CandidateExperienceDao candidateExperienceDao ) { this.candidateExperienceDao = candidateExperienceDao; } public Result add(CandidateExperience candidateExperience) { this.candidateExperienceDao.save(candidateExperience); return new SuccessResult(); } }
UTF-8
Java
889
java
CandidateExperienceManager.java
Java
[]
null
[]
package com.example.hrms.business.concretes; import org.springframework.stereotype.Service; import com.example.hrms.business.abstracts.CandidateExperienceService; import com.example.hrms.core.concretes.utilities.results.Result; import com.example.hrms.core.concretes.utilities.results.SuccessResult; import com.example.hrms.dataAccess.abstracts.CandidateExperienceDao; import com.example.hrms.entities.concretes.CandidateExperience; @Service public class CandidateExperienceManager implements CandidateExperienceService { private CandidateExperienceDao candidateExperienceDao; public CandidateExperienceManager(CandidateExperienceDao candidateExperienceDao ) { this.candidateExperienceDao = candidateExperienceDao; } public Result add(CandidateExperience candidateExperience) { this.candidateExperienceDao.save(candidateExperience); return new SuccessResult(); } }
889
0.849269
0.849269
26
33.192307
31.175705
84
false
false
0
0
0
0
0
0
1
false
false
9
2076b03ba34ce751a47710952babc7c5c8ed1863
7,387,343,779,682
c191db3fd5ab1cde296ce7470785670fe484b846
/ArrayReverse.java
6fb0150f291d7e248e6cf1c123007fff3833e8b1
[]
no_license
AnuragSharma231197/Java_Programs
https://github.com/AnuragSharma231197/Java_Programs
632e4356ebb143e5c5b89a5c6a0ce1d57bd46fc7
a462c66b144f1688255539cb8a4c114e916bed29
refs/heads/master
2021-01-02T23:10:46.642000
2018-01-18T19:37:07
2018-01-18T19:37:07
99,484,257
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class ArrayReverse{ public static void main(String []args){ Scanner scan=new Scanner(System.in); System.out.println("Enter how many numbers you want to enter"); int number=scan.nextInt(); int swap; int array[]=new int[number]; for(int i=0;i<number;i++){ array[i]=scan.nextInt(); } for(int i=0;i<array.length;i++){ for(int j=i+1;j<array.length;j++){ if(array[j]<array[i]){ swap=array[i]; array[i]=array[j]; array[j]=swap; } } System.out.println(array[i]); } System.out.println("Largest number is:"+array[array.length-1]); } }
UTF-8
Java
613
java
ArrayReverse.java
Java
[]
null
[]
import java.util.*; public class ArrayReverse{ public static void main(String []args){ Scanner scan=new Scanner(System.in); System.out.println("Enter how many numbers you want to enter"); int number=scan.nextInt(); int swap; int array[]=new int[number]; for(int i=0;i<number;i++){ array[i]=scan.nextInt(); } for(int i=0;i<array.length;i++){ for(int j=i+1;j<array.length;j++){ if(array[j]<array[i]){ swap=array[i]; array[i]=array[j]; array[j]=swap; } } System.out.println(array[i]); } System.out.println("Largest number is:"+array[array.length-1]); } }
613
0.626427
0.619902
25
23.559999
17.352995
65
false
false
0
0
0
0
0
0
3.16
false
false
9
c6eea928c45b2edd486e7249e62fe9142cbdf698
35,450,660,068,201
9a979e8b190af872e2ea870ed2a49267491b1171
/src/main/java/com/socialnetwork/servlets/AuthorizationServlet.java
910faa0a71f5835783dcf804c64497b76c7a6be4
[]
no_license
gloomygenius/SocialNetwork2
https://github.com/gloomygenius/SocialNetwork2
2957fe79648619e30f522a670b5176ca370a0633
b4671c6018b65b08020d28f09c5ca1e76d28d48e
refs/heads/master
2020-12-24T12:29:22.763000
2016-12-05T09:59:25
2016-12-05T09:59:25
72,995,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.socialnetwork.servlets; import com.socialnetwork.dao.exception.DaoException; import com.socialnetwork.models.Relation; import com.socialnetwork.models.User; import lombok.extern.log4j.Log4j; import org.apache.commons.codec.digest.DigestUtils; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Map; import java.util.Optional; import static com.socialnetwork.servlets.ErrorHandler.ErrorCode.LOGIN_FAIL; @Log4j public class AuthorizationServlet extends CommonHttpServlet { static final String NEW_FRIENDS = "newFriends"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, String[]> parameterMap = request.getParameterMap(); if (parameterMap.containsKey("j_password") && parameterMap.containsKey("j_username")) { Optional<User> authorize = authorize(parameterMap); if (authorize.isPresent()) { HttpSession session = request.getSession(true); session.setAttribute(CURRENT_USER, authorize.get()); session.setAttribute(NEW_FRIENDS, getCountNewFriend(authorize.get().getId())); response.sendRedirect("/"); } else { log.info("Login fail"); request.setAttribute(ERROR_MSG, LOGIN_FAIL.getPropertyName()); request.setAttribute(INCLUDED_PAGE, "login"); request.getRequestDispatcher("/index.jsp").forward(request, response); } } else { log.info("Redirecting to login page"); request.setAttribute(INCLUDED_PAGE, "login"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp"); requestDispatcher.forward(request, response); } } private Optional<User> authorize(Map<String, String[]> parameterMap) { String login = parameterMap.get("j_username")[0]; String password = DigestUtils.md5Hex(parameterMap.get("j_password")[0]); Optional<User> userOptional = Optional.empty(); try { userOptional = userDao.getByEmail(login); } catch (DaoException e) { log.error("Error in userDao when user " + login + " try login", e); } if (userOptional.isPresent() && userOptional.get().getPassword().equals(password)) return userOptional; return Optional.empty(); } private int getCountNewFriend(long id) { Relation incoming = null; try { incoming = relationDao.getIncoming(id); } catch (DaoException e) { log.error("Error in relationDao when user " + id + " try get count of new friends", e); } return incoming != null ? incoming.getIdSet().size() : 0; } }
UTF-8
Java
3,175
java
AuthorizationServlet.java
Java
[ { "context": "ap.get(\"j_username\")[0];\n String password = DigestUtils.md5Hex(parameterMap.get(\"j_password\")[0]);\n ", "end": 2362, "score": 0.9938777089118958, "start": 2356, "tag": "PASSWORD", "value": "Digest" } ]
null
[]
package com.socialnetwork.servlets; import com.socialnetwork.dao.exception.DaoException; import com.socialnetwork.models.Relation; import com.socialnetwork.models.User; import lombok.extern.log4j.Log4j; import org.apache.commons.codec.digest.DigestUtils; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Map; import java.util.Optional; import static com.socialnetwork.servlets.ErrorHandler.ErrorCode.LOGIN_FAIL; @Log4j public class AuthorizationServlet extends CommonHttpServlet { static final String NEW_FRIENDS = "newFriends"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, String[]> parameterMap = request.getParameterMap(); if (parameterMap.containsKey("j_password") && parameterMap.containsKey("j_username")) { Optional<User> authorize = authorize(parameterMap); if (authorize.isPresent()) { HttpSession session = request.getSession(true); session.setAttribute(CURRENT_USER, authorize.get()); session.setAttribute(NEW_FRIENDS, getCountNewFriend(authorize.get().getId())); response.sendRedirect("/"); } else { log.info("Login fail"); request.setAttribute(ERROR_MSG, LOGIN_FAIL.getPropertyName()); request.setAttribute(INCLUDED_PAGE, "login"); request.getRequestDispatcher("/index.jsp").forward(request, response); } } else { log.info("Redirecting to login page"); request.setAttribute(INCLUDED_PAGE, "login"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp"); requestDispatcher.forward(request, response); } } private Optional<User> authorize(Map<String, String[]> parameterMap) { String login = parameterMap.get("j_username")[0]; String password = <PASSWORD>Utils.md5Hex(parameterMap.get("j_password")[0]); Optional<User> userOptional = Optional.empty(); try { userOptional = userDao.getByEmail(login); } catch (DaoException e) { log.error("Error in userDao when user " + login + " try login", e); } if (userOptional.isPresent() && userOptional.get().getPassword().equals(password)) return userOptional; return Optional.empty(); } private int getCountNewFriend(long id) { Relation incoming = null; try { incoming = relationDao.getIncoming(id); } catch (DaoException e) { log.error("Error in relationDao when user " + id + " try get count of new friends", e); } return incoming != null ? incoming.getIdSet().size() : 0; } }
3,179
0.671811
0.669606
75
41.346668
31.349426
119
false
false
0
0
0
0
0
0
0.773333
false
false
9
709df93ae33e998ffe7ca3055917e2e750c1f8a4
16,381,005,318,146
d8ee98ca9e2da1fa285cfb620d74f72dcd4843c0
/app/src/main/java/com/qianfeng/yiyuantao/activity/RegisterActivity.java
7979ff085bdaeec421961d9ff43ab025253bff71
[]
no_license
azMallco/YiYuanTao
https://github.com/azMallco/YiYuanTao
d7b862f7c99b33ea3559cf1d6bb694164ede22bd
4264dc13b20bb99ff6d1ee172ea994da16f374e0
refs/heads/master
2021-01-24T20:14:11.718000
2015-12-02T07:58:41
2015-12-02T07:58:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qianfeng.yiyuantao.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.qianfeng.yiyuantao.R; /** * Created by LXL on 2015/11/25. */ public class RegisterActivity extends Activity{ private ImageView reg_ico_return; private EditText regist_phonenum; private EditText regist_password; private Button bt_regist; private TextView tv_fastregist; private TextView tv_findpassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.registerlayout); initView(); /** * 按返回键返回 */ reg_ico_return.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(RegisterActivity.this, HomeActivity.class); finish(); } }); } private void initView() { reg_ico_return = (ImageView) findViewById(R.id.reg_ico_return); regist_phonenum = (EditText) findViewById(R.id.regist_phonenum); regist_password = (EditText) findViewById(R.id.regist_password); bt_regist = (Button) findViewById(R.id.bt_regist); tv_fastregist = (TextView) findViewById(R.id.tv_fastregist); tv_findpassword = (TextView) findViewById(R.id.tv_findpassword); } /** * 登录按钮监听事件 */ public void regist(View view) { String phonenum = regist_phonenum.getText().toString().trim(); String password = regist_password.getText().toString().trim(); if(phonenum!=null&&password!=null&&!phonenum.equals("")&&!password.equals("")){ Toast.makeText(RegisterActivity.this,"已登录。。。",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(RegisterActivity.this,"请完整填写。。。",Toast.LENGTH_SHORT).show(); } } /** * 快速登录 */ public void fastRegist(View view){ Toast.makeText(RegisterActivity.this,"fast。。。",Toast.LENGTH_SHORT).show(); } /** * 找回密码 */ public void findPassword(View view){ Toast.makeText(RegisterActivity.this,"find。。。",Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
2,526
java
RegisterActivity.java
Java
[ { "context": "mport com.qianfeng.yiyuantao.R;\n\n/**\n * Created by LXL on 2015/11/25.\n */\npublic class RegisterActivity ", "end": 366, "score": 0.9994346499443054, "start": 363, "tag": "USERNAME", "value": "LXL" } ]
null
[]
package com.qianfeng.yiyuantao.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.qianfeng.yiyuantao.R; /** * Created by LXL on 2015/11/25. */ public class RegisterActivity extends Activity{ private ImageView reg_ico_return; private EditText regist_phonenum; private EditText regist_password; private Button bt_regist; private TextView tv_fastregist; private TextView tv_findpassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.registerlayout); initView(); /** * 按返回键返回 */ reg_ico_return.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(RegisterActivity.this, HomeActivity.class); finish(); } }); } private void initView() { reg_ico_return = (ImageView) findViewById(R.id.reg_ico_return); regist_phonenum = (EditText) findViewById(R.id.regist_phonenum); regist_password = (EditText) findViewById(R.id.regist_password); bt_regist = (Button) findViewById(R.id.bt_regist); tv_fastregist = (TextView) findViewById(R.id.tv_fastregist); tv_findpassword = (TextView) findViewById(R.id.tv_findpassword); } /** * 登录按钮监听事件 */ public void regist(View view) { String phonenum = regist_phonenum.getText().toString().trim(); String password = regist_password.getText().toString().trim(); if(phonenum!=null&&password!=null&&!phonenum.equals("")&&!password.equals("")){ Toast.makeText(RegisterActivity.this,"已登录。。。",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(RegisterActivity.this,"请完整填写。。。",Toast.LENGTH_SHORT).show(); } } /** * 快速登录 */ public void fastRegist(View view){ Toast.makeText(RegisterActivity.this,"fast。。。",Toast.LENGTH_SHORT).show(); } /** * 找回密码 */ public void findPassword(View view){ Toast.makeText(RegisterActivity.this,"find。。。",Toast.LENGTH_SHORT).show(); } }
2,526
0.645373
0.642097
79
29.911392
26.307428
87
false
false
0
0
0
0
0
0
0.556962
false
false
9
9207c7702f47d41689e5f3f294fc2b07c67f67eb
13,795,434,985,574
8f03336087d38a87b81f50857bce5c09b27e0876
/app/src/main/java/com/example/spart/recupmynews/Controller/SplashScreen.java
0bcd044519df04d3519705ce403ba955aa48ec30
[]
no_license
spartam72/RecupMyNews
https://github.com/spartam72/RecupMyNews
3e4e7070ac6e341bd0ebbfc8a512efbb5fca2af2
62444b40676ba4e0d71d261386f716341436cb56
refs/heads/master
2020-05-17T09:49:03.637000
2019-05-11T14:45:18
2019-05-11T14:45:18
183,473,944
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.spart.recupmynews.Controller; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import com.example.spart.recupmynews.R; public class SplashScreen extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_splash_screen); getWindow().setStatusBarColor( ContextCompat.getColor(this, R.color.colorStatusBarHome )); new Handler( ).postDelayed( new Runnable() { @Override public void run() { Intent i = new Intent(SplashScreen.this, MainActivity.class); startActivity(i); finish(); } }, 7000); } }
UTF-8
Java
1,036
java
SplashScreen.java
Java
[]
null
[]
package com.example.spart.recupmynews.Controller; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import com.example.spart.recupmynews.R; public class SplashScreen extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_splash_screen); getWindow().setStatusBarColor( ContextCompat.getColor(this, R.color.colorStatusBarHome )); new Handler( ).postDelayed( new Runnable() { @Override public void run() { Intent i = new Intent(SplashScreen.this, MainActivity.class); startActivity(i); finish(); } }, 7000); } }
1,036
0.677606
0.671815
36
27.777779
22.779268
77
false
false
0
0
0
0
0
0
0.527778
false
false
9
5ddf85b88e7877f2d8fdf309c3b73365a3a586bf
29,867,202,627,762
137b087ef2383b8bc7148496ca985002fa615321
/src/main/java/org/dpi/department/DepartmentReportServiceImpl.java
caf180c2a9746720f65c337d37430eeb08966ea8
[]
no_license
moradaniel/humanResources
https://github.com/moradaniel/humanResources
7b898c17b6fb6cc90bfc7c241c288dd53364ddfd
f39ed276d6d7b91b0bed5b7a8497650c68d9dd7b
refs/heads/master
2023-07-07T22:50:22.158000
2023-07-03T10:46:17
2023-07-03T10:46:17
11,310,851
0
0
null
false
2022-12-16T06:30:21
2013-07-10T12:04:35
2022-07-01T10:56:55
2022-12-16T06:30:18
13,323
0
0
26
HTML
false
false
package org.dpi.department; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.dpi.creditsManagement.CreditsManagerService; import org.dpi.creditsPeriod.CreditsPeriod; import org.dpi.creditsPeriod.CreditsPeriodService; import org.dpi.security.UserAccessService; import org.dpi.stats.PeriodSummaryData; import org.janux.bus.security.Account; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.security.core.context.SecurityContextHolder; public class DepartmentReportServiceImpl implements DepartmentReportService { Logger log = LoggerFactory.getLogger(this.getClass()); private ApplicationContext applicationContext; private UserAccessService userAccessService; private CreditsPeriodService creditsPeriodService; private CreditsManagerService creditsManagerService; private DepartmentService departmentService; public void setApplicationContext(final ApplicationContext aApplicationContext) throws BeansException { this.applicationContext = aApplicationContext; } public List<PeriodSummaryData> getPeriodDepartmentsSummaryData(CreditsPeriod creditsPeriod){ Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String accountName = ((Account) principal).getName(); Set<DepartmentAdminInfo> departmentsInfoSet = userAccessService.getDepartmentListForAccount(accountName, null); List<DepartmentAdminInfo> departmentsInfoList = new ArrayList<DepartmentAdminInfo>(departmentsInfoSet); //List<GenericTreeNode<DepartmentResults<String>>> childrenArrayList = node.getChildren(); Collections.sort(departmentsInfoList, new Comparator<DepartmentAdminInfo>() { public int compare( DepartmentAdminInfo one, DepartmentAdminInfo another){ return one.getCode().compareTo(another.getCode()); } } ); //int i = 0; List<PeriodSummaryData> periodDepartmentsSummaryData = new ArrayList<PeriodSummaryData>(); for( DepartmentAdminInfo departmentInfo : departmentsInfoList){ //TODO cambiar esto. Se debe buscar las reparticiones que no esten desactivadas. //No buscar una por una si esta desactivada. Usar un quiery filter de department Department department = departmentService.findById(departmentInfo.getId()); if(department.getValidToPeriod()!=null){ continue; } /* if (department instanceof Department) { model.addAttribute(KEY_DEPARTMENT_LIST, department.getId()); }*/ //build current year log.debug("Generating listDepartmentsCreditsSummary, building buildCurrentPeriodSummaryData for department {}",department.getCode()+department.getName()); PeriodSummaryData periodSummaryData = buildPeriodSummaryData(department, creditsPeriod); periodDepartmentsSummaryData.add(periodSummaryData); /* i++; if(i==13) { break; }*/ } return periodDepartmentsSummaryData; } public PeriodSummaryData buildPeriodSummaryData(Department department, CreditsPeriod creditsPeriod){ //--------------------- current year //CreditsPeriod currentCreditsPeriod = creditsPeriodService.getCurrentCreditsPeriod(); PeriodSummaryData periodSummaryData = new PeriodSummaryData(); periodSummaryData.setDepartment(department); periodSummaryData.setMinisterioDeReparticion(departmentService.getMinisterioOSecretariaDeEstado(department)); periodSummaryData.setYear(creditsPeriod.getName()); Long creditosDisponiblesInicioPeriodo = this.creditsManagerService.getCreditosDisponiblesAlInicioPeriodo(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesInicioPeriodo(creditosDisponiblesInicioPeriodo); Long creditosAcreditadosPorBajaDurantePeriodoActual = this.creditsManagerService.getCreditosPorBajasDeReparticion(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosAcreditadosPorBajaDurantePeriodo(creditosAcreditadosPorBajaDurantePeriodoActual); Long periodRetainedCredits = this.creditsManagerService.getRetainedCreditsByDepartment(creditsPeriod.getId(), department.getId()); periodSummaryData.setRetainedCredits(periodRetainedCredits); Long currentPeriodTotalAvailableCredits = this.creditsManagerService.getTotalCreditosDisponiblesAlInicioPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalAvailableCredits(currentPeriodTotalAvailableCredits); Long creditosConsumidosPorIngresosOAscensosSolicitadosPeriodo = this.creditsManagerService.getCreditosPorIngresosOAscensosSolicitados(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosConsumidosPorIngresosOAscensosSolicitadosPeriodo(creditosConsumidosPorIngresosOAscensosSolicitadosPeriodo); Long creditosPorIngresosOAscensosOtorgadosPeriodo = this.creditsManagerService.getCreditosPorIngresosOAscensosOtorgados(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosPorIngresosOAscensosOtorgadosPeriodo(creditosPorIngresosOAscensosOtorgadosPeriodo); Long creditosDisponiblesSegunSolicitadoPeriodo = this.creditsManagerService.getCreditosDisponiblesSegunSolicitado(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesSegunSolicitadoPeriodo(creditosDisponiblesSegunSolicitadoPeriodo); Long creditosDisponiblesSegunOtorgadoPeriodo = this.creditsManagerService.getCreditosDisponiblesSegunOtorgado(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesSegunOtorgadoPeriodo(creditosDisponiblesSegunOtorgadoPeriodo); Long totalCreditosReparticionAjustes_Debito_Periodo = this.creditsManagerService.getCreditosReparticionAjustesDebitoPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticionAjustes_Debito_Periodo(totalCreditosReparticionAjustes_Debito_Periodo); Long totalCreditosReparticionAjustes_Credito_Periodo = this.creditsManagerService.getCreditosReparticionAjustesCreditoPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticionAjustes_Credito_Periodo(totalCreditosReparticionAjustes_Credito_Periodo); Long totalCreditosReparticion_ReasignadosDeRetencion_Periodo = this.creditsManagerService.getCreditosReparticion_ReasignadosDeRetencion_Periodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticion_ReasignadosDeRetencion_Periodo(totalCreditosReparticion_ReasignadosDeRetencion_Periodo); Long totalCreditosReparticion_ReubicacionReparticion_Periodo = this.creditsManagerService.getCreditosReparticion_ReubicacionDeReparticion_Periodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticion_Reubicacion_Periodo(totalCreditosReparticion_ReubicacionReparticion_Periodo); return periodSummaryData; } public UserAccessService getUserAccessService() { return userAccessService; } public void setUserAccessService(UserAccessService userAccessService) { this.userAccessService = userAccessService; } public CreditsPeriodService getCreditsPeriodService() { return creditsPeriodService; } public void setCreditsPeriodService(CreditsPeriodService creditsPeriodService) { this.creditsPeriodService = creditsPeriodService; } public CreditsManagerService getCreditsManagerService() { return creditsManagerService; } public void setCreditsManagerService( CreditsManagerService creditsManagerService) { this.creditsManagerService = creditsManagerService; } public DepartmentService getDepartmentService() { return departmentService; } public void setDepartmentService(DepartmentService departmentService) { this.departmentService = departmentService; } }
UTF-8
Java
8,961
java
DepartmentReportServiceImpl.java
Java
[]
null
[]
package org.dpi.department; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.dpi.creditsManagement.CreditsManagerService; import org.dpi.creditsPeriod.CreditsPeriod; import org.dpi.creditsPeriod.CreditsPeriodService; import org.dpi.security.UserAccessService; import org.dpi.stats.PeriodSummaryData; import org.janux.bus.security.Account; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.security.core.context.SecurityContextHolder; public class DepartmentReportServiceImpl implements DepartmentReportService { Logger log = LoggerFactory.getLogger(this.getClass()); private ApplicationContext applicationContext; private UserAccessService userAccessService; private CreditsPeriodService creditsPeriodService; private CreditsManagerService creditsManagerService; private DepartmentService departmentService; public void setApplicationContext(final ApplicationContext aApplicationContext) throws BeansException { this.applicationContext = aApplicationContext; } public List<PeriodSummaryData> getPeriodDepartmentsSummaryData(CreditsPeriod creditsPeriod){ Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String accountName = ((Account) principal).getName(); Set<DepartmentAdminInfo> departmentsInfoSet = userAccessService.getDepartmentListForAccount(accountName, null); List<DepartmentAdminInfo> departmentsInfoList = new ArrayList<DepartmentAdminInfo>(departmentsInfoSet); //List<GenericTreeNode<DepartmentResults<String>>> childrenArrayList = node.getChildren(); Collections.sort(departmentsInfoList, new Comparator<DepartmentAdminInfo>() { public int compare( DepartmentAdminInfo one, DepartmentAdminInfo another){ return one.getCode().compareTo(another.getCode()); } } ); //int i = 0; List<PeriodSummaryData> periodDepartmentsSummaryData = new ArrayList<PeriodSummaryData>(); for( DepartmentAdminInfo departmentInfo : departmentsInfoList){ //TODO cambiar esto. Se debe buscar las reparticiones que no esten desactivadas. //No buscar una por una si esta desactivada. Usar un quiery filter de department Department department = departmentService.findById(departmentInfo.getId()); if(department.getValidToPeriod()!=null){ continue; } /* if (department instanceof Department) { model.addAttribute(KEY_DEPARTMENT_LIST, department.getId()); }*/ //build current year log.debug("Generating listDepartmentsCreditsSummary, building buildCurrentPeriodSummaryData for department {}",department.getCode()+department.getName()); PeriodSummaryData periodSummaryData = buildPeriodSummaryData(department, creditsPeriod); periodDepartmentsSummaryData.add(periodSummaryData); /* i++; if(i==13) { break; }*/ } return periodDepartmentsSummaryData; } public PeriodSummaryData buildPeriodSummaryData(Department department, CreditsPeriod creditsPeriod){ //--------------------- current year //CreditsPeriod currentCreditsPeriod = creditsPeriodService.getCurrentCreditsPeriod(); PeriodSummaryData periodSummaryData = new PeriodSummaryData(); periodSummaryData.setDepartment(department); periodSummaryData.setMinisterioDeReparticion(departmentService.getMinisterioOSecretariaDeEstado(department)); periodSummaryData.setYear(creditsPeriod.getName()); Long creditosDisponiblesInicioPeriodo = this.creditsManagerService.getCreditosDisponiblesAlInicioPeriodo(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesInicioPeriodo(creditosDisponiblesInicioPeriodo); Long creditosAcreditadosPorBajaDurantePeriodoActual = this.creditsManagerService.getCreditosPorBajasDeReparticion(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosAcreditadosPorBajaDurantePeriodo(creditosAcreditadosPorBajaDurantePeriodoActual); Long periodRetainedCredits = this.creditsManagerService.getRetainedCreditsByDepartment(creditsPeriod.getId(), department.getId()); periodSummaryData.setRetainedCredits(periodRetainedCredits); Long currentPeriodTotalAvailableCredits = this.creditsManagerService.getTotalCreditosDisponiblesAlInicioPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalAvailableCredits(currentPeriodTotalAvailableCredits); Long creditosConsumidosPorIngresosOAscensosSolicitadosPeriodo = this.creditsManagerService.getCreditosPorIngresosOAscensosSolicitados(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosConsumidosPorIngresosOAscensosSolicitadosPeriodo(creditosConsumidosPorIngresosOAscensosSolicitadosPeriodo); Long creditosPorIngresosOAscensosOtorgadosPeriodo = this.creditsManagerService.getCreditosPorIngresosOAscensosOtorgados(creditsPeriod.getId(), department.getId()); periodSummaryData.setCreditosPorIngresosOAscensosOtorgadosPeriodo(creditosPorIngresosOAscensosOtorgadosPeriodo); Long creditosDisponiblesSegunSolicitadoPeriodo = this.creditsManagerService.getCreditosDisponiblesSegunSolicitado(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesSegunSolicitadoPeriodo(creditosDisponiblesSegunSolicitadoPeriodo); Long creditosDisponiblesSegunOtorgadoPeriodo = this.creditsManagerService.getCreditosDisponiblesSegunOtorgado(creditsPeriod.getId(),department.getId()); periodSummaryData.setCreditosDisponiblesSegunOtorgadoPeriodo(creditosDisponiblesSegunOtorgadoPeriodo); Long totalCreditosReparticionAjustes_Debito_Periodo = this.creditsManagerService.getCreditosReparticionAjustesDebitoPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticionAjustes_Debito_Periodo(totalCreditosReparticionAjustes_Debito_Periodo); Long totalCreditosReparticionAjustes_Credito_Periodo = this.creditsManagerService.getCreditosReparticionAjustesCreditoPeriodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticionAjustes_Credito_Periodo(totalCreditosReparticionAjustes_Credito_Periodo); Long totalCreditosReparticion_ReasignadosDeRetencion_Periodo = this.creditsManagerService.getCreditosReparticion_ReasignadosDeRetencion_Periodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticion_ReasignadosDeRetencion_Periodo(totalCreditosReparticion_ReasignadosDeRetencion_Periodo); Long totalCreditosReparticion_ReubicacionReparticion_Periodo = this.creditsManagerService.getCreditosReparticion_ReubicacionDeReparticion_Periodo(creditsPeriod.getId(), department.getId()); periodSummaryData.setTotalCreditosReparticion_Reubicacion_Periodo(totalCreditosReparticion_ReubicacionReparticion_Periodo); return periodSummaryData; } public UserAccessService getUserAccessService() { return userAccessService; } public void setUserAccessService(UserAccessService userAccessService) { this.userAccessService = userAccessService; } public CreditsPeriodService getCreditsPeriodService() { return creditsPeriodService; } public void setCreditsPeriodService(CreditsPeriodService creditsPeriodService) { this.creditsPeriodService = creditsPeriodService; } public CreditsManagerService getCreditsManagerService() { return creditsManagerService; } public void setCreditsManagerService( CreditsManagerService creditsManagerService) { this.creditsManagerService = creditsManagerService; } public DepartmentService getDepartmentService() { return departmentService; } public void setDepartmentService(DepartmentService departmentService) { this.departmentService = departmentService; } }
8,961
0.732731
0.732173
204
42.926472
49.218098
197
false
false
0
0
0
0
0
0
0.544118
false
false
9
f1a5b18907d0a6a50bc28131e4b14d373e2934e4
29,222,957,488,227
6e2c0f91d2b6e1854756a303c31d348517460442
/charac.java
98cfbe74bb60b10503ab426f0a9034cd826abe09
[]
no_license
BalajiStark/html
https://github.com/BalajiStark/html
7ca2144284e62586377c1548e17582d250b7546e
31b3c26d121205517b23113b507d4055dd2adf45
refs/heads/master
2021-06-23T07:05:48.998000
2017-06-07T18:50:27
2017-06-07T18:50:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class charac { public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.nextLine(); char c=s.charAt(0); int x=(int)c; if((x>=65 && x<=90)||(x>=97 && x<=122)) System.out.println("Alphabet"); else System.out.println("Not-Alphabet"); } }
UTF-8
Java
359
java
charac.java
Java
[]
null
[]
import java.util.*; public class charac { public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.nextLine(); char c=s.charAt(0); int x=(int)c; if((x>=65 && x<=90)||(x>=97 && x<=122)) System.out.println("Alphabet"); else System.out.println("Not-Alphabet"); } }
359
0.545961
0.518106
16
21.4375
16.201731
47
false
false
0
0
0
0
0
0
0.5625
false
false
9
00c543e2e17622f02fc667857ab516ee03260dc6
22,402,549,473,137
d548d9f562386c689838938406b4bb9756ebc819
/tianhe-netty/src/main/java/com/tianhe/framework/netty/study/example/codec/kryo/KryoServerChannelInit.java
9b65b89d2c7587722926a6d245c8ec9e9d302026
[]
no_license
frametianhe/tianhe-framework
https://github.com/frametianhe/tianhe-framework
049392677e7532f2845d3cd57e421e03e423a94f
ed4fec0da86848bc45e3e3c2ac7077c575e7a7b4
refs/heads/master
2023-02-20T11:19:40.718000
2021-01-25T07:59:17
2021-01-25T07:59:17
327,812,312
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tianhe.framework.netty.study.example.codec.kryo; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author: he.tian * @time: 2018-08-02 12:24 */ public class KryoServerChannelInit extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); KryoCodecServiceImpl kryoCodecService = new KryoCodecServiceImpl(KryoPoolFactory.getKryoPoolInstance()); pipeline.addLast(new KryoEncoder(kryoCodecService)); pipeline.addLast(new KryoDecoder(kryoCodecService)); pipeline.addLast(new KryoServerHandler()); } }
UTF-8
Java
906
java
KryoServerChannelInit.java
Java
[ { "context": "y.handler.logging.LoggingHandler;\n\n/**\n * @author: he.tian\n * @time: 2018-08-02 12:24\n */\npublic class KryoS", "end": 307, "score": 0.9064174294471741, "start": 300, "tag": "USERNAME", "value": "he.tian" } ]
null
[]
package com.tianhe.framework.netty.study.example.codec.kryo; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * @author: he.tian * @time: 2018-08-02 12:24 */ public class KryoServerChannelInit extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); KryoCodecServiceImpl kryoCodecService = new KryoCodecServiceImpl(KryoPoolFactory.getKryoPoolInstance()); pipeline.addLast(new KryoEncoder(kryoCodecService)); pipeline.addLast(new KryoDecoder(kryoCodecService)); pipeline.addLast(new KryoServerHandler()); } }
906
0.766004
0.752759
24
36.75
29.310478
112
false
false
0
0
0
0
0
0
0.5
false
false
9
643bbb5ffa27f98ca9b8c3e8e8068aefb31c2bbc
2,456,721,346,552
15a6ef86c2329d2f9bd2f9ed6c4c56a351eae184
/src/main/java/br/com/cwi/apus/repository/BasketRepository.java
12c97b9556ed724ff83254dbffebcd653419fbf7
[]
no_license
leonardopereira/apus
https://github.com/leonardopereira/apus
80e7f9caea96cca9038632f8e06aadfe4408daf9
7050f7bfab93850ea3c4af9860dff2152a12879e
refs/heads/main
2023-06-15T12:11:35.286000
2021-07-16T20:03:29
2021-07-16T20:03:29
386,038,110
0
0
null
false
2021-07-15T21:30:52
2021-07-14T18:24:30
2021-07-15T21:06:05
2021-07-15T21:30:52
73
0
0
0
Java
false
false
package br.com.cwi.apus.repository; import br.com.cwi.apus.domain.Basket; import org.springframework.data.jpa.repository.JpaRepository; public interface BasketRepository extends JpaRepository<Basket, Long> { }
UTF-8
Java
212
java
BasketRepository.java
Java
[]
null
[]
package br.com.cwi.apus.repository; import br.com.cwi.apus.domain.Basket; import org.springframework.data.jpa.repository.JpaRepository; public interface BasketRepository extends JpaRepository<Basket, Long> { }
212
0.820755
0.820755
7
29.285715
27.654575
71
false
false
0
0
0
0
0
0
0.571429
false
false
9
aa21fc2a543ef6f337782e1a05823123e592d9a2
30,279,519,496,617
5fb744d8c830509ec5824a0970f9d0093dc67ca8
/workspace/OptionSlayer/src/mBret/database/DbAccess.java
7f5832e25e66512ecf5676aaa8d1c8a062f1d4b0
[]
no_license
maciej-brochocki/options
https://github.com/maciej-brochocki/options
46cf8d706322634b0f39106c9ec116e07ef44155
24d9c30a0f1f247f7c3423665f3a0df2703a1aa0
refs/heads/master
2021-01-17T07:17:06.130000
2017-03-02T16:45:26
2017-03-02T16:45:26
83,700,445
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mBret.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.Vector; /** * Class written to provide jdbc Db access to an * Allegro 7.6 table in Db PRODACI1 * The class is not generic but written specifically for * use on the Arch Coal Allegro Db implementation. To make * more generic you would need to pass in the Db url string. * * jdbc requires that the ojdbc6.jar be added to the Project Libraries - Build Path * * @author mblackford mBret Bret Blackford * */ public class DbAccess { Connection conn; Vector resultVector = new Vector(); String serverName = "acidb1.aci.corp.net"; String portNumber = "1522"; String sid = "prodaci1"; String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid; String username = "blackfordm"; String password = "--"; public DbAccess(Properties _props) { serverName = _props.getProperty("db.server"); portNumber = _props.getProperty("db.port"); sid = _props.getProperty("db.sid"); url = _props.getProperty("db.dataSource"); username = _props.getProperty("db.userName"); password = _props.getProperty("db.passWord"); } private void makeConnection() throws ClassNotFoundException, SQLException { System.out.println("in DbAccess.makeConnection()"); System.out.println("Going to try the connection now ..."); System.out.println(" url-[" + url + "]"); System.out.println(" username-[" + username + "]"); //System.out.println(" password-[" + password + "]"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { System.out.println("in DbAccess.makeConnection() ... ERROR !!"); e.printStackTrace(); } System.out.println("Connection done !!"); } public Vector makeDbCall(SqlSelection sqlObject) throws SQLException, ClassNotFoundException { System.out.println("in DbAccess.makeDbCall()"); makeConnection(); String sql = sqlObject.getSql(); System.out.println("in DbAcess.makeDbCall(" + sql + ")" ); //creating PreparedStatement object to execute query PreparedStatement preStatement = conn.prepareStatement(sql); ResultSet result = preStatement.executeQuery(); Vector dataVector = sqlObject.processResultSet(result); System.out.println(sqlObject.toString()); return dataVector; } public ResultSet makeSqlCall(String sql) throws ClassNotFoundException, SQLException { //System.out.println("in DbAccess.makeSqlCall()"); //System.out.println("SQL=[" + sql + "]"); //makeConnection(); PreparedStatement preStatement = conn.prepareStatement(sql); ResultSet result = preStatement.executeQuery(); return result; } }
UTF-8
Java
3,073
java
DbAccess.java
Java
[ { "context": " the Project Libraries - Build Path\n * \n * @author mblackford mBret Bret Blackford\n *\n */\npublic class DbAccess", "end": 610, "score": 0.9997096657752991, "start": 600, "tag": "USERNAME", "value": "mblackford" }, { "context": "t Libraries - Build Path\n * \n * @aut...
null
[]
package mBret.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.Vector; /** * Class written to provide jdbc Db access to an * Allegro 7.6 table in Db PRODACI1 * The class is not generic but written specifically for * use on the Arch Coal Allegro Db implementation. To make * more generic you would need to pass in the Db url string. * * jdbc requires that the ojdbc6.jar be added to the Project Libraries - Build Path * * @author mblackford <NAME> * */ public class DbAccess { Connection conn; Vector resultVector = new Vector(); String serverName = "acidb1.aci.corp.net"; String portNumber = "1522"; String sid = "prodaci1"; String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid; String username = "blackfordm"; String password = "--"; public DbAccess(Properties _props) { serverName = _props.getProperty("db.server"); portNumber = _props.getProperty("db.port"); sid = _props.getProperty("db.sid"); url = _props.getProperty("db.dataSource"); username = _props.getProperty("db.userName"); password = _props.getProperty("db.<PASSWORD>"); } private void makeConnection() throws ClassNotFoundException, SQLException { System.out.println("in DbAccess.makeConnection()"); System.out.println("Going to try the connection now ..."); System.out.println(" url-[" + url + "]"); System.out.println(" username-[" + username + "]"); //System.out.println(" password-[" + password + "]"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { System.out.println("in DbAccess.makeConnection() ... ERROR !!"); e.printStackTrace(); } System.out.println("Connection done !!"); } public Vector makeDbCall(SqlSelection sqlObject) throws SQLException, ClassNotFoundException { System.out.println("in DbAccess.makeDbCall()"); makeConnection(); String sql = sqlObject.getSql(); System.out.println("in DbAcess.makeDbCall(" + sql + ")" ); //creating PreparedStatement object to execute query PreparedStatement preStatement = conn.prepareStatement(sql); ResultSet result = preStatement.executeQuery(); Vector dataVector = sqlObject.processResultSet(result); System.out.println(sqlObject.toString()); return dataVector; } public ResultSet makeSqlCall(String sql) throws ClassNotFoundException, SQLException { //System.out.println("in DbAccess.makeSqlCall()"); //System.out.println("SQL=[" + sql + "]"); //makeConnection(); PreparedStatement preStatement = conn.prepareStatement(sql); ResultSet result = preStatement.executeQuery(); return result; } }
3,061
0.659616
0.656362
102
29.127451
25.284914
98
false
false
0
0
0
0
0
0
1.107843
false
false
9
d84e6472c8cf5f4db9c7acf37f84eeb21735b100
3,023,656,995,384
799eaedaa80ae7087384113841ad709ef0dd92d6
/BalancedBinaryTree.java
a0ba66c451e5548f1080c626c199e322cb8f6615
[]
no_license
MichelleXinHe/Leetcode-HeXin
https://github.com/MichelleXinHe/Leetcode-HeXin
18cff8b64265d0c08bb8d91abbd8522037035bd9
addcc86cda2fe1e9fd37e91c27c31a8f6f65bc08
refs/heads/master
2020-04-01T19:20:08.490000
2014-08-07T14:11:54
2014-08-07T14:11:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { int result=check(root); if(result>=0) return true; else return false; } public int check(TreeNode root){ if(root==null) return 0; int left=check(root.left); if(left==-1) return -1; int right=check(root.right); if(right==-1) return -1; int diff=Math.abs(left-right); if(diff>1) return -1; return Math.max(left, right)+1; } }
UTF-8
Java
676
java
BalancedBinaryTree.java
Java
[]
null
[]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { int result=check(root); if(result>=0) return true; else return false; } public int check(TreeNode root){ if(root==null) return 0; int left=check(root.left); if(left==-1) return -1; int right=check(root.right); if(right==-1) return -1; int diff=Math.abs(left-right); if(diff>1) return -1; return Math.max(left, right)+1; } }
676
0.545858
0.532544
28
23.142857
13.444899
46
false
false
0
0
0
0
0
0
0.571429
false
false
9
aa8a9acd06870e484670bf4e64f57db6e943bb01
15,822,659,562,652
fe6452f14a6a5ef6859df2f0bae6f6832062aa92
/src/data/ManagerPacket.java
ae47a928e87731c237a8dbefeaf6179f24fe6047
[ "Apache-2.0" ]
permissive
rererecursive/NodeManager
https://github.com/rererecursive/NodeManager
0b7a407d214e0be60417991059e9094e4c09bf57
7e4f554543e885bbb36a4e58cc0de1081d5b0079
refs/heads/master
2016-06-04T16:37:44.943000
2016-03-20T18:44:08
2016-03-20T18:44:08
52,447,670
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package data; public class ManagerPacket { private int version; private PacketType type; private String rego; private Direction currentDirection; private Color color; private int response; private short directions; private float speedLimit; public ManagerPacket(int version, String rego, Direction d) { this.rego = rego; this.currentDirection = d; } public ManagerPacket(int version, PacketType t, String rego, Direction cd, Color color, Responses r, float speedLimit, short directions) { this.version = version; this.type = t; this.rego = rego; this.currentDirection = cd; this.color = color; this.response = r.getValue(); this.speedLimit = speedLimit; this.directions = directions; } /* Fifteen responses can fit into one short (2 bytes - 1). */ public void setResponse(int r) { this.response |= r; } public void setType(PacketType type) { this.type = type; } public PacketType getType() { return type; } public String getRego() { return rego; } public Direction getDirection() { return currentDirection; } public int getResponse() { return response; } @Override public String toString() { return ("[" + version + " " + type + " " + rego + " " + currentDirection + " " + color + " " + response + " " + directions + " " + speedLimit + "]"); } public Color getColor() { return color; } public float getSpeedLimit() { return speedLimit; } public void setSpeedLimit(float speedLimit) { this.speedLimit = speedLimit; } public short getDirections() { return directions; } public void setDirections(short directions) { this.directions = directions; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } }
UTF-8
Java
1,771
java
ManagerPacket.java
Java
[]
null
[]
package data; public class ManagerPacket { private int version; private PacketType type; private String rego; private Direction currentDirection; private Color color; private int response; private short directions; private float speedLimit; public ManagerPacket(int version, String rego, Direction d) { this.rego = rego; this.currentDirection = d; } public ManagerPacket(int version, PacketType t, String rego, Direction cd, Color color, Responses r, float speedLimit, short directions) { this.version = version; this.type = t; this.rego = rego; this.currentDirection = cd; this.color = color; this.response = r.getValue(); this.speedLimit = speedLimit; this.directions = directions; } /* Fifteen responses can fit into one short (2 bytes - 1). */ public void setResponse(int r) { this.response |= r; } public void setType(PacketType type) { this.type = type; } public PacketType getType() { return type; } public String getRego() { return rego; } public Direction getDirection() { return currentDirection; } public int getResponse() { return response; } @Override public String toString() { return ("[" + version + " " + type + " " + rego + " " + currentDirection + " " + color + " " + response + " " + directions + " " + speedLimit + "]"); } public Color getColor() { return color; } public float getSpeedLimit() { return speedLimit; } public void setSpeedLimit(float speedLimit) { this.speedLimit = speedLimit; } public short getDirections() { return directions; } public void setDirections(short directions) { this.directions = directions; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } }
1,771
0.687182
0.686053
89
18.898876
19.287327
88
false
false
0
0
0
0
0
0
1.573034
false
false
9
9927a6ed385f5748f390750b9e4622edb59a1827
27,144,193,337,619
8ed30ae604990bc6048a9b0562f6202e27ec88de
/app/src/main/java/com/bwie/news/Adapter/FragmentAdapter.java
478f9a70312abf2e951e21c2927b8d97e0b21586
[]
no_license
huluzhu/News
https://github.com/huluzhu/News
02b895f6eec6d3ff06fd3e6b99c913024cc0dbf3
7f3e51c8d99fe4772467c80ceb49e4e4061acc3c
refs/heads/master
2021-01-01T16:53:56.832000
2017-07-21T12:38:59
2017-07-21T12:38:59
97,946,165
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bwie.news.Adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.bwie.news.Fragment.XlistFragment; import java.util.ArrayList; import java.util.List; /** * Created by hujiqinag on 2017/07/19. */ public class FragmentAdapter extends FragmentPagerAdapter { private List<Fragment> list_fragment; private String[] strings; public FragmentAdapter(FragmentManager fm, String[] strings) { super(fm); this.strings = strings; list_fragment = new ArrayList<>(); for (int i = 0; i < strings.length; i++) { XlistFragment xlist = new XlistFragment(); list_fragment.add(xlist); } } @Override public Fragment getItem(int position) { return list_fragment.get(position); } @Override public int getCount() { return strings.length; } @Override public CharSequence getPageTitle(int position) { return strings[position]; } }
UTF-8
Java
1,073
java
FragmentAdapter.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by hujiqinag on 2017/07/19.\n */\npublic class FragmentAdapter e", "end": 297, "score": 0.9996355175971985, "start": 288, "tag": "USERNAME", "value": "hujiqinag" } ]
null
[]
package com.bwie.news.Adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.bwie.news.Fragment.XlistFragment; import java.util.ArrayList; import java.util.List; /** * Created by hujiqinag on 2017/07/19. */ public class FragmentAdapter extends FragmentPagerAdapter { private List<Fragment> list_fragment; private String[] strings; public FragmentAdapter(FragmentManager fm, String[] strings) { super(fm); this.strings = strings; list_fragment = new ArrayList<>(); for (int i = 0; i < strings.length; i++) { XlistFragment xlist = new XlistFragment(); list_fragment.add(xlist); } } @Override public Fragment getItem(int position) { return list_fragment.get(position); } @Override public int getCount() { return strings.length; } @Override public CharSequence getPageTitle(int position) { return strings[position]; } }
1,073
0.665424
0.65424
46
22.326086
20.228106
66
false
false
0
0
0
0
0
0
0.434783
false
false
9
b536dbdd50feef4705ba092b5e6429fd9bfbc856
28,140,625,753,350
dd9b6d4bd04ac9d7e8624753d8919e6874148830
/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java
587790672cc3f72abd847c9f722284f592bec2a2
[ "MIT" ]
permissive
ZhangCX10032/main
https://github.com/ZhangCX10032/main
3fc9e3c192768286615c1512f401c2a5ea2cbd33
82d1f6cd346bf6688d24b2a79f9b59b593113347
refs/heads/master
2020-04-24T02:53:50.545000
2019-03-06T14:58:35
2019-03-06T14:58:35
171,653,180
0
0
NOASSERTION
true
2019-02-20T10:36:07
2019-02-20T10:36:06
2019-02-20T08:22:51
2019-02-20T08:27:28
9,690
0
0
0
null
false
null
package seedu.address.logic.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_CUSTOMER; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.EditCommand.EditCustomerDescriptor; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.HistoryCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.logic.parser.exceptions.ParseException; <<<<<<< HEAD ======= import seedu.address.model.BookingManager; import seedu.address.model.CustomerManager; >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c import seedu.address.model.customer.Customer; import seedu.address.model.customer.NameContainsKeywordsPredicate; import seedu.address.testutil.CustomerBuilder; import seedu.address.testutil.CustomerUtil; import seedu.address.testutil.EditCustomerDescriptorBuilder; public class AddressBookParserTest { @Rule public ExpectedException thrown = ExpectedException.none(); private final AddressBookParser parser = new AddressBookParser(); @Test public void parseCommand_add() throws Exception { Customer customer = new CustomerBuilder().build(); <<<<<<< HEAD AddCommand command = (AddCommand) parser.parseCommand(CustomerUtil.getAddCommand(customer)); ======= AddCommand command = (AddCommand) parser.parseCommand(CustomerUtil.getAddCommand(customer), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new AddCommand(customer), command); } @Test public void parseCommand_addAlias() throws Exception { Customer customer = new CustomerBuilder().build(); AddCommand commandAlias = (AddCommand) parser.parseCommand(AddCommand.COMMAND_ALIAS + " " <<<<<<< HEAD + CustomerUtil.getCustomerDetails(customer)); ======= + CustomerUtil.getCustomerDetails(customer), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new AddCommand(customer), commandAlias); } @Test public void parseCommand_clear() throws Exception { assertTrue(parser.parseCommand(ClearCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ClearCommand); assertTrue(parser.parseCommand(ClearCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ClearCommand); } @Test public void parseCommand_clearAlias() throws Exception { assertTrue(parser.parseCommand(ClearCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ClearCommand); assertTrue(parser.parseCommand(ClearCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ClearCommand); } @Test public void parseCommand_delete() throws Exception { DeleteCommand command = (DeleteCommand) parser.parseCommand( <<<<<<< HEAD DeleteCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= DeleteCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new DeleteCommand(INDEX_FIRST_CUSTOMER), command); } @Test public void parseCommand_deleteAlias() throws Exception { DeleteCommand commandAlias = (DeleteCommand) parser.parseCommand( <<<<<<< HEAD DeleteCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= DeleteCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new DeleteCommand(INDEX_FIRST_CUSTOMER), commandAlias); } @Test public void parseCommand_edit() throws Exception { Customer customer = new CustomerBuilder().build(); EditCommand.EditCustomerDescriptor descriptor = new EditCustomerDescriptorBuilder(customer).build(); EditCommand command = (EditCommand) parser.parseCommand(EditCommand.COMMAND_WORD + " " <<<<<<< HEAD + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor)); ======= + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new EditCommand(INDEX_FIRST_CUSTOMER, descriptor), command); } @Test public void parseCommand_editAlias() throws Exception { Customer customer = new CustomerBuilder().build(); EditCustomerDescriptor descriptor = new EditCustomerDescriptorBuilder(customer).build(); EditCommand commandAlias = (EditCommand) parser.parseCommand(EditCommand.COMMAND_ALIAS + " " <<<<<<< HEAD + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor)); ======= + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new EditCommand(INDEX_FIRST_CUSTOMER, descriptor), commandAlias); } @Test public void parseCommand_exit() throws Exception { assertTrue(parser.parseCommand(ExitCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ExitCommand); assertTrue(parser.parseCommand(ExitCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ExitCommand); } @Test public void parseCommand_exitAlias() throws Exception { assertTrue(parser.parseCommand(ExitCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ExitCommand); assertTrue(parser.parseCommand(ExitCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ExitCommand); } @Test public void parseCommand_find() throws Exception { List<String> keywords = Arrays.asList("foo", "bar", "baz"); FindCommand command = (FindCommand) parser.parseCommand( FindCommand.COMMAND_WORD + " " + keywords.stream().collect(Collectors.joining(" ")), new CustomerManager(), new BookingManager()); assertEquals(new FindCommand(new NameContainsKeywordsPredicate(keywords)), command); } @Test public void parseCommand_findAlias() throws Exception { List<String> keywords = Arrays.asList("foo", "bar", "baz"); FindCommand commandAlias = (FindCommand) parser.parseCommand( FindCommand.COMMAND_ALIAS + " " + keywords.stream().collect(Collectors.joining(" ")), new CustomerManager(), new BookingManager()); assertEquals(new FindCommand(new NameContainsKeywordsPredicate(keywords)), commandAlias); } @Test public void parseCommand_help() throws Exception { assertTrue(parser.parseCommand(HelpCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof HelpCommand); assertTrue(parser.parseCommand(HelpCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof HelpCommand); } @Test public void parseCommand_helpAlias() throws Exception { assertTrue(parser.parseCommand(HelpCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof HelpCommand); assertTrue(parser.parseCommand(HelpCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof HelpCommand); } @Test public void parseCommand_history() throws Exception { assertTrue(parser.parseCommand(HistoryCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof HistoryCommand); assertTrue(parser.parseCommand(HistoryCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof HistoryCommand); try { parser.parseCommand("histories", new CustomerManager(), new BookingManager()); throw new AssertionError("The expected ParseException was not thrown."); } catch (ParseException pe) { assertEquals(MESSAGE_UNKNOWN_COMMAND, pe.getMessage()); } } @Test public void parseCommand_historyAlias() throws Exception { assertTrue(parser.parseCommand(HistoryCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof HistoryCommand); assertTrue(parser.parseCommand(HistoryCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof HistoryCommand); try { parser.parseCommand("histories", new CustomerManager(), new BookingManager()); throw new AssertionError("The expected ParseException was not thrown."); } catch (ParseException pe) { assertEquals(MESSAGE_UNKNOWN_COMMAND, pe.getMessage()); } } @Test public void parseCommand_list() throws Exception { assertTrue(parser.parseCommand(ListCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ListCommand); assertTrue(parser.parseCommand(ListCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ListCommand); } @Test public void parseCommand_listAlias() throws Exception { assertTrue(parser.parseCommand(ListCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ListCommand); assertTrue(parser.parseCommand(ListCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ListCommand); } @Test public void parseCommand_select() throws Exception { SelectCommand command = (SelectCommand) parser.parseCommand( <<<<<<< HEAD SelectCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= SelectCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new SelectCommand(INDEX_FIRST_CUSTOMER), command); } @Test public void parseCommand_selectAlias() throws Exception { SelectCommand commandAlias = (SelectCommand) parser.parseCommand( <<<<<<< HEAD SelectCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= SelectCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new SelectCommand(INDEX_FIRST_CUSTOMER), commandAlias); } @Test public void parseCommand_redoCommandWord_returnsRedoCommand() throws Exception { assertTrue(parser.parseCommand(RedoCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof RedoCommand); assertTrue(parser.parseCommand("redo 1", new CustomerManager(), new BookingManager()) instanceof RedoCommand); } @Test public void parseCommand_redoCommandWord_returnsRedoCommandAlias() throws Exception { assertTrue(parser.parseCommand(RedoCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof RedoCommand); assertTrue(parser.parseCommand("redo 1", new CustomerManager(), new BookingManager()) instanceof RedoCommand); } @Test public void parseCommand_undoCommandWord_returnsUndoCommand() throws Exception { assertTrue(parser.parseCommand(UndoCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof UndoCommand); assertTrue(parser.parseCommand("undo 3", new CustomerManager(), new BookingManager()) instanceof UndoCommand); } @Test public void parseCommand_undoCommandWord_returnsUndoCommandAlias() throws Exception { assertTrue(parser.parseCommand(UndoCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof UndoCommand); assertTrue(parser.parseCommand("undo 3", new CustomerManager(), new BookingManager()) instanceof UndoCommand); } @Test public void parseCommand_unrecognisedInput_throwsParseException() throws Exception { thrown.expect(ParseException.class); thrown.expectMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); parser.parseCommand("", new CustomerManager(), new BookingManager()); } @Test public void parseCommand_unknownCommand_throwsParseException() throws Exception { thrown.expect(ParseException.class); thrown.expectMessage(MESSAGE_UNKNOWN_COMMAND); parser.parseCommand("unknownCommand", new CustomerManager(), new BookingManager()); } }
UTF-8
Java
14,074
java
AddressBookParserTest.java
Java
[]
null
[]
package seedu.address.logic.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_CUSTOMER; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.EditCommand.EditCustomerDescriptor; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.HistoryCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.logic.parser.exceptions.ParseException; <<<<<<< HEAD ======= import seedu.address.model.BookingManager; import seedu.address.model.CustomerManager; >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c import seedu.address.model.customer.Customer; import seedu.address.model.customer.NameContainsKeywordsPredicate; import seedu.address.testutil.CustomerBuilder; import seedu.address.testutil.CustomerUtil; import seedu.address.testutil.EditCustomerDescriptorBuilder; public class AddressBookParserTest { @Rule public ExpectedException thrown = ExpectedException.none(); private final AddressBookParser parser = new AddressBookParser(); @Test public void parseCommand_add() throws Exception { Customer customer = new CustomerBuilder().build(); <<<<<<< HEAD AddCommand command = (AddCommand) parser.parseCommand(CustomerUtil.getAddCommand(customer)); ======= AddCommand command = (AddCommand) parser.parseCommand(CustomerUtil.getAddCommand(customer), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new AddCommand(customer), command); } @Test public void parseCommand_addAlias() throws Exception { Customer customer = new CustomerBuilder().build(); AddCommand commandAlias = (AddCommand) parser.parseCommand(AddCommand.COMMAND_ALIAS + " " <<<<<<< HEAD + CustomerUtil.getCustomerDetails(customer)); ======= + CustomerUtil.getCustomerDetails(customer), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new AddCommand(customer), commandAlias); } @Test public void parseCommand_clear() throws Exception { assertTrue(parser.parseCommand(ClearCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ClearCommand); assertTrue(parser.parseCommand(ClearCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ClearCommand); } @Test public void parseCommand_clearAlias() throws Exception { assertTrue(parser.parseCommand(ClearCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ClearCommand); assertTrue(parser.parseCommand(ClearCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ClearCommand); } @Test public void parseCommand_delete() throws Exception { DeleteCommand command = (DeleteCommand) parser.parseCommand( <<<<<<< HEAD DeleteCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= DeleteCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new DeleteCommand(INDEX_FIRST_CUSTOMER), command); } @Test public void parseCommand_deleteAlias() throws Exception { DeleteCommand commandAlias = (DeleteCommand) parser.parseCommand( <<<<<<< HEAD DeleteCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= DeleteCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new DeleteCommand(INDEX_FIRST_CUSTOMER), commandAlias); } @Test public void parseCommand_edit() throws Exception { Customer customer = new CustomerBuilder().build(); EditCommand.EditCustomerDescriptor descriptor = new EditCustomerDescriptorBuilder(customer).build(); EditCommand command = (EditCommand) parser.parseCommand(EditCommand.COMMAND_WORD + " " <<<<<<< HEAD + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor)); ======= + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new EditCommand(INDEX_FIRST_CUSTOMER, descriptor), command); } @Test public void parseCommand_editAlias() throws Exception { Customer customer = new CustomerBuilder().build(); EditCustomerDescriptor descriptor = new EditCustomerDescriptorBuilder(customer).build(); EditCommand commandAlias = (EditCommand) parser.parseCommand(EditCommand.COMMAND_ALIAS + " " <<<<<<< HEAD + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor)); ======= + INDEX_FIRST_CUSTOMER.getOneBased() + " " + CustomerUtil.getEditCustomerDescriptorDetails(descriptor), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new EditCommand(INDEX_FIRST_CUSTOMER, descriptor), commandAlias); } @Test public void parseCommand_exit() throws Exception { assertTrue(parser.parseCommand(ExitCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ExitCommand); assertTrue(parser.parseCommand(ExitCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ExitCommand); } @Test public void parseCommand_exitAlias() throws Exception { assertTrue(parser.parseCommand(ExitCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ExitCommand); assertTrue(parser.parseCommand(ExitCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ExitCommand); } @Test public void parseCommand_find() throws Exception { List<String> keywords = Arrays.asList("foo", "bar", "baz"); FindCommand command = (FindCommand) parser.parseCommand( FindCommand.COMMAND_WORD + " " + keywords.stream().collect(Collectors.joining(" ")), new CustomerManager(), new BookingManager()); assertEquals(new FindCommand(new NameContainsKeywordsPredicate(keywords)), command); } @Test public void parseCommand_findAlias() throws Exception { List<String> keywords = Arrays.asList("foo", "bar", "baz"); FindCommand commandAlias = (FindCommand) parser.parseCommand( FindCommand.COMMAND_ALIAS + " " + keywords.stream().collect(Collectors.joining(" ")), new CustomerManager(), new BookingManager()); assertEquals(new FindCommand(new NameContainsKeywordsPredicate(keywords)), commandAlias); } @Test public void parseCommand_help() throws Exception { assertTrue(parser.parseCommand(HelpCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof HelpCommand); assertTrue(parser.parseCommand(HelpCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof HelpCommand); } @Test public void parseCommand_helpAlias() throws Exception { assertTrue(parser.parseCommand(HelpCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof HelpCommand); assertTrue(parser.parseCommand(HelpCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof HelpCommand); } @Test public void parseCommand_history() throws Exception { assertTrue(parser.parseCommand(HistoryCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof HistoryCommand); assertTrue(parser.parseCommand(HistoryCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof HistoryCommand); try { parser.parseCommand("histories", new CustomerManager(), new BookingManager()); throw new AssertionError("The expected ParseException was not thrown."); } catch (ParseException pe) { assertEquals(MESSAGE_UNKNOWN_COMMAND, pe.getMessage()); } } @Test public void parseCommand_historyAlias() throws Exception { assertTrue(parser.parseCommand(HistoryCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof HistoryCommand); assertTrue(parser.parseCommand(HistoryCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof HistoryCommand); try { parser.parseCommand("histories", new CustomerManager(), new BookingManager()); throw new AssertionError("The expected ParseException was not thrown."); } catch (ParseException pe) { assertEquals(MESSAGE_UNKNOWN_COMMAND, pe.getMessage()); } } @Test public void parseCommand_list() throws Exception { assertTrue(parser.parseCommand(ListCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof ListCommand); assertTrue(parser.parseCommand(ListCommand.COMMAND_WORD + " 3", new CustomerManager(), new BookingManager()) instanceof ListCommand); } @Test public void parseCommand_listAlias() throws Exception { assertTrue(parser.parseCommand(ListCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof ListCommand); assertTrue(parser.parseCommand(ListCommand.COMMAND_ALIAS + " 3", new CustomerManager(), new BookingManager()) instanceof ListCommand); } @Test public void parseCommand_select() throws Exception { SelectCommand command = (SelectCommand) parser.parseCommand( <<<<<<< HEAD SelectCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= SelectCommand.COMMAND_WORD + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new SelectCommand(INDEX_FIRST_CUSTOMER), command); } @Test public void parseCommand_selectAlias() throws Exception { SelectCommand commandAlias = (SelectCommand) parser.parseCommand( <<<<<<< HEAD SelectCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased()); ======= SelectCommand.COMMAND_ALIAS + " " + INDEX_FIRST_CUSTOMER.getOneBased(), new CustomerManager(), new BookingManager()); >>>>>>> cbebf3c46e02dcd016ad08f56b59fa61c34d5b6c assertEquals(new SelectCommand(INDEX_FIRST_CUSTOMER), commandAlias); } @Test public void parseCommand_redoCommandWord_returnsRedoCommand() throws Exception { assertTrue(parser.parseCommand(RedoCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof RedoCommand); assertTrue(parser.parseCommand("redo 1", new CustomerManager(), new BookingManager()) instanceof RedoCommand); } @Test public void parseCommand_redoCommandWord_returnsRedoCommandAlias() throws Exception { assertTrue(parser.parseCommand(RedoCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof RedoCommand); assertTrue(parser.parseCommand("redo 1", new CustomerManager(), new BookingManager()) instanceof RedoCommand); } @Test public void parseCommand_undoCommandWord_returnsUndoCommand() throws Exception { assertTrue(parser.parseCommand(UndoCommand.COMMAND_WORD, new CustomerManager(), new BookingManager()) instanceof UndoCommand); assertTrue(parser.parseCommand("undo 3", new CustomerManager(), new BookingManager()) instanceof UndoCommand); } @Test public void parseCommand_undoCommandWord_returnsUndoCommandAlias() throws Exception { assertTrue(parser.parseCommand(UndoCommand.COMMAND_ALIAS, new CustomerManager(), new BookingManager()) instanceof UndoCommand); assertTrue(parser.parseCommand("undo 3", new CustomerManager(), new BookingManager()) instanceof UndoCommand); } @Test public void parseCommand_unrecognisedInput_throwsParseException() throws Exception { thrown.expect(ParseException.class); thrown.expectMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); parser.parseCommand("", new CustomerManager(), new BookingManager()); } @Test public void parseCommand_unknownCommand_throwsParseException() throws Exception { thrown.expect(ParseException.class); thrown.expectMessage(MESSAGE_UNKNOWN_COMMAND); parser.parseCommand("unknownCommand", new CustomerManager(), new BookingManager()); } }
14,074
0.707048
0.693264
304
45.296051
35.933662
120
false
false
0
0
0
0
0
0
0.703947
false
false
9
cf04e4bddafbbf3e9311a606ed18933305580e87
1,202,590,875,280
7b5f44671ee1d27245c765521dbb54b5596672e9
/mdresourcedecorator/src/main/java/org/apache/sling/mdresource/impl/MarkdownResourceDecorator.java
eb972becfbc95ab87d1be73d415655d5b46f0a1f
[ "Apache-2.0" ]
permissive
apache/sling-whiteboard
https://github.com/apache/sling-whiteboard
f7fabaf8c59ef7d23d847a4ceae1f8c3dfb3c914
3a7681c9a294926ec67ecd7f8252c29f5b952426
refs/heads/master
2023-08-28T15:13:29.249000
2023-07-13T10:27:25
2023-07-13T10:27:25
109,401,796
42
37
Apache-2.0
false
2023-07-10T07:27:23
2017-11-03T13:58:25
2023-07-10T07:24:42
2023-07-10T07:27:19
96,495
41
31
3
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.mdresource.impl; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceDecorator; import org.apache.sling.api.resource.path.Path; import org.apache.sling.api.resource.path.PathSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.service.metatype.annotations.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(name = "org.apache.sling.resource.MarkdownResourceDecorator", service = ResourceDecorator.class, configurationPolicy = ConfigurationPolicy.REQUIRE ) @Designate(ocd = MarkdownResourceDecorator.Config.class, factory = true) public class MarkdownResourceDecorator implements ResourceDecorator { @ObjectClassDefinition(name = "Apache Sling Markdown Resource Decorator") public @interface Config { @AttributeDefinition(name = "Decoration Paths", description = "Resources contained in the tree below these paths are decorated. Patterns are supported, e.g. \"/content/**.md\".") String[] decoration_paths(); @AttributeDefinition(name = "Decoration Resource Types", description = "Only resources with these resource types are decorated. If set to \"*\" all resources match.") String[] decoration_types() default {RESOURCE_TYPE_FILE}; @AttributeDefinition(name = "Resource Type", description = "The resource type for the decorated resources") String resource_type() default "sling/markdown/file"; @AttributeDefinition(name = "Source", description = "Set the source of the markdown, either InputStream (default) or Property", options = { @Option(label = "Input Stream", value ="InputStream"), @Option(label = "Property", value = "Property") }) ResourceConfiguration.SourceType source_type() default ResourceConfiguration.SourceType.InputStream; @AttributeDefinition(name = "Source Markdown Property", description = "The property is used to read the markdown if source is set to Property.") String source_markdown_property(); @AttributeDefinition(name = "Html Property", description = "Name of the property holding the rendered html") String html_property() default "jcr:description"; @AttributeDefinition(name = "Markdown Property", description = "Name of the property holding the read markdown (optional)") String markdown_property(); @AttributeDefinition(name = "Title Property", description = "Name of the property holding the title (optional)") String title_property() default "jcr:title"; @AttributeDefinition(name = "Rewrite Links", description = "If enabled, links in the markdown are rewritten.") boolean rewrite_links() default true; } public static final Logger LOGGER = LoggerFactory.getLogger(MarkdownResourceDecorator.class); private static final String RESOURCE_TYPE_FILE = "nt:file"; private final PathSet paths; private final Set<String> resourceTypes; private final ResourceConfiguration config = new ResourceConfiguration(); @Activate public MarkdownResourceDecorator(final Config cfg) { this.paths = PathSet.fromStringCollection(Arrays.stream(cfg.decoration_paths()) .map(path -> path.contains("*") ? Path.GLOB_PREFIX.concat(path) : path) .collect(Collectors.toList())); final Set<String> rts = new HashSet<>(Arrays.asList(cfg.decoration_types())); if (rts.contains("*") ) { this.resourceTypes = null; } else { this.resourceTypes = rts; } this.config.sourceType = cfg.source_type(); this.config.resourceType = cfg.resource_type(); this.config.sourceMarkdownProperty = cleanInput(cfg.source_markdown_property()); this.config.htmlProperty = cleanInput(cfg.html_property()); this.config.titleProperty = cleanInput(cfg.title_property()); this.config.markdownProperty = cleanInput(cfg.markdown_property()); this.config.rewriteLinks = cfg.rewrite_links(); } private String cleanInput(final String value) { if ( value != null && value.isBlank() ) { return null; } return value; } @Override public @Nullable Resource decorate(final @NotNull Resource resource) { // check resource type and path if ( (this.resourceTypes == null || this.resourceTypes.contains(resource.getResourceType())) && this.paths.matches( resource.getPath() ) != null ) { return new MarkdownResourceWrapper(resource, this.config); } return null; } @Override public @Nullable Resource decorate(@NotNull Resource resource, @NotNull HttpServletRequest request) { // This method is deprecated but just in case.... return this.decorate(null); } }
UTF-8
Java
6,434
java
MarkdownResourceDecorator.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.mdresource.impl; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceDecorator; import org.apache.sling.api.resource.path.Path; import org.apache.sling.api.resource.path.PathSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.service.metatype.annotations.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(name = "org.apache.sling.resource.MarkdownResourceDecorator", service = ResourceDecorator.class, configurationPolicy = ConfigurationPolicy.REQUIRE ) @Designate(ocd = MarkdownResourceDecorator.Config.class, factory = true) public class MarkdownResourceDecorator implements ResourceDecorator { @ObjectClassDefinition(name = "Apache Sling Markdown Resource Decorator") public @interface Config { @AttributeDefinition(name = "Decoration Paths", description = "Resources contained in the tree below these paths are decorated. Patterns are supported, e.g. \"/content/**.md\".") String[] decoration_paths(); @AttributeDefinition(name = "Decoration Resource Types", description = "Only resources with these resource types are decorated. If set to \"*\" all resources match.") String[] decoration_types() default {RESOURCE_TYPE_FILE}; @AttributeDefinition(name = "Resource Type", description = "The resource type for the decorated resources") String resource_type() default "sling/markdown/file"; @AttributeDefinition(name = "Source", description = "Set the source of the markdown, either InputStream (default) or Property", options = { @Option(label = "Input Stream", value ="InputStream"), @Option(label = "Property", value = "Property") }) ResourceConfiguration.SourceType source_type() default ResourceConfiguration.SourceType.InputStream; @AttributeDefinition(name = "Source Markdown Property", description = "The property is used to read the markdown if source is set to Property.") String source_markdown_property(); @AttributeDefinition(name = "Html Property", description = "Name of the property holding the rendered html") String html_property() default "jcr:description"; @AttributeDefinition(name = "Markdown Property", description = "Name of the property holding the read markdown (optional)") String markdown_property(); @AttributeDefinition(name = "Title Property", description = "Name of the property holding the title (optional)") String title_property() default "jcr:title"; @AttributeDefinition(name = "Rewrite Links", description = "If enabled, links in the markdown are rewritten.") boolean rewrite_links() default true; } public static final Logger LOGGER = LoggerFactory.getLogger(MarkdownResourceDecorator.class); private static final String RESOURCE_TYPE_FILE = "nt:file"; private final PathSet paths; private final Set<String> resourceTypes; private final ResourceConfiguration config = new ResourceConfiguration(); @Activate public MarkdownResourceDecorator(final Config cfg) { this.paths = PathSet.fromStringCollection(Arrays.stream(cfg.decoration_paths()) .map(path -> path.contains("*") ? Path.GLOB_PREFIX.concat(path) : path) .collect(Collectors.toList())); final Set<String> rts = new HashSet<>(Arrays.asList(cfg.decoration_types())); if (rts.contains("*") ) { this.resourceTypes = null; } else { this.resourceTypes = rts; } this.config.sourceType = cfg.source_type(); this.config.resourceType = cfg.resource_type(); this.config.sourceMarkdownProperty = cleanInput(cfg.source_markdown_property()); this.config.htmlProperty = cleanInput(cfg.html_property()); this.config.titleProperty = cleanInput(cfg.title_property()); this.config.markdownProperty = cleanInput(cfg.markdown_property()); this.config.rewriteLinks = cfg.rewrite_links(); } private String cleanInput(final String value) { if ( value != null && value.isBlank() ) { return null; } return value; } @Override public @Nullable Resource decorate(final @NotNull Resource resource) { // check resource type and path if ( (this.resourceTypes == null || this.resourceTypes.contains(resource.getResourceType())) && this.paths.matches( resource.getPath() ) != null ) { return new MarkdownResourceWrapper(resource, this.config); } return null; } @Override public @Nullable Resource decorate(@NotNull Resource resource, @NotNull HttpServletRequest request) { // This method is deprecated but just in case.... return this.decorate(null); } }
6,434
0.694591
0.693659
148
42.472973
31.734848
146
false
false
0
0
0
0
0
0
0.554054
false
false
9
4f265bc1878fbe63ce907cb69f04c189007170f4
11,192,684,812,270
b8fa32064908f78e89a98d2e282f0250fb1e4d2a
/src/com/wh498574932/algorithm/lc111/MinimumDepthOfBinaryTree.java
d1592003cf819d2ce321526ad4a4ee47e2e774bb
[]
no_license
wh498574932/algorithm
https://github.com/wh498574932/algorithm
aa77c0a680b832be8a5fe70e52d99cfde220d09c
e254436dc1cab9a1bd323b442675f0bfdb15d97b
refs/heads/master
2022-05-01T02:33:35.059000
2022-03-31T04:59:06
2022-03-31T04:59:06
171,216,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wh498574932.algorithm.lc111; import com.wh498574932.algorithm.model.TreeNode; /** * Given a binary tree, find its minimum depth. * * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. * * Note: A leaf is a node with no children. * * Example: * * Given binary tree [3,9,20,null,null,15,7], * * 3 * / \ * 9 20 * / \ * 15 7 * return its minimum depth = 2. * * Time: 0 ms 100.00% O(N) * Space: 38.2 MB 99.12% O(N) * * https://leetcode.com/problems/minimum-depth-of-binary-tree/ */ public class MinimumDepthOfBinaryTree { public int minDepth(TreeNode root) { if( root == null ) { return 0; } if( root.left == null && root.right == null ) { return 1; } return Math.min( root.left == null ? Integer.MAX_VALUE : minDepth(root.left), root.right == null ? Integer.MAX_VALUE : minDepth(root.right) ) + 1; } }
UTF-8
Java
1,015
java
MinimumDepthOfBinaryTree.java
Java
[]
null
[]
package com.wh498574932.algorithm.lc111; import com.wh498574932.algorithm.model.TreeNode; /** * Given a binary tree, find its minimum depth. * * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. * * Note: A leaf is a node with no children. * * Example: * * Given binary tree [3,9,20,null,null,15,7], * * 3 * / \ * 9 20 * / \ * 15 7 * return its minimum depth = 2. * * Time: 0 ms 100.00% O(N) * Space: 38.2 MB 99.12% O(N) * * https://leetcode.com/problems/minimum-depth-of-binary-tree/ */ public class MinimumDepthOfBinaryTree { public int minDepth(TreeNode root) { if( root == null ) { return 0; } if( root.left == null && root.right == null ) { return 1; } return Math.min( root.left == null ? Integer.MAX_VALUE : minDepth(root.left), root.right == null ? Integer.MAX_VALUE : minDepth(root.right) ) + 1; } }
1,015
0.586207
0.534975
37
26.432432
27.392582
117
false
false
0
0
0
0
0
0
0.378378
false
false
9
90c87e73952a48fb7b62a62e6ace2829cdec0fc2
3,384,434,274,541
42b2563a5d3e2fa7512280db0bbd77fc64445a88
/src/main/java/com/gudi/main/good/GoodMapperCommon.java
08950baa70034edaa23005449b8b064ae07066b8
[]
no_license
camusAyong/modakbul
https://github.com/camusAyong/modakbul
e1048342991034ed5284fead37131ff169a5e15b
04bb5fd77eae8e14ad5490602b73411ec50e9f98
refs/heads/master
2023-08-16T02:43:22.171000
2021-10-05T04:13:15
2021-10-05T04:13:15
412,980,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gudi.main.good; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface GoodMapperCommon { @Select("SELECT goodNum FROM good WHERE divisionNum=#{param1} AND division=#{param2} AND id=#{param3}") String goodCheck(String contentId, String division, String loginId); @Insert("INSERT INTO good(goodNum,divisionNum,division,id) VALUES(good_seq.NEXTVAL,#{param1},#{param2},#{param3})") void goodInsert(String contentId, String division, String loginId); @Delete("DELETE FROM good WHERE divisionNum=#{param1} AND division=#{param2} AND id=#{param3}") void goodDelete(String contentId, String division, String loginId); @Select("SELECT COUNT(goodNum) FROM good WHERE divisionNum=#{param1} AND division=#{param2}") int goodCount(String contentId, String division); }
UTF-8
Java
956
java
GoodMapperCommon.java
Java
[]
null
[]
package com.gudi.main.good; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface GoodMapperCommon { @Select("SELECT goodNum FROM good WHERE divisionNum=#{param1} AND division=#{param2} AND id=#{param3}") String goodCheck(String contentId, String division, String loginId); @Insert("INSERT INTO good(goodNum,divisionNum,division,id) VALUES(good_seq.NEXTVAL,#{param1},#{param2},#{param3})") void goodInsert(String contentId, String division, String loginId); @Delete("DELETE FROM good WHERE divisionNum=#{param1} AND division=#{param2} AND id=#{param3}") void goodDelete(String contentId, String division, String loginId); @Select("SELECT COUNT(goodNum) FROM good WHERE divisionNum=#{param1} AND division=#{param2}") int goodCount(String contentId, String division); }
956
0.758368
0.746862
21
44.523811
38.429428
119
false
false
0
0
0
0
0
0
1.047619
false
false
9
133592d1287b6a3181a66c179a3dcf46a21801bd
20,426,864,507,170
9d95e8087cf4aa9eda9c822f3a0f29d6c30a4256
/809/src/j2_Advance_java_Class_Design/ex18.java
6be44e69acf4885f8db0d146d54efa54832cdde7
[]
no_license
CJ-1995/EEIT-29
https://github.com/CJ-1995/EEIT-29
403b2845437a4cb146484c02d9719a02beaae932
ed214e9df012a2a2acfda4a12abeb9b108924f2e
refs/heads/master
2023-06-08T15:46:32.587000
2021-06-27T16:24:59
2021-06-27T16:24:59
366,985,043
0
0
null
false
2021-06-27T16:25:00
2021-05-13T08:33:00
2021-06-27T16:22:14
2021-06-27T16:24:59
970
0
0
0
Java
false
false
package j2_Advance_java_Class_Design; import java.util.ArrayList; import java.util.List; public class ex18 { public static void main(String args[]) { List<Alpha> strs = new ArrayList<Alpha>(); strs.add(new Alpha()); strs.add(new Beta()); strs.add(new Gamma()); for (Alpha t : strs) { System.out.println(t.doStuff("Java")); } } } class Alpha { public String doStuff(String msg) { return msg; } } class Beta extends Alpha { public String doStuff(String msg) { return msg.replace('a', 'e'); } } class Gamma extends Beta { public String doStuff(String msg) { return msg.substring(2); } } /* Given the class definitions: class Alpha { public String doStuff(String msg) { return msg; } } class Beta extends Alpha { public String doStuff(String msg) { return msg.replace('a', 'e'); } } class Gamma extends Beta { public String doStuff(String msg) { return msg.substring(2); } } And the code fragment of the main() method, List<Alpha> strs = new ArrayList<Alpha>(); strs.add(new Alpha()); strs.add(new Beta()); strs.add(new Gamma()); for (Alpha t : strs) { System.out.println(t.doStuff("Java")); } What is the result? A. Java Java Java B. Java Jeve va C. Java Jeve ve D. Compilation fails */
UTF-8
Java
1,323
java
ex18.java
Java
[]
null
[]
package j2_Advance_java_Class_Design; import java.util.ArrayList; import java.util.List; public class ex18 { public static void main(String args[]) { List<Alpha> strs = new ArrayList<Alpha>(); strs.add(new Alpha()); strs.add(new Beta()); strs.add(new Gamma()); for (Alpha t : strs) { System.out.println(t.doStuff("Java")); } } } class Alpha { public String doStuff(String msg) { return msg; } } class Beta extends Alpha { public String doStuff(String msg) { return msg.replace('a', 'e'); } } class Gamma extends Beta { public String doStuff(String msg) { return msg.substring(2); } } /* Given the class definitions: class Alpha { public String doStuff(String msg) { return msg; } } class Beta extends Alpha { public String doStuff(String msg) { return msg.replace('a', 'e'); } } class Gamma extends Beta { public String doStuff(String msg) { return msg.substring(2); } } And the code fragment of the main() method, List<Alpha> strs = new ArrayList<Alpha>(); strs.add(new Alpha()); strs.add(new Beta()); strs.add(new Gamma()); for (Alpha t : strs) { System.out.println(t.doStuff("Java")); } What is the result? A. Java Java Java B. Java Jeve va C. Java Jeve ve D. Compilation fails */
1,323
0.631141
0.627362
88
14.045455
15.090567
44
false
false
0
0
0
0
0
0
0.454545
false
false
9
c7a070135a1eb11b362ce9a90cc61728b317dfe4
25,400,436,629,982
1a2705c9c835b7bac5d5f14055f42e69707343d1
/src/main/java/cn/newtol/springbootblog/controller/BlogController.java
ef2657a14c025892a1cd76fd07a3adc9e17a84c1
[]
no_license
Newtol/springboot-blog
https://github.com/Newtol/springboot-blog
0017093b62708ead463f5b143db145f62a222acc
781f7683b02e059a33475ff8b3a8bed22ac737f1
refs/heads/master
2022-06-29T11:34:01.630000
2020-12-31T00:47:02
2020-12-31T00:47:02
184,996,867
7
3
null
false
2022-06-17T02:33:37
2019-05-05T07:41:43
2021-11-25T06:33:50
2022-06-17T02:33:37
3,677
5
3
1
JavaScript
false
false
package cn.newtol.springbootblog.controller; import cn.newtol.springbootblog.dao.ContentInfo; import cn.newtol.springbootblog.dao.ContentPraise; import cn.newtol.springbootblog.dao.ContentType; import cn.newtol.springbootblog.entity.ResultVO; import cn.newtol.springbootblog.services.BlogService; import cn.newtol.springbootblog.utils.HttpServletUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.FileNotFoundException; import java.io.IOException; /** * @Author: 公众号:Newtol * @Description: 博客页面路由 * @Date: Created in 10:54 2019/5/15 * @params: */ @Controller public class BlogController { @Resource private BlogService blogService; /** * 获取博客编辑页面 * @return */ @GetMapping("/blog/editor") public String getEditor(){ return "blog/editor"; } /** * 获取博客首页 * @return 返回首页 */ @GetMapping("/index") public String getIndex(){ return "blog/index"; } @GetMapping("/") public String getIndex2(){ return "blog/index"; } /** * 获取文章种类列表 * @return 返回所有文章种类和各自的数量 */ @GetMapping("/blog/contentType") @ResponseBody public ResultVO getContentType(){ return blogService.getAllContentType(); } /** * 添加文章种类,返回是否成功 * @param contentType * @return */ @PostMapping("/blog/contentType") @ResponseBody public ResultVO saveContentType(@Valid ContentType contentType){ return blogService.saveContentType(contentType); } /** * 保存博客 * @param contentInfo * @return 返回博客ID * @throws FileNotFoundException */ @PostMapping("/blog/content") @ResponseBody public ResultVO saveContent(@Valid ContentInfo contentInfo) throws FileNotFoundException { return blogService.saveContentInfo(contentInfo); } /** * 文章详情页 * @param contentId:文章ID * @return 返回详情页 */ @GetMapping("/blog/info") public String aboutMe(@RequestParam String contentId){ return "blog/info"; } /** * 文章点赞 * @param contentPraise * @return 返回文章ID和当前点赞数 */ @PostMapping("/blog/praise") @ResponseBody public ResultVO addPraise(HttpServletRequest httpServletRequest,@Valid ContentPraise contentPraise){ contentPraise.setIp(HttpServletUtil.getIpAdrress(httpServletRequest)); return blogService.addPraise(contentPraise); } /** * 获取文章点赞数 * @param contentId:文章ID * @return:返回文章的点赞数 */ @GetMapping("/blog/praise") @ResponseBody public ResultVO getPraise(@RequestParam String contentId){ return blogService.getPraise(contentId); } /** * 获取文章内容 */ @GetMapping("/blog/content") @ResponseBody public ResultVO getContentInfo(@RequestParam String contentId) throws IOException { blogService.addReadNum(contentId); return blogService.getContent(contentId); } /** * 获取站长推荐 * @return:最近创建的前5条文章 */ @GetMapping("/blog/recommendationList") @ResponseBody public ResultVO getRecommendationList(){ return blogService.getRecommendationList(); } /** * 获取阅读排行榜 * @return */ @GetMapping("/blog/readRankList") @ResponseBody public ResultVO getReadRankList(){ return blogService.getReadRankList(); } /** * 获取上一篇、下一篇文章 * @param createTime:当前文章的创作时间 * @return:返回文章ID、文章标题 */ @GetMapping("/blog/nearContent") @ResponseBody public ResultVO getNearContent(@RequestParam String createTime){ return blogService.getNearContent(createTime); } /** * 根据时间顺序获取文章列表 * @param page * @return */ @GetMapping("/blog/contentList") @ResponseBody public ResultVO getContentList(@RequestParam Integer page){ return blogService.getContentList(page); } @GetMapping("/blog/list") public String getListIndex(){ return "blog/list"; } /** * 根据文章类型获取文章列表 * @param contentType:文章类型 * @param page:页数 * @return */ @GetMapping("/blog/contentList/{contentType}") @ResponseBody public ResultVO getContentListByContentType(@PathVariable String contentType,@RequestParam Integer page){ return blogService.getContentListByContentType(contentType,page); } @GetMapping("/game") public String getGame(){ return "blog/infopic"; } }
UTF-8
Java
5,035
java
BlogController.java
Java
[ { "context": "\nimport java.io.IOException;\n\n/**\n * @Author: 公众号:Newtol\n * @Description: 博客页面路由\n * @Date: Created in 10:5", "end": 658, "score": 0.9841893911361694, "start": 652, "tag": "USERNAME", "value": "Newtol" } ]
null
[]
package cn.newtol.springbootblog.controller; import cn.newtol.springbootblog.dao.ContentInfo; import cn.newtol.springbootblog.dao.ContentPraise; import cn.newtol.springbootblog.dao.ContentType; import cn.newtol.springbootblog.entity.ResultVO; import cn.newtol.springbootblog.services.BlogService; import cn.newtol.springbootblog.utils.HttpServletUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.FileNotFoundException; import java.io.IOException; /** * @Author: 公众号:Newtol * @Description: 博客页面路由 * @Date: Created in 10:54 2019/5/15 * @params: */ @Controller public class BlogController { @Resource private BlogService blogService; /** * 获取博客编辑页面 * @return */ @GetMapping("/blog/editor") public String getEditor(){ return "blog/editor"; } /** * 获取博客首页 * @return 返回首页 */ @GetMapping("/index") public String getIndex(){ return "blog/index"; } @GetMapping("/") public String getIndex2(){ return "blog/index"; } /** * 获取文章种类列表 * @return 返回所有文章种类和各自的数量 */ @GetMapping("/blog/contentType") @ResponseBody public ResultVO getContentType(){ return blogService.getAllContentType(); } /** * 添加文章种类,返回是否成功 * @param contentType * @return */ @PostMapping("/blog/contentType") @ResponseBody public ResultVO saveContentType(@Valid ContentType contentType){ return blogService.saveContentType(contentType); } /** * 保存博客 * @param contentInfo * @return 返回博客ID * @throws FileNotFoundException */ @PostMapping("/blog/content") @ResponseBody public ResultVO saveContent(@Valid ContentInfo contentInfo) throws FileNotFoundException { return blogService.saveContentInfo(contentInfo); } /** * 文章详情页 * @param contentId:文章ID * @return 返回详情页 */ @GetMapping("/blog/info") public String aboutMe(@RequestParam String contentId){ return "blog/info"; } /** * 文章点赞 * @param contentPraise * @return 返回文章ID和当前点赞数 */ @PostMapping("/blog/praise") @ResponseBody public ResultVO addPraise(HttpServletRequest httpServletRequest,@Valid ContentPraise contentPraise){ contentPraise.setIp(HttpServletUtil.getIpAdrress(httpServletRequest)); return blogService.addPraise(contentPraise); } /** * 获取文章点赞数 * @param contentId:文章ID * @return:返回文章的点赞数 */ @GetMapping("/blog/praise") @ResponseBody public ResultVO getPraise(@RequestParam String contentId){ return blogService.getPraise(contentId); } /** * 获取文章内容 */ @GetMapping("/blog/content") @ResponseBody public ResultVO getContentInfo(@RequestParam String contentId) throws IOException { blogService.addReadNum(contentId); return blogService.getContent(contentId); } /** * 获取站长推荐 * @return:最近创建的前5条文章 */ @GetMapping("/blog/recommendationList") @ResponseBody public ResultVO getRecommendationList(){ return blogService.getRecommendationList(); } /** * 获取阅读排行榜 * @return */ @GetMapping("/blog/readRankList") @ResponseBody public ResultVO getReadRankList(){ return blogService.getReadRankList(); } /** * 获取上一篇、下一篇文章 * @param createTime:当前文章的创作时间 * @return:返回文章ID、文章标题 */ @GetMapping("/blog/nearContent") @ResponseBody public ResultVO getNearContent(@RequestParam String createTime){ return blogService.getNearContent(createTime); } /** * 根据时间顺序获取文章列表 * @param page * @return */ @GetMapping("/blog/contentList") @ResponseBody public ResultVO getContentList(@RequestParam Integer page){ return blogService.getContentList(page); } @GetMapping("/blog/list") public String getListIndex(){ return "blog/list"; } /** * 根据文章类型获取文章列表 * @param contentType:文章类型 * @param page:页数 * @return */ @GetMapping("/blog/contentList/{contentType}") @ResponseBody public ResultVO getContentListByContentType(@PathVariable String contentType,@RequestParam Integer page){ return blogService.getContentListByContentType(contentType,page); } @GetMapping("/game") public String getGame(){ return "blog/infopic"; } }
5,035
0.653538
0.650725
196
22.57653
20.99415
109
false
false
0
0
0
0
0
0
0.188776
false
false
9
f93eca70f5193b50fe1fe3ef0d950c205b4c3677
25,400,436,630,981
4f4613f65ed592dfd9ed7c2971e547d1d7791205
/AbstractFactory/src/example2Vehicles/Motorcycle.java
4dd45f36d18fabbe251b0bc9e1ab7a035b15ea63
[]
no_license
aiman-khan/abstract-factory
https://github.com/aiman-khan/abstract-factory
bbbbecb3035a516ca8b0517aa744eb6079b6b19a
8e4cdfb559bc59951494d8537f18aaf714a5ad6a
refs/heads/main
2023-08-14T20:05:29.393000
2021-10-09T15:21:41
2021-10-09T15:21:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example2Vehicles; public abstract class Motorcycle { int id; static int count = 0; BrandMotorcycle brandMotorcycle; abstract int getId(); abstract void setId(int id); }
UTF-8
Java
200
java
Motorcycle.java
Java
[]
null
[]
package example2Vehicles; public abstract class Motorcycle { int id; static int count = 0; BrandMotorcycle brandMotorcycle; abstract int getId(); abstract void setId(int id); }
200
0.7
0.69
11
17.181818
14.224296
36
false
false
0
0
0
0
0
0
0.545455
false
false
9
fb27d41bff019384c63cb0332f009cfcb1bf4ded
6,837,587,987,320
92362001bfcfcf0b065108a4f88cc3254dae1c60
/src/com/tonik/model/DataGather.java
156eb6dc8b773b81f0905a67a8e53c67c2fc9e57
[]
no_license
cifsccec/OverseasAuditPlatform
https://github.com/cifsccec/OverseasAuditPlatform
0579733ac8f4718eab9149b634afeea3ce286953
c01e7f3b53da6f42b0b5815a7e6dc526c9db4ee5
refs/heads/master
2020-03-16T06:13:57.655000
2018-05-08T03:45:36
2018-05-08T03:45:36
132,549,789
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tonik.model; import java.util.Date; /** * <p> * Title: Tonik Integration * </p> * <p> * Description: This is a model object for example. * </p> * @since Sep 04, 2006 * @version 1.0 * @author bchen * * @hibernate.class table="DATAGATHER" */ public class DataGather { private Long id; private Website website; private Long tnum;//采集任务数量 private Long pnum;//商品数量 //0:空闲 //1:正在执行 //2:异常 private int state; //任务状态 private String remark; private UserInfo createPerson; private Date createTime; /** * @param id The id to set. */ public void setId(Long id) { this.id = id; } /** * @hibernate.id column="GATHER_ID" type="long" unsaved-value="null" generator-class="identity" * @return Returns the id. */ public Long getId() { return id; } /** * @hibernate.many-to-one column="GATHER_WEBSITE" not-null="false" lazy="false" class="com.tonik.model.Website" * @return Returns the website. */ public Website getWebsite() { return website; } /** * @param website The website to set. */ public void setWebsite(Website website) { this.website = website; } /** *@hibernate.property column="GATHER_TARGETNUM" type="long" not-null="false" * @return Returns the tnum. */ public Long getTnum() { return tnum; } /** * @param tnum The tnum to set. */ public void setTnum(Long tnum) { this.tnum = tnum; } /** * @hibernate.property column="GATHER_PRODUCTNUM" type="long" not-null="false" * @return Returns the pnum. */ public Long getPnum() { return pnum; } /** * @param pnum The pnum to set. */ public void setPnum(Long pnum) { this.pnum = pnum; } /** * @hibernate.property column="GATHER_STATE" type="int" not-null="false" * @return Returns the state. */ public int getState() { return state; } /** * @param state The state to set. */ public void setState(int state) { this.state = state; } /** * @hibernate.property column="GATHER_REMARK" type="string" length="2000" not-null="false" * @return Returns the remark. */ public String getRemark() { return remark; } /** * @param remark The remark to set. */ public void setRemark(String remark) { this.remark = remark; } public void setCreatePerson(UserInfo createPerson) { this.createPerson = createPerson; } /** * @hibernate.many-to-one column="GATHER_CREATEPERSON" not-null="false" lazy="false" class="com.tonik.model.UserInfo" * @return Returns the website. */ public UserInfo getCreatePerson() { return createPerson; } /** * @param createTime The createTime to set. */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @hibernate.property column="GATHER_CREATETIME" sql-type="Date" not-null="false" * @return Returns the CreateTime. */ public Date getCreateTime() { return createTime; } public String getStrState() { String strState = ""; switch(state){ case 0: strState = "空闲";break; case 1: strState = "执行中";break; case 2: strState = "异常";break; } return strState; } public String getStrPnum() { if(state == 0 || state == 2) return pnum.toString(); else return "--"; } public String getStrTnum() { if(state == 0 || state == 2) return tnum.toString(); else return "--"; } }
UTF-8
Java
4,069
java
DataGather.java
Java
[ { "context": "\n * @since Sep 04, 2006\n * @version 1.0\n * @author bchen\n * \n * @hibernate.class table=\"DATAGATHER\"\n */\npu", "end": 219, "score": 0.9995988607406616, "start": 214, "tag": "USERNAME", "value": "bchen" } ]
null
[]
package com.tonik.model; import java.util.Date; /** * <p> * Title: Tonik Integration * </p> * <p> * Description: This is a model object for example. * </p> * @since Sep 04, 2006 * @version 1.0 * @author bchen * * @hibernate.class table="DATAGATHER" */ public class DataGather { private Long id; private Website website; private Long tnum;//采集任务数量 private Long pnum;//商品数量 //0:空闲 //1:正在执行 //2:异常 private int state; //任务状态 private String remark; private UserInfo createPerson; private Date createTime; /** * @param id The id to set. */ public void setId(Long id) { this.id = id; } /** * @hibernate.id column="GATHER_ID" type="long" unsaved-value="null" generator-class="identity" * @return Returns the id. */ public Long getId() { return id; } /** * @hibernate.many-to-one column="GATHER_WEBSITE" not-null="false" lazy="false" class="com.tonik.model.Website" * @return Returns the website. */ public Website getWebsite() { return website; } /** * @param website The website to set. */ public void setWebsite(Website website) { this.website = website; } /** *@hibernate.property column="GATHER_TARGETNUM" type="long" not-null="false" * @return Returns the tnum. */ public Long getTnum() { return tnum; } /** * @param tnum The tnum to set. */ public void setTnum(Long tnum) { this.tnum = tnum; } /** * @hibernate.property column="GATHER_PRODUCTNUM" type="long" not-null="false" * @return Returns the pnum. */ public Long getPnum() { return pnum; } /** * @param pnum The pnum to set. */ public void setPnum(Long pnum) { this.pnum = pnum; } /** * @hibernate.property column="GATHER_STATE" type="int" not-null="false" * @return Returns the state. */ public int getState() { return state; } /** * @param state The state to set. */ public void setState(int state) { this.state = state; } /** * @hibernate.property column="GATHER_REMARK" type="string" length="2000" not-null="false" * @return Returns the remark. */ public String getRemark() { return remark; } /** * @param remark The remark to set. */ public void setRemark(String remark) { this.remark = remark; } public void setCreatePerson(UserInfo createPerson) { this.createPerson = createPerson; } /** * @hibernate.many-to-one column="GATHER_CREATEPERSON" not-null="false" lazy="false" class="com.tonik.model.UserInfo" * @return Returns the website. */ public UserInfo getCreatePerson() { return createPerson; } /** * @param createTime The createTime to set. */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @hibernate.property column="GATHER_CREATETIME" sql-type="Date" not-null="false" * @return Returns the CreateTime. */ public Date getCreateTime() { return createTime; } public String getStrState() { String strState = ""; switch(state){ case 0: strState = "空闲";break; case 1: strState = "执行中";break; case 2: strState = "异常";break; } return strState; } public String getStrPnum() { if(state == 0 || state == 2) return pnum.toString(); else return "--"; } public String getStrTnum() { if(state == 0 || state == 2) return tnum.toString(); else return "--"; } }
4,069
0.530836
0.525343
203
18.724138
20.53599
121
false
false
0
0
0
0
0
0
0.211823
false
false
9
0f2fcd5846be28e0b4bdf07e3d29430aa0d6f6e9
10,453,950,436,319
582ac3d66729fad52c344eeda6be1371eacb426c
/src/main/java/cn/licoy/wdog/core/service/appot/VenueDetailService.java
e29af0a1d0946a480efd03211b418473907ced73
[ "MIT" ]
permissive
adolfmc/appot
https://github.com/adolfmc/appot
6a35a66242ff06ad55109bbb0ed6a6c976ab7d92
4e4a1705dc6de0eca7914262e363da817bb1166b
refs/heads/master
2023-04-22T02:23:40.349000
2021-04-13T12:09:37
2021-04-13T12:09:37
369,094,511
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.licoy.wdog.core.service.appot; import cn.licoy.wdog.common.service.QueryService; import cn.licoy.wdog.core.dto.appot.FindVenueDetailDTO; import cn.licoy.wdog.core.entity.appot.VenueDetail; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.service.IService; /** * @author mc * @version Fri Sep 25 16:39:55 2020 */ public interface VenueDetailService extends IService<VenueDetail>,QueryService<VenueDetail, FindVenueDetailDTO>{ void saveVenueDetail(JSONObject opidJsonObject ); VenueDetail getVenueDetailByVenueId(String venueId,String sportType); };
UTF-8
Java
591
java
VenueDetailService.java
Java
[ { "context": "idou.mybatisplus.service.IService;\r\r/**\r * @author mc\r * @version Fri Sep 25 16:39:55 2020\r */\rpublic i", "end": 308, "score": 0.9979743361473083, "start": 306, "tag": "USERNAME", "value": "mc" } ]
null
[]
package cn.licoy.wdog.core.service.appot; import cn.licoy.wdog.common.service.QueryService; import cn.licoy.wdog.core.dto.appot.FindVenueDetailDTO; import cn.licoy.wdog.core.entity.appot.VenueDetail; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.service.IService; /** * @author mc * @version Fri Sep 25 16:39:55 2020 */ public interface VenueDetailService extends IService<VenueDetail>,QueryService<VenueDetail, FindVenueDetailDTO>{ void saveVenueDetail(JSONObject opidJsonObject ); VenueDetail getVenueDetailByVenueId(String venueId,String sportType); };
591
0.813875
0.79357
16
35.9375
30.338648
112
false
false
0
0
0
0
0
0
0.75
false
false
9
a00166927d44345a02657c588fe6abd0f44f568f
21,706,764,759,554
6696a0d6ecfb354f6b8b60171e91abd55c5ee6a5
/spring-boot-webmvc-security-demo/src/main/java/com/mytest/demo/SecurityConfig.java
f92d57388b08d2ff7a1a438dd8ac4b7f4d3301a2
[]
no_license
lyz170/spring-boot-demo
https://github.com/lyz170/spring-boot-demo
174e17ad03edddbb0825b56701da4420933b5916
bf3f3c33547e78440df0aa1dd08d062c9c4b4e74
refs/heads/master
2020-03-20T10:03:35.009000
2018-08-01T14:59:29
2018-08-01T14:59:29
137,357,675
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mytest.demo; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // Authorize Requests .antMatchers("/index").permitAll() // permit all .antMatchers("/a1/**").hasRole("A1") // who has access to /a1/.. url .antMatchers("/a2/**").hasRole("A2") // who has access to /a2/.. url .antMatchers("/a3/**").hasAnyRole("A1", "A3") // who has access to /a3/.. url .antMatchers("/b1/**").hasAnyRole("A1", "A2", "B1") // who has access to /b1/.. url .antMatchers("/b2/**").hasAnyRole("A1", "A2", "B2") // who has access to /b2/.. url .antMatchers("/c1/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1") // who has access to /c1/.. url .antMatchers("/c2/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C2") // who has access to /c2/.. url .antMatchers("/c3/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C3") // who has access to /c3/.. url .antMatchers("/c4/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C3", "C4") // who has access to /c4/.. url // .anyRequest().authenticated() // any other request need to authenticate .and() // AND .formLogin() // login as form .loginPage("/login") // login url (default is login page with framework) // .defaultSuccessUrl("/index") // login success url (default is index) .failureUrl("/login-error") // login fail url // .and() // AND // .logout() // logout config // .logoutUrl("/logout") // logout url (default is logout) // .logoutSuccessUrl("/index") // logout success url (default is login) ; } }
UTF-8
Java
2,516
java
SecurityConfig.java
Java
[]
null
[]
package com.mytest.demo; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // Authorize Requests .antMatchers("/index").permitAll() // permit all .antMatchers("/a1/**").hasRole("A1") // who has access to /a1/.. url .antMatchers("/a2/**").hasRole("A2") // who has access to /a2/.. url .antMatchers("/a3/**").hasAnyRole("A1", "A3") // who has access to /a3/.. url .antMatchers("/b1/**").hasAnyRole("A1", "A2", "B1") // who has access to /b1/.. url .antMatchers("/b2/**").hasAnyRole("A1", "A2", "B2") // who has access to /b2/.. url .antMatchers("/c1/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1") // who has access to /c1/.. url .antMatchers("/c2/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C2") // who has access to /c2/.. url .antMatchers("/c3/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C3") // who has access to /c3/.. url .antMatchers("/c4/**").hasAnyRole("A1", "A2", "A3", "B1", "B2", "C1", "C3", "C4") // who has access to /c4/.. url // .anyRequest().authenticated() // any other request need to authenticate .and() // AND .formLogin() // login as form .loginPage("/login") // login url (default is login page with framework) // .defaultSuccessUrl("/index") // login success url (default is index) .failureUrl("/login-error") // login fail url // .and() // AND // .logout() // logout config // .logoutUrl("/logout") // logout url (default is logout) // .logoutSuccessUrl("/index") // logout success url (default is login) ; } }
2,516
0.594197
0.57194
43
57.534885
38.815216
129
false
false
0
0
0
0
0
0
0.883721
false
false
9
f75390a3ef8c64396ae114796488f64d9a323d1e
15,109,694,951,910
f21e6fd69d26b6a07d79bded9a5083fe6698cbbe
/app/src/main/java/me/alexbakker/cve_2019_9465/MainActivity.java
027061ce01141d2838a69786ee258d01ba28ca06
[ "MIT" ]
permissive
cen123456/CVE-2019-9465
https://github.com/cen123456/CVE-2019-9465
7aa0075d2124b0d063d722615c9e5eacd9f60074
97046e867f9518f053ffc8cb1f502aedc9c05e34
refs/heads/master
2022-04-04T00:48:25.884000
2020-02-19T13:56:45
2020-02-19T13:56:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.alexbakker.cve_2019_9465; import android.content.DialogInterface; import android.hardware.biometrics.BiometricPrompt; import android.os.CancellationSignal; import android.os.Handler; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; public class MainActivity extends AppCompatActivity { private int i = 0; private SecretKey _key; private int _timeout = 2000; private boolean _decrypt = true; private boolean _userAuth = true; private boolean _randomNonce = false; private boolean _strongBox = true; private View _view; private Switch _switchAuth; private Switch _switchDecrypt; private Switch _switchNonce; private Switch _switchStrongBox; private LinearLayout _layoutTimeout; private EditText _textTimeout; private TextView _log; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _log = findViewById(R.id.log); showOptionsDialog(); } private void showOptionsDialog() { _view = getLayoutInflater().inflate(R.layout.dialog_options, null); _switchAuth = _view.findViewById(R.id.switch_auth); _switchDecrypt = _view.findViewById(R.id.switch_decrypt); _switchNonce = _view.findViewById(R.id.switch_nonce); _switchStrongBox = _view.findViewById(R.id.switch_strongBox); _layoutTimeout = _view.findViewById(R.id.layout_timeout); _textTimeout = _view.findViewById(R.id.text_timeout); _switchAuth.setChecked(_userAuth); _switchAuth.setOnCheckedChangeListener((buttonView, isChecked) -> { _layoutTimeout.setVisibility(isChecked ? View.GONE : View.VISIBLE); }); _switchDecrypt.setChecked(_decrypt); _switchNonce.setChecked(_randomNonce); _switchStrongBox.setChecked(_strongBox); _textTimeout.setText(Integer.toString(_timeout)); new AlertDialog.Builder(this) .setView(_view) .setTitle("Options") .setPositiveButton(android.R.string.ok, new OptionsListener()) .show(); } private void startEncrypt() { _log.append("\n"); try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); if (_randomNonce) { cipher.init(Cipher.ENCRYPT_MODE, _key); } else { byte[] nonce = ByteBuffer.allocate(12).order(ByteOrder.BIG_ENDIAN).putInt(8, i++).array(); cipher.init(Cipher.ENCRYPT_MODE, _key, new GCMParameterSpec(16 * 8, nonce)); } if (_userAuth) { BiometricPrompt.CryptoObject obj = new BiometricPrompt.CryptoObject(cipher); BiometricPrompt prompt = new BiometricPrompt.Builder(this) .setTitle("Encrypt") .setNegativeButton("Cancel", getMainExecutor(), (dialog, which) -> { }) .build(); prompt.authenticate(obj, new CancellationSignal(), getMainExecutor(), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { encrypt(result.getCryptoObject().getCipher()); } }); } else { new Handler().postDelayed(() -> encrypt(cipher), _timeout); } } catch (Exception e) { logError(e); showOptionsDialog(); } } private void startDecrypt(byte[] encrypted, byte[] nonce) { try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, _key, new GCMParameterSpec(16 * 8, nonce)); if (_userAuth) { BiometricPrompt.CryptoObject obj = new BiometricPrompt.CryptoObject(cipher); BiometricPrompt prompt = new BiometricPrompt.Builder(this) .setTitle("Decrypt") .setNegativeButton("Cancel", getMainExecutor(), (dialog, which) -> { }) .build(); prompt.authenticate(obj, new CancellationSignal(), getMainExecutor(), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { decrypt(result.getCryptoObject().getCipher(), encrypted); } }); } else { decrypt(cipher, encrypted); } } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { logError(e); showOptionsDialog(); } } private void encrypt(Cipher cipher) { byte[] plain = "this is a test string".getBytes(StandardCharsets.UTF_8); byte[] encrypted; try { encrypted = cipher.doFinal(plain); } catch (BadPaddingException | IllegalBlockSizeException e) { logError(e); showOptionsDialog(); return; } byte[] cipherText = Arrays.copyOfRange(encrypted, 0, encrypted.length - 16); byte[] tag = Arrays.copyOfRange(encrypted, encrypted.length - 16, encrypted.length); log(String.format("plaintext: %s", encode(plain))); log(String.format("ciphertext: %s", encode(cipherText))); log(String.format("tag: %s", encode(tag))); log(String.format("nonce: %s", encode(cipher.getIV()))); if (_decrypt) { startDecrypt(encrypted, cipher.getIV()); } else { startEncrypt(); } } private void decrypt(Cipher cipher, byte[] encrypted) { byte[] decrypted; try { decrypted = cipher.doFinal(encrypted); } catch (BadPaddingException | IllegalBlockSizeException e) { logError(e); showOptionsDialog(); return; } log(String.format("decrypted: %s", encode(decrypted))); startEncrypt(); } private void log(String msg) { Log.println(Log.DEBUG, "Main", msg); _log.append(msg + "\n"); } private void logError(Exception e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(); log("\n" + sw.toString()); } private static String encode(byte[] a) { StringBuilder sb = new StringBuilder(a.length * 2); for (byte b : a) { sb.append(String.format("%02x", b)); } return sb.toString(); } private class OptionsListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { _userAuth = _switchAuth.isChecked(); _decrypt = _switchDecrypt.isChecked(); _randomNonce = _switchNonce.isChecked(); _strongBox = _switchStrongBox.isChecked(); _timeout = Integer.parseInt(_textTimeout.getText().toString()); try { KeyStore store = KeyStore.getInstance("AndroidKeyStore"); store.load(null); // make sure the key store is empty before continuing for (String alias : Collections.list(store.aliases())) { store.deleteEntry(alias); } int purpose = KeyProperties.PURPOSE_ENCRYPT; if (_decrypt) { purpose |= KeyProperties.PURPOSE_DECRYPT; } KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); generator.init(new KeyGenParameterSpec.Builder("test", purpose) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setRandomizedEncryptionRequired(_randomNonce) .setUserAuthenticationRequired(_userAuth) .setIsStrongBoxBacked(_strongBox) .setKeySize(256) .build()); _key = generator.generateKey(); } catch (Exception e) { logError(e); showOptionsDialog(); return; } startEncrypt(); } } }
UTF-8
Java
9,817
java
MainActivity.java
Java
[ { "context": "package me.alexbakker.cve_2019_9465;\n\nimport android.content.DialogInte", "end": 21, "score": 0.9930281639099121, "start": 11, "tag": "USERNAME", "value": "alexbakker" } ]
null
[]
package me.alexbakker.cve_2019_9465; import android.content.DialogInterface; import android.hardware.biometrics.BiometricPrompt; import android.os.CancellationSignal; import android.os.Handler; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; public class MainActivity extends AppCompatActivity { private int i = 0; private SecretKey _key; private int _timeout = 2000; private boolean _decrypt = true; private boolean _userAuth = true; private boolean _randomNonce = false; private boolean _strongBox = true; private View _view; private Switch _switchAuth; private Switch _switchDecrypt; private Switch _switchNonce; private Switch _switchStrongBox; private LinearLayout _layoutTimeout; private EditText _textTimeout; private TextView _log; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _log = findViewById(R.id.log); showOptionsDialog(); } private void showOptionsDialog() { _view = getLayoutInflater().inflate(R.layout.dialog_options, null); _switchAuth = _view.findViewById(R.id.switch_auth); _switchDecrypt = _view.findViewById(R.id.switch_decrypt); _switchNonce = _view.findViewById(R.id.switch_nonce); _switchStrongBox = _view.findViewById(R.id.switch_strongBox); _layoutTimeout = _view.findViewById(R.id.layout_timeout); _textTimeout = _view.findViewById(R.id.text_timeout); _switchAuth.setChecked(_userAuth); _switchAuth.setOnCheckedChangeListener((buttonView, isChecked) -> { _layoutTimeout.setVisibility(isChecked ? View.GONE : View.VISIBLE); }); _switchDecrypt.setChecked(_decrypt); _switchNonce.setChecked(_randomNonce); _switchStrongBox.setChecked(_strongBox); _textTimeout.setText(Integer.toString(_timeout)); new AlertDialog.Builder(this) .setView(_view) .setTitle("Options") .setPositiveButton(android.R.string.ok, new OptionsListener()) .show(); } private void startEncrypt() { _log.append("\n"); try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); if (_randomNonce) { cipher.init(Cipher.ENCRYPT_MODE, _key); } else { byte[] nonce = ByteBuffer.allocate(12).order(ByteOrder.BIG_ENDIAN).putInt(8, i++).array(); cipher.init(Cipher.ENCRYPT_MODE, _key, new GCMParameterSpec(16 * 8, nonce)); } if (_userAuth) { BiometricPrompt.CryptoObject obj = new BiometricPrompt.CryptoObject(cipher); BiometricPrompt prompt = new BiometricPrompt.Builder(this) .setTitle("Encrypt") .setNegativeButton("Cancel", getMainExecutor(), (dialog, which) -> { }) .build(); prompt.authenticate(obj, new CancellationSignal(), getMainExecutor(), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { encrypt(result.getCryptoObject().getCipher()); } }); } else { new Handler().postDelayed(() -> encrypt(cipher), _timeout); } } catch (Exception e) { logError(e); showOptionsDialog(); } } private void startDecrypt(byte[] encrypted, byte[] nonce) { try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, _key, new GCMParameterSpec(16 * 8, nonce)); if (_userAuth) { BiometricPrompt.CryptoObject obj = new BiometricPrompt.CryptoObject(cipher); BiometricPrompt prompt = new BiometricPrompt.Builder(this) .setTitle("Decrypt") .setNegativeButton("Cancel", getMainExecutor(), (dialog, which) -> { }) .build(); prompt.authenticate(obj, new CancellationSignal(), getMainExecutor(), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { decrypt(result.getCryptoObject().getCipher(), encrypted); } }); } else { decrypt(cipher, encrypted); } } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { logError(e); showOptionsDialog(); } } private void encrypt(Cipher cipher) { byte[] plain = "this is a test string".getBytes(StandardCharsets.UTF_8); byte[] encrypted; try { encrypted = cipher.doFinal(plain); } catch (BadPaddingException | IllegalBlockSizeException e) { logError(e); showOptionsDialog(); return; } byte[] cipherText = Arrays.copyOfRange(encrypted, 0, encrypted.length - 16); byte[] tag = Arrays.copyOfRange(encrypted, encrypted.length - 16, encrypted.length); log(String.format("plaintext: %s", encode(plain))); log(String.format("ciphertext: %s", encode(cipherText))); log(String.format("tag: %s", encode(tag))); log(String.format("nonce: %s", encode(cipher.getIV()))); if (_decrypt) { startDecrypt(encrypted, cipher.getIV()); } else { startEncrypt(); } } private void decrypt(Cipher cipher, byte[] encrypted) { byte[] decrypted; try { decrypted = cipher.doFinal(encrypted); } catch (BadPaddingException | IllegalBlockSizeException e) { logError(e); showOptionsDialog(); return; } log(String.format("decrypted: %s", encode(decrypted))); startEncrypt(); } private void log(String msg) { Log.println(Log.DEBUG, "Main", msg); _log.append(msg + "\n"); } private void logError(Exception e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(); log("\n" + sw.toString()); } private static String encode(byte[] a) { StringBuilder sb = new StringBuilder(a.length * 2); for (byte b : a) { sb.append(String.format("%02x", b)); } return sb.toString(); } private class OptionsListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { _userAuth = _switchAuth.isChecked(); _decrypt = _switchDecrypt.isChecked(); _randomNonce = _switchNonce.isChecked(); _strongBox = _switchStrongBox.isChecked(); _timeout = Integer.parseInt(_textTimeout.getText().toString()); try { KeyStore store = KeyStore.getInstance("AndroidKeyStore"); store.load(null); // make sure the key store is empty before continuing for (String alias : Collections.list(store.aliases())) { store.deleteEntry(alias); } int purpose = KeyProperties.PURPOSE_ENCRYPT; if (_decrypt) { purpose |= KeyProperties.PURPOSE_DECRYPT; } KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); generator.init(new KeyGenParameterSpec.Builder("test", purpose) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setRandomizedEncryptionRequired(_randomNonce) .setUserAuthenticationRequired(_userAuth) .setIsStrongBoxBacked(_strongBox) .setKeySize(256) .build()); _key = generator.generateKey(); } catch (Exception e) { logError(e); showOptionsDialog(); return; } startEncrypt(); } } }
9,817
0.603137
0.599674
266
35.906013
27.099556
132
false
false
0
0
0
0
0
0
0.714286
false
false
9
38fcf40da9cc8d04c8a2d1e4e1300f0c64e7d809
8,246,337,261,676
27a37d59e88c9b91b411ce28f6bbf1c0dbfe066b
/FallCPS310-Labs/LinkedList/LinkedList.java
047845cde8aac418db354e3a32b67163b746878a
[]
no_license
adrielmartine14/CPS310
https://github.com/adrielmartine14/CPS310
297380f5e3e734429cf84a538917c5d7133ae914
07ea6e45f35024d0440c04b5671c94a0439d59b7
refs/heads/master
2020-04-01T21:42:34.197000
2018-11-08T02:46:54
2018-11-08T02:46:54
153,671,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class LinkedList{ static Node head= null; public void addFront(int data){ Node newNode= new Node(data); newNode.next= head; head=newNode; } public void printList(){ Node temp= head; while(temp !=null){ System.out.print(temp.data+"->"); temp= temp.next; } } public void addEnd(int data){ Node newNode = new Node(data); if(head==null){ head = newNode; } else{ Node temp= head; while(temp.next != null){ temp=temp.next; } temp.next=newNode ; } } public void delete(int key){ Node temp= head; Node prev= null; if(temp != null && temp.data == key){ head= temp.next; return; } while(temp != null && temp.data != key){ prev= temp; temp=temp.next; } if(temp == null){ return; } prev.next= temp.next; } public LinkedList reverse(LinkedList list){ Node prev= null; Node current= list.head; while(current != null){ Node next= current.next; current.next= prev; prev= current; current= next; } list.head= prev; return list; } }
UTF-8
Java
1,383
java
LinkedList.java
Java
[]
null
[]
public class LinkedList{ static Node head= null; public void addFront(int data){ Node newNode= new Node(data); newNode.next= head; head=newNode; } public void printList(){ Node temp= head; while(temp !=null){ System.out.print(temp.data+"->"); temp= temp.next; } } public void addEnd(int data){ Node newNode = new Node(data); if(head==null){ head = newNode; } else{ Node temp= head; while(temp.next != null){ temp=temp.next; } temp.next=newNode ; } } public void delete(int key){ Node temp= head; Node prev= null; if(temp != null && temp.data == key){ head= temp.next; return; } while(temp != null && temp.data != key){ prev= temp; temp=temp.next; } if(temp == null){ return; } prev.next= temp.next; } public LinkedList reverse(LinkedList list){ Node prev= null; Node current= list.head; while(current != null){ Node next= current.next; current.next= prev; prev= current; current= next; } list.head= prev; return list; } }
1,383
0.462039
0.462039
56
23.714285
11.641542
48
false
false
0
0
0
0
0
0
0.5
false
false
9
ef60ae4bf007b346c25e1e2052daef7e0bac9fa9
18,777,597,074,500
4b385f33d6cef8bd455631beb1bb75680c4b01b4
/src/main/java/cz/nalezen/osm/extractor/data/District.java
05ef13f74960efbf324832cf3f9251a5e0236d77
[ "Apache-2.0" ]
permissive
jkubos/osm-address-extractor
https://github.com/jkubos/osm-address-extractor
5556f7be80e056dc5ddc329e35cd0a4e339fd314
68039819dfef68183ac5d1f28f699f6f876f2a1c
refs/heads/master
2021-01-17T08:11:10.272000
2016-02-11T06:18:48
2016-02-11T06:18:48
17,545,857
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.nalezen.osm.extractor.data; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonIgnore; public class District { private String name; private ArrayList<City> cities = new ArrayList<>(); public District() { } public String getName() { return name; } public void setName(String name) { if (name.length()<3) { throw new RuntimeException(String.format("Too short district name: '%s'", name)); } this.name = name; } public ArrayList<City> getCities() { return cities; } public void setCities(ArrayList<City> cities) { this.cities = cities; cities.forEach(city->city.setDistrict(this)); } @JsonIgnore public City assureCity(String cityName) { String cname = cityName.trim().toLowerCase(); for (City city : cities) { if (city.getName().equals(cname)) { return city; } } City city = new City(this); city.setName(cname); cities.add(city); return city; } public City lookupCity(String cityName) { String cname = cityName.trim().toLowerCase(); for (City city : cities) { if (city.getName().equals(cname)) { return city; } } return null; } }
UTF-8
Java
1,169
java
District.java
Java
[]
null
[]
package cz.nalezen.osm.extractor.data; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonIgnore; public class District { private String name; private ArrayList<City> cities = new ArrayList<>(); public District() { } public String getName() { return name; } public void setName(String name) { if (name.length()<3) { throw new RuntimeException(String.format("Too short district name: '%s'", name)); } this.name = name; } public ArrayList<City> getCities() { return cities; } public void setCities(ArrayList<City> cities) { this.cities = cities; cities.forEach(city->city.setDistrict(this)); } @JsonIgnore public City assureCity(String cityName) { String cname = cityName.trim().toLowerCase(); for (City city : cities) { if (city.getName().equals(cname)) { return city; } } City city = new City(this); city.setName(cname); cities.add(city); return city; } public City lookupCity(String cityName) { String cname = cityName.trim().toLowerCase(); for (City city : cities) { if (city.getName().equals(cname)) { return city; } } return null; } }
1,169
0.663815
0.66296
64
17.265625
18.447765
84
false
false
0
0
0
0
0
0
1.765625
false
false
9
3a5aa3a3bf05b3a67f9bd110d8754e9b8ce5f985
15,436,112,496,977
f6cb5a0f2ae620fc20741b773722c4d90c631b08
/lab7-substring-search/bruteForceSearch_starter.java
24373785de22720a30e03b4009a715b4e760158d
[]
no_license
noorb98/comp20290-algorithms
https://github.com/noorb98/comp20290-algorithms
4fc6f536f5f7d6af30542c12c2f8d006b54d6f36
8523680ed3c88e92813b9475ccd9ad3c16b0e412
refs/heads/master
2022-09-22T22:17:35.971000
2020-05-31T17:14:09
2020-05-31T17:14:09
260,374,069
0
0
null
true
2020-05-01T03:49:14
2020-05-01T03:49:14
2020-04-30T12:56:45
2020-05-01T00:41:59
936
0
0
0
null
false
false
// Java program for Naive Pattern Searching public class bruteForceSearch { public static void search(String txt, String pat) { //insert your code here } } public static void main(String[] args) { //alter to take text file in.. String txt = "ABABDABACDABABCABAB"; String pat = "ABABCABAB"; search(txt, pat); } }
UTF-8
Java
422
java
bruteForceSearch_starter.java
Java
[]
null
[]
// Java program for Naive Pattern Searching public class bruteForceSearch { public static void search(String txt, String pat) { //insert your code here } } public static void main(String[] args) { //alter to take text file in.. String txt = "ABABDABACDABABCABAB"; String pat = "ABABCABAB"; search(txt, pat); } }
422
0.542654
0.542654
19
21.105263
17.814526
55
false
false
0
0
0
0
0
0
1.210526
false
false
9
5561306d4461a12fd0a85c5880e16432f284cce1
24,704,651,922,074
cb141fa0985570e217dab4c9032d5bb879feefff
/src/main/java/com/example/app/validator/user/groups/Register.java
1b8011c83cb1f1b86ec4e1b2e0032dfa0a2a5a4a
[]
no_license
Aleksa24/DiplomskiAleksaPetarMarko
https://github.com/Aleksa24/DiplomskiAleksaPetarMarko
287f62bc2dda02479934e2e5ca8641d2a20eaadc
a6fd9f9bea6fd28f0b34a2553e5507778b466871
refs/heads/master
2023-06-23T13:04:24.197000
2020-09-19T14:06:16
2020-09-19T14:06:16
279,422,697
0
0
null
false
2023-06-14T22:31:04
2020-07-13T22:14:18
2020-09-19T14:06:38
2023-06-14T22:31:04
1,596
0
0
1
Java
false
false
package com.example.app.validator.user.groups; public interface Register { }
UTF-8
Java
78
java
Register.java
Java
[]
null
[]
package com.example.app.validator.user.groups; public interface Register { }
78
0.794872
0.794872
4
18.5
19.215879
46
false
false
0
0
0
0
0
0
0.25
false
false
9
1a8489eb4c0c9f5940cb38476d4d1f5711f88d08
6,236,292,546,863
13ed02e4d8f9afa00a3f30c09172f17780115b6b
/yirui-admin/src/main/java/com/yirui/admin/sys/user/model/UserStatus.java
4c61f2fad26fe9a9e57c224f9e04215111de2bad
[ "Apache-2.0" ]
permissive
yorkchow/yirui
https://github.com/yorkchow/yirui
89ab1a0960e5154b6d79c77bec7040a06fd339a9
67b407f9efafeb9e48dd7d6f25fa75fc6227c719
refs/heads/master
2020-05-31T18:40:08.684000
2014-11-14T16:17:26
2014-11-14T16:17:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yirui.admin.sys.user.model; /** * User status * @author YorkChow<york.chow@actionsky.com> * @since 2014/11/7 * Time: 22:41 */ public enum UserStatus { normal("正常状态"), blocked("封禁状态"); private final String info; private UserStatus(String info) { this.info = info; } public String getInfo() { return info; } }
UTF-8
Java
386
java
UserStatus.java
Java
[ { "context": "min.sys.user.model;\n\n/**\n * User status\n * @author YorkChow<york.chow@actionsky.com>\n * @since 2014/11/7\n * T", "end": 79, "score": 0.9979807734489441, "start": 71, "tag": "USERNAME", "value": "YorkChow" }, { "context": "er.model;\n\n/**\n * User status\n * @autho...
null
[]
package com.yirui.admin.sys.user.model; /** * User status * @author YorkChow<<EMAIL>> * @since 2014/11/7 * Time: 22:41 */ public enum UserStatus { normal("正常状态"), blocked("封禁状态"); private final String info; private UserStatus(String info) { this.info = info; } public String getInfo() { return info; } }
370
0.613514
0.583784
22
15.818182
14.742136
44
false
false
0
0
0
0
0
0
0.272727
false
false
9
fb3f16051bb7876716c4a5ffafc46a419154f397
4,990,752,025,486
8352d839e88fe904a5384dad0f63d4f0bdc853e2
/src/main/java/com/example/demo/mapper/MyBillMapper.java
82ebec60de9f0a045a1f26277ed5235e0bdaed95
[]
no_license
imapach/demo
https://github.com/imapach/demo
246f4acde2b416fd9fd078a49c2a2f4039da40a4
29a6a76b42d29eb5f57924c1c2fadf43f6a26b45
refs/heads/master
2018-12-20T06:05:36.616000
2018-09-17T11:59:57
2018-09-17T11:59:57
149,118,019
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.mapper; import com.example.demo.entity.MyBill; import org.springframework.stereotype.Repository; @Repository public interface MyBillMapper { MyBill selectById(Integer billId); void insertBill(MyBill myBill); void updateBill(MyBill myBill); }
UTF-8
Java
281
java
MyBillMapper.java
Java
[]
null
[]
package com.example.demo.mapper; import com.example.demo.entity.MyBill; import org.springframework.stereotype.Repository; @Repository public interface MyBillMapper { MyBill selectById(Integer billId); void insertBill(MyBill myBill); void updateBill(MyBill myBill); }
281
0.786477
0.786477
11
24.545454
17.105892
49
false
false
0
0
0
0
0
0
0.545455
false
false
9
898acd7f183c35c19b294a7f055f798c19bcbe0a
12,618,613,946,405
eb1b7a8d93ff5fc1ba7fc8ed392ec06318cea4d3
/core/src/main/java/com/soffid/iam/addons/report/service/ReportSchedulerBootServiceImpl.java
66de7a6a6b4c2fb535d0c7b2770a15715c1a639f
[]
no_license
SoffidIAM/addon-reports
https://github.com/SoffidIAM/addon-reports
cc838b664965d3b9b34c220ab088bbbee6d8527b
04c32e9fd9feadf0064176816d1413f187ea9303
refs/heads/master
2023-08-05T20:47:20.521000
2018-09-12T11:22:48
2018-09-12T11:22:48
23,780,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soffid.iam.addons.report.service; import java.net.InetAddress; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import es.caib.seycon.ng.comu.Configuracio; import es.caib.seycon.ng.servei.ConfiguracioService; public class ReportSchedulerBootServiceImpl extends ReportSchedulerBootServiceBase implements ApplicationContextAware { private ApplicationContext applicationContext; @Override protected void handleSyncServerBoot() throws Exception { } @Override protected void handleConsoleBoot() throws Exception { org.apache.commons.logging.Log log = LogFactory.getLog(getClass()); ConfiguracioService cfgSvc = getConfiguracioService(); Configuracio cfg = cfgSvc.findParametreByCodiAndCodiXarxa("addon.report.server", null); String hostName = InetAddress.getLocalHost().getHostName(); if (cfg == null) { cfg = new Configuracio (); cfg.setCodi("addon.report.server"); cfg.setValor(hostName); cfg.setDescripcio("Console to execute reports"); cfgSvc.create(cfg); } else if (! cfg.getValor().equals(hostName)) { log.info("This host is not the report server ("+cfg.getValor()+")"); return; } SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); ExecutorThread executorThread = ExecutorThread.getInstance(); executorThread.setReportSchedulerService(getReportSchedulerService()); executorThread.setReportService(getReportService()); executorThread.setSessionFactory(sessionFactory); executorThread.setDocumentService(getDocumentService()); SchedulerThread schedulerThread = SchedulerThread.getInstance(); schedulerThread.setReportSchedulerService(getReportSchedulerService()); schedulerThread.setReportService(getReportService()); schedulerThread.setExecutorThread(executorThread); if (! executorThread.isAlive()) executorThread.start(); if (! schedulerThread.isAlive()) schedulerThread.start(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
UTF-8
Java
2,291
java
ReportSchedulerBootServiceImpl.java
Java
[]
null
[]
package com.soffid.iam.addons.report.service; import java.net.InetAddress; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import es.caib.seycon.ng.comu.Configuracio; import es.caib.seycon.ng.servei.ConfiguracioService; public class ReportSchedulerBootServiceImpl extends ReportSchedulerBootServiceBase implements ApplicationContextAware { private ApplicationContext applicationContext; @Override protected void handleSyncServerBoot() throws Exception { } @Override protected void handleConsoleBoot() throws Exception { org.apache.commons.logging.Log log = LogFactory.getLog(getClass()); ConfiguracioService cfgSvc = getConfiguracioService(); Configuracio cfg = cfgSvc.findParametreByCodiAndCodiXarxa("addon.report.server", null); String hostName = InetAddress.getLocalHost().getHostName(); if (cfg == null) { cfg = new Configuracio (); cfg.setCodi("addon.report.server"); cfg.setValor(hostName); cfg.setDescripcio("Console to execute reports"); cfgSvc.create(cfg); } else if (! cfg.getValor().equals(hostName)) { log.info("This host is not the report server ("+cfg.getValor()+")"); return; } SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); ExecutorThread executorThread = ExecutorThread.getInstance(); executorThread.setReportSchedulerService(getReportSchedulerService()); executorThread.setReportService(getReportService()); executorThread.setSessionFactory(sessionFactory); executorThread.setDocumentService(getDocumentService()); SchedulerThread schedulerThread = SchedulerThread.getInstance(); schedulerThread.setReportSchedulerService(getReportSchedulerService()); schedulerThread.setReportService(getReportService()); schedulerThread.setExecutorThread(executorThread); if (! executorThread.isAlive()) executorThread.start(); if (! schedulerThread.isAlive()) schedulerThread.start(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
2,291
0.794413
0.794413
66
33.71212
27.10125
96
false
false
0
0
0
0
0
0
1.909091
false
false
9
f9ff4e7bb64cff8d55c0530f81bbb224c9b1d292
6,201,932,821,223
57d4b2f7226c4c42f772ae1234e215d958996d7a
/src/main/java/abstractFactory/PlaneFactory.java
5bb95e0dc55f00d6fb3e6bbeef6bca58913fc0d3
[]
no_license
TusovskyiVolodymyr/patterns
https://github.com/TusovskyiVolodymyr/patterns
25709fc8be88e64f22d3a6ce2efb5264e612c775
27401c95cfd7cef87e49b82f837202eca2cf6c7f
refs/heads/master
2020-03-30T15:29:42.264000
2018-10-31T12:44:15
2018-10-31T12:44:15
151,365,881
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package abstractFactory; import abstractFactory.plane.Plane; import abstractFactory.plane.PropellerPlane; import abstractFactory.plane.ReactivePlane; public class PlaneFactory implements MilitaryFactory { public PlaneFactory() { } @Override public Plane createMachine(String s) { Plane plane = null; switch (s) { case "Reactive": { plane = new ReactivePlane(); } case "Propeller": { plane = new PropellerPlane(); } return plane; } return null; } }
UTF-8
Java
596
java
PlaneFactory.java
Java
[]
null
[]
package abstractFactory; import abstractFactory.plane.Plane; import abstractFactory.plane.PropellerPlane; import abstractFactory.plane.ReactivePlane; public class PlaneFactory implements MilitaryFactory { public PlaneFactory() { } @Override public Plane createMachine(String s) { Plane plane = null; switch (s) { case "Reactive": { plane = new ReactivePlane(); } case "Propeller": { plane = new PropellerPlane(); } return plane; } return null; } }
596
0.582215
0.582215
25
22.799999
16.265301
54
false
false
0
0
0
0
0
0
0.36
false
false
9
4cf937ac78638812a5c5ddebca1014bc8920c52c
4,045,859,235,731
ae81f464805d7b4bc7d4889f6ba54ef65e655be8
/app/src/main/java/com/example/hanlian/Activity/GoodsSortActivity.java
cfeff5cc2bc30a5cc49b33292a16d25118a1f6ed
[]
no_license
zhouyin1990/MyHanlian
https://github.com/zhouyin1990/MyHanlian
0aa293b0fe15fd2e0728a35e783b265641638e0a
1e6066ac2342ad72ae1b3717754442dc470a209d
refs/heads/master
2021-01-20T03:35:25.569000
2017-06-27T07:57:40
2017-06-27T07:57:40
89,561,099
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hanlian.Activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.VolleyError; import com.bumptech.glide.Glide; import com.example.hanlian.Adapter.CustomAdapter; import com.example.hanlian.Adapter.GoodsInfo; import com.example.hanlian.Adapter.MyAdapter; import com.example.hanlian.Adapter.ViewHolder; import com.example.hanlian.DateModel.Classify; import com.example.hanlian.MyApplication.MyApplication; import com.example.hanlian.R; import com.nostra13.universalimageloader.core.ImageLoader; import com.xinbo.utils.HTTPUtils; import com.xinbo.utils.ResponseListener; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import utils.JsonHelper; import utils.LogUtil; import utils.TCHConstants; /** * 产品分类 */ public class GoodsSortActivity extends Activity implements OnClickListener { private ListView sort_listView1; private ListView sort_listView3; private RecyclerView sort_recyclerview; private List<GoodsInfo> sortData1 = new ArrayList<GoodsInfo>();// 大的类别数据 private List<GoodsInfo> sortData2 = new ArrayList<GoodsInfo>();// 小的类别数据 private List<GoodsInfo> sortData3 = new ArrayList<GoodsInfo>();// 海报的类别数据 // private String[] mGridViewImgRes = new String[]{}; // private String[] data = new String[] { "上衣", "裤子" , "裙子", "亲子装", "鞋子","套装", "饰品", "家居服" }; private String sort; private JSONArray goodsList = new JSONArray();// 大的类别数据 private MyAdapter2 myAdapter2; private MyAdapter recyclerviewAdapter; private int firstId;// 第一次进来的商品id private ArrayList<Classify.ResultBean.TBSUBCLASSBean> playbillData = new ArrayList();// private ArrayList<Classify.ResultBean.TBSUBCLASSBean.TBGOODSBean> Goodlist = new ArrayList();//海报 private ArrayList<Classify.ResultBean> Result = new ArrayList(); private PalybillAdapter palybillAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goods_sort); // PushAgent.getInstance(this).onAppStart(); Intent intent = getIntent(); sort = intent.getStringExtra("sort"); int position = intent.getIntExtra("position", 0); initView(); initData(); initClassifyData(position); } private void initClassifyData(int position) { OkHttpUtils.get().url(TCHConstants.url.Classify).build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { LogUtil.e(" ==", "" + e); } @Override public void onResponse(String response, int id) { Classify classifyjson = JsonHelper.fromJson(response, Classify.class); List<Classify.ResultBean> result = classifyjson.getResult(); // TODO 点击切换时如何动态的获取下标改变海报 LogUtil.e("海报size==", result.size() + ""); List<Classify.ResultBean.TBSUBCLASSBean> tb_subclass = classifyjson.getResult().get(position).getTB_SUBCLASS(); playbillData.clear(); playbillData.addAll(tb_subclass); LogUtil.e("海报==", tb_subclass.size() + ""); Goodlist.clear(); for (int i = 0; i < playbillData.size(); i++) { List<Classify.ResultBean.TBSUBCLASSBean.TBGOODSBean> tb_goods = playbillData.get(i).getTB_GOODS(); Goodlist.addAll(tb_goods); } palybillAdapter.notifyDataSetChanged(); } }); } private void initView() { findViewById(R.id.sort_back).setOnClickListener(this); findViewById(R.id.sort_et_search).setOnClickListener(this); sort_listView1 = (ListView) findViewById(R.id.sort_listView); myAdapter2 = new MyAdapter2(); sort_listView1.setAdapter(myAdapter2); sort_listView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { initData2(sortData1.get(position).id);//点击listview切换分类 myAdapter2.setSelectItem(position); // 设置选中项目 myAdapter2.notifyDataSetChanged();//listview recyclerviewAdapter.notifyDataSetChanged(); //RecyclerView // TODO: 2017/6/14 点击切换 海报数据 // palybillAdapter.notifyDataSetChanged(); initClassifyData(position); } }); //展示页listview数据 sort_listView3 = (ListView) findViewById(R.id.sort_listView2); palybillAdapter = new PalybillAdapter(); sort_listView3.setAdapter(palybillAdapter); // sort_listView3.setAdapter(new CustomAdapter<GoodsInfo>(GoodsSortActivity.this, sortData3, // R.layout.item_sort2) { // @Override // public void convert(ViewHolder holder, GoodsInfo t) { // // ImageView item_sort_image = holder.getView(R.id.item_sort_image); // ImageLoader.getInstance().displayImage(TCHConstants.url.imgurl + t.image, item_sort_image, MyApplication.options); //// item_sort_image.setImageDrawable(getResources().getDrawable(R.drawable.new_banner_02)); // holder.getView(R.id.item_sort_name).setVisibility(View.GONE); // } // }); sort_recyclerview = (RecyclerView) findViewById(R.id.sort_recyclerview); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);//水平流 sort_recyclerview.setLayoutManager(layoutManager); recyclerviewAdapter = new MyAdapter(sortData2, this); sort_recyclerview.setAdapter(recyclerviewAdapter); } // 左侧 listview public class MyAdapter2 extends BaseAdapter { public int getCount() { return sortData1.size(); // a ? b :c a==ture 取值 b a==false 取值 c // return sortData1.size()==0 ? sortData1.size() : 1 ; } public Object getItem(int arg0) { return 0; } public long getItemId(int arg0) { return arg0; } public View getView(int position, View convertView, ViewGroup parent) { // position listview 对应的条数 converView 返回视图 parent 加载对应的xml Holder holder = null; if (convertView == null) { holder = new Holder(); convertView = getLayoutInflater().inflate(R.layout.item_sort0, null); holder.name = (TextView) convertView.findViewById(R.id.item_sort_name); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.name.setText(sortData1.get(position).name); if (position == selectItem) { // 设置点击选中item背景 convertView.setBackgroundColor(getResources().getColor(R.color.gray)); } else { convertView.setBackgroundColor(getResources().getColor(R.color.white)); } return convertView; } public void setSelectItem(int selectItem) { this.selectItem = selectItem; } private int selectItem = -1; } //获取主分类数据 private void initData() { Map<String, String> params = new HashMap<String, String>(); params.put("type", "1"); params.put("classifyid", "0"); HTTPUtils.get(getApplicationContext(), TCHConstants.url.goodsSort, params, new ResponseListener() { private int firstId; @Override public void onResponse(String arg0) { try { goodsList = new JSONObject(arg0.toString()).getJSONArray("Result"); if (goodsList.length() > 0) { for (int i = 0; i < goodsList.length(); i++) { JSONObject goodsObject = goodsList.getJSONObject(i); String name = goodsObject.getString("CM_CLASSIFYNAME"); int goodsId = goodsObject.getInt("CM_CLASSIFYID"); sortData1.add(new GoodsInfo("", name, goodsId)); if (name.equals(sort)) {// 设置初始进入时选中listview firstId = goodsId; myAdapter2.setSelectItem(i);//设置选中项 } } myAdapter2.notifyDataSetChanged(); initData2(firstId); } else { // 搜索为空 Toast.makeText(getApplicationContext(), "获取数据失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onErrorResponse(VolleyError arg0) { } }); } //二级分类数据 private void initData2(int id) { sortData2.clear(); Map<String, String> params = new HashMap<String, String>(); params.put("type", 2 + ""); params.put("classifyid", id + ""); //获取分类详情数据 HTTPUtils.get(getApplicationContext(), TCHConstants.url.goodsSort, params, new ResponseListener() { @Override public void onResponse(String arg0) { try { goodsList = new JSONObject(arg0.toString()).getJSONArray("Result"); if (goodsList.length() > 0) { // LogUtil.e("二级分类数据==", goodsList.toString()); for (int i = 0; i < goodsList.length(); i++) { JSONObject goodsObject = goodsList.getJSONObject(i); String name = goodsObject.getString("CM_CLASSIFYNAME"); String imageUrl = goodsObject.getString("CM_IMGPATH"); int goodsId = goodsObject.getInt("CM_CLASSIFYID"); sortData2.add(new GoodsInfo(imageUrl, name, goodsId)); sortData3.add(new GoodsInfo(imageUrl, name, goodsId)); /** * 海报图片路径 */ // JSONArray tb_subclass = goodsObject.getJSONArray("TB_SUBCLASS"); // if (tb_subclass.length() >0) // { // JSONObject jsonObject = tb_subclass.getJSONObject(i); // JSONArray tb_goods = jsonObject.getJSONArray("TB_GOODS"); // String cm_mainfigurepath = tb_goods.getJSONObject(i).getString("CM_MAINFIGUREPATH"); // String cm_goodsid = tb_goods.getJSONObject(i).getString("CM_GOODSID"); // int goodsid = Integer.parseInt(cm_goodsid); // // sortData3.add(new GoodsInfo(cm_mainfigurepath, "", goodsid)); // } } recyclerviewAdapter.notifyDataSetChanged(); } else { // 搜索为空 Toast.makeText(getApplicationContext(), "获取数据失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onErrorResponse(VolleyError arg0) { } }); } private void gosearch() { Intent intent = new Intent(GoodsSortActivity.this, SearchActivity.class); startActivity(intent); // 开启无动画 overridePendingTransition(0, 0); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sort_back: finish(); break; case R.id.sort_et_search: break; default: break; } } private class Holder { TextView name; ImageView img_paybill_item; } class PalybillAdapter extends BaseAdapter { private String cm_mainfigurepath; @Override public int getCount() { return Goodlist.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { Holder holder = null; if (convertView == null) { holder = new Holder(); convertView = getLayoutInflater().inflate(R.layout.palybillitem, null); holder.img_paybill_item = (ImageView) convertView.findViewById(R.id.img_paybill_item); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } if (Goodlist.size() != 0) { cm_mainfigurepath = Goodlist.get(position).getCM_MAINFIGUREPATH(); } if (cm_mainfigurepath.length() != 0 || cm_mainfigurepath != null) { Glide.with(GoodsSortActivity.this).load(TCHConstants.url.imgurl + cm_mainfigurepath).into(holder.img_paybill_item); } else { } holder.img_paybill_item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String cm_goodsid = Goodlist.get(position).getCM_GOODSID(); OkHttpUtils.get().addParams("goodsid", cm_goodsid).addParams("token", TCHConstants.url.token).url(TCHConstants.url.detailsurl).build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { Intent intent = new Intent(GoodsSortActivity.this, GoodsDetailActivity.class); intent.putExtra("goodsid", cm_goodsid); startActivity(intent); } }); } }); return convertView; } } }
UTF-8
Java
15,785
java
GoodsSortActivity.java
Java
[]
null
[]
package com.example.hanlian.Activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.VolleyError; import com.bumptech.glide.Glide; import com.example.hanlian.Adapter.CustomAdapter; import com.example.hanlian.Adapter.GoodsInfo; import com.example.hanlian.Adapter.MyAdapter; import com.example.hanlian.Adapter.ViewHolder; import com.example.hanlian.DateModel.Classify; import com.example.hanlian.MyApplication.MyApplication; import com.example.hanlian.R; import com.nostra13.universalimageloader.core.ImageLoader; import com.xinbo.utils.HTTPUtils; import com.xinbo.utils.ResponseListener; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import utils.JsonHelper; import utils.LogUtil; import utils.TCHConstants; /** * 产品分类 */ public class GoodsSortActivity extends Activity implements OnClickListener { private ListView sort_listView1; private ListView sort_listView3; private RecyclerView sort_recyclerview; private List<GoodsInfo> sortData1 = new ArrayList<GoodsInfo>();// 大的类别数据 private List<GoodsInfo> sortData2 = new ArrayList<GoodsInfo>();// 小的类别数据 private List<GoodsInfo> sortData3 = new ArrayList<GoodsInfo>();// 海报的类别数据 // private String[] mGridViewImgRes = new String[]{}; // private String[] data = new String[] { "上衣", "裤子" , "裙子", "亲子装", "鞋子","套装", "饰品", "家居服" }; private String sort; private JSONArray goodsList = new JSONArray();// 大的类别数据 private MyAdapter2 myAdapter2; private MyAdapter recyclerviewAdapter; private int firstId;// 第一次进来的商品id private ArrayList<Classify.ResultBean.TBSUBCLASSBean> playbillData = new ArrayList();// private ArrayList<Classify.ResultBean.TBSUBCLASSBean.TBGOODSBean> Goodlist = new ArrayList();//海报 private ArrayList<Classify.ResultBean> Result = new ArrayList(); private PalybillAdapter palybillAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goods_sort); // PushAgent.getInstance(this).onAppStart(); Intent intent = getIntent(); sort = intent.getStringExtra("sort"); int position = intent.getIntExtra("position", 0); initView(); initData(); initClassifyData(position); } private void initClassifyData(int position) { OkHttpUtils.get().url(TCHConstants.url.Classify).build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { LogUtil.e(" ==", "" + e); } @Override public void onResponse(String response, int id) { Classify classifyjson = JsonHelper.fromJson(response, Classify.class); List<Classify.ResultBean> result = classifyjson.getResult(); // TODO 点击切换时如何动态的获取下标改变海报 LogUtil.e("海报size==", result.size() + ""); List<Classify.ResultBean.TBSUBCLASSBean> tb_subclass = classifyjson.getResult().get(position).getTB_SUBCLASS(); playbillData.clear(); playbillData.addAll(tb_subclass); LogUtil.e("海报==", tb_subclass.size() + ""); Goodlist.clear(); for (int i = 0; i < playbillData.size(); i++) { List<Classify.ResultBean.TBSUBCLASSBean.TBGOODSBean> tb_goods = playbillData.get(i).getTB_GOODS(); Goodlist.addAll(tb_goods); } palybillAdapter.notifyDataSetChanged(); } }); } private void initView() { findViewById(R.id.sort_back).setOnClickListener(this); findViewById(R.id.sort_et_search).setOnClickListener(this); sort_listView1 = (ListView) findViewById(R.id.sort_listView); myAdapter2 = new MyAdapter2(); sort_listView1.setAdapter(myAdapter2); sort_listView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { initData2(sortData1.get(position).id);//点击listview切换分类 myAdapter2.setSelectItem(position); // 设置选中项目 myAdapter2.notifyDataSetChanged();//listview recyclerviewAdapter.notifyDataSetChanged(); //RecyclerView // TODO: 2017/6/14 点击切换 海报数据 // palybillAdapter.notifyDataSetChanged(); initClassifyData(position); } }); //展示页listview数据 sort_listView3 = (ListView) findViewById(R.id.sort_listView2); palybillAdapter = new PalybillAdapter(); sort_listView3.setAdapter(palybillAdapter); // sort_listView3.setAdapter(new CustomAdapter<GoodsInfo>(GoodsSortActivity.this, sortData3, // R.layout.item_sort2) { // @Override // public void convert(ViewHolder holder, GoodsInfo t) { // // ImageView item_sort_image = holder.getView(R.id.item_sort_image); // ImageLoader.getInstance().displayImage(TCHConstants.url.imgurl + t.image, item_sort_image, MyApplication.options); //// item_sort_image.setImageDrawable(getResources().getDrawable(R.drawable.new_banner_02)); // holder.getView(R.id.item_sort_name).setVisibility(View.GONE); // } // }); sort_recyclerview = (RecyclerView) findViewById(R.id.sort_recyclerview); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);//水平流 sort_recyclerview.setLayoutManager(layoutManager); recyclerviewAdapter = new MyAdapter(sortData2, this); sort_recyclerview.setAdapter(recyclerviewAdapter); } // 左侧 listview public class MyAdapter2 extends BaseAdapter { public int getCount() { return sortData1.size(); // a ? b :c a==ture 取值 b a==false 取值 c // return sortData1.size()==0 ? sortData1.size() : 1 ; } public Object getItem(int arg0) { return 0; } public long getItemId(int arg0) { return arg0; } public View getView(int position, View convertView, ViewGroup parent) { // position listview 对应的条数 converView 返回视图 parent 加载对应的xml Holder holder = null; if (convertView == null) { holder = new Holder(); convertView = getLayoutInflater().inflate(R.layout.item_sort0, null); holder.name = (TextView) convertView.findViewById(R.id.item_sort_name); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.name.setText(sortData1.get(position).name); if (position == selectItem) { // 设置点击选中item背景 convertView.setBackgroundColor(getResources().getColor(R.color.gray)); } else { convertView.setBackgroundColor(getResources().getColor(R.color.white)); } return convertView; } public void setSelectItem(int selectItem) { this.selectItem = selectItem; } private int selectItem = -1; } //获取主分类数据 private void initData() { Map<String, String> params = new HashMap<String, String>(); params.put("type", "1"); params.put("classifyid", "0"); HTTPUtils.get(getApplicationContext(), TCHConstants.url.goodsSort, params, new ResponseListener() { private int firstId; @Override public void onResponse(String arg0) { try { goodsList = new JSONObject(arg0.toString()).getJSONArray("Result"); if (goodsList.length() > 0) { for (int i = 0; i < goodsList.length(); i++) { JSONObject goodsObject = goodsList.getJSONObject(i); String name = goodsObject.getString("CM_CLASSIFYNAME"); int goodsId = goodsObject.getInt("CM_CLASSIFYID"); sortData1.add(new GoodsInfo("", name, goodsId)); if (name.equals(sort)) {// 设置初始进入时选中listview firstId = goodsId; myAdapter2.setSelectItem(i);//设置选中项 } } myAdapter2.notifyDataSetChanged(); initData2(firstId); } else { // 搜索为空 Toast.makeText(getApplicationContext(), "获取数据失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onErrorResponse(VolleyError arg0) { } }); } //二级分类数据 private void initData2(int id) { sortData2.clear(); Map<String, String> params = new HashMap<String, String>(); params.put("type", 2 + ""); params.put("classifyid", id + ""); //获取分类详情数据 HTTPUtils.get(getApplicationContext(), TCHConstants.url.goodsSort, params, new ResponseListener() { @Override public void onResponse(String arg0) { try { goodsList = new JSONObject(arg0.toString()).getJSONArray("Result"); if (goodsList.length() > 0) { // LogUtil.e("二级分类数据==", goodsList.toString()); for (int i = 0; i < goodsList.length(); i++) { JSONObject goodsObject = goodsList.getJSONObject(i); String name = goodsObject.getString("CM_CLASSIFYNAME"); String imageUrl = goodsObject.getString("CM_IMGPATH"); int goodsId = goodsObject.getInt("CM_CLASSIFYID"); sortData2.add(new GoodsInfo(imageUrl, name, goodsId)); sortData3.add(new GoodsInfo(imageUrl, name, goodsId)); /** * 海报图片路径 */ // JSONArray tb_subclass = goodsObject.getJSONArray("TB_SUBCLASS"); // if (tb_subclass.length() >0) // { // JSONObject jsonObject = tb_subclass.getJSONObject(i); // JSONArray tb_goods = jsonObject.getJSONArray("TB_GOODS"); // String cm_mainfigurepath = tb_goods.getJSONObject(i).getString("CM_MAINFIGUREPATH"); // String cm_goodsid = tb_goods.getJSONObject(i).getString("CM_GOODSID"); // int goodsid = Integer.parseInt(cm_goodsid); // // sortData3.add(new GoodsInfo(cm_mainfigurepath, "", goodsid)); // } } recyclerviewAdapter.notifyDataSetChanged(); } else { // 搜索为空 Toast.makeText(getApplicationContext(), "获取数据失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onErrorResponse(VolleyError arg0) { } }); } private void gosearch() { Intent intent = new Intent(GoodsSortActivity.this, SearchActivity.class); startActivity(intent); // 开启无动画 overridePendingTransition(0, 0); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sort_back: finish(); break; case R.id.sort_et_search: break; default: break; } } private class Holder { TextView name; ImageView img_paybill_item; } class PalybillAdapter extends BaseAdapter { private String cm_mainfigurepath; @Override public int getCount() { return Goodlist.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { Holder holder = null; if (convertView == null) { holder = new Holder(); convertView = getLayoutInflater().inflate(R.layout.palybillitem, null); holder.img_paybill_item = (ImageView) convertView.findViewById(R.id.img_paybill_item); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } if (Goodlist.size() != 0) { cm_mainfigurepath = Goodlist.get(position).getCM_MAINFIGUREPATH(); } if (cm_mainfigurepath.length() != 0 || cm_mainfigurepath != null) { Glide.with(GoodsSortActivity.this).load(TCHConstants.url.imgurl + cm_mainfigurepath).into(holder.img_paybill_item); } else { } holder.img_paybill_item.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String cm_goodsid = Goodlist.get(position).getCM_GOODSID(); OkHttpUtils.get().addParams("goodsid", cm_goodsid).addParams("token", TCHConstants.url.token).url(TCHConstants.url.detailsurl).build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { Intent intent = new Intent(GoodsSortActivity.this, GoodsDetailActivity.class); intent.putExtra("goodsid", cm_goodsid); startActivity(intent); } }); } }); return convertView; } } }
15,785
0.57088
0.565545
435
34.335632
31.265898
185
false
false
0
0
0
0
0
0
0.622989
false
false
9
6c536fdb697a81d02254237ec2d9d450cc789651
23,235,773,087,469
c360ed8b4ef36b8fdbd7e1296c2e38f098f576f2
/shanghai/service/spdHERPService/src/main/java/gyqx/ws/yg/vo/reqVo/YY165_REQ_XML.java
b804adb37ff60bcc5824ec523a6a47e87d155eab
[]
no_license
itcmicwl/SC_SPD
https://github.com/itcmicwl/SC_SPD
fb2004fd34fe9a14771bb1a2f8c28e8c9e209cdb
6e08627e527327f3c56fd4ee164ab89b994e2070
refs/heads/master
2020-04-12T03:04:51.683000
2018-12-18T09:23:31
2018-12-18T09:23:31
162,263,058
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package gyqx.ws.yg.vo.reqVo; import javax.xml.bind.annotation.XmlAccessOrder; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import gyqx.ws.yg.vo.ReqHead; /** * 企业资证信息获取 YY165 * * @author LIWENKANG * */ @XmlType(propOrder = { "reqHead", "main" }) @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "XMLDATA") public class YY165_REQ_XML { /** * 消息头 */ @XmlElement(name = "HEAD") private ReqHead reqHead; /** * 消息主条目 */ @XmlElement(name = "MAIN") private YY165_REQ_MAIN main; public ReqHead getReqHead() { return reqHead; } public void setReqHead(ReqHead reqHead) { this.reqHead = reqHead; } public YY165_REQ_MAIN getMain() { return main; } public void setMain(YY165_REQ_MAIN main) { this.main = main; } }
UTF-8
Java
1,075
java
YY165_REQ_XML.java
Java
[ { "context": ".vo.ReqHead;\n\n/**\n * 企业资证信息获取 YY165\n * \n * @author LIWENKANG\n *\n */\n@XmlType(propOrder = { \"reqHead\", \"main\" }", "end": 442, "score": 0.9989050626754761, "start": 433, "tag": "USERNAME", "value": "LIWENKANG" } ]
null
[]
package gyqx.ws.yg.vo.reqVo; import javax.xml.bind.annotation.XmlAccessOrder; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import gyqx.ws.yg.vo.ReqHead; /** * 企业资证信息获取 YY165 * * @author LIWENKANG * */ @XmlType(propOrder = { "reqHead", "main" }) @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "XMLDATA") public class YY165_REQ_XML { /** * 消息头 */ @XmlElement(name = "HEAD") private ReqHead reqHead; /** * 消息主条目 */ @XmlElement(name = "MAIN") private YY165_REQ_MAIN main; public ReqHead getReqHead() { return reqHead; } public void setReqHead(ReqHead reqHead) { this.reqHead = reqHead; } public YY165_REQ_MAIN getMain() { return main; } public void setMain(YY165_REQ_MAIN main) { this.main = main; } }
1,075
0.730585
0.716203
52
19.057692
17.651993
50
false
false
0
0
0
0
0
0
0.807692
false
false
9
a5e65fc9394f8c49629b9078bb62150fefe2d83a
3,719,441,695,685
35d18f877556897f27f2abb0f24cd5280a50ae77
/app/src/main/java/com/example/scanner/MainActivity.java
b2528befb73ebc702ecce937b5597d12ebd26bb7
[]
no_license
manHoos786/ScannerAppForVendingMachine
https://github.com/manHoos786/ScannerAppForVendingMachine
b0d53ad9282285e9f13347ee2a0695c832296497
413bdc45c2d114dd53eb423d627666a9132e5927
refs/heads/master
2023-07-11T18:56:36.776000
2021-09-02T09:23:03
2021-09-02T09:23:03
402,357,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.scanner; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity{ private Button buttonScan; private IntentIntegrator qrScan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonScan = (Button) findViewById(R.id.buttonScan); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100); buttonScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // startActivity(new Intent(getApplicationContext(), QrScanner.class)); IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES); integrator.setPrompt("Scan a barcode"); integrator.setCameraId(0); integrator.setBeepEnabled(true); integrator.setBarcodeImageEnabled(true); integrator.setCaptureActivity(CustomScanActivity.class); integrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { Intent intent = new Intent(getApplicationContext(), QrScanner.class); intent.putExtra("a", result.getContents()); startActivity(intent); } else { super.onActivityResult(requestCode, resultCode, data); // startActivity(new Intent(getApplicationContext(), MainActivity.class)); } } @Override public void onBackPressed(){ Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } }
UTF-8
Java
2,669
java
MainActivity.java
Java
[]
null
[]
package com.example.scanner; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity{ private Button buttonScan; private IntentIntegrator qrScan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonScan = (Button) findViewById(R.id.buttonScan); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100); buttonScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // startActivity(new Intent(getApplicationContext(), QrScanner.class)); IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES); integrator.setPrompt("Scan a barcode"); integrator.setCameraId(0); integrator.setBeepEnabled(true); integrator.setBarcodeImageEnabled(true); integrator.setCaptureActivity(CustomScanActivity.class); integrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { Intent intent = new Intent(getApplicationContext(), QrScanner.class); intent.putExtra("a", result.getContents()); startActivity(intent); } else { super.onActivityResult(requestCode, resultCode, data); // startActivity(new Intent(getApplicationContext(), MainActivity.class)); } } @Override public void onBackPressed(){ Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } }
2,669
0.686774
0.685275
67
38.850746
27.599077
99
false
false
0
0
0
0
0
0
0.80597
false
false
9
3452db79cb305e93ff2514281a3499ed917f9f1c
2,929,167,715,609
d8b7b7d21353a3a0183270dc055deb39c14f800c
/easykrkBackend/src/main/java/com/easykrk/infrastructure/repository/CyklRepository.java
2c44f5a05b01675821cb783b2a52311768d325b3
[]
no_license
szymonjasniak/psiEasyKrk
https://github.com/szymonjasniak/psiEasyKrk
879b433ebdc7b6119de15d5c58cac4ea049c072c
9669fd93e146355eeef62257811acf5501e91ebd
refs/heads/master
2021-01-10T02:47:28.670000
2016-02-10T16:48:20
2016-02-10T16:48:20
49,367,173
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.easykrk.infrastructure.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.easykrk.domain.model.Cykl; public interface CyklRepository extends CrudRepository<Cykl, Long>{ List<Cykl> findByNazwaContaining(String nazwa); }
UTF-8
Java
291
java
CyklRepository.java
Java
[]
null
[]
package com.easykrk.infrastructure.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.easykrk.domain.model.Cykl; public interface CyklRepository extends CrudRepository<Cykl, Long>{ List<Cykl> findByNazwaContaining(String nazwa); }
291
0.824742
0.824742
12
23.25
25.232668
67
false
false
0
0
0
0
0
0
0.583333
false
false
9
62f343142e614d413edc8a239df3fafdeb37ac16
24,197,845,752,088
cb5da48587c39f87a0337b7255338347f868d97f
/HuffmanCodes.java
57c35059c09d7edb4541c6c4e11ad4809f9bd4a3
[]
no_license
IsaacLyh/HuffMan-Encoder-Decoder
https://github.com/IsaacLyh/HuffMan-Encoder-Decoder
30285360cfea51b6c3897c20c6286a8ca5a451b3
7004c6336c216630b734b392ccc07f22f084fade
refs/heads/master
2021-01-16T00:41:18.397000
2017-08-10T23:03:27
2017-08-10T23:03:27
99,971,369
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pa4; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import javax.xml.soap.Text; import pa4.ArgsParser.Bindings; public class HuffmanCodes { //maps and variables for compressing private PriorityQueue<Node> store = new PriorityQueue<>(); private HashMap<Character,Integer> frequency = new HashMap<>(); private HashMap<Character, String> encode = new HashMap<>(); private HashMap<String,Character> decode = new HashMap<>(); private String main = ""; private String unique = ""; private String out = ""; private String in = ""; private int inSize = 0; private int outSize = 0; private final Option ENCODE, DECODE; private final Option SHOW_FREQUENCY, SHOW_CODES, SHOW_BINARY; private final ArgsParser parser; private final Operand<File> IN, OUT; private ArgsParser.Bindings settings; public HuffmanCodes() { this.ENCODE = Option.create("-e, --encode").summary("Encodes IN to OUT"); this.DECODE = Option.create("-d, --decode").summary("Decodes IN to OUT"); this.SHOW_FREQUENCY = Option.create("--show-frequency") .associatedWith(ENCODE).summary("Output byte frequencies"); this.SHOW_CODES = Option.create("--show-codes") .summary("Output the code for each byte"); this.SHOW_BINARY = Option.create("--show-binary").associatedWith(ENCODE) .summary("Output a base-two representation of the encoded sequence"); this.parser = ArgsParser.create("java HuffmanCodes") .summary("Encodes and decodes files using Huffman's technique") .helpFlags("-h, --help"); this.IN = Operand.create(File.class, "IN"); this.OUT = Operand.create(File.class, "OUT"); parser.requireOneOf("mode required", ENCODE, DECODE) .optional(SHOW_FREQUENCY).optional(SHOW_CODES).optional(SHOW_BINARY) .requiredOperand(IN).requiredOperand(OUT); } public static void main(String[] args) throws FileNotFoundException { HuffmanCodes app = new HuffmanCodes(); app.start(args); } private void init(Bindings settings) throws FileNotFoundException { String fileName = settings.operands.get(IN).get(0); File readIn = new File(fileName); main = getText(readIn); createMap(main); addNode(); Node root = createTree(); makeCodeX(root,""); } public void start(String[] args) throws FileNotFoundException { settings = parser.parse(args); if(settings.hasOption(ENCODE)) { init(settings); encode(); } else if(settings.hasOption(DECODE)) { init(settings); decode(); } if(settings.hasOption(SHOW_FREQUENCY)) { showFrequency(); } else if(settings.hasOption(SHOW_CODES)) { showCodes(); } else if( settings.hasOption(SHOW_BINARY)) { showBinary(); } } private void decode(){ } private String encode(){ for(int i = 0 ; i < main.length();i++) { out += encode.get(main.charAt(i)); outSize++; } return out; } private void showBinary() { System.out.println("ENCODED SEQUENCE"); System.out.println(out); System.out.println("input: "+inSize+" bytes "+"[ "+inSize*8+"Bytes ]"); } private void showCodes() { // TODO Auto-generated method stub System.out.println("CODES:"); for(int i = 0; i < unique.length();i++) { System.out.println(encode.get(unique.charAt(i))+" -> "+unique.charAt(i)); } } private void showFrequency() { for(int i = 0 ; i < unique.length(); i++) { System.out.println(unique.charAt(i)+" :" + frequency.get(unique.charAt(i))); } } private void makeCodeX(Node root,String input) { if(root != null) { if(root.left == null && root.right == null) { encode.put(root.name,input); decode.put(input, root.name); } } makeCodeX(root.left,input+"0"); makeCodeX(root.right,input+"1"); } private Node createTree() { for(int i = 0; i < store.size(); i++) { Node add = new Node(); add.right = store.poll(); add.left = store.poll(); add.frequency = add.right.frequency+add.left.frequency; store.add(add); } return store.poll(); } private void addNode() { for(int i = 0; i < unique.length(); i++) { Node add = new Node(unique.charAt(i),frequency.get(unique.charAt(i))); store.add(add); } } private void createMap(String main) { for(int i = 0; i < main.length(); i++){ char probe = main.charAt(i); if(!frequency.containsKey(probe)) { frequency.put(probe, 1); unique+=probe; } else { frequency.put(probe,frequency.get(probe)+1); } } } private String getText(File readIn) throws FileNotFoundException { // TODO Auto-generated method stub String main = ""; Scanner read = new Scanner(readIn); while(read.hasNext()) { main += read.next(); inSize++; } return main; } class Node { private Node left = null; private Node right = null; private char name; private int frequency; public Node() { } public Node(char name, int frequency){ this.name = name; this.frequency = frequency; } } }
UTF-8
Java
5,450
java
HuffmanCodes.java
Java
[]
null
[]
package pa4; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import javax.xml.soap.Text; import pa4.ArgsParser.Bindings; public class HuffmanCodes { //maps and variables for compressing private PriorityQueue<Node> store = new PriorityQueue<>(); private HashMap<Character,Integer> frequency = new HashMap<>(); private HashMap<Character, String> encode = new HashMap<>(); private HashMap<String,Character> decode = new HashMap<>(); private String main = ""; private String unique = ""; private String out = ""; private String in = ""; private int inSize = 0; private int outSize = 0; private final Option ENCODE, DECODE; private final Option SHOW_FREQUENCY, SHOW_CODES, SHOW_BINARY; private final ArgsParser parser; private final Operand<File> IN, OUT; private ArgsParser.Bindings settings; public HuffmanCodes() { this.ENCODE = Option.create("-e, --encode").summary("Encodes IN to OUT"); this.DECODE = Option.create("-d, --decode").summary("Decodes IN to OUT"); this.SHOW_FREQUENCY = Option.create("--show-frequency") .associatedWith(ENCODE).summary("Output byte frequencies"); this.SHOW_CODES = Option.create("--show-codes") .summary("Output the code for each byte"); this.SHOW_BINARY = Option.create("--show-binary").associatedWith(ENCODE) .summary("Output a base-two representation of the encoded sequence"); this.parser = ArgsParser.create("java HuffmanCodes") .summary("Encodes and decodes files using Huffman's technique") .helpFlags("-h, --help"); this.IN = Operand.create(File.class, "IN"); this.OUT = Operand.create(File.class, "OUT"); parser.requireOneOf("mode required", ENCODE, DECODE) .optional(SHOW_FREQUENCY).optional(SHOW_CODES).optional(SHOW_BINARY) .requiredOperand(IN).requiredOperand(OUT); } public static void main(String[] args) throws FileNotFoundException { HuffmanCodes app = new HuffmanCodes(); app.start(args); } private void init(Bindings settings) throws FileNotFoundException { String fileName = settings.operands.get(IN).get(0); File readIn = new File(fileName); main = getText(readIn); createMap(main); addNode(); Node root = createTree(); makeCodeX(root,""); } public void start(String[] args) throws FileNotFoundException { settings = parser.parse(args); if(settings.hasOption(ENCODE)) { init(settings); encode(); } else if(settings.hasOption(DECODE)) { init(settings); decode(); } if(settings.hasOption(SHOW_FREQUENCY)) { showFrequency(); } else if(settings.hasOption(SHOW_CODES)) { showCodes(); } else if( settings.hasOption(SHOW_BINARY)) { showBinary(); } } private void decode(){ } private String encode(){ for(int i = 0 ; i < main.length();i++) { out += encode.get(main.charAt(i)); outSize++; } return out; } private void showBinary() { System.out.println("ENCODED SEQUENCE"); System.out.println(out); System.out.println("input: "+inSize+" bytes "+"[ "+inSize*8+"Bytes ]"); } private void showCodes() { // TODO Auto-generated method stub System.out.println("CODES:"); for(int i = 0; i < unique.length();i++) { System.out.println(encode.get(unique.charAt(i))+" -> "+unique.charAt(i)); } } private void showFrequency() { for(int i = 0 ; i < unique.length(); i++) { System.out.println(unique.charAt(i)+" :" + frequency.get(unique.charAt(i))); } } private void makeCodeX(Node root,String input) { if(root != null) { if(root.left == null && root.right == null) { encode.put(root.name,input); decode.put(input, root.name); } } makeCodeX(root.left,input+"0"); makeCodeX(root.right,input+"1"); } private Node createTree() { for(int i = 0; i < store.size(); i++) { Node add = new Node(); add.right = store.poll(); add.left = store.poll(); add.frequency = add.right.frequency+add.left.frequency; store.add(add); } return store.poll(); } private void addNode() { for(int i = 0; i < unique.length(); i++) { Node add = new Node(unique.charAt(i),frequency.get(unique.charAt(i))); store.add(add); } } private void createMap(String main) { for(int i = 0; i < main.length(); i++){ char probe = main.charAt(i); if(!frequency.containsKey(probe)) { frequency.put(probe, 1); unique+=probe; } else { frequency.put(probe,frequency.get(probe)+1); } } } private String getText(File readIn) throws FileNotFoundException { // TODO Auto-generated method stub String main = ""; Scanner read = new Scanner(readIn); while(read.hasNext()) { main += read.next(); inSize++; } return main; } class Node { private Node left = null; private Node right = null; private char name; private int frequency; public Node() { } public Node(char name, int frequency){ this.name = name; this.frequency = frequency; } } }
5,450
0.612477
0.609541
217
23.096775
21.879116
79
false
false
0
0
0
0
0
0
2.124424
false
false
9
db597b500a81cf42d0696ddcf83eeba765ad9534
14,379,550,572,392
eb99b39eaa23da6491b305a1df738f8cd6d9c3e1
/SplitFileSeasonThree/src/com/xdc/SplitRasFile.java
5b0c404546f078a464b56c3d58b3855ca0c159ff
[]
no_license
xiadc/MyHadoopProjectCode
https://github.com/xiadc/MyHadoopProjectCode
3deb2b27e18b7679ebd9a3506759e1c0e4c4be69
a89a1e908fb4faa2ba86e0868739b7ea87d58e58
refs/heads/master
2021-01-21T10:05:23.063000
2017-03-14T03:41:20
2017-03-14T03:41:20
83,378,449
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xdc; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import com.UtilClass.myDataOutputStream; import com.hbaseClients.HBaseClient; public class SplitRasFile { //private static final short START=60;//数据头偏移量 private static final float INVAILDDATA=1.70141E38f;//填充的无用数据,与地图中无用数据一致,为1.70141E38 private short tileSize; private int COL;//grd数据的像素列 private int ROW;//grd数据的像素行 private int COL_NUM=0;//数据块的列数 private int ROW_NUM=0;//数据块的行数 private boolean stateX;//数据块是否需要填充X的标志 private boolean stateY;//数据头偏移量否需要填充Y的标志 private short COL_ADD;//数据需要填充的像素列 private short ROW_ADD;//数据需要填充的像素行 private double x1,x2,y1,y2,z1,z2; private RandomAccessFile raf = null; public ArrayList<Integer> doSplit(short START,short TILE_SIZE,String RAS_PATH,String DES_PATH) { // TODO Auto-generated method stub tileSize = TILE_SIZE; String rowKey = this.getRowKey(DES_PATH); ArrayList<Integer> invaildTileNoList = new ArrayList<Integer>(); try { raf = new RandomAccessFile(RAS_PATH,"r"); this.init(TILE_SIZE,RAS_PATH,rowKey);//初始化 this.split(START,TILE_SIZE,DES_PATH,rowKey,invaildTileNoList);//分片 this.writeHeadFile(DES_PATH+"/headMsg");//写新的头文件信息 } catch (Exception e) { System.out.println("分片异常!文件转换失败"); e.printStackTrace(); }finally{ try { raf.close(); System.out.println("转换为tile文件完成!"); } catch (IOException e) { e.printStackTrace(); } } return invaildTileNoList; } /** * 初始化,得到文件相validNo关信息 * @param raf * @throws IOException */ private void init(short TILE_SIZE,String RAS_PATH,String rowKey) throws IOException{//读入数据初始化 RasHead rashead = new RasHead(RAS_PATH); this.ROW = rashead.getNx(); this.COL = rashead.getNy(); //this.no_use = rashead.getNo_use(); this.x1 = rashead.getX1(); this.x2 = rashead.getX2(); this.y1 = rashead.getY1(); this.y2 = rashead.getY2(); this.z1 = rashead.getZ1(); this.z2 = rashead.getZ2(); System.out.println("ROW="+ROW); System.out.println("COL="+COL); if(COL%TILE_SIZE!=0){//数据块列尾需要填充 COL_NUM=(short) ((COL/TILE_SIZE)+1); COL_ADD=(short) (COL_NUM*TILE_SIZE-COL); System.out.println("COL_NUM="+COL_NUM); System.out.println("COL_ADD="+COL_ADD); stateY = true; }else{//数据块列尾不需要填充 COL_NUM=(short) (COL/TILE_SIZE); COL_ADD=0; stateY = false; } if(ROW%TILE_SIZE!=0){//数据块行尾需要填充 ROW_NUM=(short) ((ROW/TILE_SIZE)+1); ROW_ADD=(short) ((ROW_NUM*TILE_SIZE)-ROW); System.out.println("ROW_NUM="+ROW_NUM); System.out.println("ROW_ADD="+ROW_ADD); stateX = true; }else{ ROW_NUM=(short) (ROW/TILE_SIZE); ROW_ADD=0; stateX = false; } saveHeadMsgtoHBase(rowKey); //元信息写入HBase数据 } /** * 处理分块 * @param raf * @throws IOException */ @SuppressWarnings("resource") private void split(short START,short TILE_SIZE,String DES_PATH,String rowKey,ArrayList<Integer> invaildTileNoList) throws IOException{//切分 long startPX = Long.MAX_VALUE; int byteSize = TILE_SIZE*4; byte[] bytes = new byte[byteSize]; //noUseTileNoList数组存储无效块编号,最后导入HBase StringBuilder valueString = new StringBuilder(); myDataOutputStream mydos = null; DataOutputStream dos =null; BufferedOutputStream bos = null; bos =new BufferedOutputStream(new FileOutputStream(DES_PATH +"/tile")); dos = new DataOutputStream(bos);//输出流 mydos = new myDataOutputStream(dos); //无效块标记,true代表是无效块,false代表有效块 boolean label; for(int x=0;x<ROW_NUM;x++){//x,y代表逻辑上的第x行,第y列的数据块 for(int y=0;y<COL_NUM;y++){ label = true; //默认为无效块 bytes = null;//bytes数组清空 bytes = new byte[byteSize];//再new一个新的bytes数组 startPX = x*COL*4L*TILE_SIZE+y*TILE_SIZE*4L+START;//当前实际要读取的位置,加L是为了强制转换为long类型 int i = 0; int check = 0; if((y==COL_NUM-1&&stateY)||(x==ROW_NUM-1&&stateX)){//如果处于边界,且要填充数据 if(y==COL_NUM-1&&stateY){//列 raf.seek(startPX); while((check=raf.read(bytes, 0, (TILE_SIZE-COL_ADD)*4))!=-1&&i<TILE_SIZE){ if(label == true){ label = isValid(bytes); } dos.write(bytes,0,(TILE_SIZE-COL_ADD)*4);//读入有数据信息内容 i++; short temp = COL_ADD; while(temp>0){//填充无用数据 mydos.writeFloat(INVAILDDATA); temp--; } startPX+=4L*COL; if(startPX>=4L*COL*ROW+START){//如果当前操作像素节点超过输入流总节点,退出循环 break; } raf.seek(startPX); } } if(x==ROW_NUM-1&&stateX){//行填充 if(!(y==COL_NUM-1&&stateY)){//如果当前不处于所有数据块的最后一块,防止最后一块被写入2次 raf.seek(startPX); for(int row=0;row<TILE_SIZE-ROW_ADD;row++){ raf.read(bytes,0,byteSize); if(label == true){ label = isValid(bytes); } dos.write(bytes,0,byteSize); startPX+=4L*COL; raf.seek(startPX); } } short temp = ROW_ADD; while(temp>0){//填充无用数据 for(int t=0;t<TILE_SIZE;t++){ mydos.writeFloat(INVAILDDATA); } temp--; } } }else{//正常情况读取一块数据块内容 i=0; raf.seek(startPX); while(raf.read(bytes, 0, byteSize)!=-1&&i<TILE_SIZE){ if(label == true){ label = isValid(bytes); } dos.write(bytes,0,byteSize);//读入有数据信息内容 i++; startPX+=4L*COL; raf.seek(startPX); } } if(label == true){ //写出无效值的块号 int TileNo = x*COL_NUM+(y+1); invaildTileNoList.add(TileNo); valueString.append(TileNo+" "); } } } dos.close(); fos.close(); //nonoUseTileNoList中数据导入HBase StringBuilder family = new StringBuilder("RAS_BLK"); StringBuilder qualifier = new StringBuilder("InvaildTileNo"); StringBuilder[] sbs = {family,qualifier,valueString}; ArrayList<StringBuilder[]> al= new ArrayList<StringBuilder[]>(); al.add(sbs); HBaseClient.addRecord("RAS_INFO",rowKey,al); } /** * 写新的头文件 * @param headPath * @throws IOException */ private void writeHeadFile(String headPath) throws IOException{ TileHeadFile sp = new TileHeadFile(ROW, COL, x1,x2,y1,y2,z1,z2,ROW_NUM, COL_NUM, ROW_ADD, COL_ADD); sp.writeHeadFile(headPath); } /** * 判断字节数组中是否全为无效值,是则返回true,否则返回false * @param bytes * @return */ private boolean isValid(byte[] bytes){ float tmp; for(int i=0;i<bytes.length;i+=4){ tmp = fromBytestoFloat(bytes, i); if(tmp != INVAILDDATA) { return false; } } return true; } /** * 辅助类,bytes转int * @param b * @param start * @return */ public int fromBytestoInt(byte[] b,int start){ int temp; if(b.length >= start+4) temp=(0xff & b[start]) | (0xff00 & (b[start+1] << 8)) | (0xff0000 & (b[start+2] << 16)) | (0xff000000 & (b[start+3] << 24)); else temp = Integer.MAX_VALUE; return temp; } /** * 辅助类,bytes转Float * @param b * @param start * @return */ public Float fromBytestoFloat(byte[] b,int start){ Float temp; int tempi = fromBytestoInt(b,start); if(tempi ==Integer.MAX_VALUE) temp = Float.MAX_VALUE; else temp = Float.intBitsToFloat(tempi); return temp; } /** 辅助类,获取rowkey,以便后面数据写入HBase、 * @param RAS_PATH * @return */ private String getRowKey(String DES_PATH){ String[] tmpStringList = DES_PATH.split("/"); return tmpStringList[tmpStringList.length-1]; } /** * 保存元信息到HBase * @throws IOException */ private void saveHeadMsgtoHBase(String rowKey) throws IOException{ String [] qualifiers = {"TileSize","Row", "Col","XMin","XMax","YMin","YMax","ZMin","ZMax","TileRowNum","TileColNum","TileRowPixelAdd","TileColPixelAdd"}; String [] values = {tileSize+"",ROW+"",COL+"",x1+"",x2+"",y1+"",y2+"",z1+"",z2+"",ROW_NUM+"",COL_NUM+"",ROW_ADD+"",COL_ADD+""}; ArrayList<StringBuilder[]> ls = new ArrayList<StringBuilder[]>(); StringBuilder family = new StringBuilder("RAS_BASE"); for (int i=0; i<qualifiers.length; i++){ StringBuilder Qualifier = new StringBuilder(qualifiers[i]); StringBuilder value = new StringBuilder(values[i]); StringBuilder [] sbs = {family,Qualifier,value}; ls.add(sbs); } HBaseClient.addRecord("RAS_INFO",rowKey , ls); } }
UTF-8
Java
9,564
java
SplitRasFile.java
Java
[]
null
[]
package com.xdc; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import com.UtilClass.myDataOutputStream; import com.hbaseClients.HBaseClient; public class SplitRasFile { //private static final short START=60;//数据头偏移量 private static final float INVAILDDATA=1.70141E38f;//填充的无用数据,与地图中无用数据一致,为1.70141E38 private short tileSize; private int COL;//grd数据的像素列 private int ROW;//grd数据的像素行 private int COL_NUM=0;//数据块的列数 private int ROW_NUM=0;//数据块的行数 private boolean stateX;//数据块是否需要填充X的标志 private boolean stateY;//数据头偏移量否需要填充Y的标志 private short COL_ADD;//数据需要填充的像素列 private short ROW_ADD;//数据需要填充的像素行 private double x1,x2,y1,y2,z1,z2; private RandomAccessFile raf = null; public ArrayList<Integer> doSplit(short START,short TILE_SIZE,String RAS_PATH,String DES_PATH) { // TODO Auto-generated method stub tileSize = TILE_SIZE; String rowKey = this.getRowKey(DES_PATH); ArrayList<Integer> invaildTileNoList = new ArrayList<Integer>(); try { raf = new RandomAccessFile(RAS_PATH,"r"); this.init(TILE_SIZE,RAS_PATH,rowKey);//初始化 this.split(START,TILE_SIZE,DES_PATH,rowKey,invaildTileNoList);//分片 this.writeHeadFile(DES_PATH+"/headMsg");//写新的头文件信息 } catch (Exception e) { System.out.println("分片异常!文件转换失败"); e.printStackTrace(); }finally{ try { raf.close(); System.out.println("转换为tile文件完成!"); } catch (IOException e) { e.printStackTrace(); } } return invaildTileNoList; } /** * 初始化,得到文件相validNo关信息 * @param raf * @throws IOException */ private void init(short TILE_SIZE,String RAS_PATH,String rowKey) throws IOException{//读入数据初始化 RasHead rashead = new RasHead(RAS_PATH); this.ROW = rashead.getNx(); this.COL = rashead.getNy(); //this.no_use = rashead.getNo_use(); this.x1 = rashead.getX1(); this.x2 = rashead.getX2(); this.y1 = rashead.getY1(); this.y2 = rashead.getY2(); this.z1 = rashead.getZ1(); this.z2 = rashead.getZ2(); System.out.println("ROW="+ROW); System.out.println("COL="+COL); if(COL%TILE_SIZE!=0){//数据块列尾需要填充 COL_NUM=(short) ((COL/TILE_SIZE)+1); COL_ADD=(short) (COL_NUM*TILE_SIZE-COL); System.out.println("COL_NUM="+COL_NUM); System.out.println("COL_ADD="+COL_ADD); stateY = true; }else{//数据块列尾不需要填充 COL_NUM=(short) (COL/TILE_SIZE); COL_ADD=0; stateY = false; } if(ROW%TILE_SIZE!=0){//数据块行尾需要填充 ROW_NUM=(short) ((ROW/TILE_SIZE)+1); ROW_ADD=(short) ((ROW_NUM*TILE_SIZE)-ROW); System.out.println("ROW_NUM="+ROW_NUM); System.out.println("ROW_ADD="+ROW_ADD); stateX = true; }else{ ROW_NUM=(short) (ROW/TILE_SIZE); ROW_ADD=0; stateX = false; } saveHeadMsgtoHBase(rowKey); //元信息写入HBase数据 } /** * 处理分块 * @param raf * @throws IOException */ @SuppressWarnings("resource") private void split(short START,short TILE_SIZE,String DES_PATH,String rowKey,ArrayList<Integer> invaildTileNoList) throws IOException{//切分 long startPX = Long.MAX_VALUE; int byteSize = TILE_SIZE*4; byte[] bytes = new byte[byteSize]; //noUseTileNoList数组存储无效块编号,最后导入HBase StringBuilder valueString = new StringBuilder(); myDataOutputStream mydos = null; DataOutputStream dos =null; BufferedOutputStream bos = null; bos =new BufferedOutputStream(new FileOutputStream(DES_PATH +"/tile")); dos = new DataOutputStream(bos);//输出流 mydos = new myDataOutputStream(dos); //无效块标记,true代表是无效块,false代表有效块 boolean label; for(int x=0;x<ROW_NUM;x++){//x,y代表逻辑上的第x行,第y列的数据块 for(int y=0;y<COL_NUM;y++){ label = true; //默认为无效块 bytes = null;//bytes数组清空 bytes = new byte[byteSize];//再new一个新的bytes数组 startPX = x*COL*4L*TILE_SIZE+y*TILE_SIZE*4L+START;//当前实际要读取的位置,加L是为了强制转换为long类型 int i = 0; int check = 0; if((y==COL_NUM-1&&stateY)||(x==ROW_NUM-1&&stateX)){//如果处于边界,且要填充数据 if(y==COL_NUM-1&&stateY){//列 raf.seek(startPX); while((check=raf.read(bytes, 0, (TILE_SIZE-COL_ADD)*4))!=-1&&i<TILE_SIZE){ if(label == true){ label = isValid(bytes); } dos.write(bytes,0,(TILE_SIZE-COL_ADD)*4);//读入有数据信息内容 i++; short temp = COL_ADD; while(temp>0){//填充无用数据 mydos.writeFloat(INVAILDDATA); temp--; } startPX+=4L*COL; if(startPX>=4L*COL*ROW+START){//如果当前操作像素节点超过输入流总节点,退出循环 break; } raf.seek(startPX); } } if(x==ROW_NUM-1&&stateX){//行填充 if(!(y==COL_NUM-1&&stateY)){//如果当前不处于所有数据块的最后一块,防止最后一块被写入2次 raf.seek(startPX); for(int row=0;row<TILE_SIZE-ROW_ADD;row++){ raf.read(bytes,0,byteSize); if(label == true){ label = isValid(bytes); } dos.write(bytes,0,byteSize); startPX+=4L*COL; raf.seek(startPX); } } short temp = ROW_ADD; while(temp>0){//填充无用数据 for(int t=0;t<TILE_SIZE;t++){ mydos.writeFloat(INVAILDDATA); } temp--; } } }else{//正常情况读取一块数据块内容 i=0; raf.seek(startPX); while(raf.read(bytes, 0, byteSize)!=-1&&i<TILE_SIZE){ if(label == true){ label = isValid(bytes); } dos.write(bytes,0,byteSize);//读入有数据信息内容 i++; startPX+=4L*COL; raf.seek(startPX); } } if(label == true){ //写出无效值的块号 int TileNo = x*COL_NUM+(y+1); invaildTileNoList.add(TileNo); valueString.append(TileNo+" "); } } } dos.close(); fos.close(); //nonoUseTileNoList中数据导入HBase StringBuilder family = new StringBuilder("RAS_BLK"); StringBuilder qualifier = new StringBuilder("InvaildTileNo"); StringBuilder[] sbs = {family,qualifier,valueString}; ArrayList<StringBuilder[]> al= new ArrayList<StringBuilder[]>(); al.add(sbs); HBaseClient.addRecord("RAS_INFO",rowKey,al); } /** * 写新的头文件 * @param headPath * @throws IOException */ private void writeHeadFile(String headPath) throws IOException{ TileHeadFile sp = new TileHeadFile(ROW, COL, x1,x2,y1,y2,z1,z2,ROW_NUM, COL_NUM, ROW_ADD, COL_ADD); sp.writeHeadFile(headPath); } /** * 判断字节数组中是否全为无效值,是则返回true,否则返回false * @param bytes * @return */ private boolean isValid(byte[] bytes){ float tmp; for(int i=0;i<bytes.length;i+=4){ tmp = fromBytestoFloat(bytes, i); if(tmp != INVAILDDATA) { return false; } } return true; } /** * 辅助类,bytes转int * @param b * @param start * @return */ public int fromBytestoInt(byte[] b,int start){ int temp; if(b.length >= start+4) temp=(0xff & b[start]) | (0xff00 & (b[start+1] << 8)) | (0xff0000 & (b[start+2] << 16)) | (0xff000000 & (b[start+3] << 24)); else temp = Integer.MAX_VALUE; return temp; } /** * 辅助类,bytes转Float * @param b * @param start * @return */ public Float fromBytestoFloat(byte[] b,int start){ Float temp; int tempi = fromBytestoInt(b,start); if(tempi ==Integer.MAX_VALUE) temp = Float.MAX_VALUE; else temp = Float.intBitsToFloat(tempi); return temp; } /** 辅助类,获取rowkey,以便后面数据写入HBase、 * @param RAS_PATH * @return */ private String getRowKey(String DES_PATH){ String[] tmpStringList = DES_PATH.split("/"); return tmpStringList[tmpStringList.length-1]; } /** * 保存元信息到HBase * @throws IOException */ private void saveHeadMsgtoHBase(String rowKey) throws IOException{ String [] qualifiers = {"TileSize","Row", "Col","XMin","XMax","YMin","YMax","ZMin","ZMax","TileRowNum","TileColNum","TileRowPixelAdd","TileColPixelAdd"}; String [] values = {tileSize+"",ROW+"",COL+"",x1+"",x2+"",y1+"",y2+"",z1+"",z2+"",ROW_NUM+"",COL_NUM+"",ROW_ADD+"",COL_ADD+""}; ArrayList<StringBuilder[]> ls = new ArrayList<StringBuilder[]>(); StringBuilder family = new StringBuilder("RAS_BASE"); for (int i=0; i<qualifiers.length; i++){ StringBuilder Qualifier = new StringBuilder(qualifiers[i]); StringBuilder value = new StringBuilder(values[i]); StringBuilder [] sbs = {family,Qualifier,value}; ls.add(sbs); } HBaseClient.addRecord("RAS_INFO",rowKey , ls); } }
9,564
0.605556
0.591898
294
28.387754
23.950899
155
false
false
0
0
0
0
0
0
3.996599
false
false
9
5c3d78400ac1b8afb89120e7c9ccbb963c724d60
27,152,783,308,276
1b59cc7b7c9f97d8ecaa8733331a1575296ce5d8
/springboot-4/src/main/java/com/example/springboot4/constant/FileCategoryEnum.java
909a4625fc38845837c2343f4c052a938b549549
[]
no_license
zhanglucf/springboot-review
https://github.com/zhanglucf/springboot-review
69075de5188fd4301fb006a96710c66e6a5e5620
569d7ffc92fdc92ded3370d684b8e4b9e3859665
refs/heads/master
2023-06-06T22:30:52.977000
2021-07-12T04:06:37
2021-07-12T04:06:37
373,779,723
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.springboot4.constant; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * @author ZhangZhenhua * @date 2021/1/19 9:33 */ public enum FileCategoryEnum implements BaseEnum { ICON(0, "p-icon", "头像、图片"), OPINION(1, "p-opinion", "个人或者专家意见表"), EXPERT_FEE(2, "p-expert_fee", "专家费用发放表"), SIGN(3, "p-sign", "专家签到表"); private Integer value; private String desc; private String descCN; FileCategoryEnum() {} FileCategoryEnum(Integer value, String desc, String descCN) { this.value = value; this.desc = desc; this.descCN = descCN; } @JsonValue @Override public int getValue() { return this.value; } @Override public String getDesc() { return desc; } public static FileCategoryEnum intToEnum(int i) { FileCategoryEnum[] values = FileCategoryEnum.values(); for (FileCategoryEnum fileCategoryEnum : values) { if (fileCategoryEnum.getValue() == i) { return fileCategoryEnum; } } return null; } @JsonCreator public static FileCategoryEnum create(Object obj) { String value = obj == null ? null: obj.toString(); try { return FileCategoryEnum.valueOf(value); } catch (IllegalArgumentException e) { for (FileCategoryEnum fileCategoryEnum : FileCategoryEnum.values()) { try { if (fileCategoryEnum.value == (Integer.parseInt(value))) { return fileCategoryEnum; } } catch (NumberFormatException n) { if (fileCategoryEnum.desc.equals(value)) { return fileCategoryEnum; } } } throw new IllegalArgumentException("No element matches " + value); } } @Override public String toString() { return this.value + ""; } }
UTF-8
Java
2,108
java
FileCategoryEnum.java
Java
[ { "context": "rxml.jackson.annotation.JsonValue;\n\n/**\n * @author ZhangZhenhua\n * @date 2021/1/19 9:33\n */\npublic enum FileCateg", "end": 175, "score": 0.9998449683189392, "start": 163, "tag": "NAME", "value": "ZhangZhenhua" } ]
null
[]
package com.example.springboot4.constant; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * @author ZhangZhenhua * @date 2021/1/19 9:33 */ public enum FileCategoryEnum implements BaseEnum { ICON(0, "p-icon", "头像、图片"), OPINION(1, "p-opinion", "个人或者专家意见表"), EXPERT_FEE(2, "p-expert_fee", "专家费用发放表"), SIGN(3, "p-sign", "专家签到表"); private Integer value; private String desc; private String descCN; FileCategoryEnum() {} FileCategoryEnum(Integer value, String desc, String descCN) { this.value = value; this.desc = desc; this.descCN = descCN; } @JsonValue @Override public int getValue() { return this.value; } @Override public String getDesc() { return desc; } public static FileCategoryEnum intToEnum(int i) { FileCategoryEnum[] values = FileCategoryEnum.values(); for (FileCategoryEnum fileCategoryEnum : values) { if (fileCategoryEnum.getValue() == i) { return fileCategoryEnum; } } return null; } @JsonCreator public static FileCategoryEnum create(Object obj) { String value = obj == null ? null: obj.toString(); try { return FileCategoryEnum.valueOf(value); } catch (IllegalArgumentException e) { for (FileCategoryEnum fileCategoryEnum : FileCategoryEnum.values()) { try { if (fileCategoryEnum.value == (Integer.parseInt(value))) { return fileCategoryEnum; } } catch (NumberFormatException n) { if (fileCategoryEnum.desc.equals(value)) { return fileCategoryEnum; } } } throw new IllegalArgumentException("No element matches " + value); } } @Override public String toString() { return this.value + ""; } }
2,108
0.571012
0.563716
75
26.4
21.967855
81
false
false
0
0
0
0
0
0
0.453333
false
false
9
94b626fe935a2f71d2728419f34d55f9010bdc99
31,078,383,418,331
69f418cd16cb5c913c86d02282220922129261bc
/app/src/main/java/inhalo/titansmora/org/inhaloapp/adapters/MedicineDetailsAdpater.java
22e28443ae7196b5a733381e6217b3081d4f21b2
[]
no_license
DimuthuLakmal/InhaloApp
https://github.com/DimuthuLakmal/InhaloApp
7e278f7693e22f14963d7871f8f46fca69ebdeb7
ad7341530ecff4cfaae77940ebe72e74bfe58017
refs/heads/master
2021-01-23T04:59:28.999000
2017-07-02T16:54:51
2017-07-02T16:54:51
92,948,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inhalo.titansmora.org.inhaloapp.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import inhalo.titansmora.org.inhaloapp.R; /** * Created by kjtdi on 5/31/2017. */ public class MedicineDetailsAdpater extends BaseAdapter implements ListAdapter { private ArrayList<ArrayList<String>[]> list = new ArrayList<ArrayList<String>[]>(); private Context context; public MedicineDetailsAdpater(ArrayList<ArrayList<String>[]> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int pos) { return list.get(pos); } @Override public long getItemId(int pos) { return pos; //just return 0 if your list items do not have an Id variable. } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.medicine_details_list_view, null); } //Handle TextView and display string from your list Spinner amountSpinner = (Spinner) view.findViewById(R.id.amount_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[0]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); amountSpinner.setAdapter(adapter); //Handle TextView and display string from your list Spinner formSpinner = (Spinner) view.findViewById(R.id.form_spinner); ArrayAdapter<String> formAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[1]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); formSpinner.setAdapter(formAdapter); //Handle TextView and display string from your list Spinner doseSpinner = (Spinner) view.findViewById(R.id.dose_spinner); ArrayAdapter<String> doseAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[2]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); doseSpinner.setAdapter(doseAdapter); //Handle TextView and display string from your list Spinner frequencySpinner = (Spinner) view.findViewById(R.id.frequency_spinner); ArrayAdapter<String> frequencyAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[3]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); frequencySpinner.setAdapter(frequencyAdapter); return view; } }
UTF-8
Java
3,254
java
MedicineDetailsAdpater.java
Java
[ { "context": "alo.titansmora.org.inhaloapp.R;\n\n/**\n * Created by kjtdi on 5/31/2017.\n */\npublic class MedicineDetailsAdp", "end": 464, "score": 0.9996880292892456, "start": 459, "tag": "USERNAME", "value": "kjtdi" } ]
null
[]
package inhalo.titansmora.org.inhaloapp.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import inhalo.titansmora.org.inhaloapp.R; /** * Created by kjtdi on 5/31/2017. */ public class MedicineDetailsAdpater extends BaseAdapter implements ListAdapter { private ArrayList<ArrayList<String>[]> list = new ArrayList<ArrayList<String>[]>(); private Context context; public MedicineDetailsAdpater(ArrayList<ArrayList<String>[]> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int pos) { return list.get(pos); } @Override public long getItemId(int pos) { return pos; //just return 0 if your list items do not have an Id variable. } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.medicine_details_list_view, null); } //Handle TextView and display string from your list Spinner amountSpinner = (Spinner) view.findViewById(R.id.amount_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[0]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); amountSpinner.setAdapter(adapter); //Handle TextView and display string from your list Spinner formSpinner = (Spinner) view.findViewById(R.id.form_spinner); ArrayAdapter<String> formAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[1]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); formSpinner.setAdapter(formAdapter); //Handle TextView and display string from your list Spinner doseSpinner = (Spinner) view.findViewById(R.id.dose_spinner); ArrayAdapter<String> doseAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[2]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); doseSpinner.setAdapter(doseAdapter); //Handle TextView and display string from your list Spinner frequencySpinner = (Spinner) view.findViewById(R.id.frequency_spinner); ArrayAdapter<String> frequencyAdapter = new ArrayAdapter<String>(view.getContext() , android.R.layout.simple_spinner_item, list.get(position)[3]); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); frequencySpinner.setAdapter(frequencyAdapter); return view; } }
3,254
0.716656
0.712969
82
38.695122
38.829422
154
false
false
0
0
0
0
0
0
0.634146
false
false
9
b0425727384d3d5eb03c6e876a06624595e12087
31,078,383,418,882
f8153963af4f5fd50d3b4483cf7e6534360d106e
/kun-data-platform/kun-data-platform-web/src/test/java/com/miotech/kun/dataplatform/mocking/MockDeployFactory.java
2f20f9ca5bc141be9ccd278a67b61ede1c93ec89
[ "Apache-2.0" ]
permissive
hypmiotech/kun-scheduler
https://github.com/hypmiotech/kun-scheduler
1c8409cd20f014ec1041d320657b46cabe751673
a53ced5b75ba49972350cc1b38f8bfac9ad1874d
refs/heads/master
2023-07-27T19:42:49.988000
2021-09-03T09:55:53
2021-09-03T09:55:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miotech.kun.dataplatform.mocking; import com.miotech.kun.dataplatform.common.utils.DataPlatformIdGenerator; import com.miotech.kun.dataplatform.model.commit.TaskCommit; import com.miotech.kun.dataplatform.model.deploy.Deploy; import com.miotech.kun.dataplatform.model.deploy.DeployCommit; import com.miotech.kun.dataplatform.model.deploy.DeployStatus; import com.miotech.kun.workflow.utils.DateTimeUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MockDeployFactory { private MockDeployFactory() {} public static Deploy createDeploy() { return createDeploy(1).get(0); } public static List<Deploy> createDeploy(int num) { List<Deploy> deploys = new ArrayList<>(); for (int i = 0; i < num; i++) { TaskCommit taskCommit = MockTaskCommitFactory.createTaskCommit(); long deployId = DataPlatformIdGenerator.nextDeployId(); DeployCommit deployCommit = DeployCommit.newBuilder() .withDeployId(deployId) .withCommit(taskCommit.getId()) .withDeployStatus(DeployStatus.CREATED) .build(); deploys.add(Deploy.newBuilder() .withId(deployId) .withName(taskCommit.getSnapshot().getName()) .withCreator(1L) .withSubmittedAt(DateTimeUtils.now()) .withDeployer(1L) .withDeployedAt(DateTimeUtils.now()) .withCommits(Collections.singletonList(deployCommit)) .withStatus(DeployStatus.CREATED) .build()); } return deploys; } }
UTF-8
Java
1,743
java
MockDeployFactory.java
Java
[]
null
[]
package com.miotech.kun.dataplatform.mocking; import com.miotech.kun.dataplatform.common.utils.DataPlatformIdGenerator; import com.miotech.kun.dataplatform.model.commit.TaskCommit; import com.miotech.kun.dataplatform.model.deploy.Deploy; import com.miotech.kun.dataplatform.model.deploy.DeployCommit; import com.miotech.kun.dataplatform.model.deploy.DeployStatus; import com.miotech.kun.workflow.utils.DateTimeUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MockDeployFactory { private MockDeployFactory() {} public static Deploy createDeploy() { return createDeploy(1).get(0); } public static List<Deploy> createDeploy(int num) { List<Deploy> deploys = new ArrayList<>(); for (int i = 0; i < num; i++) { TaskCommit taskCommit = MockTaskCommitFactory.createTaskCommit(); long deployId = DataPlatformIdGenerator.nextDeployId(); DeployCommit deployCommit = DeployCommit.newBuilder() .withDeployId(deployId) .withCommit(taskCommit.getId()) .withDeployStatus(DeployStatus.CREATED) .build(); deploys.add(Deploy.newBuilder() .withId(deployId) .withName(taskCommit.getSnapshot().getName()) .withCreator(1L) .withSubmittedAt(DateTimeUtils.now()) .withDeployer(1L) .withDeployedAt(DateTimeUtils.now()) .withCommits(Collections.singletonList(deployCommit)) .withStatus(DeployStatus.CREATED) .build()); } return deploys; } }
1,743
0.632817
0.629948
47
36.085106
24.006054
77
false
false
0
0
0
0
0
0
0.404255
false
false
9
62db7bd6550abc20c4df096709d2de45d99db1ef
171,798,702,700
5c5c0cd759a8ba95fe7a43dfe46ad1916b9a07c5
/Job.java
5ca4b9d2ae3dc281ef4532088a8f74c70bce2702
[]
no_license
Ganesh-Dongre/job3
https://github.com/Ganesh-Dongre/job3
6eadc9654f1c1cf972b0d23109a54084c16b962e
01fea263b7227f3fdca0297126557940bea23783
refs/heads/master
2023-03-26T14:09:30.591000
2021-03-29T16:09:48
2021-03-29T16:09:48
352,704,265
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Job { public static void main(String args[]) { System.out.println("Job3 done again trying out pipeline"); } }
UTF-8
Java
117
java
Job.java
Java
[]
null
[]
class Job { public static void main(String args[]) { System.out.println("Job3 done again trying out pipeline"); } }
117
0.717949
0.709402
7
15.857142
21.556759
59
false
false
0
0
0
0
0
0
0.285714
false
false
9
e4bc347504ebf6752a0321977928f3ee8193bbc0
635,655,230,167
a44673b9ea4142df1bd900931368a945f3d896ae
/bridge/src/main/java/fr/unice/smart_campus/data/ControllerException.java
de4c3cbe5a8c19e34a915e9907d1a9888bac6a65
[]
no_license
SmartCampus/bridge
https://github.com/SmartCampus/bridge
3061b6f4f93b55cf2f25001e31073337f0f9c031
66380e791dd27d027462d1fefce30b45adfe23fb
refs/heads/master
2016-09-05T22:00:22.185000
2014-02-27T19:49:42
2014-02-27T19:49:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.unice.smart_campus.data; /** * Arduino exceptions manager. * * @author Jean Oudot - IUT Nice / Sophia Antipolis - S4D * @version 1.0.0 */ public class ControllerException extends Exception { /** * Default constructor. * * @param message Exception message. */ public ControllerException(String message) { super(message); } /** * Second constructor. * * @param e Received exception. */ public ControllerException(Exception e) { super(e); } }
UTF-8
Java
479
java
ControllerException.java
Java
[ { "context": "/**\n * Arduino exceptions manager.\n * \n * @author Jean Oudot - IUT Nice / Sophia Antipolis - S4D\n * @version 1", "end": 99, "score": 0.9998399615287781, "start": 89, "tag": "NAME", "value": "Jean Oudot" }, { "context": "s manager.\n * \n * @author Jean Oudot - IUT...
null
[]
package fr.unice.smart_campus.data; /** * Arduino exceptions manager. * * @author <NAME> - IUT Nice / <NAME> - S4D * @version 1.0.0 */ public class ControllerException extends Exception { /** * Default constructor. * * @param message Exception message. */ public ControllerException(String message) { super(message); } /** * Second constructor. * * @param e Received exception. */ public ControllerException(Exception e) { super(e); } }
465
0.680585
0.672234
33
13.484848
15.763636
58
false
false
0
0
0
0
0
0
0.090909
false
false
9
287ce6b6409bfdca8810a485bb80ddbc4e5bc591
3,143,916,113,162
200e267dd0c6e791ed557add7ea9e2e1b897d848
/src/FastCollinearPoints.java
c9a5fda248fb1ba3b61cf759ea5c1176f94f1829
[]
no_license
NadiaDal/queues
https://github.com/NadiaDal/queues
676140c10f9141a2aceae5948263e7646d13e140
66b26f0f33ba3c547090c8d114c5512e65681079
refs/heads/master
2021-10-20T14:41:35.983000
2019-02-28T10:24:50
2019-02-28T10:24:50
173,090,635
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import edu.princeton.cs.algs4.MergeX; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FastCollinearPoints { private final LineSegment[] lineSegments; public FastCollinearPoints(Point[] points) { if (points == null) throw new IllegalArgumentException(""); MergeX.sort(points); lineSegments = findSegments(points); } // finds all line segments containing 4 or more points public int numberOfSegments() { return lineSegments.length; } // the number of line segments public LineSegment[] segments() { return lineSegments; } // the line segments private LineSegment[] findSegments(Point[] points) { List<LineSegment> list = new ArrayList<>(); int N = points.length; for (int p = 0; p < N - 1; p++) { int l = p + 1; Point[] clone = new Point[N - l]; for (int i = l; i < N; i++) { clone[i - (p + 1)] = points[i]; } Point point = points[p]; Arrays.sort(clone, point.slopeOrder()); int counter = 0; Point lastInSegment = clone[0]; for (int i = 1; i < N - l; i++) { double last = lastInSegment.slopeTo(point); double current = clone[i].slopeTo(point); boolean hasEqualSlopes = Double.compare(last, current) == 0; if (hasEqualSlopes) { counter++; if (lastInSegment.compareTo(clone[i]) < 0) lastInSegment = clone[i]; if (i == N - l - 1 && counter >= 2) { LineSegment ls = new LineSegment(point, lastInSegment); list.add(ls); } } else { if (counter >= 2) { LineSegment ls = new LineSegment(point, lastInSegment); list.add(ls); } counter = 0; lastInSegment = clone[i]; } } } return list.toArray(new LineSegment[]{}); } }
UTF-8
Java
2,170
java
FastCollinearPoints.java
Java
[]
null
[]
import edu.princeton.cs.algs4.MergeX; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FastCollinearPoints { private final LineSegment[] lineSegments; public FastCollinearPoints(Point[] points) { if (points == null) throw new IllegalArgumentException(""); MergeX.sort(points); lineSegments = findSegments(points); } // finds all line segments containing 4 or more points public int numberOfSegments() { return lineSegments.length; } // the number of line segments public LineSegment[] segments() { return lineSegments; } // the line segments private LineSegment[] findSegments(Point[] points) { List<LineSegment> list = new ArrayList<>(); int N = points.length; for (int p = 0; p < N - 1; p++) { int l = p + 1; Point[] clone = new Point[N - l]; for (int i = l; i < N; i++) { clone[i - (p + 1)] = points[i]; } Point point = points[p]; Arrays.sort(clone, point.slopeOrder()); int counter = 0; Point lastInSegment = clone[0]; for (int i = 1; i < N - l; i++) { double last = lastInSegment.slopeTo(point); double current = clone[i].slopeTo(point); boolean hasEqualSlopes = Double.compare(last, current) == 0; if (hasEqualSlopes) { counter++; if (lastInSegment.compareTo(clone[i]) < 0) lastInSegment = clone[i]; if (i == N - l - 1 && counter >= 2) { LineSegment ls = new LineSegment(point, lastInSegment); list.add(ls); } } else { if (counter >= 2) { LineSegment ls = new LineSegment(point, lastInSegment); list.add(ls); } counter = 0; lastInSegment = clone[i]; } } } return list.toArray(new LineSegment[]{}); } }
2,170
0.498157
0.491244
63
33.444443
21.37108
88
false
false
0
0
0
0
0
0
0.650794
false
false
9
140b3e1af574bb7809968bdf2d00915ca6a8d2db
4,088,808,928,133
afeb694caaa73271bf8c149159375a4e0c9fa43c
/src/_java/_se/_02/SimpleSingletone.java
bcb4aea53299e4d054af7b535e420e16fcb8bf34
[]
no_license
Hook10/javaLab
https://github.com/Hook10/javaLab
68caf7094ed8bf1bce52e0e14c47640870db3ee8
d81823b322544efed5ac55a90f9b31a9034fc43d
refs/heads/master
2020-12-13T16:24:02.569000
2020-03-07T05:12:53
2020-03-07T05:12:53
234,470,913
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package _java._se._02; public class SimpleSingletone { private static SimpleSingletone instance; private SimpleSingletone(){} public static SimpleSingletone getInstance(){ if(null == instance){ instance = new SimpleSingletone(); } return instance; } }
UTF-8
Java
307
java
SimpleSingletone.java
Java
[]
null
[]
package _java._se._02; public class SimpleSingletone { private static SimpleSingletone instance; private SimpleSingletone(){} public static SimpleSingletone getInstance(){ if(null == instance){ instance = new SimpleSingletone(); } return instance; } }
307
0.638436
0.631922
14
20.928572
17.734003
49
false
false
0
0
0
0
0
0
0.285714
false
false
9
62522795cc1e748cfa5d855ab015c26a5ccf5bf0
4,088,808,929,611
e8763b6e0fd9d03884a484daa16d2bc2eb115015
/src/main/java/de/m3y3r/jettycloud/App.java
9ffbe5d1e65d76c3c2538ec13b7fd91aa0f168d7
[ "Apache-2.0" ]
permissive
thomasmey/jetty-cloud
https://github.com/thomasmey/jetty-cloud
8a76db7ef57ed33e6ca81e0eafe265cb452da05d
e78a516733ff2930dbbf45604e5f4c849c52bb65
refs/heads/master
2021-01-10T19:31:19.589000
2015-07-25T23:14:32
2015-07-25T23:14:32
38,939,529
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.m3y3r.jettycloud; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonStructure; import javax.json.JsonValue; import javax.json.JsonValue.ValueType; import javax.sql.DataSource; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.SimpleInstanceManager; import org.eclipse.jetty.annotations.ServletContainerInitializersStarter; import org.eclipse.jetty.apache.jsp.JettyJasperInitializer; import org.eclipse.jetty.plus.annotation.ContainerInitializer; import org.eclipse.jetty.plus.jndi.Resource; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.webapp.WebAppContext; import org.postgresql.ds.PGSimpleDataSource; /** * Start en embedded Jetty for usage in an cloudfoundry environment * see also https://eclipse.org/jetty/documentation/current/embedding-jetty.html * @author thomas * */ public class App implements Runnable { private static final String CF_ENV_PORT = "PORT"; private static final String CF_VCAP_SERVICES = "VCAP_SERVICES"; private final Logger log; public static void main(String... args) { App app = new App(); app.run(); } public App() { log = Logger.getLogger(App.class.getName()); } public void run() { /* for environment variables see: * http://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html */ int port = Integer.valueOf(System.getenv(CF_ENV_PORT)); int maxThreads = 10; try { QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMaxThreads(maxThreads); Server server = new Server(threadPool); HttpConfiguration httpConfig = new HttpConfiguration(); // httpConfig.setSecureScheme("https"); // httpConfig.setSecurePort(8443); httpConfig.setOutputBufferSize(32768); httpConfig.setRequestHeaderSize(8192); httpConfig.setResponseHeaderSize(8192); httpConfig.setSendServerVersion(true); httpConfig.setSendDateHeader(false); ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); httpConnector.setPort(port); httpConnector.setIdleTimeout(30000); server.addConnector(httpConnector); // JSP support ServletHolder jspHolder = new ServletHolder(new org.eclipse.jetty.jsp.JettyJspServlet()); jspHolder.setName("jsp"); jspHolder.setInitParameter("xpoweredBy", "false"); jspHolder.setInitParameter("fork", "false"); jspHolder.setInitParameter("logVerbosityLevel", "DEBUG"); jspHolder.setInitParameter("compilerTargetVM", "1.7"); jspHolder.setInitParameter("compilerSourceVM", "1.7"); jspHolder.setInitOrder(0); WebAppContext wac = new WebAppContext(); wac.setContextPath("/contextpath"); URL warUrl = App.class.getClassLoader().getResource("war/yourapp.war"); wac.setWar(warUrl.toString()); wac.addServlet(jspHolder, "*.jsp"); wac.addEventListener(new org.eclipse.jetty.servlet.listener.ELContextCleaner()); wac.addEventListener(new org.eclipse.jetty.servlet.listener.IntrospectorCleaner()); // WAT?! - Inspired from https://github.com/jetty-project/embedded-jetty-jsp/blob/master/src/main/java/org/eclipse/jetty/demo/Main.java JettyJasperInitializer sci = new JettyJasperInitializer(); ContainerInitializer initializer = new ContainerInitializer(sci, null); List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>(); initializers.add(initializer); wac.setAttribute("org.eclipse.jetty.containerInitializers", initializers); wac.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); wac.addBean(new ServletContainerInitializersStarter(wac), true); // ClassLoader classLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); // wac.setClassLoader(classLoader); // wac.setResourceBase(System.getProperty("java.io.tmpdir")); // ResourceHandler resourceHandler = new ResourceHandler(); // resourceHandler.setDirectoriesListed(false); // resourceHandler.setWelcomeFiles(new String[] { "index.html" }); // resourceHandler.setResourceBase("static-content"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { wac, /* resourceHandler, */ new DefaultHandler() }); server.setHandler(handlers); /* parse service and bind as DataSource via JNDI */ Map<String, DataSource> datasource = getDataSourceFromVcapService(); for(String key: datasource.keySet()) { new Resource("jdbc/" + key, datasource.get(key)); } server.setDumpAfterStart(false); server.setDumpBeforeStop(false); server.setStopAtShutdown(true); server.start(); // server.dumpStdErr(); server.join(); } catch(Exception e) { log.log(Level.SEVERE, "server failed", e); } } /** * this expects VCAP_SERVICES v2 style json * @return */ private Map<String, DataSource> getDataSourceFromVcapService() { Map<String, DataSource> datasources = new HashMap<>(); // http://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html String vcapService = System.getenv(CF_VCAP_SERVICES); if(vcapService == null) { return datasources; } StringReader reader = new StringReader(vcapService); JsonReader jsonReader = Json.createReader(reader); JsonStructure js = jsonReader.read(); assert js.getValueType() == ValueType.OBJECT; // extract database services JsonObject jo = (JsonObject) js; for(String serviceType: jo.keySet()) { JsonArray jaSqldb = jo.getJsonArray(serviceType); switch(serviceType) { case "elephantsql": for(JsonValue entry: jaSqldb) { assert entry.getValueType() == ValueType.OBJECT; JsonObject dbEntry = (JsonObject) entry; JsonObject jsCred = dbEntry.getJsonObject("credentials"); String pUri = jsCred.getString("uri"); DataSource ds = pgDataSourceFromUrl(pUri); datasources.put(dbEntry.getString("name"), ds); } break; case "sqldb": break; } } return datasources; } public static DataSource pgDataSourceFromUrl(String pUri) { /* sadly the postgres jdbc driver has no convert utility * to convert a connection string to a jdbc url :-( */ Pattern pattern = Pattern.compile("postgres://(.+):(.+)@(.+):(\\d+)/(.+)"); Matcher matcher = pattern.matcher(pUri); if(!matcher.matches()) return null; String username = matcher.group(1); String password = matcher.group(2); String hostname = matcher.group(3); String port = matcher.group(4); String databaseName = matcher.group(5); PGSimpleDataSource datasource = new PGSimpleDataSource(); datasource.setServerName(hostname); datasource.setPassword(password); datasource.setPortNumber(Integer.valueOf(port)); datasource.setUser(username); datasource.setDatabaseName(databaseName); return datasource; } }
UTF-8
Java
7,486
java
App.java
Java
[ { "context": "umentation/current/embedding-jetty.html\n * @author thomas\n *\n */\npublic class App implements Runnable {\n\n\tp", "end": 1596, "score": 0.836470901966095, "start": 1590, "tag": "USERNAME", "value": "thomas" }, { "context": ";\n\n\t\t\t// WAT?! - Inspired from https:/...
null
[]
package de.m3y3r.jettycloud; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonStructure; import javax.json.JsonValue; import javax.json.JsonValue.ValueType; import javax.sql.DataSource; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.SimpleInstanceManager; import org.eclipse.jetty.annotations.ServletContainerInitializersStarter; import org.eclipse.jetty.apache.jsp.JettyJasperInitializer; import org.eclipse.jetty.plus.annotation.ContainerInitializer; import org.eclipse.jetty.plus.jndi.Resource; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.webapp.WebAppContext; import org.postgresql.ds.PGSimpleDataSource; /** * Start en embedded Jetty for usage in an cloudfoundry environment * see also https://eclipse.org/jetty/documentation/current/embedding-jetty.html * @author thomas * */ public class App implements Runnable { private static final String CF_ENV_PORT = "PORT"; private static final String CF_VCAP_SERVICES = "VCAP_SERVICES"; private final Logger log; public static void main(String... args) { App app = new App(); app.run(); } public App() { log = Logger.getLogger(App.class.getName()); } public void run() { /* for environment variables see: * http://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html */ int port = Integer.valueOf(System.getenv(CF_ENV_PORT)); int maxThreads = 10; try { QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMaxThreads(maxThreads); Server server = new Server(threadPool); HttpConfiguration httpConfig = new HttpConfiguration(); // httpConfig.setSecureScheme("https"); // httpConfig.setSecurePort(8443); httpConfig.setOutputBufferSize(32768); httpConfig.setRequestHeaderSize(8192); httpConfig.setResponseHeaderSize(8192); httpConfig.setSendServerVersion(true); httpConfig.setSendDateHeader(false); ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); httpConnector.setPort(port); httpConnector.setIdleTimeout(30000); server.addConnector(httpConnector); // JSP support ServletHolder jspHolder = new ServletHolder(new org.eclipse.jetty.jsp.JettyJspServlet()); jspHolder.setName("jsp"); jspHolder.setInitParameter("xpoweredBy", "false"); jspHolder.setInitParameter("fork", "false"); jspHolder.setInitParameter("logVerbosityLevel", "DEBUG"); jspHolder.setInitParameter("compilerTargetVM", "1.7"); jspHolder.setInitParameter("compilerSourceVM", "1.7"); jspHolder.setInitOrder(0); WebAppContext wac = new WebAppContext(); wac.setContextPath("/contextpath"); URL warUrl = App.class.getClassLoader().getResource("war/yourapp.war"); wac.setWar(warUrl.toString()); wac.addServlet(jspHolder, "*.jsp"); wac.addEventListener(new org.eclipse.jetty.servlet.listener.ELContextCleaner()); wac.addEventListener(new org.eclipse.jetty.servlet.listener.IntrospectorCleaner()); // WAT?! - Inspired from https://github.com/jetty-project/embedded-jetty-jsp/blob/master/src/main/java/org/eclipse/jetty/demo/Main.java JettyJasperInitializer sci = new JettyJasperInitializer(); ContainerInitializer initializer = new ContainerInitializer(sci, null); List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>(); initializers.add(initializer); wac.setAttribute("org.eclipse.jetty.containerInitializers", initializers); wac.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); wac.addBean(new ServletContainerInitializersStarter(wac), true); // ClassLoader classLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); // wac.setClassLoader(classLoader); // wac.setResourceBase(System.getProperty("java.io.tmpdir")); // ResourceHandler resourceHandler = new ResourceHandler(); // resourceHandler.setDirectoriesListed(false); // resourceHandler.setWelcomeFiles(new String[] { "index.html" }); // resourceHandler.setResourceBase("static-content"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { wac, /* resourceHandler, */ new DefaultHandler() }); server.setHandler(handlers); /* parse service and bind as DataSource via JNDI */ Map<String, DataSource> datasource = getDataSourceFromVcapService(); for(String key: datasource.keySet()) { new Resource("jdbc/" + key, datasource.get(key)); } server.setDumpAfterStart(false); server.setDumpBeforeStop(false); server.setStopAtShutdown(true); server.start(); // server.dumpStdErr(); server.join(); } catch(Exception e) { log.log(Level.SEVERE, "server failed", e); } } /** * this expects VCAP_SERVICES v2 style json * @return */ private Map<String, DataSource> getDataSourceFromVcapService() { Map<String, DataSource> datasources = new HashMap<>(); // http://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html String vcapService = System.getenv(CF_VCAP_SERVICES); if(vcapService == null) { return datasources; } StringReader reader = new StringReader(vcapService); JsonReader jsonReader = Json.createReader(reader); JsonStructure js = jsonReader.read(); assert js.getValueType() == ValueType.OBJECT; // extract database services JsonObject jo = (JsonObject) js; for(String serviceType: jo.keySet()) { JsonArray jaSqldb = jo.getJsonArray(serviceType); switch(serviceType) { case "elephantsql": for(JsonValue entry: jaSqldb) { assert entry.getValueType() == ValueType.OBJECT; JsonObject dbEntry = (JsonObject) entry; JsonObject jsCred = dbEntry.getJsonObject("credentials"); String pUri = jsCred.getString("uri"); DataSource ds = pgDataSourceFromUrl(pUri); datasources.put(dbEntry.getString("name"), ds); } break; case "sqldb": break; } } return datasources; } public static DataSource pgDataSourceFromUrl(String pUri) { /* sadly the postgres jdbc driver has no convert utility * to convert a connection string to a jdbc url :-( */ Pattern pattern = Pattern.compile("postgres://(.+):(.+)@(.+):(\\d+)/(.+)"); Matcher matcher = pattern.matcher(pUri); if(!matcher.matches()) return null; String username = matcher.group(1); String password = matcher.group(2); String hostname = matcher.group(3); String port = matcher.group(4); String databaseName = matcher.group(5); PGSimpleDataSource datasource = new PGSimpleDataSource(); datasource.setServerName(hostname); datasource.setPassword(<PASSWORD>); datasource.setPortNumber(Integer.valueOf(port)); datasource.setUser(username); datasource.setDatabaseName(databaseName); return datasource; } }
7,488
0.749399
0.744323
223
32.569508
25.910044
138
false
false
0
0
0
0
0
0
2.278027
false
false
9
c392fd4cfee0499657b35f5fea4a86ea1a525cba
14,774,687,564,166
f68153f28f746efdc043f429bcdc27c22a5c4a23
/EP-J-Tasks/ArithmeticOperations/src/main/java/ua/epam/ArithmeticOperations.java
71b4065e0b49a59d0f02b8bec5d12b15d19ac3fd
[]
no_license
Susirya/EP_J
https://github.com/Susirya/EP_J
f75984f141ab2caaced82c4efc72bb04ebd1f194
577da9aedaad6d422d222e0eef6aad4d140cd5f7
refs/heads/master
2019-06-23T18:14:40.378000
2016-11-13T13:50:11
2016-11-13T13:50:11
68,110,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.epam; public class ArithmeticOperations { public double add (double val1, double val2){ return val1 + val2; } public double deduct(double val1, double val2){ return val1 - val2; } public double mult(double val1, double val2){ return val1 * val2; } public double div(double val1, double val2){ if (val2 == 0.0) { throw new ArithmeticException(); } return val1 / val2; } }
UTF-8
Java
479
java
ArithmeticOperations.java
Java
[]
null
[]
package ua.epam; public class ArithmeticOperations { public double add (double val1, double val2){ return val1 + val2; } public double deduct(double val1, double val2){ return val1 - val2; } public double mult(double val1, double val2){ return val1 * val2; } public double div(double val1, double val2){ if (val2 == 0.0) { throw new ArithmeticException(); } return val1 / val2; } }
479
0.582463
0.542798
22
20.772728
18.414253
51
false
false
0
0
0
0
0
0
0.454545
false
false
9
f668142ebadf412b3c23cc54dd4ffa130ace0104
20,349,555,072,552
2ff1788018444648aa60ef34027accac0fbb55c2
/app/src/main/java/com/uos/kyungimlee/ourmenu/FoodInfoContents.java
1bad8030e9d9c6dc59c4e513734999fce8f3db0b
[]
no_license
katie0809/OurMenu
https://github.com/katie0809/OurMenu
38d62638748a1fa46edb694357a213859c1dd753
ac16749a84ade610693bde7f490491ff420a76ff
refs/heads/master
2022-12-24T01:05:05.748000
2020-10-01T07:19:21
2020-10-01T07:19:21
109,944,049
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uos.kyungimlee.ourmenu; /** * Created by kyungimlee on 2017. 12. 6.. */ class FoodInfoContents { private String originNurientsTitle = "Nutrients"; private String originFlavorsTitle = "Flavors"; private String originIngreTitle = "Ingredients"; private String originAllergenTitle = "Allergen"; private String originPoweredByTitle = "Powered By"; private String originDataFromTitle = "Data From"; private String originBitter = "Bitter"; private String originMeaty = "Meaty"; private String originPiquant = "Piquant"; private String originSalty = "Salty"; private String originSour = "Sour"; private String originSweet = "Sweet"; private String originFoodName = new String(); private String originNutrientsContext = new String(); private String originIngreContext = new String(); private String originAllergenContext = new String(); private boolean isTranslated = false; private String transNurientsTitle = new String(); private String transFlavorsTitle = new String(); private String transIngreTitle = new String(); private String transAllergenTitle = new String(); private String transPoweredByTitle = new String(); private String transDataFromTitle = new String(); private String transBitter = new String(); private String transMeaty = new String(); private String transPiquant = new String(); private String transSalty = new String(); private String transSour = new String(); private String transSweet = new String(); private String transFoodName = new String(); private String transNutrientsContext = new String(); private String transIngreContext = new String(); private String transAllergenContext = new String(); public boolean isTranslated() { return isTranslated; } public void setTranslated(boolean translated) { isTranslated = translated; } public String getOriginNurientsTitle() { return originNurientsTitle; } public void setOriginNurientsTitle(String originNurientsTitle) { this.originNurientsTitle = originNurientsTitle; } public String getOriginFlavorsTitle() { return originFlavorsTitle; } public void setOriginFlavorsTitle(String originFlavorsTitle) { this.originFlavorsTitle = originFlavorsTitle; } public String getOriginIngreTitle() { return originIngreTitle; } public void setOriginIngreTitle(String originIngreTitle) { this.originIngreTitle = originIngreTitle; } public String getOriginPoweredByTitle() { return originPoweredByTitle; } public void setOriginPoweredByTitle(String originPoweredByTitle) { this.originPoweredByTitle = originPoweredByTitle; } public String getOriginDataFromTitle() { return originDataFromTitle; } public void setOriginDataFromTitle(String originDataFromTitle) { this.originDataFromTitle = originDataFromTitle; } public String getOriginBitter() { return originBitter; } public void setOriginBitter(String originBitter) { this.originBitter = originBitter; } public String getOriginMeaty() { return originMeaty; } public void setOriginMeaty(String originMeaty) { this.originMeaty = originMeaty; } public String getOriginPiquant() { return originPiquant; } public void setOriginPiquant(String originPiquant) { this.originPiquant = originPiquant; } public String getOriginSalty() { return originSalty; } public void setOriginSalty(String originSalty) { this.originSalty = originSalty; } public String getOriginSour() { return originSour; } public void setOriginSour(String originSour) { this.originSour = originSour; } public String getOriginSweet() { return originSweet; } public void setOriginSweet(String originSweet) { this.originSweet = originSweet; } public String getOriginFoodName() { return originFoodName; } public void setOriginFoodName(String originFoodName) { this.originFoodName = originFoodName; } public String getOriginNutrientsContext() { return originNutrientsContext; } public void setOriginNutrientsContext(String originNutrientsContext) { this.originNutrientsContext = originNutrientsContext; } public String getOriginIngreContext() { return originIngreContext; } public void setOriginIngreContext(String originIngreContext) { this.originIngreContext = originIngreContext; } public String getTransNurientsTitle() { return transNurientsTitle; } public void setTransNurientsTitle(String transNurientsTitle) { this.transNurientsTitle = transNurientsTitle; } public String getTransFlavorsTitle() { return transFlavorsTitle; } public void setTransFlavorsTitle(String transFlavorsTitle) { this.transFlavorsTitle = transFlavorsTitle; } public String getTransIngreTitle() { return transIngreTitle; } public void setTransIngreTitle(String transIngreTitle) { this.transIngreTitle = transIngreTitle; } public String getTransPoweredByTitle() { return transPoweredByTitle; } public void setTransPoweredByTitle(String transPoweredByTitle) { this.transPoweredByTitle = transPoweredByTitle; } public String getTransDataFromTitle() { return transDataFromTitle; } public void setTransDataFromTitle(String transDataFromTitle) { this.transDataFromTitle = transDataFromTitle; } public String getTransBitter() { return transBitter; } public void setTransBitter(String transBitter) { this.transBitter = transBitter; } public String getTransMeaty() { return transMeaty; } public void setTransMeaty(String transMeaty) { this.transMeaty = transMeaty; } public String getTransPiquant() { return transPiquant; } public void setTransPiquant(String transPiquant) { this.transPiquant = transPiquant; } public String getTransSalty() { return transSalty; } public void setTransSalty(String transSalty) { this.transSalty = transSalty; } public String getTransSour() { return transSour; } public void setTransSour(String transSour) { this.transSour = transSour; } public String getTransSweet() { return transSweet; } public void setTransSweet(String transSweet) { this.transSweet = transSweet; } public String getTransFoodName() { return transFoodName; } public void setTransFoodName(String transFoodName) { this.transFoodName = transFoodName; } public String getTransNutrientsContext() { return transNutrientsContext; } public void setTransNutrientsContext(String transNutrientsContext) { this.transNutrientsContext = transNutrientsContext; } public String getTransIngreContext() { return transIngreContext; } public void setTransIngreContext(String transIngreContext) { this.transIngreContext = transIngreContext; } public String getOriginAllergenTitle() { return originAllergenTitle; } public void setOriginAllergenTitle(String originAllergenTitle) { this.originAllergenTitle = originAllergenTitle; } public String getOriginAllergenContext() { return originAllergenContext; } public void setOriginAllergenContext(String originAllergenContext) { this.originAllergenContext = originAllergenContext; } public String getTransAllergenTitle() { return transAllergenTitle; } public void setTransAllergenTitle(String transAllergenTitle) { this.transAllergenTitle = transAllergenTitle; } public String getTransAllergenContext() { return transAllergenContext; } public void setTransAllergenContext(String transAllergenContext) { this.transAllergenContext = transAllergenContext; } }
UTF-8
Java
8,281
java
FoodInfoContents.java
Java
[ { "context": "age com.uos.kyungimlee.ourmenu;\n\n/**\n * Created by kyungimlee on 2017. 12. 6..\n */\n\nclass FoodInfoContents {\n\n ", "end": 65, "score": 0.9996899366378784, "start": 55, "tag": "USERNAME", "value": "kyungimlee" } ]
null
[]
package com.uos.kyungimlee.ourmenu; /** * Created by kyungimlee on 2017. 12. 6.. */ class FoodInfoContents { private String originNurientsTitle = "Nutrients"; private String originFlavorsTitle = "Flavors"; private String originIngreTitle = "Ingredients"; private String originAllergenTitle = "Allergen"; private String originPoweredByTitle = "Powered By"; private String originDataFromTitle = "Data From"; private String originBitter = "Bitter"; private String originMeaty = "Meaty"; private String originPiquant = "Piquant"; private String originSalty = "Salty"; private String originSour = "Sour"; private String originSweet = "Sweet"; private String originFoodName = new String(); private String originNutrientsContext = new String(); private String originIngreContext = new String(); private String originAllergenContext = new String(); private boolean isTranslated = false; private String transNurientsTitle = new String(); private String transFlavorsTitle = new String(); private String transIngreTitle = new String(); private String transAllergenTitle = new String(); private String transPoweredByTitle = new String(); private String transDataFromTitle = new String(); private String transBitter = new String(); private String transMeaty = new String(); private String transPiquant = new String(); private String transSalty = new String(); private String transSour = new String(); private String transSweet = new String(); private String transFoodName = new String(); private String transNutrientsContext = new String(); private String transIngreContext = new String(); private String transAllergenContext = new String(); public boolean isTranslated() { return isTranslated; } public void setTranslated(boolean translated) { isTranslated = translated; } public String getOriginNurientsTitle() { return originNurientsTitle; } public void setOriginNurientsTitle(String originNurientsTitle) { this.originNurientsTitle = originNurientsTitle; } public String getOriginFlavorsTitle() { return originFlavorsTitle; } public void setOriginFlavorsTitle(String originFlavorsTitle) { this.originFlavorsTitle = originFlavorsTitle; } public String getOriginIngreTitle() { return originIngreTitle; } public void setOriginIngreTitle(String originIngreTitle) { this.originIngreTitle = originIngreTitle; } public String getOriginPoweredByTitle() { return originPoweredByTitle; } public void setOriginPoweredByTitle(String originPoweredByTitle) { this.originPoweredByTitle = originPoweredByTitle; } public String getOriginDataFromTitle() { return originDataFromTitle; } public void setOriginDataFromTitle(String originDataFromTitle) { this.originDataFromTitle = originDataFromTitle; } public String getOriginBitter() { return originBitter; } public void setOriginBitter(String originBitter) { this.originBitter = originBitter; } public String getOriginMeaty() { return originMeaty; } public void setOriginMeaty(String originMeaty) { this.originMeaty = originMeaty; } public String getOriginPiquant() { return originPiquant; } public void setOriginPiquant(String originPiquant) { this.originPiquant = originPiquant; } public String getOriginSalty() { return originSalty; } public void setOriginSalty(String originSalty) { this.originSalty = originSalty; } public String getOriginSour() { return originSour; } public void setOriginSour(String originSour) { this.originSour = originSour; } public String getOriginSweet() { return originSweet; } public void setOriginSweet(String originSweet) { this.originSweet = originSweet; } public String getOriginFoodName() { return originFoodName; } public void setOriginFoodName(String originFoodName) { this.originFoodName = originFoodName; } public String getOriginNutrientsContext() { return originNutrientsContext; } public void setOriginNutrientsContext(String originNutrientsContext) { this.originNutrientsContext = originNutrientsContext; } public String getOriginIngreContext() { return originIngreContext; } public void setOriginIngreContext(String originIngreContext) { this.originIngreContext = originIngreContext; } public String getTransNurientsTitle() { return transNurientsTitle; } public void setTransNurientsTitle(String transNurientsTitle) { this.transNurientsTitle = transNurientsTitle; } public String getTransFlavorsTitle() { return transFlavorsTitle; } public void setTransFlavorsTitle(String transFlavorsTitle) { this.transFlavorsTitle = transFlavorsTitle; } public String getTransIngreTitle() { return transIngreTitle; } public void setTransIngreTitle(String transIngreTitle) { this.transIngreTitle = transIngreTitle; } public String getTransPoweredByTitle() { return transPoweredByTitle; } public void setTransPoweredByTitle(String transPoweredByTitle) { this.transPoweredByTitle = transPoweredByTitle; } public String getTransDataFromTitle() { return transDataFromTitle; } public void setTransDataFromTitle(String transDataFromTitle) { this.transDataFromTitle = transDataFromTitle; } public String getTransBitter() { return transBitter; } public void setTransBitter(String transBitter) { this.transBitter = transBitter; } public String getTransMeaty() { return transMeaty; } public void setTransMeaty(String transMeaty) { this.transMeaty = transMeaty; } public String getTransPiquant() { return transPiquant; } public void setTransPiquant(String transPiquant) { this.transPiquant = transPiquant; } public String getTransSalty() { return transSalty; } public void setTransSalty(String transSalty) { this.transSalty = transSalty; } public String getTransSour() { return transSour; } public void setTransSour(String transSour) { this.transSour = transSour; } public String getTransSweet() { return transSweet; } public void setTransSweet(String transSweet) { this.transSweet = transSweet; } public String getTransFoodName() { return transFoodName; } public void setTransFoodName(String transFoodName) { this.transFoodName = transFoodName; } public String getTransNutrientsContext() { return transNutrientsContext; } public void setTransNutrientsContext(String transNutrientsContext) { this.transNutrientsContext = transNutrientsContext; } public String getTransIngreContext() { return transIngreContext; } public void setTransIngreContext(String transIngreContext) { this.transIngreContext = transIngreContext; } public String getOriginAllergenTitle() { return originAllergenTitle; } public void setOriginAllergenTitle(String originAllergenTitle) { this.originAllergenTitle = originAllergenTitle; } public String getOriginAllergenContext() { return originAllergenContext; } public void setOriginAllergenContext(String originAllergenContext) { this.originAllergenContext = originAllergenContext; } public String getTransAllergenTitle() { return transAllergenTitle; } public void setTransAllergenTitle(String transAllergenTitle) { this.transAllergenTitle = transAllergenTitle; } public String getTransAllergenContext() { return transAllergenContext; } public void setTransAllergenContext(String transAllergenContext) { this.transAllergenContext = transAllergenContext; } }
8,281
0.693998
0.693153
309
25.799353
23.136122
74
false
false
0
0
0
0
0
0
0.323625
false
false
9
2ce098e38428db35de27efbb63408469ae40ef52
12,567,074,349,527
806af95288dd408cdec6f578749f284a49ceaafd
/old_20131116/mylife.home.ircd/src/main/java/mylife/home/irc/server/commands/Quit.java
d75c71db246662a9dbd2b4aff4756d68474900ed
[]
no_license
vincent-tr/bouh-mylife
https://github.com/vincent-tr/bouh-mylife
fe664a08a5529865eeac3df74f41c7391ffd8d43
6f98ada460fce3488b9db167e55ceebd179a6dec
refs/heads/master
2021-01-01T20:11:53.403000
2014-12-07T21:51:10
2014-12-07T21:51:10
38,362,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mylife.home.irc.server.commands; public class Quit { }
UTF-8
Java
70
java
Quit.java
Java
[]
null
[]
package mylife.home.irc.server.commands; public class Quit { }
70
0.7
0.7
5
12
15.760711
40
false
false
0
0
0
0
0
0
0.2
false
false
9
7b6f3b3f56a6e0379b4af31540c65259c0f12bec
12,567,074,350,966
c53ceae5b10b1e0172fabb30cb9bde46b2af9371
/StudentServer/src/main/java/com/wipro/dao/StudentDao.java
eb46a15d481ecb5e4f8a63abdade69209abeca3d
[]
no_license
singhrajesh8699/StudentTeacherRelationDemo
https://github.com/singhrajesh8699/StudentTeacherRelationDemo
415e5653a92743f5b9e044d1cd47dfa72254196d
6792465c5779e1de6df7fc52c9a2baa2e070981b
refs/heads/master
2021-01-20T07:02:34.220000
2017-05-01T19:09:22
2017-05-01T19:09:22
89,951,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wipro.dao; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.transaction.Transactional; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.wipro.dto.ClassRoom; import com.wipro.dto.Course; import com.wipro.dto.Department; import com.wipro.dto.Student; import com.wipro.dto.Address; import com.wipro.dto.Teacher; @Transactional @Repository("stdDao") public class StudentDao implements IStudentDao{ @Autowired private SessionFactory sessionFactory; @Override public void insertData(String request) { JSONObject reqJson = null; JSONObject teacher = null; JSONObject course = null; JSONObject departmet = null; JSONObject student=null; JSONObject address=null; JSONObject classroom=null; Session session = sessionFactory.openSession(); try { reqJson = new JSONObject(request); course = reqJson.getJSONObject("course"); student = reqJson.getJSONObject("student"); address = reqJson.getJSONObject("address"); classroom = reqJson.getJSONObject("classroom"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); Department dept=mapper.readValue(departmet.toString(),Department.class); Teacher tchrObj=mapper.readValue(teacher.toString(), Teacher.class); Course crsObj=mapper.readValue(course.toString(), Course.class); Student stdObj=mapper.readValue(student.toString(), Student.class); Address addStd=mapper.readValue(address.toString(), Address.class); ClassRoom clsObj=mapper.readValue(classroom.toString(), ClassRoom.class); addStd.setStdAdd(stdObj); //stdObj.setAddress(addStd); crsObj.setTeacherCrs(tchrObj); crsObj.setStdCrs(new HashSet<Student>(0)); crsObj.getStdCrs().add(stdObj); // stdObj.setClassRoom(clsObj); clsObj.setStdCls(new ArrayList<Student>(0)); clsObj.getStdCls().add(stdObj); clsObj.setTcrCls(new HashSet<Teacher>(0)); clsObj.getTcrCls().add(tchrObj); tchrObj.setTcourse(new ArrayList<Course>(0)); tchrObj.getTcourse().add(crsObj); tchrObj.setDepartment(dept); dept.setTeacher(new ArrayList<Teacher>()); dept.getTeacher().add(tchrObj); session.save(dept); session.flush(); session.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
2,870
java
StudentDao.java
Java
[]
null
[]
package com.wipro.dao; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.transaction.Transactional; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.wipro.dto.ClassRoom; import com.wipro.dto.Course; import com.wipro.dto.Department; import com.wipro.dto.Student; import com.wipro.dto.Address; import com.wipro.dto.Teacher; @Transactional @Repository("stdDao") public class StudentDao implements IStudentDao{ @Autowired private SessionFactory sessionFactory; @Override public void insertData(String request) { JSONObject reqJson = null; JSONObject teacher = null; JSONObject course = null; JSONObject departmet = null; JSONObject student=null; JSONObject address=null; JSONObject classroom=null; Session session = sessionFactory.openSession(); try { reqJson = new JSONObject(request); course = reqJson.getJSONObject("course"); student = reqJson.getJSONObject("student"); address = reqJson.getJSONObject("address"); classroom = reqJson.getJSONObject("classroom"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); Department dept=mapper.readValue(departmet.toString(),Department.class); Teacher tchrObj=mapper.readValue(teacher.toString(), Teacher.class); Course crsObj=mapper.readValue(course.toString(), Course.class); Student stdObj=mapper.readValue(student.toString(), Student.class); Address addStd=mapper.readValue(address.toString(), Address.class); ClassRoom clsObj=mapper.readValue(classroom.toString(), ClassRoom.class); addStd.setStdAdd(stdObj); //stdObj.setAddress(addStd); crsObj.setTeacherCrs(tchrObj); crsObj.setStdCrs(new HashSet<Student>(0)); crsObj.getStdCrs().add(stdObj); // stdObj.setClassRoom(clsObj); clsObj.setStdCls(new ArrayList<Student>(0)); clsObj.getStdCls().add(stdObj); clsObj.setTcrCls(new HashSet<Teacher>(0)); clsObj.getTcrCls().add(tchrObj); tchrObj.setTcourse(new ArrayList<Course>(0)); tchrObj.getTcourse().add(crsObj); tchrObj.setDepartment(dept); dept.setTeacher(new ArrayList<Teacher>()); dept.getTeacher().add(tchrObj); session.save(dept); session.flush(); session.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2,870
0.69547
0.694077
128
21.421875
21.081541
77
false
false
0
0
0
0
0
0
2.859375
false
false
9
7440dc3f52aafa947a0f2092aed0172122aa4f50
33,509,334,859,114
6d2f416c1d7acb237ff1e86da8adbab0722cafaa
/Arrays/Frequency.java
904764c8450a34ba3584092cc24226a5419da528
[]
no_license
Shivanirudh/OOP-JAVA
https://github.com/Shivanirudh/OOP-JAVA
86f16273dafa44029f610f88378cb50bd00f49ae
6536095e45757ae629d99f51ece14013fa915021
refs/heads/master
2020-06-20T12:04:20.093000
2019-10-30T17:18:55
2019-10-30T17:18:55
197,116,432
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*4. Write a program to Find the Number of Non-Repeated Elements in an Array.*/ import java.util.Scanner; public class Frequency{ public static void main(String args[]){ int Arr[]=new int[100]; int numLimit; Scanner in=new Scanner(System.in); System.out.print("Enter the number of elements ");numLimit=in.nextInt(); System.out.println("\nEnter the Array: "); for(int i=0;i<numLimit;i++) Arr[i]=in.nextInt(); int Distinct[]=new int[100]; int distinctCounter=0,flag=0; for(int i=0;i<numLimit;i++){ flag=0; for(int j=i+1;j<numLimit&&flag==0;j++){ if(Arr[i]==Arr[j]) flag=1; } for(int j=0;j<i&&flag==0;j++){ if(Arr[i]==Arr[j]) flag=1; } if(flag==0) Distinct[distinctCounter++]=Arr[i]; } System.out.println("\nThe number of Non-repetitive elements is "+distinctCounter); System.out.println("\nThey are: "); for(int i=0;i<distinctCounter;i++) System.out.print(Distinct[i]+" "); } } /*Output: Enter the number of elements 10 Enter the Array: 5 5 5 5 5 6 6 6 6 7 The number of Non-repetitive elements is 1 They are: 7 */
UTF-8
Java
1,104
java
Frequency.java
Java
[]
null
[]
/*4. Write a program to Find the Number of Non-Repeated Elements in an Array.*/ import java.util.Scanner; public class Frequency{ public static void main(String args[]){ int Arr[]=new int[100]; int numLimit; Scanner in=new Scanner(System.in); System.out.print("Enter the number of elements ");numLimit=in.nextInt(); System.out.println("\nEnter the Array: "); for(int i=0;i<numLimit;i++) Arr[i]=in.nextInt(); int Distinct[]=new int[100]; int distinctCounter=0,flag=0; for(int i=0;i<numLimit;i++){ flag=0; for(int j=i+1;j<numLimit&&flag==0;j++){ if(Arr[i]==Arr[j]) flag=1; } for(int j=0;j<i&&flag==0;j++){ if(Arr[i]==Arr[j]) flag=1; } if(flag==0) Distinct[distinctCounter++]=Arr[i]; } System.out.println("\nThe number of Non-repetitive elements is "+distinctCounter); System.out.println("\nThey are: "); for(int i=0;i<distinctCounter;i++) System.out.print(Distinct[i]+" "); } } /*Output: Enter the number of elements 10 Enter the Array: 5 5 5 5 5 6 6 6 6 7 The number of Non-repetitive elements is 1 They are: 7 */
1,104
0.639493
0.608696
48
22
20.45829
84
false
false
0
0
0
0
0
0
2.270833
false
false
9
d970243b820a0bc9f645334aab6fb013c3355998
2,619,930,101,631
4d899fb969ff1603e79aeae3869e6f21198ce505
/RedirectForward/src/kr/co/softcampus/controller/TestController.java
3633e4460713dd25e3c49219f9847550b070c7e4
[]
no_license
dev-gyus/springframwork
https://github.com/dev-gyus/springframwork
862d9b9b873f3511dfd740ccf328ef6b49eb1fc1
14688a9b122e5c16843bdd559eaf157ae0ceb125
refs/heads/main
2023-02-26T08:51:02.209000
2021-02-06T14:40:39
2021-02-06T14:40:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.softcampus.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { @GetMapping("/test1") public String redirect() { // redirect: 붙여서 ViewResolver로 반환하면 해당 페이지로 리다이렉트됨 // redirect: 다음에오는 url을 새로 요청하라는 의미가됨 -> Request객체 새로생성됨 return "redirect:/sub1"; } @GetMapping("/sub1") public String sub1() { return "sub1"; } @GetMapping("/test2") public String test2() { // forward: 붙여서 ViewResolver로 반환하면 해당 페이지로 포워딩함 // forward: 다음에 오는 url로 포워딩함 -> url변경없이 /sub2를 대응하는 컨트롤러 메소드(바로아래 메소드)호출 return "forward:/sub2"; } @GetMapping("/sub2") public String sub2() { return "sub2"; } }
UTF-8
Java
914
java
TestController.java
Java
[]
null
[]
package kr.co.softcampus.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { @GetMapping("/test1") public String redirect() { // redirect: 붙여서 ViewResolver로 반환하면 해당 페이지로 리다이렉트됨 // redirect: 다음에오는 url을 새로 요청하라는 의미가됨 -> Request객체 새로생성됨 return "redirect:/sub1"; } @GetMapping("/sub1") public String sub1() { return "sub1"; } @GetMapping("/test2") public String test2() { // forward: 붙여서 ViewResolver로 반환하면 해당 페이지로 포워딩함 // forward: 다음에 오는 url로 포워딩함 -> url변경없이 /sub2를 대응하는 컨트롤러 메소드(바로아래 메소드)호출 return "forward:/sub2"; } @GetMapping("/sub2") public String sub2() { return "sub2"; } }
914
0.713889
0.697222
28
24.714285
19.784296
74
false
false
0
0
0
0
0
0
1.285714
false
false
9
138755b5e46c52650de5eadee634f7e3a1bef5c1
10,110,353,071,438
138093741ef41cd0fdf6d519ec3ee323ff4d031c
/mj/src/com/telemune/dao/UserManager.java
88e39be91517755dacea6e190d3824e0309b934e
[]
no_license
mahavastudev/mahajyotish_2
https://github.com/mahavastudev/mahajyotish_2
93b89f4b29e8ea2797edd1e27532b3fc65a226b1
c49808350ff4758c648362b34487c40754c7cf6d
refs/heads/master
2023-08-05T20:40:07.381000
2021-09-21T07:47:46
2021-09-21T07:47:46
408,730,746
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.telemune.dao; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.telemune.dbutilities.Connection; import com.telemune.dbutilities.PreparedStatement; import com.telemune.mobileAstro.TSSJavaUtil; import com.telemune.model.UserInfo; public class UserManager { private static final Logger logger = Logger.getLogger(UserManager.class); private Connection con = null; private PreparedStatement pstmt = null; private ResultSet rs = null; public int addUser(UserInfo userInfo) { logger.info("Inside addUser method of UserManager dao class. userInfo:[" + userInfo.toString() + "]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "insert into adminlogin" + "(NAME,PASSWORD,EMAIL,MOBILE_NO,ROLE_ID,create_date) values" + "(?,?,?,?,?,now())"; pstmt = con.prepareStatement(query); pstmt.setString(1, userInfo.getUname().trim()); pstmt.setString(2, userInfo.getUpassword()); pstmt.setString(3, userInfo.getEmail()); pstmt.setString(4, userInfo.getMobileNo()); pstmt.setString(5, userInfo.getRoleId()); int result = pstmt.executeUpdate(); if (result > 0) { return 1; } } catch (Exception e) { logger.error("Inside catch block of addUser method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return 0; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of addUser method of UserManager dao class. Exception : " + e.toString()); } } return 0; } public int modifyUserInfo(UserInfo userInfo) { logger.info("Inside modifyUserInfo method of UserManager dao class."); try { con = TSSJavaUtil.instance().getconnection(); String query = "update adminlogin set " + "NAME=?,PASSWORD=?,EMAIL=?,MOBILE_NO=?,ROLE_ID=? " + "where ID=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, userInfo.getUname().trim()); pstmt.setString(2, userInfo.getUpassword()); pstmt.setString(3, userInfo.getEmail()); pstmt.setString(4, userInfo.getMobileNo()); pstmt.setString(5, userInfo.getRoleId()); pstmt.setInt(6, userInfo.getuId()); int result = pstmt.executeUpdate(); logger.info("user modify info result " + result); if (result > 0) { return 1; } } catch (Exception e) { logger.error("Inside catch block of modifyUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return 0; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of modifyUserInfo method of UserManager dao class. Exception : " + e.toString()); } } return 0; } public int deleteUser(String userId) { logger.info("Inside deleteUser method of UserManager dao class."); int result = 0; try { logger.info("inside,delete user info " + userId.toString()); String[] id = userId.split(","); for (String uId : id) { con = TSSJavaUtil.instance().getconnection(); String query = "delete from adminlogin where ID=?"; pstmt = con.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(uId.trim())); result = pstmt.executeUpdate(); } } catch (Exception e) { logger.error("Inside catch block of deleteUser method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return result; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of deleteUser method of UserManager dao class. Exception : " + e.toString()); } } return result; } public List<UserInfo> getUserList() { logger.info("Inside getUserList method of UserManager dao class."); List<UserInfo> userLst = new ArrayList<UserInfo>(); try { con = TSSJavaUtil.instance().getconnection(); String query = "select a.ID,a.NAME,a.MOBILE_NO,a.EMAIL,a.PASSWORD,a.create_date,a.ROLE_ID,b.ROLE_NAME from adminlogin a ,ROLES_MASTER b where a.ROLE_ID=b.ROLE_ID"; pstmt = con.prepareStatement(query); rs = pstmt.executeQuery(); while (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); userInfo.setRoleName(rs.getString("ROLE_NAME")); userLst.add(userInfo); } } catch (Exception e) { logger.error("Inside catch block of getUserList method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return userLst; } finally { try { if (pstmt != null) { pstmt.close(); } if (rs != null) { rs.close(); } if (con != null) { TSSJavaUtil.instance().freeConnection(con); } } catch (Exception e) { logger.error( "Inside finally block of getUserList method of UserManager dao class. Exception : " + e.toString()); } } return userLst; } public UserInfo getUserInfo(int uId) { logger.info("Inside getUserInfo method of UserManager dao class with userId:["+uId+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where ID=?"; pstmt = con.prepareStatement(query); pstmt.setInt(1, uId); rs = pstmt.executeQuery(); if (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); return userInfo; } return null; } catch (Exception e) { logger.error("Inside catch block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); } } } public List<UserInfo> getUserList(String roleId) { logger.info("Inside getUserList method of UserManager dao class."); List<UserInfo> userLst = new ArrayList<UserInfo>(); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where ROLE_ID=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, roleId); rs = pstmt.executeQuery(); while (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); userLst.add(userInfo); } return userLst; } catch (Exception e) { logger.error("Inside catch block of getUserList method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) { pstmt.close(); } if (rs != null) { rs.close(); } if (con != null) { TSSJavaUtil.instance().freeConnection(con); } } catch (Exception e) { logger.error( "Inside finally block of getUserList method of UserManager dao class. Exception : " + e.toString()); } } } public boolean isUserExist(String userEmail) { logger.info("Inside isUserExist method of UserManager dao class where userEmail:["+userEmail+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where email=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, userEmail); rs = pstmt.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { logger.error("Inside catch block of isUserExist method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of isUserExist method of UserManager dao class. Exception : " + e.toString()); } } return false; } public UserInfo getUserInfo(String email) { logger.info("Inside getUserInfo method of UserManager dao class. where email:["+email+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where EMAIL=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, email); rs = pstmt.executeQuery(); if (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); return userInfo; } return null; } catch (Exception e) { logger.error("Inside catch block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); } } } }
UTF-8
Java
10,519
java
UserManager.java
Java
[]
null
[]
package com.telemune.dao; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.telemune.dbutilities.Connection; import com.telemune.dbutilities.PreparedStatement; import com.telemune.mobileAstro.TSSJavaUtil; import com.telemune.model.UserInfo; public class UserManager { private static final Logger logger = Logger.getLogger(UserManager.class); private Connection con = null; private PreparedStatement pstmt = null; private ResultSet rs = null; public int addUser(UserInfo userInfo) { logger.info("Inside addUser method of UserManager dao class. userInfo:[" + userInfo.toString() + "]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "insert into adminlogin" + "(NAME,PASSWORD,EMAIL,MOBILE_NO,ROLE_ID,create_date) values" + "(?,?,?,?,?,now())"; pstmt = con.prepareStatement(query); pstmt.setString(1, userInfo.getUname().trim()); pstmt.setString(2, userInfo.getUpassword()); pstmt.setString(3, userInfo.getEmail()); pstmt.setString(4, userInfo.getMobileNo()); pstmt.setString(5, userInfo.getRoleId()); int result = pstmt.executeUpdate(); if (result > 0) { return 1; } } catch (Exception e) { logger.error("Inside catch block of addUser method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return 0; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of addUser method of UserManager dao class. Exception : " + e.toString()); } } return 0; } public int modifyUserInfo(UserInfo userInfo) { logger.info("Inside modifyUserInfo method of UserManager dao class."); try { con = TSSJavaUtil.instance().getconnection(); String query = "update adminlogin set " + "NAME=?,PASSWORD=?,EMAIL=?,MOBILE_NO=?,ROLE_ID=? " + "where ID=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, userInfo.getUname().trim()); pstmt.setString(2, userInfo.getUpassword()); pstmt.setString(3, userInfo.getEmail()); pstmt.setString(4, userInfo.getMobileNo()); pstmt.setString(5, userInfo.getRoleId()); pstmt.setInt(6, userInfo.getuId()); int result = pstmt.executeUpdate(); logger.info("user modify info result " + result); if (result > 0) { return 1; } } catch (Exception e) { logger.error("Inside catch block of modifyUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return 0; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of modifyUserInfo method of UserManager dao class. Exception : " + e.toString()); } } return 0; } public int deleteUser(String userId) { logger.info("Inside deleteUser method of UserManager dao class."); int result = 0; try { logger.info("inside,delete user info " + userId.toString()); String[] id = userId.split(","); for (String uId : id) { con = TSSJavaUtil.instance().getconnection(); String query = "delete from adminlogin where ID=?"; pstmt = con.prepareStatement(query); pstmt.setInt(1, Integer.parseInt(uId.trim())); result = pstmt.executeUpdate(); } } catch (Exception e) { logger.error("Inside catch block of deleteUser method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return result; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of deleteUser method of UserManager dao class. Exception : " + e.toString()); } } return result; } public List<UserInfo> getUserList() { logger.info("Inside getUserList method of UserManager dao class."); List<UserInfo> userLst = new ArrayList<UserInfo>(); try { con = TSSJavaUtil.instance().getconnection(); String query = "select a.ID,a.NAME,a.MOBILE_NO,a.EMAIL,a.PASSWORD,a.create_date,a.ROLE_ID,b.ROLE_NAME from adminlogin a ,ROLES_MASTER b where a.ROLE_ID=b.ROLE_ID"; pstmt = con.prepareStatement(query); rs = pstmt.executeQuery(); while (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); userInfo.setRoleName(rs.getString("ROLE_NAME")); userLst.add(userInfo); } } catch (Exception e) { logger.error("Inside catch block of getUserList method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return userLst; } finally { try { if (pstmt != null) { pstmt.close(); } if (rs != null) { rs.close(); } if (con != null) { TSSJavaUtil.instance().freeConnection(con); } } catch (Exception e) { logger.error( "Inside finally block of getUserList method of UserManager dao class. Exception : " + e.toString()); } } return userLst; } public UserInfo getUserInfo(int uId) { logger.info("Inside getUserInfo method of UserManager dao class with userId:["+uId+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where ID=?"; pstmt = con.prepareStatement(query); pstmt.setInt(1, uId); rs = pstmt.executeQuery(); if (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); return userInfo; } return null; } catch (Exception e) { logger.error("Inside catch block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); } } } public List<UserInfo> getUserList(String roleId) { logger.info("Inside getUserList method of UserManager dao class."); List<UserInfo> userLst = new ArrayList<UserInfo>(); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where ROLE_ID=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, roleId); rs = pstmt.executeQuery(); while (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); userLst.add(userInfo); } return userLst; } catch (Exception e) { logger.error("Inside catch block of getUserList method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) { pstmt.close(); } if (rs != null) { rs.close(); } if (con != null) { TSSJavaUtil.instance().freeConnection(con); } } catch (Exception e) { logger.error( "Inside finally block of getUserList method of UserManager dao class. Exception : " + e.toString()); } } } public boolean isUserExist(String userEmail) { logger.info("Inside isUserExist method of UserManager dao class where userEmail:["+userEmail+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where email=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, userEmail); rs = pstmt.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { logger.error("Inside catch block of isUserExist method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of isUserExist method of UserManager dao class. Exception : " + e.toString()); } } return false; } public UserInfo getUserInfo(String email) { logger.info("Inside getUserInfo method of UserManager dao class. where email:["+email+"]."); try { con = TSSJavaUtil.instance().getconnection(); String query = "select * from adminlogin where EMAIL=?"; pstmt = con.prepareStatement(query); pstmt.setString(1, email); rs = pstmt.executeQuery(); if (rs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setuId(rs.getInt("ID")); userInfo.setUname(rs.getString("NAME")); userInfo.setMobileNo(rs.getString("MOBILE_NO")); userInfo.setEmail(rs.getString("EMAIL")); userInfo.setUpassword(rs.getString("PASSWORD")); userInfo.setCreateDate(rs.getString("create_date")); userInfo.setRoleId(rs.getString("ROLE_ID")); return userInfo; } return null; } catch (Exception e) { logger.error("Inside catch block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); e.printStackTrace(); return null; } finally { try { if (pstmt != null) pstmt.close(); if (rs != null) rs.close(); if (con != null) TSSJavaUtil.instance().freeConnection(con); } catch (Exception e) { logger.error( "Inside finally block of getUserInfo method of UserManager dao class. Exception : " + e.toString()); } } } }
10,519
0.660804
0.658333
322
31.667702
27.878365
166
false
false
0
0
0
0
0
0
3.661491
false
false
9
094ddb99dc23bbfc8afbacd83a585aa9e06b5cb8
13,563,506,777,758
3670a839be04ca0876d7106b11ea2735602d224f
/src/empleados/directivos.java
0fc25c10d0990718a9d5811e3e261d059cc5f068
[]
no_license
casm2203/empleados
https://github.com/casm2203/empleados
272ff5eab7f7c7ded8cacf7649da7a7860c0e7ed
9af676a66b31bf846b3cf3c9b06a4b1bf79fdd42
refs/heads/master
2021-01-04T04:19:56.753000
2020-02-19T18:44:56
2020-02-19T18:44:56
240,384,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package empleados; /** * * @author csuarez25 */ public class directivos extends Empleados { private String dependencia; private int antiguedad; private int horasDeTrabajo; private int valorHora; public directivos() { super(); dependencia = ""; antiguedad = 0; horasDeTrabajo = 0; valorHora = 0; } public String getDependencia() { return dependencia; } public void setDependencia(String dependencia) { this.dependencia = dependencia; } public int getAntiguedad() { return antiguedad; } public void setAntiguedad(int antiguedad) { this.antiguedad = antiguedad; } public int getHorasDeTrabajo() { return horasDeTrabajo; } public void setHorasDeTrabajo(int horasDeTrabajo) { this.horasDeTrabajo = horasDeTrabajo; } public int getValorHora() { return valorHora; } public void setValorHora(int valorHora) { this.valorHora = valorHora; } public int salario() { int nomina = this.valorHora * this.horasDeTrabajo; return nomina; } public String mostrar (){ String info = super.mostrar()+"\n-Dependencia: "+this.dependencia+"\n-Antiguedad(meses): "+this.antiguedad+"\n-Horas trabajadas: " +this.horasDeTrabajo+"\n-Valor hora: $"+this.valorHora+ "\n-Salario: $"+this.salario(); return info; } }
UTF-8
Java
1,671
java
directivos.java
Java
[ { "context": " editor.\n */\npackage empleados;\n\n/**\n *\n * @author csuarez25\n */\npublic class directivos extends Empleados {\n\n", "end": 232, "score": 0.9996297955513, "start": 223, "tag": "USERNAME", "value": "csuarez25" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package empleados; /** * * @author csuarez25 */ public class directivos extends Empleados { private String dependencia; private int antiguedad; private int horasDeTrabajo; private int valorHora; public directivos() { super(); dependencia = ""; antiguedad = 0; horasDeTrabajo = 0; valorHora = 0; } public String getDependencia() { return dependencia; } public void setDependencia(String dependencia) { this.dependencia = dependencia; } public int getAntiguedad() { return antiguedad; } public void setAntiguedad(int antiguedad) { this.antiguedad = antiguedad; } public int getHorasDeTrabajo() { return horasDeTrabajo; } public void setHorasDeTrabajo(int horasDeTrabajo) { this.horasDeTrabajo = horasDeTrabajo; } public int getValorHora() { return valorHora; } public void setValorHora(int valorHora) { this.valorHora = valorHora; } public int salario() { int nomina = this.valorHora * this.horasDeTrabajo; return nomina; } public String mostrar (){ String info = super.mostrar()+"\n-Dependencia: "+this.dependencia+"\n-Antiguedad(meses): "+this.antiguedad+"\n-Horas trabajadas: " +this.horasDeTrabajo+"\n-Valor hora: $"+this.valorHora+ "\n-Salario: $"+this.salario(); return info; } }
1,671
0.618791
0.615799
72
22.208334
24.777866
138
false
false
0
0
0
0
0
0
0.347222
false
false
9
e588f45a6e55ad678b642b372b93b09de195b94a
1,941,325,278,689
a993770d69df8a7c7bb54bbfde5428d31854a4fc
/java-workspaces/j2se/sci/src/com/stanchart/sci/view/action/.svn/text-base/BCADetailsSearchAction.java.svn-base
fc11a8d88c251364189163d334af8ed078d83e2c
[]
no_license
chatdhana/materials
https://github.com/chatdhana/materials
9911c832c16a294e63c5fabf06076bdbfa9af1bf
95c31089e5c22788f2b0bbdf0577999fc669650b
refs/heads/master
2017-11-02T13:04:26.630000
2016-05-26T19:42:33
2016-05-26T19:42:33
58,611,183
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stanchart.sci.view.action; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.stanchart.common.exception.SCBBaseException; import com.stanchart.common.serviceexecutor.ServiceExecutor; import com.stanchart.common.serviceexecutor.ServiceExecutorException; import com.stanchart.common.serviceexecutor.ServiceExecutorProvider; import com.stanchart.common.servicelocator.ServiceLocator; import com.stanchart.common.validator.IValidator; import com.stanchart.sci.appservice.constants.FunctionIDConstants; import com.stanchart.sci.appservice.constants.ServiceConstants; import com.stanchart.sci.appservice.exceptions.ApprovedSecuritySearchException; import com.stanchart.sci.model.BCADetails; import com.stanchart.sci.model.SubProfile; import com.stanchart.sci.model.UserProfile; import com.stanchart.sci.view.action.constants.ActionConstants; import com.stanchart.sci.view.action.exceptions.AuthorisationException; import com.stanchart.sci.view.action.exceptions.InvalidSessionException; import com.stanchart.sci.view.action.exceptions.NoRecordFoundException; import com.stanchart.sci.view.form.ApprovedLimitsForm; import com.stanchart.sci.view.form.ApprovedSecuritySearchForm; import com.stanchart.sci.view.form.BCADetailsSearchForm; import com.stanchart.sci.view.form.SubProfileForm; import com.stanchart.sci.view.utils.AuthUtil; import com.stanchart.sci.view.utils.ValidatorUtil; import com.stanchart.sci.view.valueobject.BCADetailsValueObject; public class BCADetailsSearchAction extends GenericAction { /** variable for logger */ private Logger logger = getLogger(); /** variable for AuthUtil */ private AuthUtil authUtil = new AuthUtil(); /** * Method which is getting called from ActionServlet, and which contains * the logic for all actions from source JSP. This method has the * responsibility to call the specific service class method to do the * database operation and convert that data to presentation layer format. * * @param mapping ActionMapping object which contains the * struts-config.xml mappings * @param form ActionForm object which has to type casted to specific form * object * @param request Represent the HttpServletRequest * @param response Represent the HttpServletResponse * * @return ActionForward object which says to which JSP the control has to * be transfered * * @throws IOException throws IOException * @throws ServletException throws ServletException if it calls any * Servlet */ public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String forwardAction = null; String actionParam = null; BCADetailsSearchForm formObject = (BCADetailsSearchForm) form; //For BCA Count UserProfile userProfile = (UserProfile)request.getSession ().getAttribute (ActionConstants.USER_PROFILE); try { actionParam = request.getParameter (ActionConstants.REQUEST_IDENTIFIER); super.performSuper(mapping, form, request, response, actionParam); /*UserProfile userProfile = (UserProfile)request.getSession ().getAttribute (ActionConstants.USER_PROFILE);*/ if (actionParam.equals (ActionConstants.ACTION_BCA_DETAILS_SEARCH)) { setSearchFAP(formObject,userProfile); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, null); forwardAction = ActionConstants.SUCCESS_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_BCA_DETAILS_SEARCH_LIST)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_DETAILS_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_DETAILS_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); BCADetails bcaDetailsObj = (BCADetails) bcaRefNoMap.get("bcaDetailsObj"); BigDecimal count= bcaDetailsObj.getCount(); //System.out.println("bcaDetailsObj.getBcaRefNo() = " + bcaDetailsObj.getBcaRefNo() ); //System.out.println("bcaDetailsObj.getModuleType() = " + bcaDetailsObj.getModuleType() ); if(bcaDetailsObj.getBcaRefNo() != null) { if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS") /*Changed for STP-2*/ && (count.intValue()!=0) ) { /** Start CM-PH II **/ if(bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.BCA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LCA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.FIBCA_MODULE_TYPE)|| bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.IGBCA_MODULE_TYPE)) { ServiceExecutorProvider serviceExecutorProvider2 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor2 = serviceExecutorProvider2.getServiceExecutor (ActionConstants.BCA_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor2.registerServiceDefinition (ActionConstants.BCA_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor2.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor2.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor2.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRelatedMap = (Map) serviceExecutor2.executeServiceDefinition (); /**Begin of Adding of Instruction Ref No and BCA Origin Location**/ formObject.setInstructionRefNo(bcaDetailsObj.getInstructionRefNo().toString()); formObject.setBcaOrgLocation(bcaDetailsObj.getBcaOrgLocation()); /**End of Adding of Instruction Ref No and BCA Origin Location**/ loadForm(formObject, bcaRelatedMap); } else if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.CRG_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider3 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor3 = serviceExecutorProvider3.getServiceExecutor (ActionConstants.CRG_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor3.registerServiceDefinition (ActionConstants.CRG_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor3.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor3.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor3.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map crgRelatedMap = (Map) serviceExecutor3.executeServiceDefinition (); loadFormForCRGList(formObject, crgRelatedMap); } else if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.RDE_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider4 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor4 = serviceExecutorProvider4.getServiceExecutor (ActionConstants.RDE_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor4.registerServiceDefinition (ActionConstants.RDE_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor4.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor4.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor4.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map rdeRelatedMap = (Map) serviceExecutor4.executeServiceDefinition (); loadFormForRDEList(formObject, rdeRelatedMap); } } //Start STP-2 if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS") && (count.intValue()==0) ) { //System.out.println("INTO COUNT 0"); ServiceExecutorProvider serviceExecutorProvider6 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor6 = serviceExecutorProvider6.getServiceExecutor (ActionConstants.BCA_SUCCESS_MSG_SERV_DEF); serviceExecutor6.registerServiceDefinition (ActionConstants.BCA_SUCCESS_MSG_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor6.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor6.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor6.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Bca No is "+ new BigDecimal(formObject.getBcaRefNo())); serviceExecutor6.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor6.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor6.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map successMap = (Map) serviceExecutor6.executeServiceDefinition (); if(successMap.get("bcaComment") != null && successMap.get("bcaComment").toString().length() != 0) { manageActionInfo (ActionConstants.BCA_SUCCESS_MSG, request, successMap.get("bcaComment").toString()); } else { manageActionInfo (ActionConstants.BCA_SUCCESS_MSG1, request,formObject.getBcaRefNo().toString()); } //manageActionInfo (ActionConstants.BCA_SUCCESS_MSG, request, successMap.get("bcaComment").toString()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); } //End STP-2 else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("FAILURE")) { formObject.setBcaFailed(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); } /** Start CM-PH II **/ else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("REJECTED")) { formObject.setBcaRejected(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setRepublishIsEnabled(true); //ADDED ON 03-06-2010 - START manageActionInfo (ActionConstants.BCA_REJECTED, request); //ADDED ON 03-06-2010 - END } /** End CM-PH II **/ else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PUBLISHED")) { formObject.setBcaNotProcessed(true); } /** Start CM-PH II B for LCA Pending Publish **/ else if (bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PENPUB") && bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LCA_MODULE_TYPE)){ formObject.setLcaPendingPub(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setLcaPendingPubIsEnabled(true); } /** End for LCA Pending Publish **/ // For a BCA which is not new else if (bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PENPUB") && ( bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.BCA_MODULE_TYPE) ||bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.FIBCA_MODULE_TYPE) ||bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.IGBCA_MODULE_TYPE)) ){ ServiceExecutorProvider serviceExecutorProvider5 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor5 = serviceExecutorProvider5.getServiceExecutor (ActionConstants.RENEWAL_BCA_IND_DEF); serviceExecutor5.registerServiceDefinition (ActionConstants.RENEWAL_BCA_IND_DEF); serviceExecutor5.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor5.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor5.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map renewalBCARelatedMap = (Map) serviceExecutor5.executeServiceDefinition (); BCADetails renwalBcaDetailsObj = (BCADetails) renewalBCARelatedMap.get("renwalBcaDetailsObj"); /*System.out.println("renwalBcaDetailsObj"); System.out.println(" renwalBcaDetailsObj.getBcaRefNo().toString() = " + renwalBcaDetailsObj.getBcaRefNo().toString()); System.out.println(" renwalBcaDetailsObj.getIndLimitMap() = " + renwalBcaDetailsObj.getIndLimitMap()); System.out.println(" renwalBcaDetailsObj.getIndSecurityMap() = " + renwalBcaDetailsObj.getIndSecurityMap()); System.out.println(" renwalBcaDetailsObj.getIndPendingPub() = " + renwalBcaDetailsObj.getIndPendingPub()); */ formObject.setRenewBCAPendingPub(true); formObject.setBcaRefNo(renwalBcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(renwalBcaDetailsObj.getBcaStatus()); formObject.setBcaComments(renwalBcaDetailsObj.getBcaComments()); //System.out.println("renwalBcaDetailsObj.getPendingPubSysGenId().toString() = " + renwalBcaDetailsObj.getPendingPubSysGenId().toString()); formObject.setPendingPubSysGenId(renwalBcaDetailsObj.getPendingPubSysGenId().toString()); // Enable renewBCALimitMapIsEnabled by defalut i.e // Limit Ind is N and Sec Ind is N if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("N") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("N")){ formObject.setRenewBCALimitMapIsEnabled(true); } // If limit Ind is Y then enable renewBCASecurityMapIsEnabled if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("N")){ formObject.setRenewBCASecurityMapIsEnabled(true); } if(renwalBcaDetailsObj.getIndCollateralAvlbl().equalsIgnoreCase("Y")){ formObject.setRenewBCAPledgorMapIsEnabled(true); }else{ formObject.setRenewBCAPledgorMapIsEnabled(false); } // If both limit Ind and Sec Ind is Y then enable Publish button if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndPledgorMap().equalsIgnoreCase("Y")){ formObject.setRenewBCAPendingPubIsEnabled(true); } } /** End CM-PH II B **/ } else{ formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); throw new NoRecordFoundException(); } assignNavigationPath (request, formObject, actionParam); if(count != null && count.intValue()!=0 ) { forwardAction = ActionConstants.SUCCESS_RETURN; } if(count != null && count.intValue()==0 ) { forwardAction = ActionConstants.SUCCESS_MSG; } } /** Start CM-PH II **/ else if(actionParam.equals (ActionConstants.ACTION_BCA_REPUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); // serviceExecutor.addInput (ActionConstants.BCA_STATUS, ActionConstants.BCA_STATUS_PUBLISH); //Map bcaRefNoMap = //(Map) serviceExecutor.executeServiceDefinition (); //assignNavigationPath (request, formObject, actionParam); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_REPUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.REPUBLISH_RETURN; } /** End CM-PH II **/ /** Start CM-PH II B for LCA Pending Publsih**/ else if(actionParam.equals (ActionConstants.ACTION_LCA_PENDING_PUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.LCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.LCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_LCA_PUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.LCA_PUBLISH_RETURN; } /** End CM-PH II B - LCA **/ //For Renew BCA Publish else if(actionParam.equals (ActionConstants.ACTION_RENEW_BCA_PENDING_PUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.RENEW_BCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.RENEW_BCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); //System.out.println( "formObject.getPendingPubSysGenId() = " + formObject.getPendingPubSysGenId()); serviceExecutor.addInput (ActionConstants.PENDING_PUB_SYS_GEN_ID, new BigDecimal(formObject.getPendingPubSysGenId())); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_RENEW_BCA_PUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.RENEW_BCA_PUBLISH_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_BCA_RESET)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_RESET_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_RESET_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); //System.out.println( "formObject.getPendingPubSysGenId() = " + formObject.getPendingPubSysGenId()); serviceExecutor.addInput (ActionConstants.PENDING_PUB_SYS_GEN_ID, new BigDecimal(formObject.getPendingPubSysGenId())); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_RESET_BCA_MAP, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.RENEW_BCA_PUBLISH_RETURN; } // Start of CM-SCI GRDE else if(actionParam.equals (ActionConstants.ACTION_GRDE_SEARCH_LIST)) { //System.out.println(" into the Action of GRDE "); String grdeRefNo = formObject.getBcaRefNo(); ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.GRDE_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.GRDE_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Grder number is "+grdeRefNo); serviceExecutor.addInput (ActionConstants.GRDE_REF_NO, grdeRefNo); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); BCADetails bcaDetailsObj = (BCADetails) bcaRefNoMap.get("bcaDetailsObj"); //System.out.println("bcaDetailsObj.getBcaRefNo() = " + bcaDetailsObj.getGrdeRefNo() ); //System.out.println("bcaDetailsObj.getModuleType() = " + bcaDetailsObj.getModuleType() ); //System.out.println("bcaDetailsObj.getBCAStatus() = " + bcaDetailsObj.getBcaStatus() ); if(bcaDetailsObj.getGrdeRefNo() != null) { if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS")) { //System.out.println("Into GRDE success"); //System.out.println("module type is "+bcaDetailsObj.getModuleType()); //if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.GRDE_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider4 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor4 = serviceExecutorProvider4.getServiceExecutor (ActionConstants.GRDE_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor4.registerServiceDefinition (ActionConstants.GRDE_DETAILS_SEARCH_LIST_SERV_DEF); //System.out.println("Grder number is "+grdeRefNo); serviceExecutor4.addInput (ActionConstants.GRDE_REF_NO, grdeRefNo); serviceExecutor4.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor4.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map grdeRelatedMap = (Map) serviceExecutor4.executeServiceDefinition (); loadFormForGRDEList(formObject, grdeRelatedMap); //} } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("FAILURE")) { formObject.setBcaFailed(true); formObject.setBcaRefNo(bcaDetailsObj.getGrdeRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("REJECTED")) { formObject.setGrdeRejected(true); formObject.setBcaRefNo((bcaDetailsObj.getGrdeRefNo().toString())); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setRepublishIsEnabled(true); //ADDED ON 03-06-2010 - START manageActionInfo (ActionConstants.BCA_REJECTED, request); //ADDED ON 03-06-2010 - END } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PUBLISHED")) { formObject.setBcaNotProcessed(true); } } else{ formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); throw new NoRecordFoundException(); } assignNavigationPath (request, formObject, actionParam); forwardAction = ActionConstants.SUCCESS_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_GRDE_REPUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.GRDE_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.GRDE_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, formObject.getBcaRefNo()); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); // serviceExecutor.addInput (ActionConstants.BCA_STATUS, ActionConstants.BCA_STATUS_PUBLISH); //Map bcaRefNoMap = //(Map) serviceExecutor.executeServiceDefinition (); //assignNavigationPath (request, formObject, actionParam); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_REPUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.REPUBLISH_RETURN; } // End of CM-SCI GRDE } catch (InvalidSessionException sessEx) { manageActionErrors (ActionConstants.INVALID_SESSION, request); forwardAction = ActionConstants.INVALID_SESSION; logger.error (sessEx.toString()); } catch (ServiceExecutorException seEx) { Throwable exObj = seEx.getCause(); if (exObj != null) { if (exObj instanceof AuthorisationException) { handleMessage (exObj, request); forwardAction = ActionConstants.AUTH_ERROR; logger.error (exObj.toString()); } else if (exObj instanceof ApprovedSecuritySearchException) { handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (exObj.toString()); } else if (exObj instanceof SCBBaseException) { exObj.printStackTrace(); handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (exObj.toString()); } else { handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error ("Unhandled exception : " + exObj.toString()); } } else { handleMessage (seEx, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error ("ServiceExecutor exception : " + seEx.toString()); } } catch (NoRecordFoundException norec){ // Start BCA Count try { System.out.println("Into NoRecords Found "); ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_COUNT_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_COUNT_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Bca No is "+ new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); //System.out.println("After executet the service"); BigDecimal count = (BigDecimal)bcaRefNoMap.get("bcaCount"); if(count.intValue() == 0) { manageActionInfo (ActionConstants.NO_RECORD_FOUND, request); } else { manageActionInfo (ActionConstants.RECORD_TOBE_PUBLISHED, request); } logger.error (norec.toString()); forwardAction = ActionConstants.ERROR_RETURN; //End BCA Count } catch(Exception e ) { e.printStackTrace(); handleMessage (e, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (e.toString()); } } catch (SCBBaseException scbBase) { handleMessage (scbBase, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (scbBase.toString()); } catch (Exception e) { handleMessage (e, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (e.toString()); } return mapping.findForward (forwardAction); } /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadForm(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); /** Start CM-PH II **/ formObject.setBcaModule(true); /** End CM-PH II **/ formObject.setMainBorrowerList((ArrayList) comboMap.get("bcaMainBorrowList")); formObject.setCoBorrowerList((ArrayList) comboMap.get("bcaCoBorrowList")); formObject.setPledgorList((ArrayList) comboMap.get("bcaPledgorList")); formObject.setSecurityList((ArrayList) comboMap.get("bcaSecurityList")); formObject.setGroupList((ArrayList) comboMap.get("bcaGroupList")); if(formObject.getMainBorrowerList().size() > 0 ) { formObject.setLeIsEnabled(true); } if(formObject.getCoBorrowerList().size() > 0 ) { formObject.setCoBorrowIsEnabled(true); } if(formObject.getPledgorList().size() > 0 ) { formObject.setPledgorIsEnabled(true); } //System.out.println(" FormObjkect Securitty : "+formObject.getSecurityList().size()); if(formObject.getSecurityList().size() > 0 ) { formObject.setSecurityIsEnabled(true); } if(formObject.getGroupList().size() > 0 ) { formObject.setGroupIsEnabled(true); } } /** Start CM-PH II **/ /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadFormForCRGList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setCrgModule(true); formObject.setCrgList((ArrayList) comboMap.get("bcaCRGList")); formObject.setCrgListGroup((ArrayList) comboMap.get("bcaCRGListGroup")); formObject.setCrgListPledgor((ArrayList) comboMap.get("bcaCRGListPledgor")); if(formObject.getCrgList().size() > 0 ) { formObject.setCrgIsEnabled(true); } if(formObject.getCrgListGroup().size() > 0 ) { formObject.setCrgGroupIsEnabled(true); } if(formObject.getCrgListPledgor().size() > 0 ) { formObject.setCrgPledgorIsEnabled(true); } } /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadFormForRDEList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setRdeModule(true); formObject.setRdeList((ArrayList) comboMap.get("bcaRDEList")); if(formObject.getRdeList().size() > 0 ) { formObject.setRdeIsEnabled(true); } } /** End CM-PH II **/ /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ //Start of CM-SCI-GRDE private void loadFormForGRDEList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setGrdeModule(true); formObject.setGrdeList((ArrayList) comboMap.get("bcaGRDEList")); if(formObject.getGrdeList().size() > 0 ) { formObject.setGrdeIsEnabled(true); } } //End of CM-SCI-GRDE /** * Method which is used to assign the navigation path of this * functionality. * * @param request HttpServletRequest * @param actionParam action string passed by the application */ private void assignNavigationPath(HttpServletRequest request, BCADetailsSearchForm formObject, String actionParam) { /* Get the session navigationPath if applicable and append to it */ /* If applicable for different navigationPath check for the actionParam & accordingly append */ String contextPath = request.getContextPath (); /* String navigationPath = (String) request.getSession ().getAttribute (ActionConstants.NAVIGATION_PATH); if (navigationPath == null) { navigationPath = ""; } */ String navigationPath = ""; navigationPath = navigationPath + "<a href='" + contextPath + "/BCADetailsSearch.do?Action=bcaDetailsSearch'>" + ActionConstants.BCA_DETAILS_SEARCH_NP + "</a>"; request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, navigationPath); } /** * Method which sets the FAP for Search screen * * @param formObject form obejct * @param userProfile userProfile * @param screenId screenId * @throws SCBBaseException throws SCBBaseException. * @throws Exception throws Exception. */ private void setSearchFAP (BCADetailsSearchForm formObject, UserProfile userProfile) throws SCBBaseException, Exception { Map authMap; authMap = authUtil.getFunctionalAccess (userProfile, FunctionIDConstants.BCA_DETAILS_SEARCH); if (authMap != null && authMap.get (ActionConstants.ACCESS_VIEW) != null) { formObject.setSearchIsEnabled (true); formObject.setBcaRefNoIsEnabled(true); } } /** * Method which gives the logger object which is associated with this * class * * @return Logger */ private Logger getLogger() { return Logger.getLogger(this.getClass()); } }
UTF-8
Java
47,718
BCADetailsSearchAction.java.svn-base
Java
[]
null
[]
package com.stanchart.sci.view.action; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.stanchart.common.exception.SCBBaseException; import com.stanchart.common.serviceexecutor.ServiceExecutor; import com.stanchart.common.serviceexecutor.ServiceExecutorException; import com.stanchart.common.serviceexecutor.ServiceExecutorProvider; import com.stanchart.common.servicelocator.ServiceLocator; import com.stanchart.common.validator.IValidator; import com.stanchart.sci.appservice.constants.FunctionIDConstants; import com.stanchart.sci.appservice.constants.ServiceConstants; import com.stanchart.sci.appservice.exceptions.ApprovedSecuritySearchException; import com.stanchart.sci.model.BCADetails; import com.stanchart.sci.model.SubProfile; import com.stanchart.sci.model.UserProfile; import com.stanchart.sci.view.action.constants.ActionConstants; import com.stanchart.sci.view.action.exceptions.AuthorisationException; import com.stanchart.sci.view.action.exceptions.InvalidSessionException; import com.stanchart.sci.view.action.exceptions.NoRecordFoundException; import com.stanchart.sci.view.form.ApprovedLimitsForm; import com.stanchart.sci.view.form.ApprovedSecuritySearchForm; import com.stanchart.sci.view.form.BCADetailsSearchForm; import com.stanchart.sci.view.form.SubProfileForm; import com.stanchart.sci.view.utils.AuthUtil; import com.stanchart.sci.view.utils.ValidatorUtil; import com.stanchart.sci.view.valueobject.BCADetailsValueObject; public class BCADetailsSearchAction extends GenericAction { /** variable for logger */ private Logger logger = getLogger(); /** variable for AuthUtil */ private AuthUtil authUtil = new AuthUtil(); /** * Method which is getting called from ActionServlet, and which contains * the logic for all actions from source JSP. This method has the * responsibility to call the specific service class method to do the * database operation and convert that data to presentation layer format. * * @param mapping ActionMapping object which contains the * struts-config.xml mappings * @param form ActionForm object which has to type casted to specific form * object * @param request Represent the HttpServletRequest * @param response Represent the HttpServletResponse * * @return ActionForward object which says to which JSP the control has to * be transfered * * @throws IOException throws IOException * @throws ServletException throws ServletException if it calls any * Servlet */ public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String forwardAction = null; String actionParam = null; BCADetailsSearchForm formObject = (BCADetailsSearchForm) form; //For BCA Count UserProfile userProfile = (UserProfile)request.getSession ().getAttribute (ActionConstants.USER_PROFILE); try { actionParam = request.getParameter (ActionConstants.REQUEST_IDENTIFIER); super.performSuper(mapping, form, request, response, actionParam); /*UserProfile userProfile = (UserProfile)request.getSession ().getAttribute (ActionConstants.USER_PROFILE);*/ if (actionParam.equals (ActionConstants.ACTION_BCA_DETAILS_SEARCH)) { setSearchFAP(formObject,userProfile); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, null); forwardAction = ActionConstants.SUCCESS_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_BCA_DETAILS_SEARCH_LIST)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_DETAILS_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_DETAILS_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); BCADetails bcaDetailsObj = (BCADetails) bcaRefNoMap.get("bcaDetailsObj"); BigDecimal count= bcaDetailsObj.getCount(); //System.out.println("bcaDetailsObj.getBcaRefNo() = " + bcaDetailsObj.getBcaRefNo() ); //System.out.println("bcaDetailsObj.getModuleType() = " + bcaDetailsObj.getModuleType() ); if(bcaDetailsObj.getBcaRefNo() != null) { if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS") /*Changed for STP-2*/ && (count.intValue()!=0) ) { /** Start CM-PH II **/ if(bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.BCA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LCA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LA_MODULE_TYPE) || bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.FIBCA_MODULE_TYPE)|| bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.IGBCA_MODULE_TYPE)) { ServiceExecutorProvider serviceExecutorProvider2 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor2 = serviceExecutorProvider2.getServiceExecutor (ActionConstants.BCA_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor2.registerServiceDefinition (ActionConstants.BCA_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor2.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor2.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor2.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRelatedMap = (Map) serviceExecutor2.executeServiceDefinition (); /**Begin of Adding of Instruction Ref No and BCA Origin Location**/ formObject.setInstructionRefNo(bcaDetailsObj.getInstructionRefNo().toString()); formObject.setBcaOrgLocation(bcaDetailsObj.getBcaOrgLocation()); /**End of Adding of Instruction Ref No and BCA Origin Location**/ loadForm(formObject, bcaRelatedMap); } else if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.CRG_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider3 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor3 = serviceExecutorProvider3.getServiceExecutor (ActionConstants.CRG_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor3.registerServiceDefinition (ActionConstants.CRG_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor3.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor3.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor3.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map crgRelatedMap = (Map) serviceExecutor3.executeServiceDefinition (); loadFormForCRGList(formObject, crgRelatedMap); } else if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.RDE_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider4 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor4 = serviceExecutorProvider4.getServiceExecutor (ActionConstants.RDE_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor4.registerServiceDefinition (ActionConstants.RDE_DETAILS_SEARCH_LIST_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor4.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor4.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor4.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map rdeRelatedMap = (Map) serviceExecutor4.executeServiceDefinition (); loadFormForRDEList(formObject, rdeRelatedMap); } } //Start STP-2 if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS") && (count.intValue()==0) ) { //System.out.println("INTO COUNT 0"); ServiceExecutorProvider serviceExecutorProvider6 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor6 = serviceExecutorProvider6.getServiceExecutor (ActionConstants.BCA_SUCCESS_MSG_SERV_DEF); serviceExecutor6.registerServiceDefinition (ActionConstants.BCA_SUCCESS_MSG_SERV_DEF); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor6.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor6.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor6.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Bca No is "+ new BigDecimal(formObject.getBcaRefNo())); serviceExecutor6.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor6.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor6.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map successMap = (Map) serviceExecutor6.executeServiceDefinition (); if(successMap.get("bcaComment") != null && successMap.get("bcaComment").toString().length() != 0) { manageActionInfo (ActionConstants.BCA_SUCCESS_MSG, request, successMap.get("bcaComment").toString()); } else { manageActionInfo (ActionConstants.BCA_SUCCESS_MSG1, request,formObject.getBcaRefNo().toString()); } //manageActionInfo (ActionConstants.BCA_SUCCESS_MSG, request, successMap.get("bcaComment").toString()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); } //End STP-2 else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("FAILURE")) { formObject.setBcaFailed(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); } /** Start CM-PH II **/ else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("REJECTED")) { formObject.setBcaRejected(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setRepublishIsEnabled(true); //ADDED ON 03-06-2010 - START manageActionInfo (ActionConstants.BCA_REJECTED, request); //ADDED ON 03-06-2010 - END } /** End CM-PH II **/ else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PUBLISHED")) { formObject.setBcaNotProcessed(true); } /** Start CM-PH II B for LCA Pending Publish **/ else if (bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PENPUB") && bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.LCA_MODULE_TYPE)){ formObject.setLcaPendingPub(true); formObject.setBcaRefNo(bcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setLcaPendingPubIsEnabled(true); } /** End for LCA Pending Publish **/ // For a BCA which is not new else if (bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PENPUB") && ( bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.BCA_MODULE_TYPE) ||bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.FIBCA_MODULE_TYPE) ||bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.IGBCA_MODULE_TYPE)) ){ ServiceExecutorProvider serviceExecutorProvider5 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor5 = serviceExecutorProvider5.getServiceExecutor (ActionConstants.RENEWAL_BCA_IND_DEF); serviceExecutor5.registerServiceDefinition (ActionConstants.RENEWAL_BCA_IND_DEF); serviceExecutor5.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor5.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor5.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map renewalBCARelatedMap = (Map) serviceExecutor5.executeServiceDefinition (); BCADetails renwalBcaDetailsObj = (BCADetails) renewalBCARelatedMap.get("renwalBcaDetailsObj"); /*System.out.println("renwalBcaDetailsObj"); System.out.println(" renwalBcaDetailsObj.getBcaRefNo().toString() = " + renwalBcaDetailsObj.getBcaRefNo().toString()); System.out.println(" renwalBcaDetailsObj.getIndLimitMap() = " + renwalBcaDetailsObj.getIndLimitMap()); System.out.println(" renwalBcaDetailsObj.getIndSecurityMap() = " + renwalBcaDetailsObj.getIndSecurityMap()); System.out.println(" renwalBcaDetailsObj.getIndPendingPub() = " + renwalBcaDetailsObj.getIndPendingPub()); */ formObject.setRenewBCAPendingPub(true); formObject.setBcaRefNo(renwalBcaDetailsObj.getBcaRefNo().toString()); formObject.setBcaStatus(renwalBcaDetailsObj.getBcaStatus()); formObject.setBcaComments(renwalBcaDetailsObj.getBcaComments()); //System.out.println("renwalBcaDetailsObj.getPendingPubSysGenId().toString() = " + renwalBcaDetailsObj.getPendingPubSysGenId().toString()); formObject.setPendingPubSysGenId(renwalBcaDetailsObj.getPendingPubSysGenId().toString()); // Enable renewBCALimitMapIsEnabled by defalut i.e // Limit Ind is N and Sec Ind is N if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("N") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("N")){ formObject.setRenewBCALimitMapIsEnabled(true); } // If limit Ind is Y then enable renewBCASecurityMapIsEnabled if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("N")){ formObject.setRenewBCASecurityMapIsEnabled(true); } if(renwalBcaDetailsObj.getIndCollateralAvlbl().equalsIgnoreCase("Y")){ formObject.setRenewBCAPledgorMapIsEnabled(true); }else{ formObject.setRenewBCAPledgorMapIsEnabled(false); } // If both limit Ind and Sec Ind is Y then enable Publish button if (renwalBcaDetailsObj.getIndLimitMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndSecurityMap().equalsIgnoreCase("Y") && renwalBcaDetailsObj.getIndPledgorMap().equalsIgnoreCase("Y")){ formObject.setRenewBCAPendingPubIsEnabled(true); } } /** End CM-PH II B **/ } else{ formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); throw new NoRecordFoundException(); } assignNavigationPath (request, formObject, actionParam); if(count != null && count.intValue()!=0 ) { forwardAction = ActionConstants.SUCCESS_RETURN; } if(count != null && count.intValue()==0 ) { forwardAction = ActionConstants.SUCCESS_MSG; } } /** Start CM-PH II **/ else if(actionParam.equals (ActionConstants.ACTION_BCA_REPUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //Start CM PH 2 //Changing BCA ref no from Integer to BigDecimal serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); // serviceExecutor.addInput (ActionConstants.BCA_STATUS, ActionConstants.BCA_STATUS_PUBLISH); //Map bcaRefNoMap = //(Map) serviceExecutor.executeServiceDefinition (); //assignNavigationPath (request, formObject, actionParam); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_REPUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.REPUBLISH_RETURN; } /** End CM-PH II **/ /** Start CM-PH II B for LCA Pending Publsih**/ else if(actionParam.equals (ActionConstants.ACTION_LCA_PENDING_PUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.LCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.LCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_LCA_PUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.LCA_PUBLISH_RETURN; } /** End CM-PH II B - LCA **/ //For Renew BCA Publish else if(actionParam.equals (ActionConstants.ACTION_RENEW_BCA_PENDING_PUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.RENEW_BCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.RENEW_BCA_DETAILS_PENDING_PUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); //System.out.println( "formObject.getPendingPubSysGenId() = " + formObject.getPendingPubSysGenId()); serviceExecutor.addInput (ActionConstants.PENDING_PUB_SYS_GEN_ID, new BigDecimal(formObject.getPendingPubSysGenId())); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_RENEW_BCA_PUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.RENEW_BCA_PUBLISH_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_BCA_RESET)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_RESET_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_RESET_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); //System.out.println( "formObject.getPendingPubSysGenId() = " + formObject.getPendingPubSysGenId()); serviceExecutor.addInput (ActionConstants.PENDING_PUB_SYS_GEN_ID, new BigDecimal(formObject.getPendingPubSysGenId())); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.executeServiceDefinition (); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_RESET_BCA_MAP, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.RENEW_BCA_PUBLISH_RETURN; } // Start of CM-SCI GRDE else if(actionParam.equals (ActionConstants.ACTION_GRDE_SEARCH_LIST)) { //System.out.println(" into the Action of GRDE "); String grdeRefNo = formObject.getBcaRefNo(); ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.GRDE_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.GRDE_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Grder number is "+grdeRefNo); serviceExecutor.addInput (ActionConstants.GRDE_REF_NO, grdeRefNo); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); BCADetails bcaDetailsObj = (BCADetails) bcaRefNoMap.get("bcaDetailsObj"); //System.out.println("bcaDetailsObj.getBcaRefNo() = " + bcaDetailsObj.getGrdeRefNo() ); //System.out.println("bcaDetailsObj.getModuleType() = " + bcaDetailsObj.getModuleType() ); //System.out.println("bcaDetailsObj.getBCAStatus() = " + bcaDetailsObj.getBcaStatus() ); if(bcaDetailsObj.getGrdeRefNo() != null) { if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("SUCCESS")) { //System.out.println("Into GRDE success"); //System.out.println("module type is "+bcaDetailsObj.getModuleType()); //if (bcaDetailsObj.getModuleType().equalsIgnoreCase(ServiceConstants.GRDE_MODULE_TYPE)){ ServiceExecutorProvider serviceExecutorProvider4 = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor4 = serviceExecutorProvider4.getServiceExecutor (ActionConstants.GRDE_DETAILS_SEARCH_LIST_SERV_DEF); serviceExecutor4.registerServiceDefinition (ActionConstants.GRDE_DETAILS_SEARCH_LIST_SERV_DEF); //System.out.println("Grder number is "+grdeRefNo); serviceExecutor4.addInput (ActionConstants.GRDE_REF_NO, grdeRefNo); serviceExecutor4.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor4.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map grdeRelatedMap = (Map) serviceExecutor4.executeServiceDefinition (); loadFormForGRDEList(formObject, grdeRelatedMap); //} } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("FAILURE")) { formObject.setBcaFailed(true); formObject.setBcaRefNo(bcaDetailsObj.getGrdeRefNo().toString()); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("REJECTED")) { formObject.setGrdeRejected(true); formObject.setBcaRefNo((bcaDetailsObj.getGrdeRefNo().toString())); formObject.setBcaStatus(bcaDetailsObj.getBcaStatus()); formObject.setBcaComments(bcaDetailsObj.getBcaComments()); formObject.setRepublishIsEnabled(true); //ADDED ON 03-06-2010 - START manageActionInfo (ActionConstants.BCA_REJECTED, request); //ADDED ON 03-06-2010 - END } else if(bcaDetailsObj.getBcaStatus().equalsIgnoreCase("PUBLISHED")) { formObject.setBcaNotProcessed(true); } } else{ formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); throw new NoRecordFoundException(); } assignNavigationPath (request, formObject, actionParam); forwardAction = ActionConstants.SUCCESS_RETURN; } else if(actionParam.equals (ActionConstants.ACTION_GRDE_REPUBLISH)) { ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.GRDE_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.GRDE_DETAILS_REPUBLISH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, formObject.getBcaRefNo()); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); // serviceExecutor.addInput (ActionConstants.BCA_STATUS, ActionConstants.BCA_STATUS_PUBLISH); //Map bcaRefNoMap = //(Map) serviceExecutor.executeServiceDefinition (); //assignNavigationPath (request, formObject, actionParam); request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, ""); manageActionInfo (ActionConstants.SUCCESS_REPUBLISH, request, formObject.getBcaRefNo()); formObject.setBcaRefNoIsEnabled(true); formObject.setSearchIsEnabled(true); formObject.setBcaRefNo(""); forwardAction = ActionConstants.REPUBLISH_RETURN; } // End of CM-SCI GRDE } catch (InvalidSessionException sessEx) { manageActionErrors (ActionConstants.INVALID_SESSION, request); forwardAction = ActionConstants.INVALID_SESSION; logger.error (sessEx.toString()); } catch (ServiceExecutorException seEx) { Throwable exObj = seEx.getCause(); if (exObj != null) { if (exObj instanceof AuthorisationException) { handleMessage (exObj, request); forwardAction = ActionConstants.AUTH_ERROR; logger.error (exObj.toString()); } else if (exObj instanceof ApprovedSecuritySearchException) { handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (exObj.toString()); } else if (exObj instanceof SCBBaseException) { exObj.printStackTrace(); handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (exObj.toString()); } else { handleMessage (exObj, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error ("Unhandled exception : " + exObj.toString()); } } else { handleMessage (seEx, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error ("ServiceExecutor exception : " + seEx.toString()); } } catch (NoRecordFoundException norec){ // Start BCA Count try { System.out.println("Into NoRecords Found "); ServiceExecutorProvider serviceExecutorProvider = (ServiceExecutorProvider) ServiceLocator.getInstance (ActionConstants.SERV_EXEC_PROVIDER, null); ServiceExecutor serviceExecutor = serviceExecutorProvider.getServiceExecutor (ActionConstants.BCA_COUNT_SEARCH_SERV_DEF); serviceExecutor.registerServiceDefinition (ActionConstants.BCA_COUNT_SEARCH_SERV_DEF); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE, userProfile); serviceExecutor.addInput (ActionConstants.BCA_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); serviceExecutor.addInput (ActionConstants.BCA_ACCESS_VIEW, ActionConstants.ACCESS_VIEW); //System.out.println("Bca No is "+ new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_REF_NO, new BigDecimal(formObject.getBcaRefNo())); serviceExecutor.addInput (ActionConstants.BCA_USERPROFILE_PROCESS, userProfile); serviceExecutor.addInput (ActionConstants.BCA_NEXT_FUNCTION_ID, FunctionIDConstants.BCA_DETAILS_SEARCH); Map bcaRefNoMap = (Map) serviceExecutor.executeServiceDefinition (); //System.out.println("After executet the service"); BigDecimal count = (BigDecimal)bcaRefNoMap.get("bcaCount"); if(count.intValue() == 0) { manageActionInfo (ActionConstants.NO_RECORD_FOUND, request); } else { manageActionInfo (ActionConstants.RECORD_TOBE_PUBLISHED, request); } logger.error (norec.toString()); forwardAction = ActionConstants.ERROR_RETURN; //End BCA Count } catch(Exception e ) { e.printStackTrace(); handleMessage (e, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (e.toString()); } } catch (SCBBaseException scbBase) { handleMessage (scbBase, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (scbBase.toString()); } catch (Exception e) { handleMessage (e, request); forwardAction = ActionConstants.ERROR_RETURN; logger.error (e.toString()); } return mapping.findForward (forwardAction); } /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadForm(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); /** Start CM-PH II **/ formObject.setBcaModule(true); /** End CM-PH II **/ formObject.setMainBorrowerList((ArrayList) comboMap.get("bcaMainBorrowList")); formObject.setCoBorrowerList((ArrayList) comboMap.get("bcaCoBorrowList")); formObject.setPledgorList((ArrayList) comboMap.get("bcaPledgorList")); formObject.setSecurityList((ArrayList) comboMap.get("bcaSecurityList")); formObject.setGroupList((ArrayList) comboMap.get("bcaGroupList")); if(formObject.getMainBorrowerList().size() > 0 ) { formObject.setLeIsEnabled(true); } if(formObject.getCoBorrowerList().size() > 0 ) { formObject.setCoBorrowIsEnabled(true); } if(formObject.getPledgorList().size() > 0 ) { formObject.setPledgorIsEnabled(true); } //System.out.println(" FormObjkect Securitty : "+formObject.getSecurityList().size()); if(formObject.getSecurityList().size() > 0 ) { formObject.setSecurityIsEnabled(true); } if(formObject.getGroupList().size() > 0 ) { formObject.setGroupIsEnabled(true); } } /** Start CM-PH II **/ /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadFormForCRGList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setCrgModule(true); formObject.setCrgList((ArrayList) comboMap.get("bcaCRGList")); formObject.setCrgListGroup((ArrayList) comboMap.get("bcaCRGListGroup")); formObject.setCrgListPledgor((ArrayList) comboMap.get("bcaCRGListPledgor")); if(formObject.getCrgList().size() > 0 ) { formObject.setCrgIsEnabled(true); } if(formObject.getCrgListGroup().size() > 0 ) { formObject.setCrgGroupIsEnabled(true); } if(formObject.getCrgListPledgor().size() > 0 ) { formObject.setCrgPledgorIsEnabled(true); } } /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ private void loadFormForRDEList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setRdeModule(true); formObject.setRdeList((ArrayList) comboMap.get("bcaRDEList")); if(formObject.getRdeList().size() > 0 ) { formObject.setRdeIsEnabled(true); } } /** End CM-PH II **/ /** * Method to load the combo values to form object based on action parameter * * @param formObject Represents the form object * @param comboMap Represents the Map object from service which contains * the combo values * * @throws RuntimeException throws RuntimeException if any unchecked error * occurs * @throws SCBBaseException throws SCBBaseException if any combo values are * not populated */ //Start of CM-SCI-GRDE private void loadFormForGRDEList(BCADetailsSearchForm formObject, Map comboMap) throws RuntimeException, SCBBaseException { formObject.setBcaProcessed(true); formObject.setGrdeModule(true); formObject.setGrdeList((ArrayList) comboMap.get("bcaGRDEList")); if(formObject.getGrdeList().size() > 0 ) { formObject.setGrdeIsEnabled(true); } } //End of CM-SCI-GRDE /** * Method which is used to assign the navigation path of this * functionality. * * @param request HttpServletRequest * @param actionParam action string passed by the application */ private void assignNavigationPath(HttpServletRequest request, BCADetailsSearchForm formObject, String actionParam) { /* Get the session navigationPath if applicable and append to it */ /* If applicable for different navigationPath check for the actionParam & accordingly append */ String contextPath = request.getContextPath (); /* String navigationPath = (String) request.getSession ().getAttribute (ActionConstants.NAVIGATION_PATH); if (navigationPath == null) { navigationPath = ""; } */ String navigationPath = ""; navigationPath = navigationPath + "<a href='" + contextPath + "/BCADetailsSearch.do?Action=bcaDetailsSearch'>" + ActionConstants.BCA_DETAILS_SEARCH_NP + "</a>"; request.getSession ().setAttribute (ActionConstants.NAVIGATION_PATH, navigationPath); } /** * Method which sets the FAP for Search screen * * @param formObject form obejct * @param userProfile userProfile * @param screenId screenId * @throws SCBBaseException throws SCBBaseException. * @throws Exception throws Exception. */ private void setSearchFAP (BCADetailsSearchForm formObject, UserProfile userProfile) throws SCBBaseException, Exception { Map authMap; authMap = authUtil.getFunctionalAccess (userProfile, FunctionIDConstants.BCA_DETAILS_SEARCH); if (authMap != null && authMap.get (ActionConstants.ACCESS_VIEW) != null) { formObject.setSearchIsEnabled (true); formObject.setBcaRefNoIsEnabled(true); } } /** * Method which gives the logger object which is associated with this * class * * @return Logger */ private Logger getLogger() { return Logger.getLogger(this.getClass()); } }
47,718
0.616371
0.614045
987
47.346504
35.530022
157
false
false
0
0
0
0
0
0
1.954407
false
false
9
9871c9edcda724f436b0cb75b0d296502b6324e8
1,941,325,277,288
39b4a0c80e1897cccd4e43e8c3959505dbf7faed
/DeepThoughtLib/src/main/java/net/deepthought/IDependencyResolver.java
3a4dfa862f3f54d3b8f5c96569512e83bf00042a
[ "Apache-2.0" ]
permissive
divid3byzero/DeepThought
https://github.com/divid3byzero/DeepThought
10cf84342a6505e502c7ad62df06e5bf641ddf30
71a256e2c8df44992698bf49f2009e53c44da9dc
refs/heads/master
2020-12-25T04:45:01.023000
2016-06-05T10:34:19
2016-06-05T10:34:19
60,457,533
0
0
null
true
2016-06-05T11:52:43
2016-06-05T11:52:42
2015-04-23T21:49:54
2016-06-04T21:19:15
7,902
0
0
0
null
null
null
package net.deepthought; import net.deepthought.communication.IDeepThoughtsConnector; import net.deepthought.data.IDataManager; import net.deepthought.data.backup.IBackupManager; import net.deepthought.data.compare.IDataComparer; import net.deepthought.data.contentextractor.IContentExtractorManager; import net.deepthought.data.download.IFileDownloader; import net.deepthought.data.html.IHtmlHelper; import net.deepthought.data.merger.IDataMerger; import net.deepthought.data.persistence.EntityManagerConfiguration; import net.deepthought.data.persistence.IEntityManager; import net.deepthought.data.search.ISearchEngine; import net.deepthought.language.ILanguageDetector; import net.deepthought.platform.IPlatformTools; import net.deepthought.plugin.IPluginManager; import net.deepthought.util.IThreadPool; /** * Created by ganymed on 05/01/15. */ public interface IDependencyResolver { IThreadPool createThreadPool(); IEntityManager createEntityManager(EntityManagerConfiguration configuration) throws Exception; IDataManager createDataManager(IEntityManager entityManager); IPlatformTools createPlatformTools(); IBackupManager createBackupManager(); IDataComparer createDataComparer(); IDataMerger createDataMerger(); ILanguageDetector createLanguageDetector(); ISearchEngine createSearchEngine(); IHtmlHelper createHtmlHelper(); IFileDownloader createDownloader(); IPluginManager createPluginManager(); IContentExtractorManager createContentExtractorManager(); IDeepThoughtsConnector createDeepThoughtsConnector(); }
UTF-8
Java
1,569
java
IDependencyResolver.java
Java
[ { "context": "t.deepthought.util.IThreadPool;\n\n/**\n * Created by ganymed on 05/01/15.\n */\npublic interface IDependencyReso", "end": 836, "score": 0.9996303915977478, "start": 829, "tag": "USERNAME", "value": "ganymed" } ]
null
[]
package net.deepthought; import net.deepthought.communication.IDeepThoughtsConnector; import net.deepthought.data.IDataManager; import net.deepthought.data.backup.IBackupManager; import net.deepthought.data.compare.IDataComparer; import net.deepthought.data.contentextractor.IContentExtractorManager; import net.deepthought.data.download.IFileDownloader; import net.deepthought.data.html.IHtmlHelper; import net.deepthought.data.merger.IDataMerger; import net.deepthought.data.persistence.EntityManagerConfiguration; import net.deepthought.data.persistence.IEntityManager; import net.deepthought.data.search.ISearchEngine; import net.deepthought.language.ILanguageDetector; import net.deepthought.platform.IPlatformTools; import net.deepthought.plugin.IPluginManager; import net.deepthought.util.IThreadPool; /** * Created by ganymed on 05/01/15. */ public interface IDependencyResolver { IThreadPool createThreadPool(); IEntityManager createEntityManager(EntityManagerConfiguration configuration) throws Exception; IDataManager createDataManager(IEntityManager entityManager); IPlatformTools createPlatformTools(); IBackupManager createBackupManager(); IDataComparer createDataComparer(); IDataMerger createDataMerger(); ILanguageDetector createLanguageDetector(); ISearchEngine createSearchEngine(); IHtmlHelper createHtmlHelper(); IFileDownloader createDownloader(); IPluginManager createPluginManager(); IContentExtractorManager createContentExtractorManager(); IDeepThoughtsConnector createDeepThoughtsConnector(); }
1,569
0.841938
0.838113
52
29.173077
25.216539
96
false
false
0
0
0
0
0
0
0.576923
false
false
9
ea52560fe6ad21629d2978984f5f7fd168abd4bc
31,765,578,186,946
53424abc393f6140a44d2e407ddc65ef711f9bf9
/Week07/IntegerDemo/bin/cn/itcast_01/IntegerDemo.java
94e5e8b34648ba20e1315000a2e539a8197a2c99
[]
no_license
yuanyongbin/JavaDemo
https://github.com/yuanyongbin/JavaDemo
7ade82dfe160c1c78b19f24ebab3e72ea95f5a58
2ef212d8e047932d1dd895b8c801088fb1904dbf
refs/heads/master
2020-05-24T07:35:45.008000
2017-09-11T01:37:54
2017-09-11T01:37:54
84,835,382
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://kpdus.tripod.com/jad.html // Decompiler options: packimports(3) fieldsfirst ansi space // Source File Name: IntegerDemo.java package cn.itcast_01; import java.io.PrintStream; public class IntegerDemo { public IntegerDemo() { } public static void main(String args[]) { Integer ii = Integer.valueOf(100); ii = Integer.valueOf(ii.intValue() + 200); System.out.println((new StringBuilder("ii :")).append(ii).toString()); } }
UTF-8
Java
530
java
IntegerDemo.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://kpdus.tripod.com/jad.ht", "end": 62, "score": 0.9997086524963379, "start": 46, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e2. Copyright 2001 <NAME>. // Jad home page: http://kpdus.tripod.com/jad.html // Decompiler options: packimports(3) fieldsfirst ansi space // Source File Name: IntegerDemo.java package cn.itcast_01; import java.io.PrintStream; public class IntegerDemo { public IntegerDemo() { } public static void main(String args[]) { Integer ii = Integer.valueOf(100); ii = Integer.valueOf(ii.intValue() + 200); System.out.println((new StringBuilder("ii :")).append(ii).toString()); } }
520
0.711321
0.679245
23
22.043478
23.477053
72
false
false
0
0
0
0
0
0
0.73913
false
false
9
fe59649e37e36ec15e0ce5e1be3b88da1a922ee6
31,765,578,187,327
66d3122f8f031d6e8b27e8ead7aa5ae0d7e33b45
/net/minecraft/world/gen/chunk/ChunkGeneratorFactory.java
6c5ccd6e6e7f962a87bf2863a57f0834995d111b
[]
no_license
gurachan/minecraft1.14-dp
https://github.com/gurachan/minecraft1.14-dp
c10059787555028f87a4c8183ff74e6e1cfbf056
34daddc03be27d5a0ee2ab9bc8b1deb050277208
refs/heads/master
2022-01-07T01:43:52.836000
2019-05-08T17:18:13
2019-05-08T17:18:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minecraft.world.gen.chunk; import net.minecraft.world.biome.source.BiomeSource; import net.minecraft.world.World; interface ChunkGeneratorFactory<C extends ChunkGeneratorConfig, T extends ChunkGenerator<C>> { T create(final World arg1, final BiomeSource arg2, final C arg3); }
UTF-8
Java
295
java
ChunkGeneratorFactory.java
Java
[]
null
[]
package net.minecraft.world.gen.chunk; import net.minecraft.world.biome.source.BiomeSource; import net.minecraft.world.World; interface ChunkGeneratorFactory<C extends ChunkGeneratorConfig, T extends ChunkGenerator<C>> { T create(final World arg1, final BiomeSource arg2, final C arg3); }
295
0.80339
0.79322
9
31.777779
32.275818
92
false
false
0
0
0
0
0
0
0.777778
false
false
9
5196ca187a4c80cc886d5ed5ad4cf1a9de5a2526
16,750,372,512,704
1f2cfa50629e53890ca7a8ebbfef2265a66533c3
/src/main/java/com/dmore/memorize/model/UserWord.java
fd353331da9ff799ba7bd9579512f3811b08500e
[]
no_license
dmorozzov/memorize-back
https://github.com/dmorozzov/memorize-back
a069ac50e12fe239e5974c80d977a7028f85b180
d2854c83633c443f373d4b9944ab3fe25bd1a832
refs/heads/master
2021-04-15T09:34:42.378000
2018-09-23T10:14:12
2018-09-23T10:14:12
126,705,582
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dmore.memorize.model; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import javax.persistence.AssociationOverride; import javax.persistence.AssociationOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Table; import javax.persistence.Transient; import java.time.LocalDateTime; @Entity @EqualsAndHashCode @Getter @Setter @Table(name = "user_words") @AssociationOverrides({ @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "user_id")), @AssociationOverride(name = "pk.word", joinColumns = @JoinColumn(name = "word_id")) }) public class UserWord implements java.io.Serializable { public UserWord() { createdAt = LocalDateTime.now(); } @EmbeddedId private UserWordId pk = new UserWordId(); @Column(name = "created_at") private LocalDateTime createdAt; public UserWordId getPk() { return pk; } public void setPk(UserWordId pk) { this.pk = pk; } @Transient public User getUser() { return getPk().getUser(); } public void setUser(User user) { getPk().setUser(user); } @Transient public Word getWord() { return getPk().getWord(); } public void setWord(Word word) { getPk().setWord(word); } }
UTF-8
Java
1,469
java
UserWord.java
Java
[]
null
[]
package com.dmore.memorize.model; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import javax.persistence.AssociationOverride; import javax.persistence.AssociationOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Table; import javax.persistence.Transient; import java.time.LocalDateTime; @Entity @EqualsAndHashCode @Getter @Setter @Table(name = "user_words") @AssociationOverrides({ @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "user_id")), @AssociationOverride(name = "pk.word", joinColumns = @JoinColumn(name = "word_id")) }) public class UserWord implements java.io.Serializable { public UserWord() { createdAt = LocalDateTime.now(); } @EmbeddedId private UserWordId pk = new UserWordId(); @Column(name = "created_at") private LocalDateTime createdAt; public UserWordId getPk() { return pk; } public void setPk(UserWordId pk) { this.pk = pk; } @Transient public User getUser() { return getPk().getUser(); } public void setUser(User user) { getPk().setUser(user); } @Transient public Word getWord() { return getPk().getWord(); } public void setWord(Word word) { getPk().setWord(word); } }
1,469
0.669843
0.669843
64
21.96875
17.30965
63
false
false
0
0
0
0
0
0
0.390625
false
false
9
e5c35ae86f91566a67e76013fedb48e73c5e743a
1,219,770,777,279
d128a16ab9025552449462747810fcc82db3a925
/src/main/java/ru/study/shop/adapters/hibernate/CustomerRepository.java
b2ddcec78dde2bbb5cf9adf001c3a75802160a56
[]
no_license
Joker-developer-java/Shop-app-backend
https://github.com/Joker-developer-java/Shop-app-backend
d40acd8d0bfcf6020c4266629601629ddffeff69
6cb48ccf5cc6574476d8f00e9a97c47dfafdba25
refs/heads/master
2023-07-13T23:12:29.493000
2021-06-29T13:59:16
2021-06-29T13:59:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.study.shop.adapters.hibernate; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import ru.study.shop.entities.Customer; public interface CustomerRepository extends JpaRepository<Customer, Long> { @Query(value = "SELECT * " + "FROM survey AS s " + "WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date;", nativeQuery = true) boolean getActiveSurveys(); }
UTF-8
Java
474
java
CustomerRepository.java
Java
[]
null
[]
package ru.study.shop.adapters.hibernate; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import ru.study.shop.entities.Customer; public interface CustomerRepository extends JpaRepository<Customer, Long> { @Query(value = "SELECT * " + "FROM survey AS s " + "WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date;", nativeQuery = true) boolean getActiveSurveys(); }
474
0.736287
0.736287
14
32.857143
28.147207
91
false
false
0
0
0
0
0
0
0.571429
false
false
9
b9a0f0fca82b408eef98b4fbb1fc8e0b49f9b8fa
3,856,880,678,442
3afc2efb2eb57c1840868f56d4aa2c81b454c4aa
/learn/DesignMod/SingleInstance/StaticSingleStudent.java
87ab6e796319d659a65cfbdf234c0bc7f13d7c0d
[]
no_license
sthgreat/JAVA_Learn2
https://github.com/sthgreat/JAVA_Learn2
499b2f13f7f8a83efcbfa6f30064a7ba44e0912e
3b7f5e9257024ca495bea3487953716e23fd8ac8
refs/heads/master
2021-07-10T06:59:26.287000
2020-10-24T07:15:09
2020-10-24T07:15:09
199,764,102
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DesignMod.SingleInstance; public class StaticSingleStudent { private StaticSingleStudent(){ } public static StaticSingleStudent getInstance(){ return Instance.student; } private static class Instance{ private static final StaticSingleStudent student = new StaticSingleStudent(); } }
UTF-8
Java
348
java
StaticSingleStudent.java
Java
[]
null
[]
package DesignMod.SingleInstance; public class StaticSingleStudent { private StaticSingleStudent(){ } public static StaticSingleStudent getInstance(){ return Instance.student; } private static class Instance{ private static final StaticSingleStudent student = new StaticSingleStudent(); } }
348
0.692529
0.692529
14
22.857143
24.307133
85
false
false
0
0
0
0
0
0
0.214286
false
false
9
d4743206988daf2d9b1650baa9a6e3b2a6495234
9,998,683,897,140
52c0e6c56cc3025de3f17281dd0c64df2144c455
/xc-service-manage-cms/src/main/java/com/xuecheng/manage_cms/service/PageService.java
dd4cdd1edf2bf1933848f68f45032fd4c849d956
[]
no_license
Lhhdz1231/xczx
https://github.com/Lhhdz1231/xczx
d85e047dda120104e342c586abc5e1e02039c28c
57343c9c4d086929febf8f6a70332abcdc77fcc0
refs/heads/master
2020-04-16T06:25:08.593000
2019-01-22T13:33:39
2019-01-22T13:33:39
165,345,885
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xuecheng.manage_cms.service; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSDownloadStream; import com.mongodb.client.gridfs.model.GridFSFile; import com.xuecheng.framework.domain.cms.CmsConfig; import com.xuecheng.framework.domain.cms.CmsPage; import com.xuecheng.framework.domain.cms.CmsTemplate; import com.xuecheng.framework.domain.cms.request.QueryPageRequest; import com.xuecheng.framework.domain.cms.response.CmsCode; import com.xuecheng.framework.domain.cms.response.CmsPageResult; import com.xuecheng.framework.exception.ExceptionCase; import com.xuecheng.framework.model.response.CommonCode; import com.xuecheng.framework.model.response.QueryResponseResult; import com.xuecheng.framework.model.response.QueryResult; import com.xuecheng.framework.model.response.ResponseResult; import com.xuecheng.manage_cms.dao.CmsConfigRepository; import com.xuecheng.manage_cms.dao.CmsPageRepository; import com.xuecheng.manage_cms.dao.CmsTemplateRepository; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.gridfs.GridFsResource; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.*; /** * @author Administrator * @version 1.0 * @create 2018-09-12 18:32 **/ @Service public class PageService { @Autowired CmsPageRepository cmsPageRepository; @Autowired CmsConfigRepository cmsConfigRepository; @Autowired RestTemplate restTemplate; @Autowired CmsTemplateRepository cmsTemplateRepository; @Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; /** * 页面查询方法 * @param page 页码,从1开始记数 * @param size 每页记录数 * @param queryPageRequest 查询条件 * @return */ public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest){ if (queryPageRequest == null) { return null; } CmsPage cmsPage = new CmsPage(); ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains()); if (StringUtils.isNotEmpty(queryPageRequest.getSiteId())){ cmsPage.setSiteId(queryPageRequest.getSiteId()); } if (StringUtils.isNotEmpty(queryPageRequest.getPageId())){ cmsPage.setPageId(queryPageRequest.getPageId()); } if (StringUtils.isNotEmpty(queryPageRequest.getPageAliase())){ cmsPage.setPageAliase(queryPageRequest.getPageAliase()); } if (StringUtils.isNotEmpty(queryPageRequest.getTemplateId())){ cmsPage.setTemplateId(queryPageRequest.getTemplateId()); } //分页参数 if(page <=0){ page = 1; } page = page -1; if(size<=0){ size = 10; } Example<CmsPage> example = Example.of(cmsPage, exampleMatcher); Pageable pageable = PageRequest.of(page, size); Page<CmsPage> all = cmsPageRepository.findAll(example, pageable); List<CmsPage> content = all.getContent(); long totalElements = all.getTotalElements(); QueryResult<CmsPage> queryResult = new QueryResult<>(); queryResult.setList(content);//数据列表 queryResult.setTotal(totalElements);//数据总记录数 return new QueryResponseResult(CommonCode.SUCCESS,queryResult); } /** * 获取全部的CmsPage */ public List<CmsPage> findAllPage(){ return cmsPageRepository.findAll(); } /** * 获取CmsPage的siteId */ public Set<String> siteId_list() { Set<String> set = new HashSet<>(); for (CmsPage cmsPage : findAllPage()) { String siteId = cmsPage.getSiteId(); set.add(siteId); } return set; } /** * 查询所有的模板并以set返回 */ public Set<String> template_list(){ Set<String> set = new HashSet<>(); for (CmsPage cmsPage : findAllPage()) { String templateId = cmsPage.getTemplateId(); set.add(templateId); } return set; } /** * 通过唯一索引查询cmspage */ public CmsPage findByPageNameAndSiteIdAndPageWebPath(CmsPage cmsPage){ return cmsPageRepository.findByPageNameAndSiteIdAndPageWebPath(cmsPage.getPageName(), cmsPage.getSiteId(), cmsPage.getPageWebPath()); } /** * 通过PageId查询索引 */ public CmsPage findByPageId(String pageId){ Optional<CmsPage> byId = cmsPageRepository.findById(pageId); return byId.orElse(null); } /** * 保存页面 */ public CmsPageResult add(CmsPage cmsPage) { CmsPage exactPage = this.findByPageNameAndSiteIdAndPageWebPath(cmsPage); if (exactPage != null) { ExceptionCase.cthrow(CmsCode.CMS_ADDPAGE_EXISTSNAME); } CmsPage save = cmsPageRepository.save(cmsPage); return new CmsPageResult(CommonCode.SUCCESS, save); } public CmsPageResult update(String pageId, CmsPage cmsPage) { CmsPage byPageId = this.findByPageId(pageId); if (byPageId != null) { CmsPage save = cmsPageRepository.save(cmsPage); return new CmsPageResult(CommonCode.SUCCESS, save); } return new CmsPageResult(CommonCode.FAIL, null); } /** * 删除页面 */ public ResponseResult delete(String pageId) { CmsPage byPageId = this.findByPageId(pageId); if (byPageId != null) { cmsPageRepository.deleteById(pageId); return new ResponseResult(CommonCode.SUCCESS); } return new ResponseResult(CommonCode.FAIL); } /** * 查询cms配置信息 */ public CmsConfig getCmsConfig(String id){ Optional<CmsConfig> byId = cmsConfigRepository.findById(id); return byId.orElse(null); } /** * 静态化方法 */ public String getPageHtml(String pageId){ //获取页面 CmsPage byPageId = this.findByPageId(pageId); //获取页面数据模型 Map model = this.getModelByPageId(byPageId); //获取页面模板 String templateId = byPageId.getTemplateId(); String pageTemplate = this.getPageTemplateByPageId(templateId); //生成页面 String generatedHtml = this.generateHtml(model, pageTemplate); return generatedHtml; } private String generateHtml(Map model, String pageTemplate) { Configuration configuration = new Configuration(Configuration.getVersion()); StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); stringTemplateLoader.putTemplate("template", pageTemplate); configuration.setTemplateLoader(stringTemplateLoader); Template template = null; try { template = configuration.getTemplate("template"); return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取页面的模板 */ private String getPageTemplateByPageId(String templateId){ Optional<CmsTemplate> byId = cmsTemplateRepository.findById(templateId); if (byId.isPresent()) { CmsTemplate cmsTemplate = byId.get(); String templateFileId = cmsTemplate.getTemplateFileId(); GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId))); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream); try { return IOUtils.toString(gridFsResource.getInputStream(), "utf-8"); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 获取数据model */ private Map getModelByPageId(CmsPage cmsPage) { //取出页面的DataUrl String dataUrl = cmsPage.getDataUrl(); if (StringUtils.isEmpty(dataUrl)) { ExceptionCase.cthrow(CmsCode.CMS_GENERATEHTML_DATAURLISNULL); } //通过restTemplate请求dataUrl获取数据 ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class); return forEntity.getBody(); } private CmsPage getById(String pageId) { Optional<CmsPage> byId = cmsPageRepository.findById(pageId); return byId.orElse(null); } /** * 页面发布 */ // public R }
UTF-8
Java
9,461
java
PageService.java
Java
[ { "context": "o.IOException;\nimport java.util.*;\n\n/**\n * @author Administrator\n * @version 1.0\n * @create 2018-09-12 18:32\n **/\n", "end": 1856, "score": 0.9777411222457886, "start": 1843, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.xuecheng.manage_cms.service; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSDownloadStream; import com.mongodb.client.gridfs.model.GridFSFile; import com.xuecheng.framework.domain.cms.CmsConfig; import com.xuecheng.framework.domain.cms.CmsPage; import com.xuecheng.framework.domain.cms.CmsTemplate; import com.xuecheng.framework.domain.cms.request.QueryPageRequest; import com.xuecheng.framework.domain.cms.response.CmsCode; import com.xuecheng.framework.domain.cms.response.CmsPageResult; import com.xuecheng.framework.exception.ExceptionCase; import com.xuecheng.framework.model.response.CommonCode; import com.xuecheng.framework.model.response.QueryResponseResult; import com.xuecheng.framework.model.response.QueryResult; import com.xuecheng.framework.model.response.ResponseResult; import com.xuecheng.manage_cms.dao.CmsConfigRepository; import com.xuecheng.manage_cms.dao.CmsPageRepository; import com.xuecheng.manage_cms.dao.CmsTemplateRepository; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.gridfs.GridFsResource; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.*; /** * @author Administrator * @version 1.0 * @create 2018-09-12 18:32 **/ @Service public class PageService { @Autowired CmsPageRepository cmsPageRepository; @Autowired CmsConfigRepository cmsConfigRepository; @Autowired RestTemplate restTemplate; @Autowired CmsTemplateRepository cmsTemplateRepository; @Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; /** * 页面查询方法 * @param page 页码,从1开始记数 * @param size 每页记录数 * @param queryPageRequest 查询条件 * @return */ public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest){ if (queryPageRequest == null) { return null; } CmsPage cmsPage = new CmsPage(); ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains()); if (StringUtils.isNotEmpty(queryPageRequest.getSiteId())){ cmsPage.setSiteId(queryPageRequest.getSiteId()); } if (StringUtils.isNotEmpty(queryPageRequest.getPageId())){ cmsPage.setPageId(queryPageRequest.getPageId()); } if (StringUtils.isNotEmpty(queryPageRequest.getPageAliase())){ cmsPage.setPageAliase(queryPageRequest.getPageAliase()); } if (StringUtils.isNotEmpty(queryPageRequest.getTemplateId())){ cmsPage.setTemplateId(queryPageRequest.getTemplateId()); } //分页参数 if(page <=0){ page = 1; } page = page -1; if(size<=0){ size = 10; } Example<CmsPage> example = Example.of(cmsPage, exampleMatcher); Pageable pageable = PageRequest.of(page, size); Page<CmsPage> all = cmsPageRepository.findAll(example, pageable); List<CmsPage> content = all.getContent(); long totalElements = all.getTotalElements(); QueryResult<CmsPage> queryResult = new QueryResult<>(); queryResult.setList(content);//数据列表 queryResult.setTotal(totalElements);//数据总记录数 return new QueryResponseResult(CommonCode.SUCCESS,queryResult); } /** * 获取全部的CmsPage */ public List<CmsPage> findAllPage(){ return cmsPageRepository.findAll(); } /** * 获取CmsPage的siteId */ public Set<String> siteId_list() { Set<String> set = new HashSet<>(); for (CmsPage cmsPage : findAllPage()) { String siteId = cmsPage.getSiteId(); set.add(siteId); } return set; } /** * 查询所有的模板并以set返回 */ public Set<String> template_list(){ Set<String> set = new HashSet<>(); for (CmsPage cmsPage : findAllPage()) { String templateId = cmsPage.getTemplateId(); set.add(templateId); } return set; } /** * 通过唯一索引查询cmspage */ public CmsPage findByPageNameAndSiteIdAndPageWebPath(CmsPage cmsPage){ return cmsPageRepository.findByPageNameAndSiteIdAndPageWebPath(cmsPage.getPageName(), cmsPage.getSiteId(), cmsPage.getPageWebPath()); } /** * 通过PageId查询索引 */ public CmsPage findByPageId(String pageId){ Optional<CmsPage> byId = cmsPageRepository.findById(pageId); return byId.orElse(null); } /** * 保存页面 */ public CmsPageResult add(CmsPage cmsPage) { CmsPage exactPage = this.findByPageNameAndSiteIdAndPageWebPath(cmsPage); if (exactPage != null) { ExceptionCase.cthrow(CmsCode.CMS_ADDPAGE_EXISTSNAME); } CmsPage save = cmsPageRepository.save(cmsPage); return new CmsPageResult(CommonCode.SUCCESS, save); } public CmsPageResult update(String pageId, CmsPage cmsPage) { CmsPage byPageId = this.findByPageId(pageId); if (byPageId != null) { CmsPage save = cmsPageRepository.save(cmsPage); return new CmsPageResult(CommonCode.SUCCESS, save); } return new CmsPageResult(CommonCode.FAIL, null); } /** * 删除页面 */ public ResponseResult delete(String pageId) { CmsPage byPageId = this.findByPageId(pageId); if (byPageId != null) { cmsPageRepository.deleteById(pageId); return new ResponseResult(CommonCode.SUCCESS); } return new ResponseResult(CommonCode.FAIL); } /** * 查询cms配置信息 */ public CmsConfig getCmsConfig(String id){ Optional<CmsConfig> byId = cmsConfigRepository.findById(id); return byId.orElse(null); } /** * 静态化方法 */ public String getPageHtml(String pageId){ //获取页面 CmsPage byPageId = this.findByPageId(pageId); //获取页面数据模型 Map model = this.getModelByPageId(byPageId); //获取页面模板 String templateId = byPageId.getTemplateId(); String pageTemplate = this.getPageTemplateByPageId(templateId); //生成页面 String generatedHtml = this.generateHtml(model, pageTemplate); return generatedHtml; } private String generateHtml(Map model, String pageTemplate) { Configuration configuration = new Configuration(Configuration.getVersion()); StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); stringTemplateLoader.putTemplate("template", pageTemplate); configuration.setTemplateLoader(stringTemplateLoader); Template template = null; try { template = configuration.getTemplate("template"); return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取页面的模板 */ private String getPageTemplateByPageId(String templateId){ Optional<CmsTemplate> byId = cmsTemplateRepository.findById(templateId); if (byId.isPresent()) { CmsTemplate cmsTemplate = byId.get(); String templateFileId = cmsTemplate.getTemplateFileId(); GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId))); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream); try { return IOUtils.toString(gridFsResource.getInputStream(), "utf-8"); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 获取数据model */ private Map getModelByPageId(CmsPage cmsPage) { //取出页面的DataUrl String dataUrl = cmsPage.getDataUrl(); if (StringUtils.isEmpty(dataUrl)) { ExceptionCase.cthrow(CmsCode.CMS_GENERATEHTML_DATAURLISNULL); } //通过restTemplate请求dataUrl获取数据 ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class); return forEntity.getBody(); } private CmsPage getById(String pageId) { Optional<CmsPage> byId = cmsPageRepository.findById(pageId); return byId.orElse(null); } /** * 页面发布 */ // public R }
9,461
0.671676
0.669171
293
30.341297
27.17205
141
false
false
0
0
0
0
0
0
0.464164
false
false
9
cc0185f743340a94f3dc82de4debd0cbdef1ac0b
27,968,827,101,827
f7b0ed3679bcf401c703b16ea0184cfa25557911
/NCoreV2_33/src/dk/nodes/controllers/font/NFontContainer.java
8df008a4c8e0dc7cd38bf8562b9523d925b1f6ff
[]
no_license
nodesagency-mobile/dk-nodes-ncore
https://github.com/nodesagency-mobile/dk-nodes-ncore
1f232c27275d2be9e040c04a2c5262ee19d95761
95fd3526fc945c1741002e1efb6dd0efe4c05b17
refs/heads/master
2016-05-25T22:14:17.287000
2015-02-17T15:12:13
2015-02-17T15:12:13
11,097,265
1
0
null
false
2013-09-10T13:46:59
2013-07-01T14:30:36
2013-09-10T13:46:59
2013-09-10T13:46:27
4,272
null
0
1
Java
null
null
package dk.nodes.controllers.font; /** * @author Casper Rasmussen - 2012 */ import java.util.HashMap; import android.content.Context; import android.graphics.Paint; import android.graphics.Typeface; import android.util.TypedValue; import android.widget.TextView; import dk.nodes.utils.NLog; public class NFontContainer { private static NFontContainer instance; private HashMap<String,NFontModel> fontList = new HashMap<String,NFontModel>(); public static NFontContainer getInstance(){ if(instance == null) instance = new NFontContainer(); return instance; } public void setFontList(HashMap<String,NFontModel> fontList){ if(fontList!=null) this.fontList = fontList; else NLog.w("NFontController setFontList", "fontList input was null, did'nt set list"); } public void clearFontList(){ fontList.clear(); } public void addToFontList(NFontModel mNFontModel){ fontList.put(mNFontModel.getType(),mNFontModel); } public HashMap<String,NFontModel> getFontList(){ return fontList; } /** * This method will loop * @param type * @return */ public NFontModel getNFontModel(String type){ NFontModel tempNFontModel = fontList.get(type); if(tempNFontModel!=null) return tempNFontModel; else{ NLog.w("NFontController NFontModel","No NFontModel got found with given type: "+type+" returning null"); return null; } } /** * This method will loop * @param type * @return */ public NFontModel getNFontModel(char type){ return getNFontModel(String.valueOf(type)); } /** * This method will apply the font matching the type in input, on all the TextViews listed * If Typeface is null or any TextViews is null, it skip them and log.w * @param type * @param textViewList */ public void setFont(String type, TextView...textViewList) { NFontModel mNFontModel = getNFontModel(type); if(mNFontModel!=null){ for(TextView item : textViewList){ if(item!=null){ item.setTypeface(mNFontModel.getFont()); item.setPaintFlags( item.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG ); if(mNFontModel.isSizeApplied())//Appy size if it was set. item.setTextSize(TypedValue.COMPLEX_UNIT_DIP,mNFontModel.getSizeInPixels()); } else{ NLog.w("NFontController setFont", "One of the TextViews was null, and did'nt get the typeface applied"); } } } else NLog.w("NFontController setFont", "NFontModel was not found: "+type+", no typeface applied"); } /** * This method will apply the font matching the type in input, on all the TextViews listed * If Typeface is null or any TextViews is null, it skip them and log.w * @param type * @param textViewList */ public void setFont(char type, TextView...textViewList) { setFont(String.valueOf(type), textViewList); } /** * Use this method if you just need to apply a Typeface on a list of TextView * If Typeface is null or any TextViews is null, it skip them and log.w * @param font * @param textViewList */ public static void setFont(Typeface font, TextView...textViewList){ if(font==null){ NLog.w("NFontController setFont", "font was null, returning wihtout applying anything"); } for(TextView item : textViewList){ if(item!=null){ item.setTypeface(font); item.setPaintFlags( item.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG ); } else NLog.w("NFontController setFont", "One of the TextViews was null, and did'nt get the typeface applied"); } } /** * Use this method to load a typeface from assets folder * @param mContext * @param path, fx "fonts/Berthold Akzidenz Grotesk BE Light Condensed.ttf" * @return Typeface */ public static Typeface getTypeFontFromPath(Context mContext, String path) throws Exception{ return Typeface.createFromAsset(mContext.getAssets(),path); } }
UTF-8
Java
3,955
java
NFontContainer.java
Java
[ { "context": "ackage dk.nodes.controllers.font;\r\n/**\r\n * @author Casper Rasmussen - 2012\r\n */\r\nimport java.util.HashMap;\r\n\r\nimport ", "end": 68, "score": 0.9998422265052795, "start": 52, "tag": "NAME", "value": "Casper Rasmussen" } ]
null
[]
package dk.nodes.controllers.font; /** * @author <NAME> - 2012 */ import java.util.HashMap; import android.content.Context; import android.graphics.Paint; import android.graphics.Typeface; import android.util.TypedValue; import android.widget.TextView; import dk.nodes.utils.NLog; public class NFontContainer { private static NFontContainer instance; private HashMap<String,NFontModel> fontList = new HashMap<String,NFontModel>(); public static NFontContainer getInstance(){ if(instance == null) instance = new NFontContainer(); return instance; } public void setFontList(HashMap<String,NFontModel> fontList){ if(fontList!=null) this.fontList = fontList; else NLog.w("NFontController setFontList", "fontList input was null, did'nt set list"); } public void clearFontList(){ fontList.clear(); } public void addToFontList(NFontModel mNFontModel){ fontList.put(mNFontModel.getType(),mNFontModel); } public HashMap<String,NFontModel> getFontList(){ return fontList; } /** * This method will loop * @param type * @return */ public NFontModel getNFontModel(String type){ NFontModel tempNFontModel = fontList.get(type); if(tempNFontModel!=null) return tempNFontModel; else{ NLog.w("NFontController NFontModel","No NFontModel got found with given type: "+type+" returning null"); return null; } } /** * This method will loop * @param type * @return */ public NFontModel getNFontModel(char type){ return getNFontModel(String.valueOf(type)); } /** * This method will apply the font matching the type in input, on all the TextViews listed * If Typeface is null or any TextViews is null, it skip them and log.w * @param type * @param textViewList */ public void setFont(String type, TextView...textViewList) { NFontModel mNFontModel = getNFontModel(type); if(mNFontModel!=null){ for(TextView item : textViewList){ if(item!=null){ item.setTypeface(mNFontModel.getFont()); item.setPaintFlags( item.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG ); if(mNFontModel.isSizeApplied())//Appy size if it was set. item.setTextSize(TypedValue.COMPLEX_UNIT_DIP,mNFontModel.getSizeInPixels()); } else{ NLog.w("NFontController setFont", "One of the TextViews was null, and did'nt get the typeface applied"); } } } else NLog.w("NFontController setFont", "NFontModel was not found: "+type+", no typeface applied"); } /** * This method will apply the font matching the type in input, on all the TextViews listed * If Typeface is null or any TextViews is null, it skip them and log.w * @param type * @param textViewList */ public void setFont(char type, TextView...textViewList) { setFont(String.valueOf(type), textViewList); } /** * Use this method if you just need to apply a Typeface on a list of TextView * If Typeface is null or any TextViews is null, it skip them and log.w * @param font * @param textViewList */ public static void setFont(Typeface font, TextView...textViewList){ if(font==null){ NLog.w("NFontController setFont", "font was null, returning wihtout applying anything"); } for(TextView item : textViewList){ if(item!=null){ item.setTypeface(font); item.setPaintFlags( item.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG ); } else NLog.w("NFontController setFont", "One of the TextViews was null, and did'nt get the typeface applied"); } } /** * Use this method to load a typeface from assets folder * @param mContext * @param path, fx "fonts/Berthold Akzidenz Grotesk BE Light Condensed.ttf" * @return Typeface */ public static Typeface getTypeFontFromPath(Context mContext, String path) throws Exception{ return Typeface.createFromAsset(mContext.getAssets(),path); } }
3,945
0.689001
0.68799
132
27.962122
29.13485
109
false
false
0
0
0
0
0
0
2.106061
false
false
9
8f55af4f93a0663608da921ec04856b953e852bf
27,968,827,100,723
b7ad7bfcf5808d3b73458b9726f33e78aa66f874
/java-core/src/java1/algorithm/bisearch/Bisearch.java
2991e53ca3c8585de750eea428f516a6a2528b2a
[]
no_license
jianweizhao/java-master
https://github.com/jianweizhao/java-master
72d87515ef93b68e5998a80dde5d4e9a1fc96613
3c7a72f30d24535bebeff22bc1f1acf1bf09243d
refs/heads/master
2021-10-24T13:48:22.242000
2019-03-26T11:51:17
2019-03-26T11:51:17
108,370,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java1.algorithm.bisearch; import java.util.Scanner; /** * 折半查找 * @author Administrator * */ public class Bisearch { static final int MAX_LEN=15; public static void main(String[] args) { Scanner scanner=new Scanner(System.in); long[] nums=new long[MAX_LEN]; for (int i = 0; i < MAX_LEN; i++) { nums[i]=(long) (Math.random()*99); } System.out.println("排序前数组为:"); for (long l : nums) { System.out.print(l+" "); } System.out.println("\n"); quickSort(nums, 0, MAX_LEN-1); System.out.println("排序后的数组为:"); for (long l : nums) { System.out.print(l+" "); } System.out.println("\n"); System.out.println("请输入要查找的数:"); long target=scanner.nextLong(); int n=bisearch(nums, target, 0, MAX_LEN-1); System.out.println("您要找查找的数"+target+",在第"+(n+1)+"个位置!"); } public static void quickSort(long[] num,int left,int right){ if(left<right){ int partition=partition(num, left, right); quickSort(num, left, partition-1); quickSort(num, partition+1,right); } } public static int partition(long[] num,int left,int right){ long temp=num[left]; while(left<right){ while(left<right&&num[right]>=temp){ right--; } swap(num, left, right); while(left<right&&num[left]<=temp){ left++; } swap(num, left, right); } return left; } public static void swap(long[] num,int m,int n){ long temp = num[m]; num[m]=num[n]; num[n]=temp; } public static int bisearch(long[] nums,long target,int low,int high){ int mid=-1; while(low<=high){ mid=(low+high)/2; if (target==nums[mid]) { return mid; }else if (target>nums[mid]) { low=mid+1; }else { high=mid-1; } } return mid; } }
UTF-8
Java
1,805
java
Bisearch.java
Java
[ { "context": "import java.util.Scanner;\n\n\n/**\n * 折半查找\n * @author Administrator\n *\n */\npublic class Bisearch {\n\n\tstatic final int", "end": 99, "score": 0.9443231225013733, "start": 86, "tag": "NAME", "value": "Administrator" } ]
null
[]
package java1.algorithm.bisearch; import java.util.Scanner; /** * 折半查找 * @author Administrator * */ public class Bisearch { static final int MAX_LEN=15; public static void main(String[] args) { Scanner scanner=new Scanner(System.in); long[] nums=new long[MAX_LEN]; for (int i = 0; i < MAX_LEN; i++) { nums[i]=(long) (Math.random()*99); } System.out.println("排序前数组为:"); for (long l : nums) { System.out.print(l+" "); } System.out.println("\n"); quickSort(nums, 0, MAX_LEN-1); System.out.println("排序后的数组为:"); for (long l : nums) { System.out.print(l+" "); } System.out.println("\n"); System.out.println("请输入要查找的数:"); long target=scanner.nextLong(); int n=bisearch(nums, target, 0, MAX_LEN-1); System.out.println("您要找查找的数"+target+",在第"+(n+1)+"个位置!"); } public static void quickSort(long[] num,int left,int right){ if(left<right){ int partition=partition(num, left, right); quickSort(num, left, partition-1); quickSort(num, partition+1,right); } } public static int partition(long[] num,int left,int right){ long temp=num[left]; while(left<right){ while(left<right&&num[right]>=temp){ right--; } swap(num, left, right); while(left<right&&num[left]<=temp){ left++; } swap(num, left, right); } return left; } public static void swap(long[] num,int m,int n){ long temp = num[m]; num[m]=num[n]; num[n]=temp; } public static int bisearch(long[] nums,long target,int low,int high){ int mid=-1; while(low<=high){ mid=(low+high)/2; if (target==nums[mid]) { return mid; }else if (target>nums[mid]) { low=mid+1; }else { high=mid-1; } } return mid; } }
1,805
0.605462
0.595584
84
19.488094
16.979324
70
false
false
0
0
0
0
0
0
2.369048
false
false
9
65870f1974fdb19fd147a128d7d97cb04cc83a97
4,157,528,391,063
c3445da9eff3501684f1e22dd8709d01ff414a15
/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/taskservice/taskinstance/callPayPremOutGraceInvaliBLTMThread.java
872b589a5df93e927b134233f4fb083785a88c72
[]
no_license
zhanght86/HSBC20171018
https://github.com/zhanght86/HSBC20171018
954403d25d24854dd426fa9224dfb578567ac212
c1095c58c0bdfa9d79668db9be4a250dd3f418c5
refs/heads/master
2021-05-07T03:30:31.905000
2017-11-08T08:54:46
2017-11-08T08:54:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sinosoft.lis.taskservice.taskinstance; import org.apache.log4j.Logger; import com.sinosoft.lis.bq.BqCode; import com.sinosoft.lis.db.LCContDB; import com.sinosoft.lis.db.LCPolDB; import com.sinosoft.lis.f1print.BqNameFun; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Vector; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.PubConcurrencyLock; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.schema.LCContSchema; import com.sinosoft.lis.schema.LCPolSchema; import com.sinosoft.lis.taskservice.TaskThread; import com.sinosoft.lis.vschema.LCContSet; import com.sinosoft.lis.vschema.LCPolSet; import com.sinosoft.lis.vschema.LJSPaySet; import com.sinosoft.service.ServiceA; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.ExeSQL; import com.sinosoft.utility.RSWrapper; import com.sinosoft.utility.SQLwithBindVariables; import com.sinosoft.utility.SSRS; import com.sinosoft.utility.TransferData; import com.sinosoft.utility.VData; public class callPayPremOutGraceInvaliBLTMThread extends TaskThread { private static Logger logger = Logger.getLogger(callPayPremOutGraceInvaliBLTMThread.class); public CErrors mErrors = new CErrors(); private String mCurrentDate = PubFun.getCurrentDate(); private LCPolSchema mLCPolSchema = new LCPolSchema(); private PubConcurrencyLock mPubLock = new PubConcurrencyLock(); public callPayPremOutGraceInvaliBLTMThread() { } public boolean dealMain() { /* 业务处理逻辑 */ logger.debug("================== AutoPayPrem Start!!! ================="); GlobalInput tG = new GlobalInput(); tG.ComCode = "86"; tG.Operator = "AUTO"; tG.ManageCom = "86"; //日志监控,初始化 tG.LogID[0]="TASK"+(String)mParameters.get("TaskCode"); tG.LogID[1]=(String)mParameters.get("SerialNo"); //日志监控,过程监控 PubFun.logPerformance (tG,tG.LogID[1],"垫交保单宽限期外失效批处理启动","2"); PubFun.logTrack(tG,tG.LogID[1],"垫交保单宽限期外失效批处理开始"); //启动时间 Date dNow = new Date(); long initTime =dNow.getTime(); // 每次最大取数量,默认是100条 int countJS=0; int tConutMax = 100; String tResult = ""; String tSQL_Count = "select sysvarvalue from ldsysvar where sysvar='callPayPremOutGraceInvaliBLTMCount' "; SQLwithBindVariables sqlbv=new SQLwithBindVariables(); sqlbv.sql(tSQL_Count); ExeSQL tExeSQL = new ExeSQL(); tResult = tExeSQL.getOneValue(sqlbv); // 如果有描述的话,取描述的数据 if (tResult != null && !tResult.equals("")) { tConutMax = Integer.parseInt(tResult); } Vector mTaskWaitList = new Vector(); logger.debug("垫交保单宽限期外失效批处理个单取的最大的数tConutMax:" + tConutMax); try { String strsql = "Select ContNo,PolNo from LCContState a" + " where StateType='PayPrem' and State='1' and EndDate is null " //当前日期大于垫至日期 + " and exists (select 1 from loloan where " //+ " polno=a.polno and " //zqflag 垫交至天宽限期外 垫整期的由垫缴批处理运行 + " contno=a.contno and loantype='1' and payoffflag='0' and zqflag='0' and loantodate <= '"+"?mCurrentDate?"+"')" + " and not exists(select 'X' from lcconthangupstate where posflag = '1' and contno = a.contno) " + " and exists(select 'X' from lcpol where appflag = '1' and polno=mainpolno and contno = a.contno) " + " and not exists ( select 'X' from LCContState where " //+ " PolNo=a.PolNo and " + " ContNo=a.ContNo " + " and StateType='Available' " + " and State='1' and EndDate is null)" //+ " and rownum <= 100 " ; // 不失效 SQLwithBindVariables sqlbv1=new SQLwithBindVariables(); sqlbv1.sql(strsql); sqlbv1.put("mCurrentDate", mCurrentDate); SSRS tSSRS = null; String aPolNo = ""; String aContNo = ""; String mEndDate = ""; VData tVData = new VData(); try { tSSRS = new SSRS(); tExeSQL = new ExeSQL(); tSSRS = tExeSQL.execSQL(sqlbv1); } catch (Exception e) { // @@错误处理 CError.buildErr(this, "查询贷款的保单状态信息时产生错误!"); return false; } // if (tSSRS == null ||tSSRS.MaxRow <= 0) { // return false; // } countJS=tSSRS.MaxRow; if (tSSRS != null && tSSRS.MaxRow > 0) { for (int i = 1; i <= tSSRS.MaxRow; i++) { aContNo = tSSRS.GetText(i, 1); aPolNo = tSSRS.GetText(i, 2); //取宽限期外的借至日期为有效的终止日期 SQLwithBindVariables sqlbv2=new SQLwithBindVariables(); sqlbv2.sql("select loantodate from loloan where contno='"+"?aContNo?"+"' and loantype='1' and payoffflag='0' and zqflag='0' "); sqlbv2.put("aContNo", aContNo); String tLoanToDate = tExeSQL.getOneValue(sqlbv2); //loantodate 是与paytodate一样的含义 下次交费对应日 //而这里的this.mEndDate应该是有效的止期 也就是说这个tLoanToDate是失效的startdate mEndDate = PubFun.calDate(tLoanToDate, -1, "D", null); //修改成公共的调用失效批处理 LCPolSchema tLCPolSchema = new LCPolSchema(); LCPolDB tLCPolDB = new LCPolDB(); String tMainPolSQL = "select * from lcpol where contno='"+"?aContNo?"+"' and polno=mainpolno and appflag='1' "; SQLwithBindVariables sqlbv3=new SQLwithBindVariables(); sqlbv3.sql(tMainPolSQL); sqlbv3.put("aContNo", aContNo); LCPolSet tLCPolSet = tLCPolDB.executeQuery(sqlbv3); if (tLCPolSet.size()>0) { tLCPolSchema.setSchema(tLCPolSet.get(1)); mLCPolSchema.setSchema(tLCPolSchema); } Map map = new HashMap(); map.put("LCPolSchema", mLCPolSchema); map.put("InvalidationStateReason", BqCode.BQ_InvalidationStateReason_OutGracePayPrem); map.put("GlobalInput", tG); tVData.add(map); if(i%tConutMax==0) { mTaskWaitList.add(tVData); tVData = new VData(); } if(i%tConutMax!=0&&i==tLCPolSet.size()) { mTaskWaitList.add(tVData); tVData = new VData(); } } } String TaskCode = (String) this.mParameters.get("TaskGroupCode") + ":" + (String) this.mParameters.get("TaskCode") + ":" + (String) this.mParameters.get("TaskPlanCode"); // tongmeng 2009-05-21 add // 自适应线程数 int tThreadCount = 5; tExeSQL = new ExeSQL(); String tSQL_ThreadCount = "select (case when sysvarvalue is not null then sysvarvalue else '0' end) from ldsysvar where sysvar ='callPayPremOutGraceInvaliBLTMThread'"; SQLwithBindVariables sqlbv4=new SQLwithBindVariables(); sqlbv4.sql(tSQL_ThreadCount); String tSignMThreadCount = tExeSQL.getOneValue(sqlbv4); if (tSignMThreadCount != null && !"".equals(tSignMThreadCount) && Integer.parseInt(tSignMThreadCount) > 0) { tThreadCount = Integer.parseInt(tSignMThreadCount); } if (countJS < tThreadCount) { tThreadCount = countJS; } this.mServiceA = new ServiceA( "com.sinosoft.lis.bq.ContInvaliBLTMThread", mTaskWaitList, tThreadCount, 10, TaskCode); this.mServiceA.start(); logger.debug("结束业务逻辑处理!--垫交保单宽限期外失效批处理" + PubFun.getCurrentDate() + "**" + PubFun.getCurrentTime()); //完成时间 Date dend = new Date(); long endTime = dend.getTime(); long tt=(endTime-initTime)/1000; //日志监控,结果监控 PubFun.logResult(tG,tG.LogID[1], "垫交保单宽限期外失效批处理完毕"+String.valueOf(countJS)+"笔,共花费"+tt+"秒"); //日志监控,过程监控 PubFun.logTrack(tG, tG.LogID[1], "垫交保单宽限期外失效批处理完毕"); }catch (Exception ex) { ex.printStackTrace(); } finally { mPubLock.unLock(); } return true; } public static void main(String[] args) { AutoPayTaskTMThread tAutoPayTaskTMThread = new AutoPayTaskTMThread(); tAutoPayTaskTMThread.dealMain(); } }
UTF-8
Java
8,197
java
callPayPremOutGraceInvaliBLTMThread.java
Java
[]
null
[]
package com.sinosoft.lis.taskservice.taskinstance; import org.apache.log4j.Logger; import com.sinosoft.lis.bq.BqCode; import com.sinosoft.lis.db.LCContDB; import com.sinosoft.lis.db.LCPolDB; import com.sinosoft.lis.f1print.BqNameFun; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Vector; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.PubConcurrencyLock; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.schema.LCContSchema; import com.sinosoft.lis.schema.LCPolSchema; import com.sinosoft.lis.taskservice.TaskThread; import com.sinosoft.lis.vschema.LCContSet; import com.sinosoft.lis.vschema.LCPolSet; import com.sinosoft.lis.vschema.LJSPaySet; import com.sinosoft.service.ServiceA; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.ExeSQL; import com.sinosoft.utility.RSWrapper; import com.sinosoft.utility.SQLwithBindVariables; import com.sinosoft.utility.SSRS; import com.sinosoft.utility.TransferData; import com.sinosoft.utility.VData; public class callPayPremOutGraceInvaliBLTMThread extends TaskThread { private static Logger logger = Logger.getLogger(callPayPremOutGraceInvaliBLTMThread.class); public CErrors mErrors = new CErrors(); private String mCurrentDate = PubFun.getCurrentDate(); private LCPolSchema mLCPolSchema = new LCPolSchema(); private PubConcurrencyLock mPubLock = new PubConcurrencyLock(); public callPayPremOutGraceInvaliBLTMThread() { } public boolean dealMain() { /* 业务处理逻辑 */ logger.debug("================== AutoPayPrem Start!!! ================="); GlobalInput tG = new GlobalInput(); tG.ComCode = "86"; tG.Operator = "AUTO"; tG.ManageCom = "86"; //日志监控,初始化 tG.LogID[0]="TASK"+(String)mParameters.get("TaskCode"); tG.LogID[1]=(String)mParameters.get("SerialNo"); //日志监控,过程监控 PubFun.logPerformance (tG,tG.LogID[1],"垫交保单宽限期外失效批处理启动","2"); PubFun.logTrack(tG,tG.LogID[1],"垫交保单宽限期外失效批处理开始"); //启动时间 Date dNow = new Date(); long initTime =dNow.getTime(); // 每次最大取数量,默认是100条 int countJS=0; int tConutMax = 100; String tResult = ""; String tSQL_Count = "select sysvarvalue from ldsysvar where sysvar='callPayPremOutGraceInvaliBLTMCount' "; SQLwithBindVariables sqlbv=new SQLwithBindVariables(); sqlbv.sql(tSQL_Count); ExeSQL tExeSQL = new ExeSQL(); tResult = tExeSQL.getOneValue(sqlbv); // 如果有描述的话,取描述的数据 if (tResult != null && !tResult.equals("")) { tConutMax = Integer.parseInt(tResult); } Vector mTaskWaitList = new Vector(); logger.debug("垫交保单宽限期外失效批处理个单取的最大的数tConutMax:" + tConutMax); try { String strsql = "Select ContNo,PolNo from LCContState a" + " where StateType='PayPrem' and State='1' and EndDate is null " //当前日期大于垫至日期 + " and exists (select 1 from loloan where " //+ " polno=a.polno and " //zqflag 垫交至天宽限期外 垫整期的由垫缴批处理运行 + " contno=a.contno and loantype='1' and payoffflag='0' and zqflag='0' and loantodate <= '"+"?mCurrentDate?"+"')" + " and not exists(select 'X' from lcconthangupstate where posflag = '1' and contno = a.contno) " + " and exists(select 'X' from lcpol where appflag = '1' and polno=mainpolno and contno = a.contno) " + " and not exists ( select 'X' from LCContState where " //+ " PolNo=a.PolNo and " + " ContNo=a.ContNo " + " and StateType='Available' " + " and State='1' and EndDate is null)" //+ " and rownum <= 100 " ; // 不失效 SQLwithBindVariables sqlbv1=new SQLwithBindVariables(); sqlbv1.sql(strsql); sqlbv1.put("mCurrentDate", mCurrentDate); SSRS tSSRS = null; String aPolNo = ""; String aContNo = ""; String mEndDate = ""; VData tVData = new VData(); try { tSSRS = new SSRS(); tExeSQL = new ExeSQL(); tSSRS = tExeSQL.execSQL(sqlbv1); } catch (Exception e) { // @@错误处理 CError.buildErr(this, "查询贷款的保单状态信息时产生错误!"); return false; } // if (tSSRS == null ||tSSRS.MaxRow <= 0) { // return false; // } countJS=tSSRS.MaxRow; if (tSSRS != null && tSSRS.MaxRow > 0) { for (int i = 1; i <= tSSRS.MaxRow; i++) { aContNo = tSSRS.GetText(i, 1); aPolNo = tSSRS.GetText(i, 2); //取宽限期外的借至日期为有效的终止日期 SQLwithBindVariables sqlbv2=new SQLwithBindVariables(); sqlbv2.sql("select loantodate from loloan where contno='"+"?aContNo?"+"' and loantype='1' and payoffflag='0' and zqflag='0' "); sqlbv2.put("aContNo", aContNo); String tLoanToDate = tExeSQL.getOneValue(sqlbv2); //loantodate 是与paytodate一样的含义 下次交费对应日 //而这里的this.mEndDate应该是有效的止期 也就是说这个tLoanToDate是失效的startdate mEndDate = PubFun.calDate(tLoanToDate, -1, "D", null); //修改成公共的调用失效批处理 LCPolSchema tLCPolSchema = new LCPolSchema(); LCPolDB tLCPolDB = new LCPolDB(); String tMainPolSQL = "select * from lcpol where contno='"+"?aContNo?"+"' and polno=mainpolno and appflag='1' "; SQLwithBindVariables sqlbv3=new SQLwithBindVariables(); sqlbv3.sql(tMainPolSQL); sqlbv3.put("aContNo", aContNo); LCPolSet tLCPolSet = tLCPolDB.executeQuery(sqlbv3); if (tLCPolSet.size()>0) { tLCPolSchema.setSchema(tLCPolSet.get(1)); mLCPolSchema.setSchema(tLCPolSchema); } Map map = new HashMap(); map.put("LCPolSchema", mLCPolSchema); map.put("InvalidationStateReason", BqCode.BQ_InvalidationStateReason_OutGracePayPrem); map.put("GlobalInput", tG); tVData.add(map); if(i%tConutMax==0) { mTaskWaitList.add(tVData); tVData = new VData(); } if(i%tConutMax!=0&&i==tLCPolSet.size()) { mTaskWaitList.add(tVData); tVData = new VData(); } } } String TaskCode = (String) this.mParameters.get("TaskGroupCode") + ":" + (String) this.mParameters.get("TaskCode") + ":" + (String) this.mParameters.get("TaskPlanCode"); // tongmeng 2009-05-21 add // 自适应线程数 int tThreadCount = 5; tExeSQL = new ExeSQL(); String tSQL_ThreadCount = "select (case when sysvarvalue is not null then sysvarvalue else '0' end) from ldsysvar where sysvar ='callPayPremOutGraceInvaliBLTMThread'"; SQLwithBindVariables sqlbv4=new SQLwithBindVariables(); sqlbv4.sql(tSQL_ThreadCount); String tSignMThreadCount = tExeSQL.getOneValue(sqlbv4); if (tSignMThreadCount != null && !"".equals(tSignMThreadCount) && Integer.parseInt(tSignMThreadCount) > 0) { tThreadCount = Integer.parseInt(tSignMThreadCount); } if (countJS < tThreadCount) { tThreadCount = countJS; } this.mServiceA = new ServiceA( "com.sinosoft.lis.bq.ContInvaliBLTMThread", mTaskWaitList, tThreadCount, 10, TaskCode); this.mServiceA.start(); logger.debug("结束业务逻辑处理!--垫交保单宽限期外失效批处理" + PubFun.getCurrentDate() + "**" + PubFun.getCurrentTime()); //完成时间 Date dend = new Date(); long endTime = dend.getTime(); long tt=(endTime-initTime)/1000; //日志监控,结果监控 PubFun.logResult(tG,tG.LogID[1], "垫交保单宽限期外失效批处理完毕"+String.valueOf(countJS)+"笔,共花费"+tt+"秒"); //日志监控,过程监控 PubFun.logTrack(tG, tG.LogID[1], "垫交保单宽限期外失效批处理完毕"); }catch (Exception ex) { ex.printStackTrace(); } finally { mPubLock.unLock(); } return true; } public static void main(String[] args) { AutoPayTaskTMThread tAutoPayTaskTMThread = new AutoPayTaskTMThread(); tAutoPayTaskTMThread.dealMain(); } }
8,197
0.673933
0.663698
207
35.342995
26.319538
169
false
false
0
0
0
0
0
0
2.971014
false
false
9
3dab65a560ec095cdfeb6524489c6c0dea607098
18,846,316,529,717
87bc8b425276bacf18720ac28001fa4f94542a63
/Multitier/Lernplattform/courses-service/src/main/java/at/lernplattform/application/dao/SchemaDaoImpl.java
845037d886e49d40eca163be268317f74e7fc0d5
[]
no_license
Kreidl/AWSTemplates
https://github.com/Kreidl/AWSTemplates
430e9c76b13580f33760ae88caad7c8f280dcb13
e541f56c01d52eacb5a20dfcd63bfaaac44b7f9c
refs/heads/master
2020-12-13T10:54:39.418000
2020-12-05T06:15:36
2020-12-05T06:15:36
234,394,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.lernplattform.application.dao; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.jdbc.datasource.init.ScriptUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import at.lernplattform.application.rowmapper.CourseRowMapper; import at.lernplattform.application.rowmapper.SchemaRowMapper; import at.lernplattform.rest.api.model.SchemaModel; import at.lernplattform.rest.api.model.SchemaresponseModel; @Repository public class SchemaDaoImpl implements SchemaDao{ @Autowired private NamedParameterJdbcTemplate namedjdbcTemplate; @Autowired private JdbcTemplate jdbcTemplate; @Override public SchemaresponseModel createSchema(SchemaModel schemaModel, String creator) { SchemaresponseModel response = new SchemaresponseModel(); if(schemaModel.getName().length()==0) { response.setResponse("Schemaname can not be empty"); }else { String sql = "CREATE SCHEMA " + schemaModel.getName()+ " AUTHORIZATION internaluser;"; try { jdbcTemplate.execute(sql); String sql2 = "insert into internal.Schema(name, creator) VALUES (:schema, :creator);"; Map<String,Object> map=new HashMap<String,Object>(); map.put("schema", schemaModel.getName()); map.put("creator", Integer.parseInt(creator)); namedjdbcTemplate.execute(sql2,map,new PreparedStatementCallback<Object>() { @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { return ps.executeUpdate(); } }); response.setResponse(schemaModel.getName()); }catch(Exception e) { response.setResponse(e.getMessage()); } } return response; } @Override public List<SchemaModel> getSchemas(String userid) { String sql = "select * from internal.Schema where creator = " + userid; return namedjdbcTemplate.query(sql, new SchemaRowMapper()); } @Override public SchemaModel getSchema(int _id) { String sql = "select * from internal.Schema where id = " + _id; return namedjdbcTemplate.query(sql, new SchemaRowMapper()).get(0); } @Override public SchemaresponseModel tablemanage(String schemaname, String fileContent) { SchemaresponseModel response = new SchemaresponseModel(); String sql = "set schema '"+schemaname+"';" + fileContent; try { jdbcTemplate.execute(sql); response.setResponse("Success"); }catch(Exception e) { response.setResponse(e.getMessage()); } return response; } @Override public SchemaresponseModel tablescreatedefault(String schemaname) { SchemaresponseModel response = new SchemaresponseModel(); File file = new File("src\\main\\java\\at\\lernplattform\\application\\dao\\northwind.txt"); InputStream inputStream; StringBuilder resultStringBuilder = new StringBuilder(); try { inputStream = new FileInputStream(file); try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { resultStringBuilder.append(line).append("\n"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = resultStringBuilder.toString(); sql = sql.replaceAll("schemaname", schemaname); try { jdbcTemplate.execute(sql); response.setResponse("Success"); }catch(Exception e) { response.setResponse(e.getMessage()); } return response; } }
UTF-8
Java
4,740
java
SchemaDaoImpl.java
Java
[]
null
[]
package at.lernplattform.application.dao; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.jdbc.datasource.init.ScriptUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import at.lernplattform.application.rowmapper.CourseRowMapper; import at.lernplattform.application.rowmapper.SchemaRowMapper; import at.lernplattform.rest.api.model.SchemaModel; import at.lernplattform.rest.api.model.SchemaresponseModel; @Repository public class SchemaDaoImpl implements SchemaDao{ @Autowired private NamedParameterJdbcTemplate namedjdbcTemplate; @Autowired private JdbcTemplate jdbcTemplate; @Override public SchemaresponseModel createSchema(SchemaModel schemaModel, String creator) { SchemaresponseModel response = new SchemaresponseModel(); if(schemaModel.getName().length()==0) { response.setResponse("Schemaname can not be empty"); }else { String sql = "CREATE SCHEMA " + schemaModel.getName()+ " AUTHORIZATION internaluser;"; try { jdbcTemplate.execute(sql); String sql2 = "insert into internal.Schema(name, creator) VALUES (:schema, :creator);"; Map<String,Object> map=new HashMap<String,Object>(); map.put("schema", schemaModel.getName()); map.put("creator", Integer.parseInt(creator)); namedjdbcTemplate.execute(sql2,map,new PreparedStatementCallback<Object>() { @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { return ps.executeUpdate(); } }); response.setResponse(schemaModel.getName()); }catch(Exception e) { response.setResponse(e.getMessage()); } } return response; } @Override public List<SchemaModel> getSchemas(String userid) { String sql = "select * from internal.Schema where creator = " + userid; return namedjdbcTemplate.query(sql, new SchemaRowMapper()); } @Override public SchemaModel getSchema(int _id) { String sql = "select * from internal.Schema where id = " + _id; return namedjdbcTemplate.query(sql, new SchemaRowMapper()).get(0); } @Override public SchemaresponseModel tablemanage(String schemaname, String fileContent) { SchemaresponseModel response = new SchemaresponseModel(); String sql = "set schema '"+schemaname+"';" + fileContent; try { jdbcTemplate.execute(sql); response.setResponse("Success"); }catch(Exception e) { response.setResponse(e.getMessage()); } return response; } @Override public SchemaresponseModel tablescreatedefault(String schemaname) { SchemaresponseModel response = new SchemaresponseModel(); File file = new File("src\\main\\java\\at\\lernplattform\\application\\dao\\northwind.txt"); InputStream inputStream; StringBuilder resultStringBuilder = new StringBuilder(); try { inputStream = new FileInputStream(file); try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { resultStringBuilder.append(line).append("\n"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = resultStringBuilder.toString(); sql = sql.replaceAll("schemaname", schemaname); try { jdbcTemplate.execute(sql); response.setResponse("Success"); }catch(Exception e) { response.setResponse(e.getMessage()); } return response; } }
4,740
0.68481
0.683966
170
25.882353
25.508205
97
false
false
0
0
0
0
0
0
1.735294
false
false
9
f6003b18845c5381e22b71845357730d8af692fe
4,672,924,469,710
4f393dafae7353d9caf5ba0220f459664d39c866
/mein project/math-master/math/src/main/java/gz/math/stillwell/CardinalsUtil.java
d3a99f233406cfa982c348c5d01ac56779021606
[]
no_license
mazen33/mazen
https://github.com/mazen33/mazen
dd00e7635b9879a676a7fec7f6859cb5f9e5f209
ed347019e2f1821a67a7e657af51eba961f57215
refs/heads/master
2020-12-30T10:51:18.543000
2019-10-13T18:09:46
2019-10-13T18:09:46
98,826,294
0
0
null
false
2020-10-13T16:41:21
2017-07-30T21:38:14
2019-10-13T18:10:38
2020-10-13T16:41:20
13,144
0
0
2
Java
false
false
package gz.math.stillwell; import java.util.HashSet; import java.util.Set; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CardinalsUtil { public static Set cardinals(int n) { Set result = new HashSet<>(); Set tmp; if (n != 0) { for (; n > 0; n--) { tmp = new HashSet<>(); tmp.add(cardinals(n - 1)); result.addAll(tmp); } } return result; } public static void printElements(Set set) { for (Object o : set) { System.out.println(o + " -> " + ((Set) o).size()); } } }
UTF-8
Java
521
java
CardinalsUtil.java
Java
[]
null
[]
package gz.math.stillwell; import java.util.HashSet; import java.util.Set; @SuppressWarnings({ "rawtypes", "unchecked" }) public class CardinalsUtil { public static Set cardinals(int n) { Set result = new HashSet<>(); Set tmp; if (n != 0) { for (; n > 0; n--) { tmp = new HashSet<>(); tmp.add(cardinals(n - 1)); result.addAll(tmp); } } return result; } public static void printElements(Set set) { for (Object o : set) { System.out.println(o + " -> " + ((Set) o).size()); } } }
521
0.59501
0.589251
28
17.607143
15.664654
53
false
false
0
0
0
0
0
0
1.857143
false
false
9