blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
bd3dfb47adb20fa4d43bb49230b2a0b7fb631e2c
8c5965939957d8aaf8b96f5bef0bd79772fae381
/ConsolePaint/src/Main.java
c81e6cb55afbb4dbd923e96d37332f6439c852f4
[]
no_license
NicolainaV/SDA_Nicolaina
734b13c974af33a86482a0744445401c3a72c128
46d3ca616b5647fe8056e4a2e542c9ef4e93c893
refs/heads/master
2021-02-15T20:03:40.179972
2020-06-03T13:09:45
2020-06-03T13:09:45
244,927,427
0
0
null
null
null
null
UTF-8
Java
false
false
632
java
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Shape> shapes = new ArrayList<>(); shapes.add( new Square(5,"#a09542", 1)); shapes.add( new Rectangle(2, 5,"#f5f6f5", 1)); shapes.add( new Circle("#f5f6f5", 1, 5)); for(Shape s: shapes) { System.out.println("Shape name: "+s.getName()); System.out.println("Shape area: "+s.getArea()); System.out.println("Shape fillColor: "+s.getColor()); System.out.println("Shape borderWidth: "+s.getBorder()); System.out.println(); s.draw(); System.out.println(); } } }
[ "vlad.nicolaina@gmail.com" ]
vlad.nicolaina@gmail.com
902539f5b855bfedb771ee303772b416f724affb
b1bdb7ebd7e65c645b13d4c438ca448c5bbcc11d
/src/main/java/com/bootcamp/enums/TypeImpact.java
b0d531a240f67b48af377b3b7733e923368d5116
[]
no_license
Iso-Doss/bootcampDataBase
654a5ce5435f2a22a99d0b15e9cc4923c556b38e
3c4d435462226dfa6a02a6072f6b8900901e7485
refs/heads/master
2021-08-16T20:26:02.426642
2017-11-20T09:21:57
2017-11-20T09:21:57
111,381,063
0
0
null
null
null
null
UTF-8
Java
false
false
148
java
package com.bootcamp.enums; public enum TypeImpact { SOCIAL, ECONOMIQUE, CLIMATIQUE, ENVIRONNEMENTAL, INSTITUTIONNEL }
[ "dossou.israel48@gmail.com" ]
dossou.israel48@gmail.com
3f71d9c05f54756891368a1bfaa6ebb7fb947dd9
eaee5cfb2079f2597156e62b978849c7ae18de47
/jdk/src/main/java/org/omg/IOP/CodecFactoryPackage/UnknownEncodingHelper.java
df55c9dbaee82d9623eeec735fd527527bdd56cc
[ "Apache-2.0" ]
permissive
dibt/spring-framework
b3a9895974e6a2708b2681e0ed0045c409242461
ce2dfa68e2331a07d36bdcf7aa92597c91a391ee
refs/heads/master
2023-01-23T04:12:50.868839
2020-11-19T12:51:40
2020-11-19T12:51:40
262,491,183
1
0
null
null
null
null
UTF-8
Java
false
false
2,336
java
package org.omg.IOP.CodecFactoryPackage; /** * org/omg/IOP/CodecFactoryPackage/UnknownEncodingHelper.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u191/11896/corba/src/share/classes/org/omg/PortableInterceptor/IOP.idl * Saturday, October 6, 2018 8:38:58 AM PDT */ abstract public class UnknownEncodingHelper { private static String _id = "IDL:omg.org/IOP/CodecFactory/UnknownEncoding:1.0"; public static void insert (org.omg.CORBA.Any a, org.omg.IOP.CodecFactoryPackage.UnknownEncoding that) { org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); a.type (type ()); write (out, that); a.read_value (out.create_input_stream (), type ()); } public static org.omg.IOP.CodecFactoryPackage.UnknownEncoding extract (org.omg.CORBA.Any a) { return read (a.create_input_stream ()); } private static org.omg.CORBA.TypeCode __typeCode = null; private static boolean __active = false; synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { synchronized (org.omg.CORBA.TypeCode.class) { if (__typeCode == null) { if (__active) { return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); } __active = true; org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; org.omg.CORBA.TypeCode _tcOf_members0 = null; __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper.id (), "UnknownEncoding", _members0); __active = false; } } } return __typeCode; } public static String id () { return _id; } public static org.omg.IOP.CodecFactoryPackage.UnknownEncoding read (org.omg.CORBA.portable.InputStream istream) { org.omg.IOP.CodecFactoryPackage.UnknownEncoding value = new org.omg.IOP.CodecFactoryPackage.UnknownEncoding (); // read and discard the repository ID istream.read_string (); return value; } public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.IOP.CodecFactoryPackage.UnknownEncoding value) { // write the repository ID ostream.write_string (id ()); } }
[ "dibenteng@hzsuidifu.com" ]
dibenteng@hzsuidifu.com
06e927bcc1568c80d3a9b713e88f8c1e9a33ea93
6dde7a7984de7b42d0614d20af6d7d527af323b7
/raf/android/android/src/com/jamescho/game/state/State.java
5049a1616e5a89a974515b2cd5d07e34119a03ae
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
randyzingle/javaalg
6ee0eb42196ef819a7e1afeb02af46e0587e6577
e7c70935f6db20be9b86e599cf373daa107c971a
refs/heads/master
2021-06-09T07:43:01.135183
2017-06-03T17:59:34
2017-06-03T17:59:34
16,564,750
0
1
null
2014-10-28T20:12:03
2014-02-06T01:13:47
JavaScript
UTF-8
Java
false
false
511
java
package com.jamescho.game.state; import android.view.MotionEvent; import com.jamescho.framework.util.Painter; import com.jamescho.simpleandroidgdf.GameMainActivity; public abstract class State { public void setCurrentState(State newState) { GameMainActivity.sGame.setCurrentState(newState); } public abstract void init(); public abstract void update(float delta); public abstract void render(Painter g); public abstract boolean onTouch(MotionEvent e, int scaledX, int scaledY); }
[ "randy.zingle@gmail.com" ]
randy.zingle@gmail.com
ef4f844c345ced793c7d33bef4cf660183bd20da
affab296672a5dd6717d1a57f44e2c43cb10ef9c
/src/environment/Area.java
afefa10caa9e829a0600cd8fb88394dbd9bd0fb3
[]
no_license
AxBS/RoadSimTruck
c79e3d82da7962e98c80fbfdc647b985fa421a05
f319d5175e0dfae67492b44bc2a4fdd64edb01b5
refs/heads/master
2021-03-27T21:25:54.491558
2017-11-14T08:54:06
2017-11-14T08:54:06
109,815,818
0
0
null
null
null
null
UTF-8
Java
false
false
2,856
java
package environment; import agents.AreaAgent; import jade.wrapper.AgentController; import jade.wrapper.StaleProxyException; public class Area { //Location of the Area private int locationX, locationY; private float locationPK; private Segment locationSegment; //Capacity private int capacity; //Area Info private String id; //Variable to draw the GUI private boolean drawGUI; //The container where the agents will be created @SuppressWarnings("unused") private transient jade.wrapper.AgentContainer areaContainer; //Area agent representing the area private AreaAgent areaAgent; public Area(int locationX, int locationY, float locationPK, Segment locationSegment, int capacity, String id, jade.wrapper.AgentContainer areaContainer ) { this.locationX = locationX; this.locationY = locationY; this.locationPK = locationPK; this.locationSegment = locationSegment; this.capacity = capacity; this.id = id; this.areaContainer = areaContainer; //Create the agents try { //Agent Controller to segments with Interface AgentController agent = areaContainer.createNewAgent( this.id, "agents.AreaAgent", new Object[]{this, this.drawGUI}); agent.start(); } catch (StaleProxyException e) { System.out.println("Error starting " + this.id); e.printStackTrace(); } } public Area() { this.locationX = 0; this.locationY = 0; this.locationPK = 0.0f; this.locationSegment = new Segment(); this.capacity = 0; this.id = "defaultID"; } public int getLocationX() { return locationX; } public void setLocationX(int locationX) { this.locationX = locationX; } public int getLocationY() { return locationY; } public void setLocationY(int locationY) { this.locationY = locationY; } public float getLocationPK() { return locationPK; } public void setLocationPK(float locationPK) { this.locationPK = locationPK; } public Segment getLocationSegment() { return locationSegment; } public void setLocationSegment(Segment locationSegment) { this.locationSegment = locationSegment; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public String getId() { return id; } public void setId(String id) { this.id = id; } public boolean isDrawGUI() { return drawGUI; } public void setDrawGUI(boolean drawGUI) { this.drawGUI = drawGUI; } public AreaAgent getAreaAgent() { return areaAgent; } public void setAreaAgent(AreaAgent areaAgent) { this.areaAgent = areaAgent; } @Override public String toString() { return "Area [locationX=" + locationX + ", locationY=" + locationY + ", locationPK=" + locationPK + ", locationSegment=" + locationSegment + ", capacity=" + capacity + ", id=" + id + "]"; } }
[ "alexbeltransist@MacBook-Pro-de-Alex.local" ]
alexbeltransist@MacBook-Pro-de-Alex.local
53e356b19d590b8776c0180f26944cbfcbeab2f5
2d877a1dc8fe7ff343c4320db8d492d23aae0b2f
/src/Display.java
1a6928445247df159a1b321cbce518103b9d3343
[]
no_license
sbeuhatsxb/chess_java
f7f5dcd7c6e9b6cc8423b71f5cfa5248676d17cd
7da2f1fcf9e80e7e5f1705a3571b167214af636f
refs/heads/main
2023-02-13T00:32:49.791486
2020-12-16T15:25:34
2020-12-16T15:25:34
320,584,195
0
0
null
null
null
null
UTF-8
Java
false
false
5,222
java
import Board.Chessboard; import Board.Square; public interface Display { static final String ANSI_RESET = "\u001B[0m"; static final String ANSI_BLACK = "\u001B[30m"; static final String ANSI_RED = "\u001B[31m"; static final String ANSI_GREEN = "\u001B[32m"; static final String ANSI_YELLOW = "\u001B[33m"; static final String ANSI_BLUE = "\u001B[34m"; static final String ANSI_PURPLE = "\u001B[35m"; static final String ANSI_CYAN = "\u001B[36m"; static final String ANSI_WHITE = "\u001B[37m"; static void displayChessBoard(Chessboard chessboard){ int fullTabsize = 43; System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); int i = 0; for (Square square : chessboard.getSquares()) { String pieceName = ""; String shortName = " "; String pieceColor = ""; String displayPieceColor = ""; if(square.getHasPiece()){ pieceName = square.getPiece().getName(); if(square.getPiece().getColor()){ pieceColor = "White"; } else { pieceColor = "Black"; } shortName = square.getPiece().getShortname(); displayPieceColor = pieceColor.substring(0, 1).toLowerCase(); } i++; if(pieceColor == "Black"){ System.out.print( " | " + ANSI_RED + shortName + displayPieceColor + ANSI_RESET ); } else { System.out.print( " | " + ANSI_YELLOW + shortName + displayPieceColor + ANSI_RESET ); } if(i%8 == 0){ System.out.print( " | " ); System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); } } } //DEBUG CHESSBOARD static void displayChessBoard2(Chessboard chessboard){ int fullTabsize = 43; System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); int i = 0; for (Square square : chessboard.getSquares()) { String pieceName = ""; String shortName = " "; String pieceColor = ""; String displayPieceColor = ""; if(square.getHasPiece()){ pieceName = square.getPiece().getName(); if(square.getPiece().getColor()){ pieceColor = "White"; } else { pieceColor = "Black"; } shortName = square.getPiece().getShortname(); displayPieceColor = pieceColor.substring(0, 1).toLowerCase(); } i++; if(pieceColor == "Black"){ System.out.print( " | " + ANSI_RED + /* square.getId() + " * " + square.getLocation()[0] + square.getLocation()[1] + " * " + */ square.getReadablePos() +ANSI_RESET ); } else { System.out.print( " | " + ANSI_YELLOW + /* square.getId() + " * " + square.getLocation()[0] + square.getLocation()[1] + " * " + */ square.getReadablePos() + ANSI_RESET ); } if(i%8 == 0){ System.out.print( " | " ); System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); } } } //DEBUG PIECES static void displayChessBoard3(Chessboard chessboard){ int fullTabsize = 43; System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); int i = 0; for (Square square : chessboard.getSquares()) { String pieceName = ""; String shortName = " "; String pieceColor = ""; String displayPieceColor = ""; if(square.getHasPiece()){ pieceName = square.getPiece().getName(); if(square.getPiece().getColor()){ pieceColor = "White"; } else { pieceColor = "Black"; } shortName = square.getPiece().getShortname(); displayPieceColor = pieceColor.substring(0, 1).toLowerCase(); } i++; if(pieceColor == "Black"){ System.out.print( " | " + ANSI_RED + square.getPiece().getPosition() +ANSI_RESET ); } else { if(square.getPiece() != null){ System.out.print( " | " + ANSI_YELLOW + square.getPiece().getPosition() + ANSI_RESET ); } } if(i%8 == 0){ System.out.print( " | " ); System.out.println( "\n" + Pad.padHyphen("-", fullTabsize) ); } } } }
[ "mail2sbeuh@gmail.com" ]
mail2sbeuh@gmail.com
7b0d9c3170028e23fa1a3622132076757c728d32
132a00d1fdcfaea40df8493bbfa63611bdb61af9
/src/main/java/com/uIFrameWork/companyName/projectNmae/hepler/browserConfigaration/FirefoxBrowser.java
c28a20aeca0948bac07f23c27dd25b813a77ca67
[]
no_license
someone369/Pom-Practice
720dc05eb9799e45f56fbacf06cf9aa9ce7f04e7
73f85e69aecd6210afa94e5497959e030f7cbdbb
refs/heads/master
2023-08-09T00:44:44.033396
2019-12-05T18:44:50
2019-12-05T18:44:50
226,090,971
0
0
null
2023-07-22T23:32:40
2019-12-05T11:53:22
HTML
UTF-8
Java
false
false
1,912
java
package com.uIFrameWork.companyName.projectNmae.hepler.browserConfigaration; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.DesiredCapabilities; import com.uIFrameWork.companyName.projectNmae.hepler.resource.ResourecHelper; public class FirefoxBrowser { public FirefoxOptions getFirefoxOptions() { DesiredCapabilities firefox = DesiredCapabilities.firefox(); FirefoxProfile profile = new FirefoxProfile(); profile.setAcceptUntrustedCertificates(true); profile.setAssumeUntrustedCertificateIssuer(true); firefox.setCapability(FirefoxDriver.PROFILE, profile); firefox.setCapability("marionette", true); FirefoxOptions firefoxOptions = new FirefoxOptions(); // Linux if (System.getProperty("os.name").contains("Linux")) { firefoxOptions.addArguments("--headless", "window-size=1024,768", "--no-sandbox"); } return firefoxOptions; } public WebDriver getFirefoxDriver(FirefoxOptions cap) { if (System.getProperty("os.name").contains("Mac")) { System.setProperty("webdriver.gecko.driver",ResourecHelper.getResourcePath("/Driverss/geckodriver")); return new FirefoxDriver(cap); } else if (System.getProperty("os.name").contains("Window")) { System.setProperty("webdriver.gecko.driver",ResourecHelper.getResourcePath("/Driverss/geckodriver.exe")); return new FirefoxDriver(cap); } else if (System.getProperty("os.name").contains("Linux")) { System.setProperty("webdriver.gecko.driver", "/usr/bin/geckodriver"); return new FirefoxDriver(cap); } return null; } public static void main(String[] args) { FirefoxBrowser obj = new FirefoxBrowser(); WebDriver driver = obj.getFirefoxDriver(obj.getFirefoxOptions()); driver.get("https://www.bankofamerica.com/"); } }
[ "useforoverall@gmail.com" ]
useforoverall@gmail.com
ebd0cf49f4f0dc2c5265eccf73df0e1492927b28
d84b812db1dc550f70739e7bd4ef5ee052f8d9ed
/day21/src/cn/itcast/listener/HttpSessionDemoListener.java
9e87983f987abe06c7b68acc71f4ae382e31c5bf
[]
no_license
acuteMouse/repo
a29f5a454d99047de85ec7cd3f65697d9def851a
7b8dadc3e4472a1c0991226fe8a55ab1de1429ba
refs/heads/master
2020-04-02T13:19:39.512638
2016-06-11T11:04:12
2016-06-11T11:04:12
60,902,565
0
0
null
null
null
null
GB18030
Java
false
false
577
java
package cn.itcast.listener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class HttpSessionDemoListener implements HttpSessionListener { //HttpSession对象被创建时调用 public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println(session+"被创建了"); } public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println(session+"被销毁了"); } }
[ "1012592349@qq.com" ]
1012592349@qq.com
4f229722aa08c7dfb2d832a1d0766417382831b1
87a968d52caff01460e8e6266f31b4b5d74fc7e2
/helper/src/main/java/com/wings/helper/GooglePlaceAPIHelper.java
63c8d55aaa7427e9f840029a3972c57a292f5241
[]
no_license
TestWts2017/android-helper
8176aa34c8994f653095e1979c3e22ae7b4a989a
a53b608dbec69e0ecdc3322fee4bacb652242792
refs/heads/master
2020-04-22T20:12:26.285982
2019-06-26T13:50:28
2019-06-26T13:50:28
170,633,643
1
0
null
null
null
null
UTF-8
Java
false
false
12,905
java
package com.wings.helper; import android.content.Context; import android.location.Location; import android.location.LocationManager; import com.google.android.gms.common.api.Status; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.net.PlacesClient; import com.google.android.libraries.places.widget.AutocompleteSupportFragment; import com.google.android.libraries.places.widget.listener.PlaceSelectionListener; import com.wings.utils.HttpHandler; import org.json.JSONArray; import org.json.JSONObject; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Purpose: Google GeoCoding, Reverse GeoCoding, Place AutoComplete, Direction & Place API * * @author HetalD * Created On June 26,2019 * Modified On June 26,2019 */ public class GooglePlaceAPIHelper { /** * Google GeoCoding API - Get Address From Latitude & Longitude * * @param address Address to get Latitude & Longitude * @param API_KEY Google Authorized API KEY * @return List of latitude & longitude */ public static Location getLatLngFromAddress(final String address, final String API_KEY) { final Location location = new Location(LocationManager.NETWORK_PROVIDER); location.setLatitude(0.0); location.setLongitude(0.0); Thread thread = new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?" + "address=" + address + "&key=" + API_KEY); HttpHandler handler = new HttpHandler(); String jsonStr = handler.makeServiceCall(String.valueOf(url)); if (jsonStr != null) { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonObject.getJSONArray("results"); if (jsonArray != null && jsonArray.length() > 0) { JSONObject geometryObject = jsonArray.getJSONObject(2).getJSONObject("geometry"); if (geometryObject != null) { JSONObject locationObject = geometryObject.getJSONObject("location"); double lat = locationObject.getDouble("lat"); double lng = locationObject.getDouble("lng"); location.setLatitude(lat); location.setLongitude(lng); //String lat_lng = "Lat: " + lat + "\n" + "Long: " + lng; } } } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return location; } /** * Google Reverse GeoCoding API - Get Latitude & Longitude From Address * * @param latitude Double latitude * @param longitude Double longitude * @param API_KEY Google Authorized API KEY * @return String[] address */ public static String getAddressFromLatLng(final double latitude, final double longitude, final String API_KEY) { final List<Double> list = new ArrayList<>(); final String[] formatted_address = new String[1]; Thread thread = new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=" + latitude + "," + longitude + "&key=" + API_KEY); HttpHandler handler = new HttpHandler(); String jsonStr = handler.makeServiceCall(String.valueOf(url)); if (jsonStr != null) { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray latlngArray = jsonObject.getJSONArray("results"); if (latlngArray != null && latlngArray.length() > 0) { JSONObject addressObj = latlngArray.getJSONObject(1); formatted_address[0] = addressObj.getString("formatted_address"); } } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } String address = ""; if (formatted_address[0] != null) { address = formatted_address[0]; } return address; } /** * Google Place AutoComplete API * * @param context context to activity * @param API_KEY Google Authorized API KEY * @param autocompleteSupportFragment AutocompleteSupportFragment to search * @return String of Place ID & Place Name */ public static String getPlaceAutoComplete(Context context, String API_KEY, AutocompleteSupportFragment autocompleteSupportFragment) { final String[] place_str = new String[1]; Places.initialize(context, API_KEY); PlacesClient placesClient = Places.createClient(context); if (autocompleteSupportFragment != null) { autocompleteSupportFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME)); autocompleteSupportFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // TODO: Get info about the selected place. // textView.setText(place.getName()+","+place.getId()); // Log.i(TAG, "Place: " + place.getName() + ", " + place.getId()); place_str[0] = place.getName() + "," + place.getId(); } @Override public void onError(Status status) { // TODO: Handle the error. //Log.i(TAG, "An error occurred: " + status); } }); } String places = ""; if (place_str[0] != null) { places = place_str[0]; } return places; } /** * Google Direction API - Get direction between two locations (Ex: turn left,turn right...) * * @param sourceAddress Source address * @param destinationAddress Destination address * @param API_KEY Google Authorized API KEY * @return List of direction points */ public static List<Object> getDirectionBetweenTwoLocation(final String sourceAddress, final String destinationAddress, final String API_KEY) { final List<String> list = new ArrayList<>(); final List<Object> directionList = new ArrayList<>(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("https://maps.googleapis.com/maps/api/directions/json?" + "origin=" + sourceAddress + "&destination=" + destinationAddress + "&key=" + API_KEY); HttpHandler handler = new HttpHandler(); String jsonStr = handler.makeServiceCall(String.valueOf(url)); if (jsonStr != null) { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonObject.getJSONArray("routes"); if (jsonArray != null && jsonArray.length() > 0) { JSONArray legsObject = jsonArray.getJSONObject(2).getJSONArray("legs"); if (legsObject != null) { JSONArray stepsArray = legsObject.getJSONObject(6).getJSONArray("steps"); if (stepsArray != null && stepsArray.length() > 0) { for (int i = 1; i < stepsArray.length(); i++) { JSONObject object = stepsArray.getJSONObject(i); System.out.println("response1" + object); String maneuver = object.getString("maneuver"); list.add(maneuver); } directionList.addAll(list); } } } } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return directionList; } /** * Google Place API - Get mid locations between two locations * * @param sourceAddress Source address * @param destinationAddress Destination address * @param API_KEY Google Authorized API KEY * @return List of mid location points */ public static List<Object> getMidLocationBetweenTwoLocation(final String sourceAddress, final String destinationAddress, final String API_KEY) { final List<String> list = new ArrayList<>(); final List<Object> midPointList = new ArrayList<>(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("https://maps.googleapis.com/maps/api/directions/json?" + "origin=" + sourceAddress + "&destination=" + destinationAddress + "&key=" + API_KEY); HttpHandler handler = new HttpHandler(); String jsonStr = handler.makeServiceCall(String.valueOf(url)); if (jsonStr != null) { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonObject.getJSONArray("routes"); System.out.println("response:" + jsonArray); if (jsonArray != null && jsonArray.length() > 0) { JSONArray legsObject = jsonArray.getJSONObject(2).getJSONArray("legs"); if (legsObject != null) { JSONArray stepsArray = legsObject.getJSONObject(6).getJSONArray("steps"); if (stepsArray != null && stepsArray.length() > 0) { for (int i = 0; i < stepsArray.length(); i++) { JSONObject object = stepsArray.getJSONObject(i); if (object.has("end_location")) { JSONObject end_locationObject = object.getJSONObject("end_location"); double lat = end_locationObject.getDouble("lat"); double lng = end_locationObject.getDouble("lng"); URL lat_lng_url = new URL("https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=" + lat + "," + lng + "&key=" + API_KEY); JSONObject latlngObject = new JSONObject(String.valueOf(lat_lng_url)); JSONArray latlngArray = latlngObject.getJSONArray("results"); if (latlngArray != null && latlngArray.length() > 0) { JSONObject addressObj = latlngArray.getJSONObject(1); String formatted_address = addressObj.getString("formatted_address"); list.add(formatted_address); } } } midPointList.addAll(list); } } } } } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return midPointList; } }
[ "nikunj.d@wingstechsolutions.com" ]
nikunj.d@wingstechsolutions.com
f5d503817ac48231e978433625931dbf19038eb6
bca7b600b411cc0e95e8dd32cfdbcf7cd3f66c13
/module2/CasestudyModule2/src/controllers/_2_customer_menu/AddCustomer.java
c701d81bcd66c9e7e0d54e9956ce268a4dec3342
[]
no_license
NguyenVanTien99/A0920I1-NguyenVanTien
57136c82fa9ee0ae489d7bc261ec8e18159cf6f0
2d8db1f2efd9607959b057e601a10a94ced1deae
refs/heads/master
2023-04-22T11:02:57.029353
2021-05-17T13:00:01
2021-05-17T13:00:01
297,355,109
0
0
null
null
null
null
UTF-8
Java
false
false
3,825
java
package controllers._2_customer_menu; import Validation.RegularException; import commons.FileUntil; import controllers.file.ReadFile; import exceptions.CustomerInformationException; import exceptions.DateOfBirthExcetion; import models.Customer; import java.util.Scanner; public class AddCustomer { public static Scanner scanner = new Scanner(System.in); public static void addNewCustomer(){ boolean flag; String fullName; String dateOfBirth; String gender; String idCard; String phoneNumber; String email; String customerType; do { flag = true; System.out.println("Enter the full name Customer"); fullName = scanner.nextLine(); try { RegularException.validateNameCustomer(fullName); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); do { flag = true; System.out.println("Enter the date of birth"); dateOfBirth = scanner.nextLine(); try { RegularException.validateDateOfBirth(dateOfBirth); } catch (DateOfBirthExcetion e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); do { flag = true; System.out.println("Enter the Gender"); gender = scanner.nextLine(); try { RegularException.validateGender(gender.toLowerCase()); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); do { flag = true; System.out.println("Enter the number of id Card"); idCard = scanner.nextLine(); try { RegularException.validateIdCard(idCard); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); do { flag = true; System.out.println("Enter the phone number"); phoneNumber = scanner.nextLine(); try { RegularException.validatePhoneNumber(phoneNumber); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); do { flag = true; System.out.println("Enter the Email"); email = scanner.nextLine(); try { RegularException.validateEmail(email); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); System.out.println("Enter the address"); String address = scanner.nextLine(); do { flag = true; System.out.println("Enter the type of Customer"); customerType = scanner.nextLine(); try { RegularException.validateCustomerType(customerType); } catch (CustomerInformationException e) { System.out.println(e.getMessage()); flag = false; } }while (!flag); Customer customer = new Customer(fullName, dateOfBirth, gender, idCard, phoneNumber , email, address, customerType); String line = customer.addInformationCustomerCsv(); FileUntil.writeInFile(ReadFile.PATH_FILE_CUSTOMER, line); System.out.println("SUCCESS"); } }
[ "tienvng99@gmail.com" ]
tienvng99@gmail.com
e7394759d60d5445dfb2a23809b1920a27049c38
f215fbacb48efce2962e5b30abc7e53e003ffa41
/DiscreteMathLabs/DiscreteMathLab2/src/Interval.java
0c7d48dc75b5c209fe2e5f737da4c5bb0de5791d
[]
no_license
PAKETA-0629/Labs
2757a216a6983441d602f596e993b0c76f1b7ffc
82929bdd1987c1ebc32f11ad6d08d737b45380bb
refs/heads/main
2023-08-19T18:41:06.954501
2021-10-26T16:04:18
2021-10-26T16:04:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
116
java
import java.math.BigDecimal; public class Interval { BigDecimal left; BigDecimal right; char aChar; }
[ "kyrylo0629@gmail.com" ]
kyrylo0629@gmail.com
99724ca184b6503a333e4b126373886e1b957d8d
3e431bc12d680417c3d1a14785b2dffb9215ca7e
/src/main/java/com/wonhwee/service/ExerciseServiceImpl.java
6d221cd83840dffa02b3a605408fcc80323dd66c
[]
no_license
wonhweeloh/mvcjpa01
93685d872f5147f4d6a11e28e85d32fdad675d56
4bf842d73bb1c8a4fc9112cfe0645205d238f19d
refs/heads/master
2021-01-02T09:06:39.643439
2017-08-02T17:26:02
2017-08-02T17:26:02
99,143,394
0
0
null
null
null
null
UTF-8
Java
false
false
1,034
java
package com.wonhwee.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wonhwee.model.Activity; import com.wonhwee.model.Exercise; import com.wonhwee.repository.ExerciseRepository; @Service("exerciseService") public class ExerciseServiceImpl implements ExerciseService { @Autowired private ExerciseRepository exerciseRepository; @Override public List<Activity> findAllActivities() { List<Activity> activities = new ArrayList<Activity>(); Activity run = new Activity(); run.setDesc("Run"); Activity bike = new Activity(); bike.setDesc("Bike"); Activity swim = new Activity(); swim.setDesc("Swim"); activities.add(run); activities.add(bike); activities.add(swim); return activities; } @Override public Exercise save(Exercise exercise) { exercise = exerciseRepository.save(exercise); return exercise; } }
[ "wonhweeloh@gmail.com" ]
wonhweeloh@gmail.com
f5a64fb0dfbf388237117ca9e634ae16352de878
cac784e1f57ee36e37f9c0aa3005efffa04163f2
/src/Package1/DataProvider1.java
aefcf9e1c41ca8cdc8d631c4f2622f56d2bdd3f6
[]
no_license
Clement211992/ClementRepo
dcfd7a67ab92f849709ed1c61c8c9b04bd001f46
ac478af00418a57213e2f255d32a07c980c85206
refs/heads/master
2021-09-11T13:14:31.848659
2018-04-07T12:41:19
2018-04-07T12:41:19
107,407,338
0
0
null
null
null
null
UTF-8
Java
false
false
989
java
package Package1; import org.testng.annotations.*; import org.testng.annotations.Test; @Test(suiteName="G") public class DataProvider1 { /* @Test(dataProvider = "DataSetA") public void TestA(String Row, String Col) { System.out.println(Row +" "+ Col); } @Test(dataProvider = "DataSetC") public void TestC(String Row, String Col) { System.out.println(Row +" "+ Col); } */ @Test(dataProvider = "Dataset", dataProviderClass = TestNG_Data.class,expectedExceptions=RuntimeException.class) public void TestB(String row, String col) { //System.out.println("Second:"+row+" "+col); throw new RuntimeException(); } @DataProvider(name="DataSetA") public Object[][] DataSetA(){ return new Object[][] { {"A11","A12"}, {"B11","B12"}, {"C11","C12"} }; } @DataProvider(name="DataSetC") public Object[][] DataSetC(){ return new Object[][] { {"c11","c12"}, {"c21","c22"}, {"C31","C32"} }; } }
[ "leodinesh21@gmail.com" ]
leodinesh21@gmail.com
5ec78a097cbb996c3aa9e3b148c040d5d4b0e53c
c885ef92397be9d54b87741f01557f61d3f794f3
/tests-without-trycatch/Time-3/org.joda.time.MutableDateTime/BBC-F0-opt-50/30/org/joda/time/MutableDateTime_ESTest_scaffolding.java
0f217f3c28dbd9ec13bde3510b743d4bf01f6d6b
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
22,651
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Sun Oct 24 03:01:40 GMT 2021 */ package org.joda.time; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; import static org.evosuite.shaded.org.mockito.Mockito.*; @EvoSuiteClassExclude public class MutableDateTime_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "org.joda.time.MutableDateTime"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {} } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("user.timezone", "Etc/UTC"); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MutableDateTime_ESTest_scaffolding.class.getClassLoader() , "org.joda.time.DateTimeZone", "org.joda.time.format.DateTimeFormatterBuilder$StringLiteral", "org.joda.time.tz.DateTimeZoneBuilder$Recurrence", "org.joda.time.format.ISODateTimeFormat$Constants", "org.joda.time.convert.ReadablePartialConverter", "org.joda.time.DateTimeUtils$MillisProvider", "org.joda.time.DateTimeUtils$OffsetMillisProvider", "org.joda.time.convert.Converter", "org.joda.time.chrono.GJYearOfEraDateTimeField", "org.joda.time.convert.PartialConverter", "org.joda.time.Seconds", "org.joda.time.field.RemainderDateTimeField", "org.joda.time.JodaTimePermission", "org.joda.time.chrono.BasicWeekOfWeekyearDateTimeField", "org.joda.time.field.StrictDateTimeField", "org.joda.time.DateTimeFieldType", "org.joda.time.convert.ConverterSet$Entry", "org.joda.time.format.DateTimeFormatterBuilder$Fraction", "org.joda.time.format.DateTimeFormatterBuilder$FixedNumber", "org.joda.time.DateTimeFieldType$StandardDateTimeFieldType", "org.joda.time.MutableDateTime$Property", "org.joda.time.chrono.BasicChronology$HalfdayField", "org.joda.time.ReadableInterval", "org.joda.time.chrono.LimitChronology$LimitDateTimeField", "org.joda.time.chrono.BasicChronology$YearInfo", "org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone", "org.joda.time.field.UnsupportedDurationField", "org.joda.time.field.LenientDateTimeField", "org.joda.time.base.AbstractDateTime", "org.joda.time.field.SkipUndoDateTimeField", "org.joda.time.convert.AbstractConverter", "org.joda.time.format.PeriodFormatterBuilder", "org.joda.time.format.DateTimePrinter", "org.joda.time.chrono.ISOChronology", "org.joda.time.base.BaseLocal", "org.joda.time.field.DelegatedDateTimeField", "org.joda.time.chrono.BasicChronology", "org.joda.time.chrono.LenientChronology", "org.joda.time.chrono.BasicYearDateTimeField", "org.joda.time.format.PeriodFormatterBuilder$FieldFormatter", "org.joda.time.field.DividedDateTimeField", "org.joda.time.convert.DateConverter", "org.joda.time.chrono.ZonedChronology", "org.joda.time.format.DateTimeFormatterBuilder$TimeZoneOffset", "org.joda.time.field.BaseDateTimeField", "org.joda.time.field.ZeroIsMaxDateTimeField", "org.joda.time.format.DateTimeFormatterBuilder", "org.joda.time.base.BaseInterval", "org.joda.time.chrono.EthiopicChronology", "org.joda.time.tz.CachedDateTimeZone$Info", "org.joda.time.Duration", "org.joda.time.format.FormatUtils", "org.joda.time.format.PeriodFormatter", "org.joda.time.PeriodType", "org.joda.time.field.MillisDurationField", "org.joda.time.chrono.GJChronology", "org.joda.time.Interval", "org.joda.time.convert.LongConverter", "org.joda.time.chrono.IslamicChronology", "org.joda.time.base.AbstractInstant", "org.joda.time.chrono.BasicFixedMonthChronology", "org.joda.time.tz.DateTimeZoneBuilder", "org.joda.time.format.DateTimeParserBucket", "org.joda.time.field.UnsupportedDateTimeField", "org.joda.time.field.ScaledDurationField", "org.joda.time.chrono.ISOYearOfEraDateTimeField", "org.joda.time.ReadWritablePeriod", "org.joda.time.convert.ConverterSet", "org.joda.time.field.PreciseDurationDateTimeField", "org.joda.time.LocalDateTime", "org.joda.time.MutablePeriod", "org.joda.time.MutableDateTime", "org.joda.time.tz.FixedDateTimeZone", "org.joda.time.base.BasePeriod$1", "org.joda.time.convert.IntervalConverter", "org.joda.time.format.PeriodPrinter", "org.joda.time.field.PreciseDateTimeField", "org.joda.time.tz.CachedDateTimeZone", "org.joda.time.chrono.LimitChronology$LimitException", "org.joda.time.ReadableDateTime", "org.joda.time.format.PeriodFormatterBuilder$Literal", "org.joda.time.convert.ReadableDurationConverter", "org.joda.time.format.PeriodParser", "org.joda.time.DateMidnight", "org.joda.time.base.BaseDuration", "org.joda.time.field.DecoratedDateTimeField", "org.joda.time.Months", "org.joda.time.YearMonthDay", "org.joda.time.format.DateTimeParser", "org.joda.time.format.DateTimeFormatterBuilder$CharacterLiteral", "org.joda.time.chrono.GJChronology$CutoverField", "org.joda.time.convert.DurationConverter", "org.joda.time.field.OffsetDateTimeField", "org.joda.time.DateTime$Property", "org.joda.time.convert.ReadablePeriodConverter", "org.joda.time.chrono.GJMonthOfYearDateTimeField", "org.joda.time.Years", "org.joda.time.format.DateTimeParserBucket$SavedState", "org.joda.time.convert.ReadableIntervalConverter", "org.joda.time.chrono.BasicWeekyearDateTimeField", "org.joda.time.Days", "org.joda.time.DateTimeField", "org.joda.time.field.FieldUtils", "org.joda.time.format.DateTimeFormatterBuilder$MatchingParser", "org.joda.time.chrono.BasicSingleEraDateTimeField", "org.joda.time.format.DateTimeFormat", "org.joda.time.format.ISODateTimeFormat", "org.joda.time.field.SkipDateTimeField", "org.joda.time.chrono.LimitChronology", "org.joda.time.base.AbstractPeriod", "org.joda.time.ReadableInstant", "org.joda.time.chrono.GJDayOfWeekDateTimeField", "org.joda.time.base.BaseSingleFieldPeriod", "org.joda.time.DateTimeUtils$SystemMillisProvider", "org.joda.time.IllegalInstantException", "org.joda.time.IllegalFieldValueException", "org.joda.time.convert.NullConverter", "org.joda.time.tz.DefaultNameProvider", "org.joda.time.format.DateTimeFormatterBuilder$Composite", "org.joda.time.format.DateTimeFormatterBuilder$UnpaddedNumber", "org.joda.time.tz.Provider", "org.joda.time.field.ImpreciseDateTimeField$LinkedDurationField", "org.joda.time.ReadablePeriod", "org.joda.time.chrono.ZonedChronology$ZonedDateTimeField", "org.joda.time.chrono.AssembledChronology$Fields", "org.joda.time.chrono.GregorianChronology", "org.joda.time.DurationFieldType", "org.joda.time.ReadWritableInstant", "org.joda.time.convert.ConverterManager", "org.joda.time.tz.NameProvider", "org.joda.time.chrono.GJChronology$LinkedDurationField", "org.joda.time.Minutes", "org.joda.time.format.DateTimeFormatterBuilder$PaddedNumber", "org.joda.time.chrono.BasicMonthOfYearDateTimeField", "org.joda.time.base.AbstractPartial", "org.joda.time.base.BasePartial", "org.joda.time.base.BaseDateTime", "org.joda.time.base.AbstractDuration", "org.joda.time.DateTimeUtils", "org.joda.time.LocalTime", "org.joda.time.base.AbstractInterval", "org.joda.time.Hours", "org.joda.time.convert.ReadableInstantConverter", "org.joda.time.convert.StringConverter", "org.joda.time.base.BasePeriod", "org.joda.time.field.DecoratedDurationField", "org.joda.time.tz.DateTimeZoneBuilder$DSTZone", "org.joda.time.convert.InstantConverter", "org.joda.time.chrono.AssembledChronology", "org.joda.time.format.DateTimeFormat$1", "org.joda.time.TimeOfDay", "org.joda.time.format.ISOPeriodFormat", "org.joda.time.chrono.GJEraDateTimeField", "org.joda.time.tz.ZoneInfoProvider", "org.joda.time.DateTimeZone$1", "org.joda.time.chrono.BaseChronology", "org.joda.time.chrono.JulianChronology", "org.joda.time.field.ImpreciseDateTimeField", "org.joda.time.chrono.CopticChronology", "org.joda.time.field.PreciseDurationField", "org.joda.time.DateTimeUtils$FixedMillisProvider", "org.joda.time.Period", "org.joda.time.tz.DateTimeZoneBuilder$OfYear", "org.joda.time.ReadableDuration", "org.joda.time.chrono.BasicGJChronology", "org.joda.time.format.DateTimeFormatterBuilder$NumberFormatter", "org.joda.time.format.DateTimeFormatter", "org.joda.time.DurationField", "org.joda.time.Weeks", "org.joda.time.chrono.IslamicChronology$LeapYearPatternType", "org.joda.time.Chronology", "org.joda.time.DateTime", "org.joda.time.format.PeriodFormatterBuilder$Composite", "org.joda.time.field.AbstractReadableInstantFieldProperty", "org.joda.time.format.PeriodFormatterBuilder$PeriodFieldAffix", "org.joda.time.format.PeriodFormatterBuilder$SimpleAffix", "org.joda.time.LocalDate", "org.joda.time.format.DateTimeParserBucket$SavedField", "org.joda.time.ReadWritableDateTime", "org.joda.time.chrono.BasicDayOfMonthDateTimeField", "org.joda.time.convert.PeriodConverter", "org.joda.time.chrono.ZonedChronology$ZonedDurationField", "org.joda.time.Instant", "org.joda.time.convert.CalendarConverter", "org.joda.time.format.PeriodFormatterBuilder$Separator", "org.joda.time.ReadablePartial", "org.joda.time.chrono.LimitChronology$LimitDurationField", "org.joda.time.chrono.BasicDayOfYearDateTimeField", "org.joda.time.chrono.GJChronology$ImpreciseCutoverField", "org.joda.time.DurationFieldType$StandardDurationFieldType", "org.joda.time.field.BaseDurationField", "org.joda.time.chrono.BuddhistChronology" ); } private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { mock(Class.forName("org.joda.time.DateTimeUtils$MillisProvider", false, MutableDateTime_ESTest_scaffolding.class.getClassLoader())); mock(Class.forName("org.joda.time.format.DateTimeParser", false, MutableDateTime_ESTest_scaffolding.class.getClassLoader())); mock(Class.forName("org.joda.time.format.DateTimePrinter", false, MutableDateTime_ESTest_scaffolding.class.getClassLoader())); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MutableDateTime_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "org.joda.time.base.AbstractInstant", "org.joda.time.base.AbstractDateTime", "org.joda.time.base.BaseDateTime", "org.joda.time.MutableDateTime", "org.joda.time.field.AbstractReadableInstantFieldProperty", "org.joda.time.MutableDateTime$Property", "org.joda.time.format.DateTimeFormatterBuilder", "org.joda.time.DateTimeFieldType$StandardDateTimeFieldType", "org.joda.time.DurationFieldType$StandardDurationFieldType", "org.joda.time.DurationFieldType", "org.joda.time.DateTimeFieldType", "org.joda.time.format.DateTimeFormatterBuilder$NumberFormatter", "org.joda.time.format.DateTimeFormatterBuilder$PaddedNumber", "org.joda.time.format.DateTimeFormatter", "org.joda.time.format.DateTimeFormatterBuilder$CharacterLiteral", "org.joda.time.format.DateTimeFormatterBuilder$Composite", "org.joda.time.format.DateTimeFormatterBuilder$StringLiteral", "org.joda.time.format.DateTimeFormatterBuilder$UnpaddedNumber", "org.joda.time.format.DateTimeFormatterBuilder$Fraction", "org.joda.time.format.DateTimeFormatterBuilder$TimeZoneOffset", "org.joda.time.format.ISODateTimeFormat", "org.joda.time.format.DateTimeFormatterBuilder$FixedNumber", "org.joda.time.format.DateTimeFormatterBuilder$MatchingParser", "org.joda.time.tz.FixedDateTimeZone", "org.joda.time.tz.ZoneInfoProvider", "org.joda.time.tz.DefaultNameProvider", "org.joda.time.DateTimeZone", "org.joda.time.format.ISODateTimeFormat$Constants", "org.joda.time.DateTimeUtils$SystemMillisProvider", "org.joda.time.tz.DateTimeZoneBuilder", "org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone", "org.joda.time.tz.DateTimeZoneBuilder$DSTZone", "org.joda.time.tz.DateTimeZoneBuilder$Recurrence", "org.joda.time.tz.DateTimeZoneBuilder$OfYear", "org.joda.time.tz.CachedDateTimeZone", "org.joda.time.DateTimeUtils", "org.joda.time.format.FormatUtils", "org.joda.time.Chronology", "org.joda.time.chrono.BaseChronology", "org.joda.time.chrono.AssembledChronology", "org.joda.time.DurationField", "org.joda.time.field.MillisDurationField", "org.joda.time.field.BaseDurationField", "org.joda.time.field.PreciseDurationField", "org.joda.time.DateTimeField", "org.joda.time.field.BaseDateTimeField", "org.joda.time.field.PreciseDurationDateTimeField", "org.joda.time.field.PreciseDateTimeField", "org.joda.time.field.DecoratedDateTimeField", "org.joda.time.field.ZeroIsMaxDateTimeField", "org.joda.time.chrono.BasicChronology$HalfdayField", "org.joda.time.chrono.BasicChronology", "org.joda.time.chrono.BasicGJChronology", "org.joda.time.chrono.AssembledChronology$Fields", "org.joda.time.field.ImpreciseDateTimeField", "org.joda.time.chrono.BasicYearDateTimeField", "org.joda.time.field.ImpreciseDateTimeField$LinkedDurationField", "org.joda.time.chrono.GJYearOfEraDateTimeField", "org.joda.time.field.OffsetDateTimeField", "org.joda.time.field.DividedDateTimeField", "org.joda.time.field.DecoratedDurationField", "org.joda.time.field.ScaledDurationField", "org.joda.time.field.RemainderDateTimeField", "org.joda.time.chrono.GJEraDateTimeField", "org.joda.time.chrono.GJDayOfWeekDateTimeField", "org.joda.time.chrono.BasicDayOfMonthDateTimeField", "org.joda.time.chrono.BasicDayOfYearDateTimeField", "org.joda.time.chrono.BasicMonthOfYearDateTimeField", "org.joda.time.chrono.GJMonthOfYearDateTimeField", "org.joda.time.chrono.BasicWeekyearDateTimeField", "org.joda.time.chrono.BasicWeekOfWeekyearDateTimeField", "org.joda.time.field.UnsupportedDurationField", "org.joda.time.chrono.GregorianChronology", "org.joda.time.chrono.ISOYearOfEraDateTimeField", "org.joda.time.chrono.ISOChronology", "org.joda.time.chrono.BasicSingleEraDateTimeField", "org.joda.time.chrono.IslamicChronology$LeapYearPatternType", "org.joda.time.DateTime", "org.joda.time.field.FieldUtils", "org.joda.time.chrono.BasicChronology$YearInfo", "org.joda.time.chrono.LimitChronology", "org.joda.time.chrono.LimitChronology$LimitDurationField", "org.joda.time.chrono.LimitChronology$LimitDateTimeField", "org.joda.time.chrono.IslamicChronology", "org.joda.time.chrono.ZonedChronology", "org.joda.time.chrono.ZonedChronology$ZonedDurationField", "org.joda.time.chrono.ZonedChronology$ZonedDateTimeField", "org.joda.time.base.AbstractDuration", "org.joda.time.base.BaseDuration", "org.joda.time.Duration", "org.joda.time.IllegalFieldValueException", "org.joda.time.PeriodType", "org.joda.time.base.AbstractPeriod", "org.joda.time.base.BasePeriod$1", "org.joda.time.base.BasePeriod", "org.joda.time.Period", "org.joda.time.format.DateTimeParserBucket", "org.joda.time.format.DateTimeParserBucket$SavedState", "org.joda.time.base.BaseSingleFieldPeriod", "org.joda.time.format.ISOPeriodFormat", "org.joda.time.format.PeriodFormatterBuilder", "org.joda.time.format.PeriodFormatterBuilder$Literal", "org.joda.time.format.PeriodFormatterBuilder$FieldFormatter", "org.joda.time.format.PeriodFormatterBuilder$SimpleAffix", "org.joda.time.format.PeriodFormatterBuilder$Composite", "org.joda.time.format.PeriodFormatterBuilder$Separator", "org.joda.time.format.PeriodFormatter", "org.joda.time.Days", "org.joda.time.Minutes", "org.joda.time.tz.UTCProvider", "org.joda.time.DateTimeUtils$FixedMillisProvider", "org.joda.time.Instant", "org.joda.time.chrono.GJChronology", "org.joda.time.field.DelegatedDateTimeField", "org.joda.time.field.SkipDateTimeField", "org.joda.time.chrono.JulianChronology", "org.joda.time.chrono.GJChronology$CutoverField", "org.joda.time.chrono.GJChronology$ImpreciseCutoverField", "org.joda.time.chrono.GJChronology$LinkedDurationField", "org.joda.time.field.SkipUndoDateTimeField", "org.joda.time.chrono.BuddhistChronology", "org.joda.time.MutablePeriod", "org.joda.time.base.AbstractPartial", "org.joda.time.base.BaseLocal", "org.joda.time.LocalDate", "org.joda.time.convert.ConverterManager", "org.joda.time.convert.ConverterSet", "org.joda.time.convert.AbstractConverter", "org.joda.time.convert.ReadableInstantConverter", "org.joda.time.convert.StringConverter", "org.joda.time.convert.CalendarConverter", "org.joda.time.convert.DateConverter", "org.joda.time.convert.LongConverter", "org.joda.time.convert.NullConverter", "org.joda.time.convert.ReadablePartialConverter", "org.joda.time.convert.ReadableDurationConverter", "org.joda.time.convert.ReadableIntervalConverter", "org.joda.time.convert.ReadablePeriodConverter", "org.joda.time.convert.ConverterSet$Entry", "org.joda.time.chrono.BasicFixedMonthChronology", "org.joda.time.chrono.CopticChronology", "org.joda.time.Partial", "org.joda.time.field.UnsupportedDateTimeField", "org.joda.time.chrono.EthiopicChronology", "org.joda.time.LocalDateTime", "org.joda.time.chrono.StrictChronology", "org.joda.time.field.StrictDateTimeField", "org.joda.time.Weeks", "org.joda.time.chrono.GJLocaleSymbols", "org.joda.time.Hours", "org.joda.time.Seconds", "org.joda.time.base.AbstractInterval", "org.joda.time.base.BaseInterval", "org.joda.time.MutableInterval", "org.joda.time.base.BasePartial", "org.joda.time.YearMonth", "org.joda.time.Interval", "org.joda.time.DateTimeZone$1", "org.joda.time.chrono.LenientChronology", "org.joda.time.field.LenientDateTimeField", "org.joda.time.chrono.LimitChronology$LimitException", "org.joda.time.LocalTime", "org.joda.time.Months", "org.joda.time.DateTimeUtils$OffsetMillisProvider", "org.joda.time.format.DateTimeFormat$1", "org.joda.time.format.DateTimeFormat", "org.joda.time.MonthDay", "org.joda.time.format.DateTimeParserBucket$SavedField", "org.joda.time.format.DateTimeFormatterBuilder$TextField", "org.joda.time.Years", "org.joda.time.LocalDate$Property", "org.joda.time.DateTime$Property", "org.joda.time.format.DateTimeFormatterBuilder$TimeZoneName", "org.joda.time.DateTimeZone$Stub", "org.joda.time.LocalTime$Property", "org.joda.time.LocalDateTime$Property", "org.joda.time.tz.CachedDateTimeZone$Info", "org.joda.time.IllegalInstantException", "org.joda.time.field.AbstractPartialFieldProperty", "org.joda.time.MonthDay$Property", "org.joda.time.YearMonth$Property" ); } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
4f3eddaa54cd8a7ff286e537c5ff62303895519e
62e294e0b26e8bf4a9d32b4d7233fd87dd10871c
/taotao-sso/src/main/java/com/taotao/sso/service/UserService.java
c02a18558a37b9ee1b6e24aa1cb82bfaac2bafec
[]
no_license
Fatesuinian/taotao
262e13cc6715a11e450c64cc3d5206d445a10697
07a7810c339d942b33db9fe2e200916eb9b4fd25
refs/heads/master
2020-03-06T15:24:25.808035
2018-07-23T09:53:02
2018-07-23T09:53:02
126,950,604
0
0
null
null
null
null
UTF-8
Java
false
false
494
java
package com.taotao.sso.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.taotao.bean.TbUser; import com.taotao.common.bean.TaotaoResult; public interface UserService { TaotaoResult checkData(String content, Integer type); TaotaoResult createUser(TbUser user); TaotaoResult userLogin(String username, String password, HttpServletRequest request, HttpServletResponse response); TaotaoResult getUserByToken(String token); }
[ "Fatesuinian@163.com" ]
Fatesuinian@163.com
a3489bf28a6449ee241ac6efb50b9d048c700594
9bbb597877d3db8236a90be79ec4cc11c7a14a63
/src/test/java/com/fanniemae/testcases/SDETTestCase.java
c4bc90ae6bba1d475dbbbc0bc94d9d74f2bccf88
[]
no_license
nyasmin/SDET
7d18b557c6cbe6366fbaa8d66f371103cea1ece0
d53be7e0158f8e3d966f14f1bc9176223e7bd7de
refs/heads/master
2021-01-01T16:37:09.726546
2017-07-21T19:46:15
2017-07-21T19:46:15
97,872,253
0
0
null
null
null
null
UTF-8
Java
false
false
1,036
java
package com.fanniemae.testcases; import java.io.IOException; import org.openqa.selenium.By; //import org.testng.Assert; //import org.testng.annotations.Test; import com.fanniemae.base.TestBase; import com.fanniemae.utilities.TestUtil; public class SDETTestCase extends TestBase{ // @Test(enabled=false) public void openURL() throws InterruptedException { // driver.get(config.getProperty("testsiteurl")); } // @Test public void loginPage() throws InterruptedException, IOException { String loginHomeButton = "id_LOGIN_BUTTON_HOME"; String loginButton = "xpath_LOGIN_BUTTON"; String username = "id_LOGIN_USERNAME"; String password = "id_LOGIN_PASSWORD"; //Assert.assertTrue(isElementPresent(By.id(OR.getProperty("id_LOGIN_BUTTON_HOME")))); click(loginHomeButton); TestUtil.captureScreenshot(); type(username,"sdet@sdettraining.com"); type(password,"Password"); click(loginButton); TestUtil.captureScreenshot(); Thread.sleep(3000); } }
[ "Huser@MININT-OH7C3JN" ]
Huser@MININT-OH7C3JN
5d68c8d1ec1a24e92e780744b6c882e8e07679b6
d36ea7189c95ac9b07f37d76479ce414f7790c5d
/calix-aem-develop/calix-aem-develop/bundle/src/main/java/com/calix/model/CarouselItem.java
867daa4b1799b1e835ac2926659561e80a425449
[]
no_license
ryanlfoster/EpsilonCode
7042a5129b4b85434695d3436c33d03c8ce2690f
2e37a473aaca9bd96065e3749dee2a4547a1b4b4
refs/heads/master
2021-01-21T08:05:58.182541
2015-08-18T06:06:08
2015-08-18T06:06:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,658
java
package com.calix.model; /** * The Class CarouselItem. */ public class CarouselItem { /** The date. */ String date = ""; /** The type. */ String type = ""; /** The description. */ String description = ""; /** The link action. */ String linkAction = ""; /** The link target. */ String linkTarget = "_self"; /** * Gets the date. * * @return the date */ public String getDate() { return date; } /** * Sets the date. * * @param date the new date */ public void setDate(String date) { this.date = date; } /** * Gets the type. * * @return the type */ public String getType() { return type; } /** * Sets the type. * * @param type the new type */ public void setType(String type) { this.type = type; } /** * Gets the description. * * @return the description */ public String getDescription() { return description; } /** * Sets the description. * * @param description the new description */ public void setDescription(String description) { this.description = description; } /** * Gets the link action. * * @return the link action */ public String getLinkAction() { return linkAction; } /** * Sets the link action. * * @param linkAction the new link action */ public void setLinkAction(String linkAction) { this.linkAction = linkAction; } /** * Gets the link target. * * @return the link target */ public String getLinkTarget() { return linkTarget; } /** * Sets the link action. * * @param linkAction the new link action */ public void setLinkTarget(String linkTarget) { this.linkTarget = linkTarget; } }
[ "narang.avi@gmail.com" ]
narang.avi@gmail.com
97366b502856059df69d71a9292d344b4892416c
4a5292ebb35fb7d3bf9fd35323a8d8317a73677c
/src/main/java/com/yang7/leetcode/editor/cn/LastStoneWeight.java
1eb10a6a2d06c6f909270b60f0591db4d5707c26
[]
no_license
77yang/leetcode
6b7d37439d26f52530172b3a99b6258370b4f644
916deec46d4a59126aa70bbb65dfc2f80e715e20
refs/heads/master
2022-06-05T12:10:38.733723
2022-03-17T09:59:55
2022-03-17T09:59:55
149,733,845
0
0
null
null
null
null
UTF-8
Java
false
false
2,230
java
//有一堆石头,每块石头的重量都是正整数。 // // 每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: // // // 如果 x == y,那么两块石头都会被完全粉碎; // 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 // // // 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 // // // // 示例: // // //输入:[2,7,4,1,8,1] //输出:1 //解释: //先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1], //再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1], //接着是 2 和 1,得到 1,所以数组转换为 [1,1,1], //最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。 // // // // 提示: // // // 1 <= stones.length <= 30 // 1 <= stones[i] <= 1000 // // Related Topics 数组 堆(优先队列) 👍 192 👎 0 package com.yang7.leetcode.editor.cn; import java.util.Comparator; import java.util.PriorityQueue; public class LastStoneWeight { public static void main(String[] args) { Solution solution = new LastStoneWeight().new Solution(); System.out.println(solution.lastStoneWeight(new int[]{2, 7, 4, 1, 8, 1})); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int lastStoneWeight(int[] stones) { PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2 - o1); for (int stone : stones) { priorityQueue.add(stone); } while (priorityQueue.size() > 1) { Integer poll1 = priorityQueue.poll(); Integer poll2 = priorityQueue.poll(); int abs = Math.abs(poll1 - poll2); if (abs != 0) { priorityQueue.add(abs); } } return priorityQueue.isEmpty() ? 0 : priorityQueue.poll(); } } //leetcode submit region end(Prohibit modification and deletion) }
[ "3227@winnermedical.com" ]
3227@winnermedical.com
4df015c7cd1763e8412f2aea71ac45fcc973756e
997cb6ae512c5b73093f2bbee7383437ef5dc3cf
/WFinal/WFinal/src/com/itshixun/service/impl/StaffSalServiceImpl.java
ab145dbd0df5e0760a15ea2837ba06552fbd7074
[]
no_license
chnzhero/enterprise_personnel_info_management
d4ef1b65fced79bc4bfe7ae56676a70e0b1bf70e
5e51318fb55d9e7e66247850f0d21263fed2f820
refs/heads/master
2020-03-22T11:15:22.728997
2018-07-06T08:58:39
2018-07-06T08:58:39
139,958,868
2
0
null
null
null
null
UTF-8
Java
false
false
2,074
java
package com.itshixun.service.impl; import java.util.Vector; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import com.itshixun.dao.StaffSalDao; import com.itshixun.dao.impl.StaffSalDaoImpl; import com.itshixun.model.StaffSal; import com.itshixun.service.StaffSalService; public class StaffSalServiceImpl implements StaffSalService{ @Override public void addStaffSal(StaffSal staffSal) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); staffSalDao.addStaffSal(staffSal); } @Override public void delStaffSal(int salChaNo) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); staffSalDao.delStaffSal(salChaNo); } @Override public void findASalChange(JTable jTable1, int salChaNo) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); Vector list=staffSalDao.findASalChange(salChaNo); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.setRowCount(0); for (int i = 0; i < list.size(); i++) { model.addRow((Vector) list.get(i)); } } @Override public void findAStaffSal(JTable jTable1, int staffId) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); Vector list=staffSalDao.findAStaffSal(staffId); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.setRowCount(0); for (int i = 0; i < list.size(); i++) { model.addRow((Vector) list.get(i)); } } @Override public void findAllStaffSal(JTable jTable1) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); Vector list=staffSalDao.findAllStaffSal(); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.setRowCount(0); for (int i = 0; i < list.size(); i++) { model.addRow((Vector) list.get(i)); } } @Override public void updateStaffSal(StaffSal staffSal) { // TODO Auto-generated method stub StaffSalDao staffSalDao=new StaffSalDaoImpl(); staffSalDao.updateStaffSal(staffSal); } }
[ "31027647+chnzhero@users.noreply.github.com" ]
31027647+chnzhero@users.noreply.github.com
12c1637e2581c1c522d984403499b8ccfe47196d
39c424446fdabb43d151e0f18adf2d275ba02b59
/HistoryVersionAlpha/src/ui/ListenerButton.java
882ab57fa076e4ff8caeb1eb2484de74849088e0
[]
no_license
oparish/HistoryVersionAlpha
cf8e45494debc0b2ed54de94468dfede86cfeda4
d7d9e6e35a4f9cc2f37c788d4e45fdc245b90e49
refs/heads/master
2021-01-01T05:34:13.150108
2013-03-26T19:34:01
2013-03-26T19:34:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
288
java
package ui; import javax.swing.*; @SuppressWarnings("serial") public class ListenerButton extends JButton { private ButtonId id; public ListenerButton(String contentText, ButtonId id) { this.id = id; setText(contentText); } public ButtonId getId() { return this.id; } }
[ "oparish4@gmail.com" ]
oparish4@gmail.com
ec230d245aacc68dfc440cdf42dd4587772b21ec
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_10963.java
33ee582f44cdddea0c419bcf46eb34fc3c5ce98d
[]
no_license
P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606717
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
363
java
/** * ???Toast??? :???? * @param context Context * @param str ??????? * @param isLong Toast.LENGTH_LONG / Toast.LENGTH_SHORT */ public static void showToast(Context context,String str,boolean isLong){ if (isLong) { Toast.makeText(context,str,Toast.LENGTH_LONG).show(); } else { Toast.makeText(context,str,Toast.LENGTH_SHORT).show(); } }
[ "sonnguyen@utdallas.edu" ]
sonnguyen@utdallas.edu
f2e403d43d906d1a7f052bdd7e70277e46e28cce
b3343820cc266a4c21cd0e84bc64c2e9ece275dc
/TestAndroidV2/app/src/main/java/br/com/altran/santander/davidmelo/ui/base/BaseActivity.java
9a9453278704537b5e93574e089f3897cd4b96ab
[]
no_license
DavidRodriguesMelo10/TesteAndroidv2
83ae9e861f0cf64025fac8f73b6ca14649960dfb
c2f29dba3f939941282c44fb412c6249c92580e1
refs/heads/master
2022-09-20T06:53:44.386496
2020-06-04T06:02:45
2020-06-04T06:02:45
269,173,988
0
0
null
2020-06-03T19:17:06
2020-06-03T19:17:05
null
UTF-8
Java
false
false
467
java
package br.com.altran.santander.davidmelo.ui.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public abstract class BaseActivity extends AppCompatActivity implements MvpView { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } protected abstract void setUp(); protected abstract void showData(); }
[ "David.13rodrigues@hotmail.com" ]
David.13rodrigues@hotmail.com
12501099de51d71774aed5273a4877f6836b056f
f55e7639cb72914e2a24e89f52d74636f5bc3317
/src/main/java/com/epam/jwd/text/chainofresp/impl/SymbolHandler.java
8ac210d1167f7f6ba854461844426c85130712d1
[]
no_license
S1mpleKnight/textProcessing
a592e4e86859b877685bae13afd0504b42de252b
9daf050ee165dc325091edce3503a6144ad8b796
refs/heads/master
2023-03-26T09:08:27.528092
2021-03-26T08:33:47
2021-03-26T08:33:47
334,184,526
0
0
null
null
null
null
UTF-8
Java
false
false
2,720
java
package com.epam.jwd.text.chainofresp.impl; import com.epam.jwd.text.chainofresp.api.BaseTextHandler; import com.epam.jwd.text.interpreter.impl.Expression; import com.epam.jwd.text.rpn.PolishParser; import com.epam.jwd.text.units.api.Unit; import com.epam.jwd.text.units.impl.Symbol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SymbolHandler implements BaseTextHandler{ private static final Logger LOGGER = LoggerFactory.getLogger(SymbolHandler.class); private static SymbolHandler symbolHandler; private SymbolHandler(){ } public static SymbolHandler getSentenceHandler(){ if (symbolHandler == null){ symbolHandler = new SymbolHandler(); } return symbolHandler; } @Override public List<Unit> handleRequest(List<String> sequence){ LOGGER.info("Handle symbol request"); List<Unit> symbols = new ArrayList<>(); if (checkSequence(sequence)){ for (String symbol : sequence){ symbols.add(new Symbol(symbol.charAt(0))); } } else { symbols.addAll(calculateExpression(sequence)); } return symbols; } private boolean checkSequence(List<String> sequence){ for (String symbol : sequence){ if (Symbol.isOperator(symbol.charAt(0))){ return false; } } return true; } private List<Unit> calculateExpression(List<String> sequence){ List<String> rpn = PolishParser.RPN(Arrays.asList(makeValidExpressionString(sequence).split(" "))); List<Unit> symbols = new ArrayList<>(); for (String symbol : Expression.getExpression(rpn).calculate().toString().split("")){ symbols.add(new Symbol(symbol.charAt(0))); } return symbols; } private String makeValidExpressionString(List<String> sequence){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < sequence.size(); i++){ if (sequence.get(i).equals(">")){ if ((i + 1) < sequence.size() && sequence.get(i + 1).equals(">")){ sb.append(">>").append(" "); } } else if (sequence.get(i).equals("<")){ if ((i + 1) < sequence.size() && sequence.get(i + 1).equals("<")){ sb.append("<<").append(" "); } } else if (i == sequence.size() - 1){ sb.append(sequence.get(i)); } else { sb.append(sequence.get(i)).append(" "); } } return sb.toString(); } }
[ "became.adult77@gmail.com" ]
became.adult77@gmail.com
fa935f196d6aa5252378a5f0fafc20d2b3ea6caf
26059db129dfc2fb5f4940f72d8136dbf09c6cc9
/6.1class/PackApp.java
991dbd742415dbdf88933febbbfd9b3ac08d4f14
[]
no_license
GU1LH3RME-LIMA/LP2
8715340cae9500d0e1143df9074b48d86cd1d690
02995d5c2330c0632e12e00a047472615f986628
refs/heads/main
2023-05-09T15:53:28.891247
2021-05-30T22:55:01
2021-05-30T22:55:01
340,196,621
0
0
null
null
null
null
UTF-8
Java
false
false
1,838
java
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.ArrayList; import java.util.Random; import figures.*; class PackApp { public static void main (String[] args) { PackFrame frame = new PackFrame(); frame.setVisible(true); } } class PackFrame extends JFrame { ArrayList<Figure> figs = new ArrayList<Figure>(); Random rand = new Random(); Word p; PackFrame () { this.addWindowListener ( new WindowAdapter() { public void windowClosing (WindowEvent e) { System.exit(0); } } ); this.addKeyListener ( new KeyAdapter() { public void keyPressed (KeyEvent evt) { if (evt.getKeyChar() == 'e') { figs.add(new Ellipse(rand.nextInt(350),rand.nextInt(350), rand.nextInt(100) ,rand.nextInt(50),new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)), new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)))); // outer.repaint() }else if(evt.getKeyChar() == 'r'){ figs.add(new Rect(rand.nextInt(350),rand.nextInt(350), rand.nextInt(100) ,rand.nextInt(100),new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)), new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)))); } repaint(); } } ); this.setTitle("Figuras Universais"); this.setSize(350, 350); } public void paint (Graphics g) { super.paint(g); for (Figure fig: this.figs) { fig.paint(g); } } }
[ "gmendoncalima@hotmail.com" ]
gmendoncalima@hotmail.com
e00d4b423a2ca6673aceed13da399a8abe215f1c
92d9789b15a248648f44a78842d588ef712a74f1
/app/src/main/java/com/example/myrecyclerview/MainActivity.java
457559ab1eb2f5b6b95dc0c98e4910a399294fbf
[]
no_license
BaariqAzhar/MyRecyclerView
a6e8436c244f2d613ec7b0e5a5068e89e852d8f0
f648b37021e3923c44163f41d263f0ffe726e61e
refs/heads/master
2020-08-15T10:31:45.316037
2019-10-21T07:25:47
2019-10-21T07:25:47
215,325,925
0
0
null
null
null
null
UTF-8
Java
false
false
2,253
java
package com.example.myrecyclerview; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.dicoding.picodiploma.myrecyclerview.adapter.GridHeroAdapter; import com.dicoding.picodiploma.myrecyclerview.adapter.ListHeroAdapter; import com.dicoding.picodiploma.myrecyclerview.model.Hero; import com.dicoding.picodiploma.myrecyclerview.model.HeroesData; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView rvHeroes; private ArrayList<Hero> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rvHeroes = findViewById(R.id.rv_heroes); rvHeroes.setHasFixedSize(true); list.addAll(HeroesData.getListData() ); showRecyclerList(); } private void showRecyclerList() { rvHeroes.setLayoutManager(new LinearLayoutManager(this)); ListHeroAdapter listHeroAdapter = new ListHeroAdapter(list); rvHeroes.setAdapter(listHeroAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { setMode(item.getItemId()); return super.onOptionsItemSelected(item); } public void setMode(int selectedMode) { switch (selectedMode) { case R.id.action_list: showRecyclerList(); break; case R.id.action_grid: showRecyclerGrid(); break; case R.id.action_cardView: break; } } public void showRecyclerGrid() { rvHeroes.setLayoutManager(new GridLayoutManager(this, 2)); GridHeroAdapter gridHeroAdapter = new GridHeroAdapter(list); rvHeroes.setAdapter(gridHeroAdapter); } }
[ "36961071+BaariqAzhar@users.noreply.github.com" ]
36961071+BaariqAzhar@users.noreply.github.com
2ac0384a6464c35a8f53b73dad238c0387b19959
b8ab7ae7f4648b7b780a9984dfc075dcaa91e27d
/src/exercise/Swap.java
7c1e7fb4759e35af6b614862b061ffb1ba3cfd26
[]
no_license
youngkangrui/Excise
cace2ea3bf2102be5622f0a6615868a59f86fafb
c9a2629950bc10539254f11615db7712a7cac6e7
refs/heads/master
2021-08-25T16:48:03.336358
2017-11-21T13:01:44
2017-11-21T13:01:44
111,545,652
0
0
null
null
null
null
GB18030
Java
false
false
1,158
java
package exercise;//java里都是按值传递,在函数处理时都是复制形式参数,在进行处理,所以函数的行为不会改变形参的值。 //但是形参都是引用,所以可以改变引用对象类的域,从而影响形式参数的内容 import java.util.List; public class Swap { static Node do_swap(Node head,Node i,Node j){ Node t1=new Node(0); Node t2=new Node(0); Node t3=new Node(0); Node k=null,m=null,x=null; t1.next=i.next; i.next=t1; t2.next=j.next; j.next=t2; t3.next=head; head=t3; Node h=head; while(h!=null) { if(h.next==i)k=h; if(h.next==j)m=h; h=h.next; } k.next=j; x=j.next; j.next=i.next; m.next=i; i.next=x; j.next=t1.next; i.next=t2.next; head=t3.next; return head; } //测试按引用专递 public static void inc(int a){ a++; } public static void main(String[] args){ Node head=new Node(1); head.next=new Node(2); head.next.next=new Node(3); Node now=do_swap(head, head, head.next.next); while(now!=null){ System.out.println(now.val); now=now.next; } //测试按引用专递 int a=5; inc(a); System.out.println(a); } }
[ "youngkangrui@foxmail.com" ]
youngkangrui@foxmail.com
119f1caceb0e613dcec7f197e7560e945049e08c
b91fc0f6e4d827526e20880a601bf75e493a0f40
/src/main/java/com/powerliftsafesolution/appaid/ws/exceptions/NoRecordFoundException.java
4b9da637c1ff43eb627b6a17226dabc00c02c29f
[]
no_license
PowerliftSafeSolution/appaid-ws
25f413583403f9307d2e759522378e61fcc059ce
1cb42d863b1f53377c5dcacce44c04b3cd2a66a4
refs/heads/master
2022-12-23T03:36:38.745491
2019-11-13T04:15:05
2019-11-13T04:15:05
137,281,378
0
1
null
2022-12-16T03:22:36
2018-06-13T23:13:29
Java
UTF-8
Java
false
false
277
java
package com.powerliftsafesolution.appaid.ws.exceptions; public class NoRecordFoundException extends RuntimeException { private static final long serialVersionUID = -7804780806112653975L; public NoRecordFoundException(String message){ super(message); } }
[ "wenhao.z@live.com" ]
wenhao.z@live.com
3e380481716340450fa05c87e951d8f1f84659f0
a9e8d0832fde9fac1bc0ef3a8908828fbdb04e16
/src/chapter1/JavaBase.java
10e3c1595834281873b2efdb29c81ae672afebc1
[]
no_license
youngqqcn/Algorithm4
150827ea4c0ae2ec6f519755736780167407ff8a
80705b379712be83855dfc914101273999161849
refs/heads/master
2021-01-21T23:53:24.443959
2017-09-16T09:02:46
2017-09-16T09:02:46
102,182,645
0
0
null
null
null
null
UTF-8
Java
false
false
507
java
package chapter1; /** * Created by yqq on 2017/9/1. */ public class JavaBase { /** * 欧几里得算法 * @param p * @param q * @return */ public static int Gcd(int p, int q){ if(0 == q) return p; return Gcd(q, p % q); } public static void main(String []args){ //System.out.print("hello world"); int a = 48; int b = 64; System.out.println(a +" " + b +"的最大公约数:" + Gcd(a, b)); } }
[ "youngqqcn@163.com" ]
youngqqcn@163.com
163eb247e84dbf9c89c34edf9f71d0e955dec7da
d6e73fc6d1be48d490f3c6a782d4a27e4f410758
/ATM/src/jtc/winnie/monetary/Nominal.java
e9b500c4be386fde8eacaf34299a24b7da673a58
[]
no_license
winnie2437/withSpring
763870c46fac97136b9fdae49ffaaae38c12c28a
0b2ba71fd8398f254f3e1e06adda9387239e32f7
refs/heads/master
2016-09-07T02:12:06.410256
2012-10-04T08:23:20
2012-10-04T08:23:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
780
java
package jtc.winnie.monetary; import jtc.winnie.monetary.Nominal; public enum Nominal { ONE(1), FIVE(5), TEN(10), FIFTY(50), ONE_HUNDRED(100), FIVE_HUNDRED(500), ONE_THOUSAND(1000), FIVE_THOUSAND(5000); private int mValue; public static Nominal enumOf(int vValue) { switch (vValue) { case 1: return ONE; case 5: return FIVE; case 10: return TEN; case 50: return FIFTY; case 100: return ONE_HUNDRED; case 500: return FIVE_HUNDRED; case 1000: return ONE_THOUSAND; case 5000: return FIVE_THOUSAND; default: throw new IllegalArgumentException(vValue + " is not valid nominal"); } } public int value() { return mValue; } private Nominal(int vValue) { mValue = vValue; } }
[ "AVynnychenko@lohika.com" ]
AVynnychenko@lohika.com
13fb429604358f9f8325abdc39965fc130914872
772b549a80062d52c6c4ea3b1bc89e4a78048064
/src/com/mfw/controller/system/role/RoleController.java
02a681fc6b9b3ad3a43742689909c68988ec12a8
[]
no_license
yangst1217/MY-OEC
3f2bba06618be8dabbd41e82abcd8e2e382674fa
1c1a1a2936cf65d8037e5582aedf675cc5a9bab6
refs/heads/master
2021-01-21T06:38:12.614498
2018-03-27T02:26:28
2018-03-27T02:26:28
83,256,394
0
0
null
null
null
null
UTF-8
Java
false
false
17,589
java
package com.mfw.controller.system.role; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.mfw.controller.base.BaseController; import com.mfw.entity.Page; import com.mfw.entity.system.Menu; import com.mfw.entity.system.Role; import com.mfw.service.system.menu.MenuService; import com.mfw.service.system.role.RoleService; import com.mfw.util.Const; import com.mfw.util.PageData; import com.mfw.util.RightsHelper; import com.mfw.util.Tools; import net.sf.json.JSONArray; /** * 类名称:RoleController 创建人:mfw 创建时间:2014年6月30日 * * @version */ @Controller @RequestMapping(value = "/role") public class RoleController extends BaseController { @Resource(name = "menuService") private MenuService menuService; @Resource(name = "roleService") private RoleService roleService; /** * 权限(增删改查) */ @RequestMapping(value = "/qx") public ModelAndView qx() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); String msg = pd.getString("msg"); roleService.updateQx(msg, pd); mv.setViewName("save_result"); mv.addObject("msg", "success"); } catch (Exception e) { logger.error(e.toString(), e); } return mv; } /** * K权限 */ @RequestMapping(value = "/kfqx") public ModelAndView kfqx() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); String msg = pd.getString("msg"); roleService.updateKFQx(msg, pd); mv.setViewName("save_result"); mv.addObject("msg", "success"); } catch (Exception e) { logger.error(e.toString(), e); } return mv; } /** * c权限 */ @RequestMapping(value = "/gysqxc") public ModelAndView gysqxc() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); String msg = pd.getString("msg"); roleService.gysqxc(msg, pd); mv.setViewName("save_result"); mv.addObject("msg", "success"); } catch (Exception e) { logger.error(e.toString(), e); } return mv; } /** * 列表 */ @RequestMapping public ModelAndView list(Page page) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); String roleId = pd.getString("ROLE_ID"); if (roleId == null || "".equals(roleId)) { pd.put("ROLE_ID", "1"); } List<Role> roleList = roleService.listAllRoles(); //列出所有部门 List<Role> roleList_z = roleService.listAllRolesByPId(pd); //列出此部门的所有下级 List<PageData> kefuqxlist = roleService.listAllkefu(pd); //管理权限列表 List<PageData> gysqxlist = roleService.listAllGysQX(pd); //用户权限列表 /* 调用权限 */ this.getHC(); //================================================================================ /* 调用权限 */ pd = roleService.findObjectById(pd); //取得点击部门 mv.addObject("pd", pd); mv.addObject("kefuqxlist", kefuqxlist); mv.addObject("gysqxlist", gysqxlist); mv.addObject("roleList", roleList); mv.addObject("roleList_z", roleList_z); mv.setViewName("system/role/role_list"); return mv; } /** * 新增页面 */ @RequestMapping(value = "/toAdd") public ModelAndView toAdd(Page page) { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); mv.setViewName("system/role/role_add"); mv.addObject("pd", pd); } catch (Exception e) { logger.error(e.toString(), e); } return mv; } /** * 保存新增信息 */ @RequestMapping(value = "/add", method = RequestMethod.POST) public ModelAndView add() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); String parent_id = pd.getString("PARENT_ID"); //父类角色id pd.put("ROLE_ID", parent_id); if ("0".equals(parent_id)) { pd.put("RIGHTS", ""); } else { String rights = roleService.findObjectById(pd).getString("RIGHTS"); pd.put("RIGHTS", (null == rights) ? "" : rights); } pd.put("QX_ID", ""); String UUID = this.get32UUID(); pd.put("GL_ID", UUID); pd.put("FX_QX", 0); //发信权限 pd.put("FW_QX", 0); //服务权限 pd.put("QX1", 0); //操作权限 pd.put("QX2", 0); //产品权限 pd.put("QX3", 0); //预留权限 pd.put("QX4", 0); //预留权限 roleService.saveKeFu(pd); //保存到K权限表 pd.put("U_ID", UUID); pd.put("C1", 0); //每日发信数量 pd.put("C2", 0); pd.put("C3", 0); pd.put("C4", 0); pd.put("Q1", 0); //权限1 pd.put("Q2", 0); //权限2 pd.put("Q3", 0); pd.put("Q4", 0); roleService.saveGYSQX(pd); //保存到G权限表 pd.put("QX_ID", UUID); pd.put("ROLE_ID", UUID); pd.put("ADD_QX", "0"); pd.put("DEL_QX", "0"); pd.put("EDIT_QX", "0"); pd.put("CHA_QX", "0"); roleService.add(pd); mv.addObject("msg", "success"); } catch (Exception e) { logger.error(e.toString(), e); mv.addObject("msg", "failed"); } mv.setViewName("save_result"); return mv; } /** * 请求编辑 */ @RequestMapping(value = "/toEdit") public ModelAndView toEdit(String ROLE_ID) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); pd.put("ROLE_ID", ROLE_ID); pd = roleService.findObjectById(pd); mv.setViewName("system/role/role_edit"); mv.addObject("pd", pd); } catch (Exception e) { logger.error(e.toString(), e); } return mv; } /** * 编辑 */ @RequestMapping(value = "/edit") public ModelAndView edit() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); pd = roleService.edit(pd); mv.addObject("msg", "success"); } catch (Exception e) { logger.error(e.toString(), e); mv.addObject("msg", "failed"); } mv.setViewName("save_result"); return mv; } /** * 返回所在组选择的菜单 */ private List<Menu> getSubList(String parentRoleRights, List<Menu> parentMenuList) throws Exception{ List<Menu> menuList = new ArrayList<Menu>(); for (Menu menu : parentMenuList) { if(RightsHelper.testRights(parentRoleRights, menu.getMENU_ID())){ List<Menu> subMenuList = menuService.listSubMenuByParentId(menu.getMENU_ID()); menu.setSubMenu(getSubList(parentRoleRights, subMenuList)); menuList.add(menu); } } return menuList; } /** * 请求角色菜单授权页面 */ @RequestMapping(value = "/auth") public String auth(@RequestParam String ROLE_ID, Model model) throws Exception { try { Role role = roleService.getRoleById(ROLE_ID); String roleRights = role.getRIGHTS(); List<Menu> menuList = new ArrayList<Menu>(); if("0".equals(role.getPARENT_ID())){//组菜单权限 menuList = menuService.listAllMenu(); }else{//组下面的角色的菜单权限 Role parentRole = roleService.getRoleById(role.getPARENT_ID()); String parentRoleRights = parentRole.getRIGHTS(); List<Menu> parentMenuList = menuService.listAllParentMenu(); menuList = getSubList(parentRoleRights, parentMenuList); } if (Tools.notEmpty(roleRights)) { for (Menu menu : menuList) { menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID())); if (menu.isHasMenu()) { List<Menu> subMenuList = menu.getSubMenu(); for (Menu sub : subMenuList) { sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID())); if (sub.isHasMenu()) { List<Menu> newSubMenuList = sub.getSubMenu(); for (Menu newSub : newSubMenuList) { newSub.setHasMenu(RightsHelper.testRights(roleRights, newSub.getMENU_ID())); } } } } } } JSONArray arr = JSONArray.fromObject(menuList); String json = arr.toString(); json = json.replaceAll("subMenu", "nodes"); json = json.replaceAll("MENU_ID", "id"); json = json.replaceAll("MENU_NAME", "name"); json = json.replaceAll("hasMenu", "checked"); model.addAttribute("zTreeNodes", json); model.addAttribute("roleId", ROLE_ID); PageData pd2 = new PageData(); List<PageData> btnRoleList = roleService.getBtnRoleListByParams(pd2); JSONArray arr2 = JSONArray.fromObject(btnRoleList); String json2 = arr2.toString(); json2 = json2.replaceAll("BUTTONS_ID", "id").replaceAll("BUTTONS_NAME", "name") .replaceAll("\"false\"", "false").replaceAll("\"true\"", "true"); model.addAttribute("zBtnTreeNodes", json2); } catch (Exception e) { logger.error(e.toString(), e); } return "authorization"; } /** * 请求角色按钮授权页面 */ @RequestMapping(value = "/button") public ModelAndView button(@RequestParam String ROLE_ID, @RequestParam String msg, Model model) throws Exception { ModelAndView mv = this.getModelAndView(); try { List<Menu> menuList = menuService.listAllMenu(); Role role = roleService.getRoleById(ROLE_ID); String roleRights = ""; if ("add_qx".equals(msg)) { roleRights = role.getADD_QX(); } else if ("del_qx".equals(msg)) { roleRights = role.getDEL_QX(); } else if ("edit_qx".equals(msg)) { roleRights = role.getEDIT_QX(); } else if ("cha_qx".equals(msg)) { roleRights = role.getCHA_QX(); } if (Tools.notEmpty(roleRights)) { for (Menu menu : menuList) { menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID())); if (menu.isHasMenu()) { List<Menu> subMenuList = menu.getSubMenu(); for (Menu sub : subMenuList) { sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID())); } } } } JSONArray arr = JSONArray.fromObject(menuList); String json = arr.toString(); //System.out.println(json); json = json.replaceAll("MENU_ID", "id").replaceAll("MENU_NAME", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked"); mv.addObject("zTreeNodes", json); mv.addObject("roleId", ROLE_ID); mv.addObject("msg", msg); } catch (Exception e) { logger.error(e.toString(), e); } mv.setViewName("system/role/role_button"); return mv; } /** * 保存角色菜单权限 */ @RequestMapping(value = "/auth/save") public void saveAuth(@RequestParam String ROLE_ID, @RequestParam String menuIds, PrintWriter out) throws Exception { PageData pd = new PageData(); try { if (null != menuIds && !"".equals(menuIds.trim())) { BigInteger rights = RightsHelper.sumRights(Tools.str2StrArray(menuIds)); Role role = roleService.getRoleById(ROLE_ID); role.setRIGHTS(rights.toString()); roleService.updateRoleRights(role); pd.put("rights", rights.toString()); } else { Role role = new Role(); role.setRIGHTS(""); role.setROLE_ID(ROLE_ID); roleService.updateRoleRights(role); pd.put("rights", ""); } pd.put("roleId", ROLE_ID); roleService.setAllRights(pd); out.write("success"); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } } /** * 保存角色按钮权限 */ @RequestMapping(value = "/roleButton/save") public void roleButtonSave(@RequestParam String ROLE_ID, @RequestParam String buttonIds, @RequestParam String MENU_ID,@RequestParam String events, PrintWriter out) throws Exception { PageData pd = new PageData(); pd = this.getPageData(); try { pd.put("roleId", ROLE_ID); pd.put("menuId", MENU_ID); roleService.deleteRoleButton(pd); pd.put("gxId", 0); String menuCode = pd.getString("MENU_CODE"); if (null != buttonIds && !"".equals(buttonIds.trim())) { String[] buttonIdArr = buttonIds.split(","); String[] eventArr = pd.get("events").toString().split(","); if(buttonIdArr.length>0){ for(int i=0;i<buttonIdArr.length;i++){ pd.put("buttonsId", buttonIdArr[i]); pd.put("anqxCode", menuCode+":"+eventArr[i]); roleService.addRoleButton(pd); } } } else { pd.put("value", ""); } pd.put("ROLE_ID", ROLE_ID); //roleService.updateQx( pd); out.write("success"); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } } /** * 删除 */ @RequestMapping(value = "/delete") public void deleteRole(@RequestParam String ROLE_ID, PrintWriter out) throws Exception { PageData pd = new PageData(); try { pd.put("ROLE_ID", ROLE_ID); List<Role> roleList_z = roleService.listAllRolesByPId(pd); //列出此部门的所有下级 if (roleList_z.size() > 1) {//不包含角色组本身 out.write("false"); } else { List<PageData> userlist = roleService.listAllUByRid(pd); List<PageData> appuserlist = roleService.listAllAppUByRid(pd); if (userlist.size() > 0 || appuserlist.size() > 0) { out.write("false2"); } else { roleService.deleteRoleById(ROLE_ID); roleService.deleteKeFuById(ROLE_ID); roleService.deleteGById(ROLE_ID); out.write("success"); } } out.close(); } catch (Exception e) { logger.error(e.toString(), e); } } /** * 请求角色按钮授权页面_new */ @RequestMapping(value = "/buttonRole") public ModelAndView buttonRole(@RequestParam String ROLE_ID, Model model) throws Exception { ModelAndView mv = this.getModelAndView(); try { List<Menu> menuList = menuService.listAllMenu(); Role role = roleService.getRoleById(ROLE_ID); String roleRights = role.getRIGHTS(); List<Menu> menuRoleList = new ArrayList<Menu>(); if (Tools.notEmpty(roleRights)) { for (int i=0;i<menuList.size();i++) { Menu menu = menuList.get(i); if(RightsHelper.testRights(roleRights, menu.getMENU_ID())){ menu.setHasMenu(true); if (menu.isHasMenu()) { List<Menu> subMenuList = menu.getSubMenu(); menu.setSubMenu(null); List<Menu> subMenuRoleList = new ArrayList<Menu>(); for (Menu sub : subMenuList) { if(RightsHelper.testRights(roleRights, sub.getMENU_ID())){ sub.setHasMenu(true); subMenuRoleList.add(sub); } } menu.setSubMenu(subMenuRoleList); } menuRoleList.add(menu); } } } JSONArray arr = JSONArray.fromObject(menuRoleList); String json = arr.toString(); json = json.replaceAll("MENU_ID", "id").replaceAll("MENU_NAME", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked"); mv.addObject("zTreeNodes", json); mv.addObject("roleId", ROLE_ID); //zBtnTree PageData pd2 = new PageData(); List btnRoleList = roleService.getBtnRoleListByParams(pd2); JSONArray arr2 = JSONArray.fromObject(btnRoleList); String json2 = arr2.toString(); json2 = json2.replaceAll("BUTTONS_ID", "id").replaceAll("BUTTONS_NAME", "name").replaceAll("\"false\"", "false").replaceAll("\"true\"", "true"); mv.addObject("zBtnTreeNodes", json2); } catch (Exception e) { logger.error(e.toString(), e); } mv.setViewName("system/role/role_button"); return mv; } /** * 通过角色、菜单,获取按钮权限 */ @RequestMapping(value = "/getBtnRole",produces = "text/html;charset=UTF-8") public void getBtnRole(@RequestParam String ROLE_ID, @RequestParam String MENU_ID, HttpServletResponse response) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); try { pd = this.getPageData(); List btnRoleList = roleService.getBtnRoleListByParams(pd); JSONArray arr = JSONArray.fromObject(btnRoleList); String json = arr.toString(); //System.out.println(json); json = json.replaceAll("BUTTONS_ID", "id").replaceAll("BUTTONS_NAME", "name").replaceAll("\"false\"", "false").replaceAll("\"true\"", "true"); // mv.addObject("zBtnTreeNodes", json); // mv.addObject("roleId", ROLE_ID); // mv.addObject("menuId", MENU_ID); // mv.addObject("msg", "success"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write(json); out.flush(); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } } /* ===============================权限================================== */ public void getHC() { ModelAndView mv = this.getModelAndView(); //shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Map<String, Integer> map = (Map<String, Integer>) session.getAttribute(Const.SESSION_QX); mv.addObject(Const.SESSION_QX, map); //按钮权限 List<Menu> menuList = (List) session.getAttribute(Const.SESSION_menuList); mv.addObject(Const.SESSION_menuList, menuList);//菜单权限 } /* ===============================权限================================== */ }
[ "630585195@qq.com" ]
630585195@qq.com
a8504c668b54af44f582d253feb58fc2efb9d3ba
5ef69d6ead7e05390fe8f84df283caa0c8b600e8
/metron-streaming/Metron-MessageParsers/src/main/java/org/apache/metron/parsing/parsers/BasicSnortParser.java
91fe312854f3563e71574789c7b22700e0304945
[ "Apache-2.0" ]
permissive
dossett/incubator-metron
e6bb5e76dde5b46da3e6a5e99663c4d2b84946fe
4536eb5fdf78c8b5e86911b968c2568f322c9a6e
refs/heads/master
2021-01-16T21:34:35.548202
2016-02-08T15:10:58
2016-02-08T15:10:58
51,331,044
0
0
null
2016-02-08T22:12:11
2016-02-08T22:12:10
null
UTF-8
Java
false
false
3,160
java
package org.apache.metron.parsing.parsers; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.metron.parser.interfaces.MessageParser; import org.json.simple.JSONObject; import java.text.ParseException; @SuppressWarnings("serial") public class BasicSnortParser extends AbstractParser implements MessageParser { /** * The default field names for Snort Alerts. */ private String[] fieldNames = new String[] { "timestamp", "sig_generator", "sig_id", "sig_rev", "msg", "proto", "src", "srcport", "dst", "dstport", "ethsrc", "ethdst", "ethlen", "tcpflags", "tcpseq", "tcpack", "tcplen", "tcpwindow", "ttl", "tos", "id", "dgmlen", "iplen", "icmptype", "icmpcode", "icmpid", "icmpseq" }; /** * Snort alerts are received as CSV records */ private String recordDelimiter = ","; @Override public JSONObject parse(byte[] rawMessage) { JSONObject jsonMessage = new JSONObject(); try { // snort alerts expected as csv records String csvMessage = new String(rawMessage, "UTF-8"); String[] records = csvMessage.split(recordDelimiter, -1); // validate the number of fields if (records.length != fieldNames.length) { throw new IllegalArgumentException("Unexpected number of fields, expected: " + fieldNames.length + " got: " + records.length); } // build the json record from each field for (int i=0; i<records.length; i++) { String field = fieldNames[i]; String record = records[i]; if("timestamp".equals(field)) { // convert the timestamp to epoch jsonMessage.put("timestamp", toEpoch(record)); } else { jsonMessage.put(field, record); } } // add original msg; required by 'checkForSchemaCorrectness' jsonMessage.put("original_string", csvMessage); } catch (Exception e) { _LOG.error("unable to parse message: " + rawMessage); e.printStackTrace(); return null; } return jsonMessage; } /** * Parses Snort's default date-time representation and * converts to epoch. * @param datetime Snort's default date-time as String '01/27-16:01:04.877970' * @return epoch time * @throws java.text.ParseException */ private long toEpoch(String snortDatetime) throws ParseException { /* * TODO how does Snort not embed the year in their default timestamp?! need to change this in * Snort configuration. for now, just assume current year. */ int year = Calendar.getInstance().get(Calendar.YEAR); String withYear = Integer.toString(year) + " " + snortDatetime; // convert to epoch time SimpleDateFormat df = new SimpleDateFormat("yyyy MM/dd-HH:mm:ss.S"); Date date = df.parse(withYear); return date.getTime(); } public String getRecordDelimiter() { return this.recordDelimiter; } public void setRecordDelimiter(String recordDelimiter) { this.recordDelimiter = recordDelimiter; } public String[] getFieldNames() { return this.fieldNames; } public void setFieldNames(String[] fieldNames) { this.fieldNames = fieldNames; } }
[ "cestella@gmail.com" ]
cestella@gmail.com
e833a1382c6af96ebcb15f6364c9a96cfc668701
74db96d1732202a3b08932c903a606fbe2ae2c20
/auth-server/src/main/java/org/tktong/workers/PokemonWorker.java
50ccc320f331811fd7d9e4a30116a27d07123a0f
[]
no_license
tehalexf/TrainerRank
0337b9fa1d726b60ebfdaec333e8e806f0dcf940
8891b373a0d707761365c20978c4301e90e50c5f
refs/heads/master
2021-01-21T20:47:58.996645
2016-08-21T01:17:07
2016-08-21T01:17:07
64,720,836
1
1
null
null
null
null
UTF-8
Java
false
false
9,416
java
package org.tktong.workers; import org.springframework.stereotype.*; import org.springframework.scheduling.annotation.*; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.servlet.ModelAndView; import org.tktong.Result; import javax.servlet.http.HttpSession; import org.tktong.services.UserAuthService; import org.tktong.datamodels.PokemonObj; import org.springframework.beans.factory.annotation.Autowired; import com.pokegoapi.api.pokemon.Pokemon; import POGOProtos.Enums.PokemonIdOuterClass; import POGOProtos.Networking.Responses.ReleasePokemonResponseOuterClass; import com.pokegoapi.api.PokemonGo; import com.pokegoapi.api.pokemon.Pokemon; import com.pokegoapi.auth.GoogleUserCredentialProvider; import com.pokegoapi.auth.PtcCredentialProvider; import com.pokegoapi.exceptions.LoginFailedException; import com.pokegoapi.exceptions.RemoteServerException; import com.pokegoapi.util.Log; import okhttp3.OkHttpClient; import org.springframework.web.bind.annotation.*; import org.tktong.datamodels.UserStats; import org.tktong.datamodels.Candies; import org.tktong.UserStatsRepository; import org.tktong.CandiesRepository; import org.tktong.PokemonRepository; import java.math.BigInteger; import POGOProtos.Data.Player.CurrencyOuterClass; import POGOProtos.Data.Player.EquippedBadgeOuterClass.EquippedBadge; import POGOProtos.Data.Player.PlayerStatsOuterClass; import POGOProtos.Data.PlayerDataOuterClass.PlayerData; import com.pokegoapi.api.player.*; import com.pokegoapi.api.inventory.Stats; import com.pokegoapi.api.inventory.Inventories; import com.pokegoapi.api.inventory.PokeBank; import com.pokegoapi.api.inventory.CandyJar; import java.lang.reflect.*; import java.lang.*; import java.util.*; import POGOProtos.Enums.PokemonFamilyIdOuterClass.PokemonFamilyId; import POGOProtos.Enums.PokemonMoveOuterClass.PokemonMove; import java.util.concurrent.Future; import java.util.concurrent.*; @Service public class PokemonWorker { @Autowired UserStatsRepository usr; @Autowired CandiesRepository cr; @Autowired PokemonRepository pr; @Async public Future<Integer> work() { String threadName = Thread.currentThread().getName(); System.out.println(" " + threadName + " beginning work"); try { Thread.sleep(10000); // simulates work } catch (InterruptedException e) { System.out.println("I stopped"); } System.out.println(" " + threadName + " completed work"); return new AsyncResult<>(0); } @Async public Future<Integer> populateDatabase(PokemonGo go, UserStats userObj) { String threadName = Thread.currentThread().getName(); System.out.println(" " + threadName + " beginning work"); try { PlayerProfile playerProfile = go.getPlayerProfile(); PlayerData playerData = playerProfile.getPlayerData(); int stardust = playerProfile.getCurrency(PlayerProfile.Currency.STARDUST); int pokecoin = playerProfile.getCurrency(PlayerProfile.Currency.POKECOIN); String authUsername = playerData.getUsername(); PlayerAvatar playerAvatar = playerProfile.getAvatar(); userObj.setPoke_storage(playerData.getMaxPokemonStorage()); userObj.setItem_storage(playerData.getMaxItemStorage()); userObj.setCreation_timestamp_ms(playerData.getCreationTimestampMs()); userObj.setTeam(playerData.getTeamValue()); userObj.setGender(playerAvatar.getGenderValue()); userObj.setShoes(playerAvatar.getShoes()); userObj.setBackpack(playerAvatar.getBackpack()); userObj.setPants(playerAvatar.getPants()); userObj.setPants(playerAvatar.getPants()); userObj.setSkin(playerAvatar.getSkin()); userObj.setShirt(playerAvatar.getShirt()); userObj.setHat(playerAvatar.getHat()); userObj.setEyes(playerAvatar.getEyes()); userObj.setEyes(playerAvatar.getEyes()); userObj.setHair(playerAvatar.getHair()); userObj.setCustom_icon(null); userObj.setCoins(pokecoin); userObj.setStardust(stardust); Stats stats = playerProfile.getStats(); userObj.setExp(stats.getExperience()); userObj.setKm_walked(stats.getKmWalked()); userObj.setPokemon_encountered(stats.getPokemonsEncountered()); userObj.setPokedex_entries(stats.getUniquePokedexEntries()); userObj.setLevel(stats.getLevel()); userObj.setPokemons_captured(stats.getPokemonsCaptured()); userObj.setEvolutions(stats.getEvolutions()); userObj.setPoke_stop_visits(stats.getPokeStopVisits()); userObj.setPokeballs_thrown(stats.getPokeballsThrown()); userObj.setEggs_hatched(stats.getEggsHatched()); userObj.setBig_magikarp_caught(stats.getBigMagikarpCaught()); userObj.setBattle_attack_won(stats.getBattleAttackWon()); userObj.setBattle_attack_total(stats.getBattleAttackTotal()); userObj.setBattle_defended_won(stats.getBattleDefendedWon()); userObj.setBattle_training_won(stats.getBattleTrainingWon()); userObj.setBattle_training_total(stats.getBattleTrainingTotal()); userObj.setPrestige_raised_total(stats.getPrestigeRaisedTotal()); userObj.setPrestige_dropped_total(stats.getPrestigeDroppedTotal()); userObj.setPokemon_deployed(stats.getPokemonDeployed()); userObj.setSmall_rattata_caught(stats.getSmallRattataCaught()); DailyBonus dailyBonus = playerProfile.getDailyBonus(); userObj.setNext_collect_timestamp_ms(dailyBonus.getNextCollectedTimestampMs()); userObj.setNext_defender_bonus_collect_timestamp_ms(dailyBonus.getNextDefenderBonusCollectTimestampMs()); usr.save(userObj); int savedId = userObj.getUser_id(); Set<PokemonObj> srt = pr.findByUser(savedId); Inventories inventories = go.getInventories(); CandyJar candyjar = inventories.getCandyjar(); PokeBank pokeBank = inventories.getPokebank(); List<Pokemon> bank = pokeBank.getPokemons(); HashMap<Long, PokemonObj> pokeMapping = new HashMap<Long, PokemonObj>(); for (PokemonObj p : srt) { p.setUpdated(false); pokeMapping.put(p.getGame_id(), p); } ArrayList<PokemonObj> pokemonToUpdate = new ArrayList<PokemonObj>(); for (Pokemon p : bank) { PokemonObj corresponding = pokeMapping.get(p.getId()); if (corresponding == null) corresponding = new PokemonObj(savedId, p.getId()); corresponding.setEgg(p.getIsEgg()); corresponding.setId(p.getMeta().getNumber()); corresponding.setCp(p.getCp()); corresponding.setFavorite(p.isFavorite()); corresponding.setMove_one(p.getMove1().getNumber()); corresponding.setMove_two(p.getMove2().getNumber()); corresponding.setIv_atk(p.getIndividualAttack()); corresponding.setIv_def(p.getIndividualDefense()); corresponding.setIv_sta(p.getIndividualStamina()); corresponding.setCp_multiplier(p.getCpMultiplier()); corresponding.setUpdated(true); corresponding.setAdditional_cp_multiplier(p.getAdditionalCpMultiplier()); corresponding.setStamina(p.getStamina()); corresponding.setStamina_max(p.getMaxStamina()); corresponding.setDeployed_fort_id(p.getDeployedFortId()); corresponding.setOrigin(p.getOrigin()); corresponding.setHeight_m(p.getHeightM()); corresponding.setWeight_kg(p.getWeightKg()); corresponding.setEgg_km_walked_target(p.getEggKmWalkedTarget()); corresponding.setEgg_km_walked_start(p.getEggKmWalkedStart()); corresponding.setPokeball(p.getPokeball().getNumber()); corresponding.setCaptured_cell_id(BigInteger.valueOf(p.getCapturedS2CellId())); corresponding.setBattles_attacked(p.getBattlesAttacked()); corresponding.setBattles_defended(p.getBattlesDefended()); corresponding.setEgg_incubator_id(p.getEggIncubatorId()); corresponding.setCreation_time_ms(BigInteger.valueOf(p.getCreationTimeMs())); corresponding.setNum_upgrades(p.getNumerOfPowerupsDone()); corresponding.setNickname(p.getNickname()); corresponding.setFrom_fort(p.getFromFort()); pokemonToUpdate.add(corresponding); } pr.save(pokemonToUpdate); pokemonToUpdate.clear(); for (PokemonObj p : srt) { if (!(p.getUpdated())) pokemonToUpdate.add(p); } pr.deleteInBatch(pokemonToUpdate); List<Candies> candySet = cr.find(userObj.getUser_id()); HashMap<Integer, Candies> jar = new HashMap<Integer, Candies>(); for (Candies c : candySet) { jar.put(c.getPokemon_family(), c); } ArrayList<Candies> toUpdate = new ArrayList<Candies>(); for (PokemonFamilyId i : PokemonFamilyId.values()) { // System.out.println(); if (i == PokemonFamilyId.UNRECOGNIZED) continue; int count = candyjar.getCandies(i); int ordinal = i.getNumber(); Candies cn = jar.get(ordinal); if (count == 0 && !jar.containsKey(ordinal)) continue; if (cn == null) cn = new Candies(savedId, ordinal, candyjar.getCandies(i)); toUpdate.add(cn); } cr.save(toUpdate); System.out.println("Got Candy!"); } catch (LoginFailedException e) { } catch (RemoteServerException e) { } catch (Exception e) { } System.out.println(" " + threadName + " completed work"); return new AsyncResult<>(0); } public void cancel() { Thread.currentThread().interrupt(); } // public void cancel() { Thread.currentThread().interrupt(); } }
[ "aafu@ucdavis.edu" ]
aafu@ucdavis.edu
cf456d89c3c11d3bd4007101796cf8be5857eaa8
12b771559c783c7af09750ad46476f242419526f
/codes-demo/src/main/java/imooc/reflect/MethodDemo1.java
463806a57d77afdd9adae1617412bc05170fde1d
[]
no_license
shixiangweii/codes
2532dabb636a0eed60a41cfa5dfcb191fd808387
13d5551dae4905fecae69eff9867429a32779401
refs/heads/master
2022-12-22T01:27:44.586557
2021-06-13T06:36:06
2021-06-13T06:36:06
115,195,692
5
1
null
2022-12-16T01:20:15
2017-12-23T12:59:39
Java
UTF-8
Java
false
false
1,827
java
package imooc.reflect; import java.lang.reflect.Method; public class MethodDemo1 { public static void main(String[] args) { //要获取print(int ,int )方法 1.要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型 A a1 = new A(); Class c = a1.getClass(); /* * 2.获取方法 名称和参数列表来决定 * getMethod获取的是public的方法 * getDelcaredMethod自己声明的方法 */ try { //Method m = c.getMethod("print", new Class[]{int.class,int.class}); Method m = c.getMethod("print", int.class,int.class); //方法的反射操作 //a1.print(10, 20);方法的反射操作是用m对象来进行方法调用 和a1.print调用的效果完全相同 //方法如果没有返回值返回null,有返回值返回具体的返回值 //Object o = m.invoke(a1,new Object[]{10,20}); Object o = m.invoke(a1, 10,20); System.out.println("=================="); //获取方法print(String,String) Method m1 = c.getMethod("print",String.class,String.class); //用方法进行反射操作 //a1.print("hello", "WORLD"); o = m1.invoke(a1, "hello","WORLD"); System.out.println("==================="); // Method m2 = c.getMethod("print", new Class[]{}); Method m2 = c.getMethod("print"); // m2.invoke(a1, new Object[]{}); m2.invoke(a1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class A{ public void print(){ System.out.println("helloworld"); } public void print(int a,int b){ System.out.println(a+b); } public void print(String a,String b){ System.out.println(a.toUpperCase()+","+b.toLowerCase()); } }
[ "fengzaoxiangtai@sina.cn" ]
fengzaoxiangtai@sina.cn
6ddf8bbb742a89f61657da502bfedb873dc60e08
53425750e6c85f36e902ec044890a30739d1826e
/app/src/main/java/com/example/dell/m3_weiduxiangmu/fragment/radio/AllFragment.java
236b2c556f7edfe60aea32b9e4715ce111c5ad3b
[]
no_license
JiaXingmei/m3_weiduxiangmu
ef3e7f212f40d4d3b6f301863714c4baefd498a6
52f3f09b039bdf4fcea994e6b5cf51c01f6f1c44
refs/heads/master
2020-04-27T12:46:50.726065
2019-03-07T12:57:26
2019-03-07T12:57:26
174,344,124
0
0
null
null
null
null
UTF-8
Java
false
false
2,368
java
package com.example.dell.m3_weiduxiangmu.fragment.radio; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.dell.m3_weiduxiangmu.R; import com.example.dell.m3_weiduxiangmu.adapter.StatusAdapter; import com.example.dell.m3_weiduxiangmu.bean.OrderListByStatusBean; import com.example.dell.m3_weiduxiangmu.dingdan.presenter.DingPresenter; import java.util.HashMap; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import static android.content.Context.MODE_PRIVATE; public class AllFragment extends Fragment { @BindView(R.id.srecy_view) RecyclerView srecyView; Unbinder unbinder; private HashMap<String, Object> map; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_all, container, false); unbinder = ButterKnife.bind(this, view); DingPresenter dingPresenter = new DingPresenter(this); SharedPreferences login = getActivity().getSharedPreferences("config", MODE_PRIVATE); int userId = login.getInt("userId", 0); String sessionId = login.getString("sessionId", ""); map = new HashMap<>(); map.put("userId", userId); map.put("sessionId", sessionId); dingPresenter.getallpdata(map, 0, 1, 5); return view; } public void getallvdata(Object object) { OrderListByStatusBean statusBean = (OrderListByStatusBean) object; List<OrderListByStatusBean.OrderListBean> orderList = statusBean.getOrderList(); LinearLayoutManager manager = new LinearLayoutManager(getActivity()); srecyView.setLayoutManager(manager); StatusAdapter adapter=new StatusAdapter(getActivity(),statusBean); srecyView.setAdapter(adapter); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } }
[ "jiaxingmei0601.163.com" ]
jiaxingmei0601.163.com
589b6439b72106bc34d5269384179ef4a77a972b
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_27688.java
8280defec7823bc18db7a4a49cd1daf3997ca9f2
[]
no_license
P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606717
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
140
java
@Override public void onSuccessfullyLoggedIn(boolean extraLogin){ checkPurchases(() -> { hideProgress(); onRestartApp(); } ); }
[ "sonnguyen@utdallas.edu" ]
sonnguyen@utdallas.edu
5b6596994a7e69d751c271505a26651731ecf74b
62b2e17ada84765b189daee6b77764100bb1fdfd
/src/UTILIDADES/Conexion.java
6ac14cc525711d2340a77efe30fe2707cbd8d9ae
[]
no_license
VicentRibes/METALICAS_MAGUISA_S.L
8f0b769039cca14a0feca308f240e3062083174a
77a225bc70024099abb64228d88077b4ef5c016c
refs/heads/master
2020-12-31T00:40:50.510096
2017-04-06T07:48:10
2017-04-06T07:48:10
80,617,520
0
1
null
null
null
null
UTF-8
Java
false
false
1,973
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UTILIDADES; import UTILIDADES.leeFichero; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Vicent */ public class Conexion { private Connection connection = null; private ResultSet resultSet = null; private Statement statement = null; private String rdbms="sqlserver"; private String db= "CARPINGEST"; private String url; public void Conexion() {} public Connection connecta(){ //ArrayList<String> lineasConfig=new ArrayList(); //lineasConfig=leeFichero.leeConfigServ(); Connection connexio = null; //url="jdbc:"+rdbms+"://"+lineasConfig.get(0)+";databaseName="+lineasConfig.get(1)+";integratedSecurity=true"; url="jdbc:"+rdbms+"://MGSGESTION;databaseName="+ db +";integratedSecurity=true;authenticationScheme=NativeAuthentication"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Carrying the driver connexio = DriverManager.getConnection(url); // connexio = DriverManager.getConnection(url, "poryectoVicent", "poryectoVicent");// Making the connection System.out.println ( "Connexió realitzada amb éxit!" ); }catch(ClassNotFoundException e){ e.printStackTrace(); JOptionPane.showMessageDialog(null, e, "ERROR EN CLASS", JOptionPane.ERROR_MESSAGE); } catch (SQLException e ){ e.printStackTrace(); JOptionPane.showMessageDialog(null, e, "ERROR EN SQL", JOptionPane.ERROR_MESSAGE); } return connexio; } }
[ "informatica@maguisa.com" ]
informatica@maguisa.com
5887cbb5952c44c4cae76a1ca839fb0a8cfc5781
e3ea91f023d96731722e3ef264f3be144401933d
/src/main/java/com/archermind/springmybatismvc/service/impl/VersionServiceImpl.java
b49118cae55061745d9decaa3d5ce2337bdf83e0
[]
no_license
heronghua/SpringMyBatisMVC
d4d93eee4454f1aeed2d2181fbd1cd163a2a0234
b40a48fa6d930dc570d8ade2c76b22f465e8d2f5
refs/heads/master
2023-03-02T15:11:09.156642
2022-09-23T15:18:55
2022-09-23T15:18:55
129,087,690
1
1
null
2023-02-22T08:05:10
2018-04-11T12:07:55
Java
UTF-8
Java
false
false
669
java
package com.archermind.springmybatismvc.service.impl; import com.archermind.springmybatismvc.dao.VersionMapper; import com.archermind.springmybatismvc.service.UserService; import com.archermind.springmybatismvc.service.VersionService; import com.archermind.springmybatismvc.vo.User; import com.archermind.springmybatismvc.vo.Version; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class VersionServiceImpl implements VersionService { @Resource private VersionMapper versionMapper; @Override public Version getVersionByType(String type) { return versionMapper.selectByType(type); } }
[ "heronghua1989@126.com" ]
heronghua1989@126.com
daeaec49bc902f6cf89f4aaf8daf8a8b5fc05b86
973fc569353d2fbda0cfc003173002debf6addca
/src/lexico/as/AS_Colon_Unexpected.java
d737679fd94d9bb85d54d9f60699c6bc4ca96d1a
[]
no_license
jaymdq/Compiladores
9edc1e4b9e0e96ad86ee3db9a620fca0dd575363
7ae10374ae1fc4ed49bb49a1d12939dabe78b9a5
refs/heads/master
2021-01-25T07:29:01.211368
2014-12-02T12:51:46
2014-12-02T12:51:46
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
540
java
package lexico.as; import lexico.AnalizadorLexico; import gui.ConsolaManager; import proyecto.Proyecto; import proyecto.Simbolo; import proyecto.Token; public class AS_Colon_Unexpected extends AccionSemantica { @Override public void ejecutar(Token t, Simbolo s, Proyecto p) { t.setLexema(""); t.setTipo(null); p.back(); ConsolaManager.getInstance().escribirError("Léxico [Línea "+p.getLineaActual()+"] No se especificó al caracter \"=\" luego del \":\"."); AnalizadorLexico.cantErrores ++; } }
[ "Ariel@Brian-PC" ]
Ariel@Brian-PC
ea34a847f4246cd3c7b64f8be1ee926195b123b6
9ec26e4459c6f51b148cf09ebf9979db0831386c
/src/test/java/com/example/kafka/springbootkafka/ApplicationIT.java
b1fee4193b20b1c00292bf63c78ac1f8c9449705
[]
no_license
tuliofergulha/kafka-event-hub
034c998705276007255e2be818042bcffc2179d6
061320ba9d8815706175c7bd3801fd31fe64e863
refs/heads/master
2023-07-05T00:00:18.142269
2021-08-13T21:29:01
2021-08-13T21:29:01
395,800,424
0
0
null
null
null
null
UTF-8
Java
false
false
441
java
package com.example.kafka.springbootkafka; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class ApplicationIT { @Test void canCreate(){ } }
[ "tfergulha@gmail.com" ]
tfergulha@gmail.com
85bb325e47417eb809d71489e7a4e9f0e336d1f3
b6b43ab106b87844f8169a96927f922bdd783752
/NewApp/app/src/test/java/com/example/swapniln/mypocket/ExampleUnitTest.java
f18e2310e03c1029155e4666e055effd5c683a19
[]
no_license
snswap828/MyPocket
80e75c20bf9d911ce34f260835fea53a22195655
3d5bcf4e67c7b208c637e33952000d2c5dddf5c3
refs/heads/master
2021-01-19T14:53:26.213667
2016-11-23T09:53:06
2016-11-23T09:53:06
74,562,970
0
0
null
null
null
null
UTF-8
Java
false
false
407
java
package com.example.swapniln.mypocket; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "swapnil.nandanwar8@gmail.com" ]
swapnil.nandanwar8@gmail.com
2fd336ce70a202c125a6719d5f9145a4429a49b7
ab44c830932517b55d1e3ddc04bf54e75dbe640e
/app/src/main/java/com/example/divyansh/yoga/MainActivity.java
fb4a5360b490282f83fba6d05e6d951976dc4b22
[]
no_license
divyanshpachauri045/Yog_Application
c8af34f9fcf8f1e7e38cf0f9b230c7a39cb1ffbf
d574df28fb7fc5beafb3cb974dd1e44d8520da36
refs/heads/master
2020-03-18T07:19:57.485517
2018-05-22T16:42:52
2018-05-22T16:42:52
134,445,408
0
0
null
null
null
null
UTF-8
Java
false
false
1,849
java
package com.example.divyansh.yoga; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private ImageView yoga; private ImageView exercise; private Toolbar toolbar; private TextView notes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = findViewById(R.id.app_barid); notes = findViewById(R.id.notestextid); notes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,notesactivity.class); startActivity(intent); } }); yoga = findViewById(R.id.mainyogaid); exercise = findViewById(R.id.mainexerciseid); yoga.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainActivity.this,MainListActivity.class); i.putExtra("imageclickdata","yoga"); startActivity(i); } }); exercise.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainActivity.this,MainListActivity.class); i.putExtra("imageclickdata","exercise"); startActivity(i); }}); } }
[ "divyanshpachauri045@gmail.com" ]
divyanshpachauri045@gmail.com
ea2c19c074082ab5fda51a110a02066dade4ebb2
60bffaedcc10f1106adf823352c94e0667ccd512
/RestClientDemo/src/com/mkyong/rest/HttpHeaderService.java
ea2b42b323fb15f08f42cf721fdec381d3cbc434
[]
no_license
aafak/java-projects
c0837300c5e7cd0249dd6679d33f47cf3ffd6ba4
a09184611745d8d008983c42fa6443d00557bca1
refs/heads/master
2021-01-10T14:43:38.741247
2015-10-07T06:42:56
2015-10-07T06:42:56
43,623,590
0
0
null
null
null
null
UTF-8
Java
false
false
2,249
java
package com.mkyong.rest; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; //pass header parameters as method inputs @Path("/http-header") public class HttpHeaderService { @GET @Path("query") public Response queryHeaderInfo(@HeaderParam("Cache-Control") String ccControl, @HeaderParam("User-Agent") String uaStr){ String resp = "Received http headers are Cache-Control: "+ccControl+ "<br>User-Agent: "+uaStr; return Response.status(200).entity(resp).build(); } //http://localhost:9080/RestClientDemo/rest/http-header/query /* * Received http headers are Cache-Control: no-cache User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.6+ (KHTML, like Gecko) Chromium/17.0.963.56 Chrome/17.0.963.56 Safari/537.6+ */ //read header parameters @GET @Path("query2") public Response queryHeaderInfo(@Context HttpHeaders httpHeaders) { /** how to get specific header info? **/ String cacheControl = httpHeaders.getRequestHeader("Cache-Control").get(0); System.out.println("Cache-Control: "+cacheControl); /** get list of all header parameters from request **/ Set<String> headerKeys = httpHeaders.getRequestHeaders().keySet(); for(String header:headerKeys){ System.out.println(header+":"+httpHeaders.getRequestHeader(header).get(0)); } return Response.status(200).entity("successfully queried header info").build(); } //http://localhost:9080/RestClientDemo/rest/http-header/query2 /* * Cache-Control: max-age=0 host:localhost:9080 user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.6+ (KHTML, like Gecko) Chromium/17.0.963.56 Chrome/17.0.963.56 Safari/537.6+ accept:text/html,application/xhtml+xml,application/xml;q=0.9,;q=0.8 cache-control:max-age=0 accept-encoding:gzip, deflate connection:Keep-Alive */ } //- See more at: http://java2novice.com/restful-web-services/jax-rs-headerparam/#sthash.LT2ci9rb.dpuf
[ "aafak.mitsmca09@gmail.com" ]
aafak.mitsmca09@gmail.com
1ab31ce1125c3725a79b11fc6f58de462a4e7f01
e62b39676bad48a46328124e0ea549dd41a9e543
/src/day05/TemperatureConverter.java
9c2fd9be3bd32ea410869450ba81c24cee180e13
[]
no_license
Erdene-cybertek/JavaProgrammingB15Online
b11ebb41cef753c7b2edd9c3108754f821ba07a9
1327785d0f06a72cecef58c1fbfddea5d5b240c4
refs/heads/master
2020-12-01T02:13:07.899276
2019-12-28T00:49:46
2019-12-28T00:49:46
230,538,866
0
0
null
null
null
null
UTF-8
Java
false
false
444
java
package day05; import java.util.Scanner; public class TemperatureConverter { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("What is the temprature in F ? "); double fahrenheit = scan.nextDouble(); double celsius = (5.0 / 9) * (fahrenheit - 32 ); System.out.println( "fahrenheit " + fahrenheit + " is " + celsius + " in celsius"); } }
[ "ts.eric@yahoo.com" ]
ts.eric@yahoo.com
bda7b44f6a723e9d3b521cf0b62e0cf76d016968
ff16c9582cfe70134256babbe5968ceee464a56b
/src/main/java/com/pageobjects/OrderSummaryPageObjects.java
c0988e2bb12194ae2ed969843e68e36912a902a0
[]
no_license
amruth963/WebAssignment
1a0d250e162d5eeb5b57bf396a9ca09f5ff25233
724c32c0bf2b43a626028e1c6c703f281fb97e34
refs/heads/master
2023-05-10T18:18:11.017960
2020-07-22T19:07:00
2020-07-22T19:07:00
281,632,669
0
0
null
2023-05-09T18:49:46
2020-07-22T09:23:22
Java
UTF-8
Java
false
false
627
java
package com.pageobjects; import org.openqa.selenium.By; public class OrderSummaryPageObjects { public static By TOTOALAMOUNT = By.cssSelector("td[class='table-amount text-body']"); public static By PILLOWNAME = By.cssSelector("span[class='item-name']"); public static By SHIPPINGDETAILSTAB = By.xpath("//span[contains(text(),'shipping details')]"); public static By SHIPPINGDETAILSSECTION = By.cssSelector("div[class='content-text-block']"); public static By CONTINUEBTN = By.cssSelector("div[class='sprite btn-main-next']"); public static By CREDITCARDPAYMENTOPTION = By.cssSelector("a[href='#/credit-card']"); }
[ "amruth963@gmail.com" ]
amruth963@gmail.com
8aad127f43eacab1c69008244bd0bd984ea2837c
4688d19282b2b3b46fc7911d5d67eac0e87bbe24
/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/DescribeMaintenanceWindowExecutionsResultJsonUnmarshaller.java
374682aaef544f7882cd7d08120b81d49cd8ae7b
[ "Apache-2.0" ]
permissive
emilva/aws-sdk-java
c123009b816963a8dc86469405b7e687602579ba
8fdbdbacdb289fdc0ede057015722b8f7a0d89dc
refs/heads/master
2021-05-13T17:39:35.101322
2018-12-12T13:11:42
2018-12-12T13:11:42
116,821,450
1
0
Apache-2.0
2018-09-19T04:17:41
2018-01-09T13:45:39
Java
UTF-8
Java
false
false
3,505
java
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeMaintenanceWindowExecutionsResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeMaintenanceWindowExecutionsResultJsonUnmarshaller implements Unmarshaller<DescribeMaintenanceWindowExecutionsResult, JsonUnmarshallerContext> { public DescribeMaintenanceWindowExecutionsResult unmarshall(JsonUnmarshallerContext context) throws Exception { DescribeMaintenanceWindowExecutionsResult describeMaintenanceWindowExecutionsResult = new DescribeMaintenanceWindowExecutionsResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return describeMaintenanceWindowExecutionsResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("WindowExecutions", targetDepth)) { context.nextToken(); describeMaintenanceWindowExecutionsResult.setWindowExecutions(new ListUnmarshaller<MaintenanceWindowExecution>( MaintenanceWindowExecutionJsonUnmarshaller.getInstance()).unmarshall(context)); } if (context.testExpression("NextToken", targetDepth)) { context.nextToken(); describeMaintenanceWindowExecutionsResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeMaintenanceWindowExecutionsResult; } private static DescribeMaintenanceWindowExecutionsResultJsonUnmarshaller instance; public static DescribeMaintenanceWindowExecutionsResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeMaintenanceWindowExecutionsResultJsonUnmarshaller(); return instance; } }
[ "" ]
341c0a1f842c90f62ca4a9a0c9f9a04622724df1
6c2d59ce65a79cf072e07ac8f155c3bbce219d49
/app/src/androidTest/java/com/codebear/demo/ExampleInstrumentedTest.java
f405fae2b611573ec36a118db0e2460b90ab4c22
[ "Apache-2.0" ]
permissive
DuShuYuan/CBRatingBar
f62d2d059e6567513e0f53c51a7f81efeadb4f52
c81c2faaeecafb6d41430cb1017d210f79fa6f54
refs/heads/master
2020-08-11T20:39:12.711573
2019-10-14T05:58:46
2019-10-14T05:58:46
214,623,459
2
0
null
2019-10-12T09:58:33
2019-10-12T09:58:33
null
UTF-8
Java
false
false
738
java
package com.codebear.demo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.codebear.demo", appContext.getPackageName()); } }
[ "249900679@qq.com" ]
249900679@qq.com
7ed61235d649b10c9c4710f690609a7927537bba
60491c463d655ab1386f3d4ebd003aa7684fae46
/molicode-manager/src/main/java/com/shareyi/molicode/manager/sys/AcUserManager.java
7e3424cce38f4c5985d366e79f35cae2472cddf6
[ "Apache-2.0" ]
permissive
SwanWZC/molicode
887a55e9a6db343669e19a66c6052ca5c40681f6
66940f13d91e7fc8ec4b4926a977296d3d75cc43
refs/heads/master
2023-04-11T14:02:38.726638
2020-04-03T06:28:30
2020-04-03T06:28:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
462
java
/** * Copyright(c) 2004-2018 bianfeng */ package com.shareyi.molicode.manager.sys; import com.shareyi.molicode.domain.sys.AcUser; import com.shareyi.molicode.manager.BaseManager; /** * 用户信息Manager接口类 * @author david * @date 2018-08-21 */ public interface AcUserManager extends BaseManager<AcUser>{ /** * 通过用户名查询用户信息 * @param userName * @return */ AcUser getByUserName(String userName); }
[ "14141414" ]
14141414
c2be4f2e3767d18212a6e7f678ef68fc46a99369
1752bf033e445bb93ed84a8c47988605de429bff
/com.zhi.springCloud/cloud-consumerconsul-order80/src/main/java/com/zhi/springcloud/OrderConsulMain80.java
5ff0e76cc125e79dad09ec75f8c7060c9eeccadd
[]
no_license
JiuQianQiO/charlesing001
f79f65c2f93c61e07879745921176bf15096ae76
0e6dc070c99b32af5d3a222502c996e54d370ed7
refs/heads/main
2023-08-24T00:22:33.583972
2021-10-02T12:20:37
2021-10-02T12:20:37
403,944,166
0
0
null
null
null
null
UTF-8
Java
false
false
417
java
package com.zhi.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class OrderConsulMain80 { public static void main(String[] args) { SpringApplication.run(OrderConsulMain80.class,args); } }
[ "wangzhi_email@163.com" ]
wangzhi_email@163.com
794ca6d817c3700b433bd3b67b1aa46623eed688
6cced3e3cff3fc77937c74fd18a3f7ba0d43ad62
/app/src/test/java/edu/uw/ezubatov/steptracker/ExampleUnitTest.java
8ba52a2c8accef18a0cad5abc13f92be97ac5c1a
[ "Apache-2.0" ]
permissive
EvgenyZubatov/StepTracker
b29748df9f261d7501986a6dfae0fd04b9ff1ab7
f88ef73cf41a572cec2bea4869af39162ad3dd2f
refs/heads/master
2020-03-10T09:47:23.290757
2018-04-15T21:55:34
2018-04-15T21:55:34
129,318,722
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package edu.uw.ezubatov.steptracker; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "evgeny.zubatov@gmail.com" ]
evgeny.zubatov@gmail.com
2fd7073da3943ea9f96aefaaf0fcaff5739999f9
b8683d6451854bbb8c291ddac43a6377cddcdd5e
/student-application/src/main/java/io/jackfrost/student/controller/StudentController.java
6e44eae4b749359d09e2a3c2b2c78c801c0ef7c6
[ "MIT" ]
permissive
jackfr0st13/centralized-swagger
f4b227f2bd572ca0606a602795385a6240d7c15a
7dfe4c586a5c4ae044fba614b4ac0335ebbee97a
refs/heads/master
2021-05-25T17:29:55.994303
2020-04-07T17:42:42
2020-04-07T17:42:42
253,844,932
0
0
null
null
null
null
UTF-8
Java
false
false
867
java
package io.jackfrost.student.controller; import io.jackfrost.student.entity.StudentEntity; import io.jackfrost.student.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/student") @CrossOrigin(origins = "http://localhost:9093") public class StudentController { @Autowired private StudentService studentService; @GetMapping public ResponseEntity<List<StudentEntity>> getAllStudents(){ return ResponseEntity.ok(studentService.getAllStudents()); } }
[ "deepak.schoudhary90@gmail.com" ]
deepak.schoudhary90@gmail.com
e5ca1eba9815169932e4f137c9a9a9e7cc068f10
de3c7f9c3615f5f081d348dd84b45bf563f06505
/answer_system/src/main/java/com/luoluohao/answer_system/x/as/admins/controller/AdminsController.java
855c490ca80f611c159608b943f761ea0fd0421a
[]
no_license
qhu-mqy/AnswerSystem
439dd73fcacbe592a32e19454994813440cd47e6
c31db55800beed0f3200391e3ed10a3c327c2915
refs/heads/master
2023-03-16T19:52:19.816557
2019-03-22T07:49:28
2019-03-22T07:49:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,443
java
package com.luoluohao.answer_system.x.as.admins.controller; import com.luoluohao.answer_system.util.ViewJSON; import com.luoluohao.answer_system.x.as.admins.dto.entity.Admins; import com.luoluohao.answer_system.x.as.admins.service.IAdminsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration @RequestMapping("/admins") public class AdminsController { @Autowired private IAdminsService adminsService; Logger logger = LoggerFactory.getLogger(this.getClass()); @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST) public ViewJSON login( @RequestParam(value = "pwd") String pwd, @RequestParam(value = "userName") String userName ) { logger.debug("user-email=" + userName + "/npwd=" + pwd); Admins admins = adminsService.searchUserByName(userName); if (admins == null) { return new ViewJSON<>("400", "管理员不存在"); } String adminsPwd = admins.getPassword(); if (!adminsPwd.equals(pwd)) { return new ViewJSON<>("400", "密码不正确"); } admins.setPassword(""); return new ViewJSON<>("200", "登陆成功", admins); } }
[ "ghaoluo@gmail.com" ]
ghaoluo@gmail.com
97dcc2105194ccdd874fbca2e74897035ba620d1
bf7570dedcab9a97670a291bfc682f5bcf63c560
/src/others/RatingSortingStrategy.java
c1a286a7f7a36c09d6910d48990200947491affd
[]
no_license
bartawilly/2alakfeen
28a83c16d780da44574306ffcfc53f72ee99b7f2
2ae03fad03bd61b88baad65f484e2eabb8057c0b
refs/heads/master
2021-01-25T11:29:02.564571
2017-06-10T09:56:39
2017-06-10T09:56:39
93,930,535
0
0
null
null
null
null
UTF-8
Java
false
false
137
java
package others; public class RatingSortingStrategy { public RatingSortingStrategy() { // TODO Auto-generated constructor stub } }
[ "ahmed nasser" ]
ahmed nasser
f6cf80ba106e4b6ee0726559c98c96e991f603b4
58da62dfc6e145a3c836a6be8ee11e4b69ff1878
/src/main/java/com/alipay/api/domain/KoubeiCateringPosDishbatchDeleteModel.java
7efd010cddb04d79a72965ec317130aea7fcf5dc
[ "Apache-2.0" ]
permissive
zhoujiangzi/alipay-sdk-java-all
00ef60ed9501c74d337eb582cdc9606159a49837
560d30b6817a590fd9d2c53c3cecac0dca4449b3
refs/heads/master
2022-12-26T00:27:31.553428
2020-09-07T03:39:05
2020-09-07T03:39:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,391
java
package com.alipay.api.domain; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 批量删除菜品 * * @author auto create * @since 1.0, 2018-11-16 17:27:05 */ public class KoubeiCateringPosDishbatchDeleteModel extends AlipayObject { private static final long serialVersionUID = 2562542366626411473L; /** * 菜谱的ID。用于删除菜谱中的菜品 */ @ApiField("cook_id") private String cookId; /** * 菜品ID */ @ApiListField("dish_ids") @ApiField("string") private List<String> dishIds; /** * 商户ID */ @ApiField("merchant_id") private String merchantId; /** * 门店ID */ @ApiField("shop_id") private String shopId; public String getCookId() { return this.cookId; } public void setCookId(String cookId) { this.cookId = cookId; } public List<String> getDishIds() { return this.dishIds; } public void setDishIds(List<String> dishIds) { this.dishIds = dishIds; } public String getMerchantId() { return this.merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getShopId() { return this.shopId; } public void setShopId(String shopId) { this.shopId = shopId; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
5323d34d3378b2d114e49a222fe3fa44cb94cfe7
d18b70a669b54eea0992b87290559a8fd37a430c
/src/com/restaurant/dao/LoginDAO.java
e2fd2f3f86c5c40a8ba1193ee526102a8909769a
[]
no_license
ANBAGAM/Restaurant-Management
3cef3701b4969c1e63f8788a9c8be017ea8642f5
2b51aa2186a2690b8b4b6cf4ee86f3473c3303f8
refs/heads/master
2020-04-26T22:31:48.905166
2019-03-05T13:09:04
2019-03-05T13:09:04
173,875,295
0
0
null
null
null
null
UTF-8
Java
false
false
2,635
java
package com.restaurant.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.restaurant.data.Login; import com.restaurant.dbconnection.ConnectionUtil; public class LoginDAO { ResultSet resultSet = null; public boolean checkEmployee(Login login) throws SQLException{ boolean check = false; Connection connection = ConnectionUtil.getConnection(); String sql = "select id from res_emp_cre where id=?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(1, login.getLoginid()); resultSet = preparedStatement.executeQuery(); try { if (resultSet.next()) { check = false; ConnectionUtil.close(connection, preparedStatement, resultSet); return check; } else { check = true; ConnectionUtil.close(connection, preparedStatement, resultSet); return check; } } catch (Exception e) { e.printStackTrace(); } ConnectionUtil.close(connection, preparedStatement, resultSet); return check; } public boolean checkEmployeePass(Login login) throws SQLException{ boolean checkp = false; Connection connection = ConnectionUtil.getConnection(); String sql = "select * from res_emp_cre where id=? and pass=?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); try { preparedStatement.setLong(1, login.getLoginid()); preparedStatement.setString(2, login.getPassword()); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { // String checkUser = resultSet.getString(1); long checkId=resultSet.getLong(1); String checkPass = resultSet.getString(2); if ((checkId==login.getLoginid()) && (checkPass.equals(login.getPassword()))) { checkp = true; } else { checkp = false; } } else { System.out.println("invalid"); } } catch (Exception e) { e.printStackTrace(); } ConnectionUtil.close(connection, preparedStatement, resultSet); return checkp; } public String checkEmployeeDesgination(Login login) throws SQLException{ String desig=" "; Connection connection = ConnectionUtil.getConnection(); String sql = "select dsgn from res_employee where id=?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(1, login.getLoginid()); resultSet = preparedStatement.executeQuery(); if(resultSet.next()){ desig = resultSet.getString(1); } ConnectionUtil.close(connection, preparedStatement, resultSet); return desig; } }
[ "anba2119@global.chainsys.com" ]
anba2119@global.chainsys.com
a552843d96534a46ee3626e0cb8d960bc52968a8
e1b973c582a68cb308e46b445381b457607e0791
/android/AndroidRendzu/src/mis/games/rendzu/android/AndroidRendzuView.java
4d86d5075aae6322286b2aeb332d306a2fc6ac2b
[]
no_license
mishagam/progs
d21cb0b1a9523b6083ff77aca69e6a8beb6a3cff
3300640d779fa14aae15a672b803381c23285582
refs/heads/master
2021-08-30T15:51:05.890530
2017-12-18T13:54:43
2017-12-18T13:54:43
114,647,485
0
0
null
null
null
null
UTF-8
Java
false
false
13,322
java
package mis.games.rendzu.android; import java.util.List; import java.util.Timer; import mis.games.rendzu.GameException; import mis.games.rendzu.RGame; import mis.games.rendzu.RMove; import mis.games.rendzu.RPoint; import mis.games.rendzu.client.RemoteGame; import mis.games.rendzu.client.RendzuClient; import mis.games.rendzu.simplegame.Rendzu; import mis.games.utils.GameState; import mis.games.utils.GameVariant; import mis.games.utils.RendzuOptions; import mis.games.utils.RendzuStatistics; import mis.games.rendzgame.RendzuGame; import mis.games.rendzgame.RendzuParameters; import mis.games.server.OneRGame; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ScrollView; public class AndroidRendzuView extends View implements View.OnClickListener, Handler.Callback { public static final String TAG = AndroidRendzuView.class.getSimpleName(); int step = 50; final int stepmax = 50; int stepmin = 21; float coefBigSmall = ((float) stepmax) / stepmin; int nx = 19; int ny = 19; int sx = nx * step + 5; int sy = ny * step + 5; int halfScreenMin = 0; ScrollView scrollV; HorizontalScrollView scrollH; boolean bigScreen = false; int lastX, lastY; public RGame game = null; /** * show simplest hints - need to close 4, close 3 */ public boolean showHints0 = false; public boolean showLastComputerMove = true; public boolean showLastYourMove = true; int X0, X1, Y0, Y1; static final int SHIFT_X = 6; static final int SHIFT_Y = 21; static final int SHIFT_X_BIG = 15; static final int SHIFT_Y_BIG = 35; int shiftX=0, shiftY=0; Timer t = null; AndroidRendzuActivity activityContext; Handler handler; public static final int MSG_COMPUTER_MOVE_DONE = 500; public static final int MSG_SCROLL = 501; public static final int MSG_OBSERVE_REMOTE_GAME = 502; private RendzuOptions opts = null; RendzuClient client = null; private RMove computerMove = null; private GameState state; private RendzuStatistics stats; public AndroidRendzuView(AndroidRendzuActivity context, ScrollView scrollV, HorizontalScrollView scrollH) { super(context); opts = GameMenuActivity.opts; this.activityContext = context; this.scrollV = scrollV; this.scrollH = scrollH; scrollV.setVerticalFadingEdgeEnabled(false); scrollV.setHorizontalFadingEdgeEnabled(false); scrollH.setVerticalFadingEdgeEnabled(false); scrollH.setHorizontalFadingEdgeEnabled(false); this.setOnClickListener(this); if (opts.gameVar == GameVariant.EASY) { game = new Rendzu(); } else if (opts.gameVar == GameVariant.OBSERVE) { OneRGame ogame = new OneRGame(opts.remoteGameId, 0); game = new RemoteGame(ogame, 0); game.setId(opts.remoteGameId); } else if (opts.gameVar == GameVariant.HARD) { int sz = RendzuOptions.DEFAULT_SIZE; byte [][]pos = new byte[sz][sz]; game = new RendzuGame(pos); } Display display = context.getWindowManager().getDefaultDisplay(); stepmin = (display.getWidth()-5) / nx; bigScreen = false; setGameSizes(); client = RendzuClient.getInstance(game, opts.gameServerUrl); if (opts.gameVar != GameVariant.OBSERVE) { if (opts.connectToServer) { client.reportNewGame(); } if (opts.compFirst) { RMove rm = new RMove(9, 9, 1); if (opts.connectToServer) { client.reportMove(rm); } game.addMove(rm); } } handler = new Handler(this); if (opts.gameVar == GameVariant.OBSERVE) { handler.sendEmptyMessageDelayed(MSG_OBSERVE_REMOTE_GAME, 500); } if (opts.gameVar == GameVariant.HARD) { RendzuGame rgame = (RendzuGame)game; rgame.moveTime = opts.timePerMove; } stats = RendzuStatistics.getInstance(); setState(GameState.WAITING); } private void setState(GameState gs) { this.state = gs; switch (gs) { case THINKING: activityContext.stateView.setText("Thinking"); break; case WAITING: activityContext.stateView.setText("Waiting"); break; case COMPUTER_WON: activityContext.stateView.setText("Computer Won!"); break; case MAN_WON: activityContext.stateView.setText("Man Won!"); break; } } @Override public void onClick(View v) { Log.i(TAG, "RendzuCanvasView.onClick() called, bigScreen = " + bigScreen); // we check field on mouse down, we only attempt to accurately // check if (opts.gameVar != GameVariant.OBSERVE && bigScreen && state == GameState.WAITING) { int xx = (int)((lastX - X0) / step); int yy = (int)((lastY - Y0) / step); RMove m = new RMove(xx, yy, game.getManSide()); long ret = game.addMove(m); if (ret == Rendzu.M_OK) { setState(GameState.THINKING); if (opts.connectToServer) { client.reportMove(m); } startComputerMove(); } } bigScreen = !bigScreen; setGameSizes(); this.onMeasure(sx, sy); this.requestLayout(); if (bigScreen) { int xx = (int) (lastX * (coefBigSmall - 1.0)); int yy = (int) (lastY * (coefBigSmall - 1.0)); Log.i(TAG, "last X, Y was " + lastX + " " + lastY + "scrolling to xx, yy = " + xx + " " + yy); if (xx < 0) { xx = 0; } if (yy < 0) { yy = 0; } if (xx > 0 || yy > 0) { Message msg = new Message(); msg.what = MSG_SCROLL; msg.arg1 = xx; msg.arg2 = yy; handler.sendMessage(msg); } } } private void setGameSizes() { if (bigScreen) { step = stepmax; shiftX = SHIFT_X_BIG; shiftY = SHIFT_Y_BIG; } else { step = stepmin; shiftX = SHIFT_X; shiftY = SHIFT_Y; } nx = game.getSx(); ny = game.getSy(); sx = nx * step + 5; sy = ny * step + 5; halfScreenMin = (nx * stepmin) / 2; coefBigSmall = ((float) stepmax) / stepmin; } @Override protected void onDraw(Canvas c) { Paint p = new Paint(); if (bigScreen) { p.setColor(Color.LTGRAY); } else { p.setColor(Color.rgb(240, 240, 216)); } c.drawPaint(p); paintDesk(c); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i(TAG, "onMeasure() called, wid, hei = " + widthMeasureSpec + " " + heightMeasureSpec); setMeasuredDimension(sx, sy); } @Override protected int getSuggestedMinimumHeight() { return sy; } @Override protected int getSuggestedMinimumWidth() { return sx; } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); int action = event.getAction(); lastX = (int) x; lastY = (int) y; int scV = scrollV.getScrollY(); int scH = scrollH.getScrollX(); Log.i("RendzuCanvasView", "onTouchEvent(), action, x, y = " + action + " " + x + " " + y); Log.i("RendzuCanvasView", "onTouchEvent(), scV, scH = " + scV + " " + scH); return super.onTouchEvent(event); } /** * painting rendzu desk. * borrowed initially from Java version. * @param g */ private void paintDesk(Canvas c) { X0 = (sx - nx*step -1) / 2; Y0 = (sy - ny*step -1) / 2; X1 = X0 + nx*step +1; Y1 = Y0 + ny*step +1; Paint p = new Paint(); p.setColor(Color.BLACK); p.setTextSize(bigScreen ? 36 : 22); p.setTypeface(Typeface.DEFAULT_BOLD); for (int i=0; i<=nx; i++) { int xx = X0 + i * step; c.drawLine(xx, Y0, xx, Y1, p); } for (int i=0; i<=ny; i++) { int yy = Y0 + i * step; c.drawLine(X0, yy, X1, yy, p); } // writing game fields String []ss = new String[] {"0", " ", "X"}; int myGreen = Color.rgb(0, 150, 0); for (int i=0; i<ny; i++) { for (int j=0; j<nx; j++) { int vb = game.getFld()[i][j]; int vkind = game.getFldTypes()[i][j]; if (!opts.compFirst) { // crosses always play first vb = -vb; } String vs = ss[vb+1]; int x = X0 + j * step + shiftX; int y = Y0 + i * step + shiftY; boolean fontChanged = false; if (vkind == RendzuParameters.LAST_MOVE && showLastComputerMove) { p.setColor(Color.BLUE); fontChanged = true; } else if (vkind == RendzuParameters.LAST_MAN_MOVE && showLastYourMove) { p.setTypeface(Typeface.DEFAULT_BOLD); p.setColor(myGreen); fontChanged = true; } c.drawText(vs, x, y, p); if (fontChanged) { p.setTypeface(Typeface.DEFAULT); p.setColor(Color.BLACK); } } } } protected void startComputerMove() { // Fire off a thread to do some work that we shouldn't do directly in the UI thread Thread t = new Thread() { public void run() { try { computerMove = game.nextMove(); if (game.getNumberMoves() <= 3) { computerMove = game.getRandomRMove(0.25); } else if (game.getNumberMoves() <= 5) { computerMove = game.getRandomRMove(0.2); } else if (game.getNumberMoves() <= 7) { computerMove = game.getRandomRMove(0.1); } } catch (GameException ge) { Log.e(TAG, "nextMove() failed: " + ge); } handler.sendEmptyMessageDelayed(MSG_COMPUTER_MOVE_DONE, 500); } }; t.start(); } /** * make next computer move after drawing your move and delay. */ public void makeNextComputerMove() throws GameException, CloneNotSupportedException { if (game.manWon()) { Log.i(TAG, "Man Won!"); showAlertMessage("You Won!!!"); stats.reportGame(true); setState(GameState.MAN_WON); } else { if (opts.connectToServer) { client.reportMove(computerMove); } game.addMove(computerMove); setState(GameState.WAITING); if (game.compWon()) { Log.i(TAG, "Computer Won!"); showAlertMessage("Computer Won!!!"); stats.reportGame(false); setState(GameState.COMPUTER_WON); } } this.invalidate(); } public void showAlertMessage(String msg) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(msg); builder.setCancelable(true); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } public void observeRemoteMove() { List<RMove> moves = client.getLastMoves(); if (moves.size() > 0) { //for(RMove m : moves) { // game.addMove(m); //} invalidate(); } handler.sendEmptyMessageDelayed(MSG_OBSERVE_REMOTE_GAME, 500); } public void undoMove() { if (opts.connectToServer) { client.reportUndoMove(); } game.undoMove(); if (state == GameState.MAN_WON) { setState(GameState.THINKING); startComputerMove(); } else { setState(GameState.WAITING); } invalidate(); } @Override public boolean handleMessage(Message msg) { Log.e(TAG, "handling message with what = " + msg.what); if (msg.what == MSG_COMPUTER_MOVE_DONE) { try { makeNextComputerMove(); } catch (GameException e) { Log.e(TAG, "makeNextComputerMove failed: " + e); } catch (CloneNotSupportedException e) { Log.e(TAG, "makeNextComputerMove failed: " + e); } } else if (msg.what == MSG_SCROLL) { int xx = msg.arg1; int yy = msg.arg2; scrollH.scrollTo(xx, 0); scrollV.scrollTo(0, yy); this.invalidate(); } else if (msg.what == MSG_OBSERVE_REMOTE_GAME) { observeRemoteMove(); } else { Log.e(TAG, "Unknown message with what = " + msg.what); return false; } return true; } }
[ "mishagam@gmail.com" ]
mishagam@gmail.com
1a08b69300d17144a9a75edb4eb1824575ebcb9a
bdcdb474f41662188636a8dcb43a2b25c0af49b5
/HR-Management-System-in-Java-using-swing-framework/src/gamemarkstudio/mainframe/MainOfficeManagement.java
b4a5edf3de16c006fa95510d5b9135a16cd4fd94
[ "MIT" ]
permissive
skYolo/HR-management-system-
eca232f65706d3aebc444269daec69f8a64f743f
23b999cc27ef168c04438a13bcbb003c4bc9baf5
refs/heads/master
2020-12-15T04:20:39.919948
2020-01-20T01:19:55
2020-01-20T01:19:55
234,993,424
0
0
null
null
null
null
UTF-8
Java
false
false
18,117
java
/* * %W% %E% Hamza Yasin * * Copyright (c) 2017-2018 Miranz Technology. All Rights Reserved. * * This software is the confidential and proprietary information of Miranz * technology. You shall not disclose such Confidential Information and * shall use it only in accordance with the terms of the license agreement * you entered into with Miranz. * */ package gamemarkstudio.mainframe; import gamemarkstudiio.salaryslips.SalarySlip; import gamemarkstudio.dailywork.DailyWorkPanel; import gamemarkstudio.login.AddNewLogin; import gamemarkstudio.login.Login; import gamemarkstudio.newemployeepane.NewEmployeePane; import gamemarkstudio.searchemployee.SearchEmployee; import gamemarkstudio.update.UpdatePanel; /* * @version 1.10 25 Aug 2017 * @author Hamza Yasin */ public class MainOfficeManagement extends javax.swing.JFrame { Login login=null; FontPanel fontPanel = null; NewEmployeePane newEmployee = null; SearchEmployee searchEmployee = null; DailyWorkPanel dailyWork = null; SalarySlip salarySlip = null; UpdatePanel updatePanel = null; AddNewLogin loginPanel = null; public MainOfficeManagement(Login login, String userName) { this.login = login; initComponents(); loadPanels(); usernameLabel.setText("Username: "+userName); fontPanel.setVisible(true); } private void loadPanels() { // Add New Login loginPanel = new AddNewLogin(); backbonePanel.add(loginPanel); loginPanel.setSize(1349, 675); //font_panel fontPanel = new FontPanel(); backbonePanel.add(fontPanel); fontPanel.setSize(1349, 675); //new_employee newEmployee = new NewEmployeePane(); backbonePanel.add(newEmployee); newEmployee.setSize(1359, 675); //search_employee searchEmployee = new SearchEmployee(); backbonePanel.add(searchEmployee); searchEmployee.setSize(1349, 675); //dailyWork_panel dailyWork = new DailyWorkPanel(); backbonePanel.add(dailyWork); dailyWork.setSize(1349, 675); //salary_Slip salarySlip = new SalarySlip(); backbonePanel.add(salarySlip); salarySlip.setSize(1349, 675); //update_panel updatePanel = new UpdatePanel(); backbonePanel.add(updatePanel); updatePanel.setSize(1349, 675); hidePanels(); } private void hidePanels() { newEmployee.setVisible(false); searchEmployee.setVisible(false); dailyWork.setVisible(false); salarySlip.setVisible(false); updatePanel.setVisible(false); fontPanel.setVisible(false); loginPanel.setVisible(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); usernameLabel = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); searchEmployeeButton = new javax.swing.JButton(); workButton = new javax.swing.JButton(); salarySlipsButton = new javax.swing.JButton(); updateButton = new javax.swing.JButton(); goBackButton = new javax.swing.JButton(); LoginButton = new javax.swing.JButton(); newEmployeeButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); backbonePanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2.setText("jLabel2"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setExtendedState(6); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); usernameLabel.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N usernameLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); usernameLabel.setText("Username_Here"); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); searchEmployeeButton.setBackground(new java.awt.Color(255, 255, 255)); searchEmployeeButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N searchEmployeeButton.setText("Search Employee"); searchEmployeeButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); searchEmployeeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchEmployeeButtonActionPerformed(evt); } }); workButton.setBackground(new java.awt.Color(255, 255, 255)); workButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N workButton.setText("Daily Work"); workButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); workButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { workButtonActionPerformed(evt); } }); salarySlipsButton.setBackground(new java.awt.Color(255, 255, 255)); salarySlipsButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N salarySlipsButton.setText("Salary Slips"); salarySlipsButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); salarySlipsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { salarySlipsButtonActionPerformed(evt); } }); updateButton.setBackground(new java.awt.Color(255, 255, 255)); updateButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N updateButton.setText("Update"); updateButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); updateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateButtonActionPerformed(evt); } }); goBackButton.setBackground(new java.awt.Color(255, 255, 255)); goBackButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N goBackButton.setForeground(new java.awt.Color(102, 0, 0)); goBackButton.setText("Logout"); goBackButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); goBackButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goBackButtonActionPerformed(evt); } }); LoginButton.setBackground(new java.awt.Color(255, 255, 255)); LoginButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N LoginButton.setText("Login"); LoginButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); LoginButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoginButtonActionPerformed(evt); } }); newEmployeeButton.setBackground(new java.awt.Color(255, 255, 255)); newEmployeeButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N newEmployeeButton.setText("New Employee"); newEmployeeButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); newEmployeeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newEmployeeButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(updateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(LoginButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(newEmployeeButton, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) .addComponent(goBackButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(salarySlipsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(workButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(searchEmployeeButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(0, 48, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(newEmployeeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(searchEmployeeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(workButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(salarySlipsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(updateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(goBackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(212, Short.MAX_VALUE)) ); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); backbonePanel.setBackground(new java.awt.Color(255, 255, 255)); backbonePanel.setName(""); // NOI18N javax.swing.GroupLayout backbonePanelLayout = new javax.swing.GroupLayout(backbonePanel); backbonePanel.setLayout(backbonePanelLayout); backbonePanelLayout.setHorizontalGroup( backbonePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 581, Short.MAX_VALUE) ); backbonePanelLayout.setVerticalGroup( backbonePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 572, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setForeground(new java.awt.Color(102, 102, 255)); jLabel1.setText("HR MANAGEMENT"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(backbonePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addGap(30, 30, 30)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(71, 71, 71) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(backbonePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jSeparator2) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void searchEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchEmployeeButtonActionPerformed hidePanels(); searchEmployee.setVisible(true); }//GEN-LAST:event_searchEmployeeButtonActionPerformed private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed hidePanels(); updatePanel.setVisible(true); }//GEN-LAST:event_updateButtonActionPerformed private void goBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackButtonActionPerformed login.setVisible(true); this.dispose(); }//GEN-LAST:event_goBackButtonActionPerformed private void newEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newEmployeeButtonActionPerformed hidePanels(); newEmployee.setVisible(true); }//GEN-LAST:event_newEmployeeButtonActionPerformed private void workButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_workButtonActionPerformed hidePanels(); dailyWork.setVisible(true); }//GEN-LAST:event_workButtonActionPerformed private void salarySlipsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salarySlipsButtonActionPerformed hidePanels(); salarySlip.setVisible(true); }//GEN-LAST:event_salarySlipsButtonActionPerformed private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed hidePanels(); loginPanel.setVisible(true); }//GEN-LAST:event_LoginButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton LoginButton; private javax.swing.JPanel backbonePanel; private javax.swing.JButton goBackButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JSeparator jSeparator2; private javax.swing.JButton newEmployeeButton; private javax.swing.JButton salarySlipsButton; private javax.swing.JButton searchEmployeeButton; private javax.swing.JButton updateButton; private javax.swing.JLabel usernameLabel; private javax.swing.JButton workButton; // End of variables declaration//GEN-END:variables }
[ "swapnaragaparuchuri@Swapnas-MacBook-Air.local" ]
swapnaragaparuchuri@Swapnas-MacBook-Air.local
308e5d7789c390308104054b40a777b945c39383
d1c21b0c1bfb49a82d261a3b9410053dfb18b996
/Green_City/app/src/main/java/com/example/greencity/ProductDatabase.java
b1e8b8d0d7807917ddcac62cccd7eb91773a0d4f
[]
no_license
Chloerlld123/GreenCity
afb763f7cbc00dbacfb7ab6c46f71f560c838394
2b06ceb9c56f9f0fed694f27d240d5bf13fe4e2c
refs/heads/main
2023-05-04T21:11:36.631700
2021-05-25T11:08:08
2021-05-25T11:08:08
346,537,278
0
1
null
2021-04-14T19:54:11
2021-03-11T01:04:02
Java
UTF-8
Java
false
false
67
java
package com.example.greencity; public class ProductDatabase { }
[ "73694451+Chloerlld123@users.noreply.github.com" ]
73694451+Chloerlld123@users.noreply.github.com
af26ed50c0074ec98e0f175ff646714f7ac26dcc
3d3d61f20e94771e3670c6aeefb6924c611df082
/src/test/java/com/pzeeman/weatherstations/config/TestDBLogProcessor.java
06b7baf6fbf7bc904615855ef059439f8b1c41fc
[]
no_license
paul-zeeman/WeatherStations
d8adfead728024c0669690a97100574025c8d9eb
7251716580167ffdc4c380868fcf231a65bcb620
refs/heads/master
2022-12-08T21:49:56.343352
2020-09-07T15:36:13
2020-09-07T15:36:13
291,117,463
0
0
null
null
null
null
UTF-8
Java
false
false
1,615
java
package com.pzeeman.weatherstations.config; import com.pzeeman.weatherstations.model.Station; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) public class TestDBLogProcessor { DBLogProcessor testDBLogProcessor = new DBLogProcessor(); private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final PrintStream originalOut = System.out; @Before public void setUpStreams() { System.setOut(new PrintStream(outContent)); } @After public void restoreStreams() { System.setOut(originalOut); } @Test public void givenDummyStation_whenStationIsProcessed_thenLogIsCreated () throws Exception { Station dummyStation = new Station(); dummyStation.setStation_Name("TEST"); dummyStation.setStation_Date("09/04/2020"); dummyStation.setProvince("QC"); dummyStation.setMean_Temp("12"); dummyStation.setLowest_Monthly_Min_Temp("-25"); dummyStation.setHighest_Monthly_Maxi_Temp(""); String expectedLog = "Inserting Stations : " + dummyStation.toString(); testDBLogProcessor.process(dummyStation); assertTrue(outContent.toString().contains(expectedLog)); } }
[ "pzeeman@icloud.com" ]
pzeeman@icloud.com
3cc22dcab1da617a4c66717a8e5d0fb19e8e763e
1547cd875e05779126b7cdf1f8f0eb29c37f2670
/all-actors/src/main/java/org/sunbird/Certification.java
c1e0b1cf87f1a8f1a7c7f6d00b1339b28b9aa0d5
[ "MIT" ]
permissive
anmol2302/certificate-registry
5b703e59624d982ad6b107308671a6364e516f11
e60104b221a6b1e7f34e34d3c70223694fc8963c
refs/heads/master
2020-08-08T16:27:39.215429
2019-10-09T08:57:51
2019-10-09T08:57:51
213,869,106
0
0
MIT
2019-10-09T08:55:46
2019-10-09T08:55:46
null
UTF-8
Java
false
false
1,974
java
package org.sunbird; import org.apache.log4j.Logger; import org.sunbird.actor.core.ActorConfig; import org.sunbird.request.Request; import org.sunbird.response.Response; import org.sunbird.service.ICertService; import org.sunbird.serviceimpl.CertsServiceImpl; @ActorConfig( tasks = {"add","validate","download","generate"}, dispatcher = "", asyncTasks = {} ) public class Certification extends BaseActor { static Logger logger = Logger.getLogger(Certification.class); private static ICertService certService = new CertsServiceImpl(); @Override public void onReceive(Request request) throws BaseException { logger.info("Certification:onReceive:request arrived with operation" + request.getOperation()); if (ActorOperations.ADD.getOperation().equalsIgnoreCase(request.getOperation())) { add(request); } else if (ActorOperations.VALIDATE.getOperation().equalsIgnoreCase(request.getOperation())) { validate(request); } else if(ActorOperations.DOWNLOAD.getOperation().equalsIgnoreCase(request.getOperation())) { download(request); } else if(ActorOperations.GENERATE.getOperation().equalsIgnoreCase(request.getOperation())) { generate(request); } } private void add(Request request) throws BaseException { String id = certService.add(request); Response response = new Response(); response.put(JsonKeys.ID, id); sender().tell(response, self()); } private void validate(Request request) throws BaseException { sender().tell(certService.validate(request), self()); } private void download(Request request) throws BaseException { sender().tell(certService.download(request),self()); } private void generate(Request request) throws BaseException { sender().tell(certService.generate(request),self()); } }
[ "anmolgupta23021997@gmail.com" ]
anmolgupta23021997@gmail.com
11b6f9f2e262081880a7381c0b301ce323a23539
fed5293c8121456ecf891a3ebbd7ad50ec25ed25
/WarGame/src/missile/Missile.java
96094b894604659afa0f84ac10e1395cda441d6a
[]
no_license
andychas/WarGame
b323cbc790b48735acd19cd730d2226b590187b7
c7bba23a3fbe960d19ef7f620479162634ffa685
refs/heads/master
2021-01-13T02:36:28.860243
2015-03-09T16:04:18
2015-03-09T16:04:18
31,902,068
0
1
null
2015-03-09T15:57:12
2015-03-09T14:12:15
Java
UTF-8
Java
false
false
4,130
java
package missile; import java.io.Serializable; import java.util.List; import java.util.logging.FileHandler; import launcher.Launcher; import war.War; import war.controller.WarEventListener; import war.db.WarDBConnection; public class Missile extends AbstractMissile implements Serializable { /** * */ public enum Status {Waiting, Launched, Destroyed, Hit}; private static final long serialVersionUID = 1L; private transient List<WarEventListener> allListeners; private String missileId; private String destination; private int flyTime; private int damage; private Launcher launcher; private Status status; /** * Constructor * @param id * @param destination * @param launchTime * @param flyTime * @param damage * @param fileHandler * @param launcher */ public Missile(String id, String destination, int launchTime, int flyTime, int damage, FileHandler fileHandler, Launcher launcher , List<WarEventListener> allListeners) { super(launchTime, fileHandler); this.missileId = id; this.destination = destination; this.flyTime = flyTime; this.damage = damage; this.launcher = launcher; this.setStatus(Status.Waiting); this.allListeners = allListeners; } /** * @return id of missile */ public String getMissileId() { return missileId; } public String getDestination() { return destination; } /** * @return launch time */ public int getLaunchTime() { return super.getDelayBeforeLaunch(); } /** * @return fly time */ public int getFlyTime() { return flyTime; } /** * @return damage */ public int getDamage() { return damage; } /** * @return missile status */ public Status getStatus() { return status; } /** * set status * @param status */ public void setStatus(Status status) { this.status = status; } /** * Run missile */ public void run() { boolean reveal_status = false; try { WarDBConnection.addNewMissile(missileId,destination,damage,flyTime,status.toString()); sleep(getLaunchTime() * War.TIME_INTERVAL); synchronized (launcher) { if (launcher.isRunning()) { this.setStatus(Status.Launched); WarDBConnection.updateMissileStatus(missileId, status.toString()); // make launcher not hidden for X amount of time if (launcher.isHidden()) { launcher.revealYourSelf(); reveal_status = true; } // java.sql.Date sqlDate = Utils.utilDateToSqlDate(birthdate); for (WarEventListener l : allListeners) { l.addedMissileToModelEvent(missileId,destination,damage,flyTime); } // notify(); logMissileLaunched(); try { for(int time = 0 ; time <= flyTime ; time++){ Thread.sleep(War.TIME_INTERVAL); for (WarEventListener l : allListeners) { l.UpdatedMissileProgressToModelEvent(time, missileId , "missile",destination,damage,flyTime); } } for (WarEventListener l : allListeners) { l.DestroyMissileProgressBar(missileId , "missile"); } } catch (InterruptedException e) { } destroyTarget(); if (reveal_status == true) { launcher.hideYourSelf(); // make launcher hide again } } } } catch (InterruptedException e) { //missile is destroyed this.setStatus(Status.Destroyed); WarDBConnection.updateMissileStatus(missileId, status.toString()); if (reveal_status == true) { launcher.hideYourSelf(); // make launcher hide again } } catch (SecurityException e) { } catch (Exception e) { } } public void logMissileLaunched() {} // aspect log @Override public void destroyTarget() { logMissileHit(); this.setStatus(Status.Hit); WarDBConnection.updateMissileStatus(missileId, status.toString()); } public void logMissileHit() {} // aspect log public String getLauncherId() { return launcher.getLauncherId(); } }
[ "andrey.chas@gmail.com" ]
andrey.chas@gmail.com
d10542ef7428a182c5aa80083ba7d10a4628acf5
1f49f152cc75c76dd6ff6556a0c863996ef24c6d
/lesson4/ReadFile.java
0802df97cc079b0bcb4c0e1f0b4fbce911980d18
[]
no_license
rainman17/java1
3b868fad7d0e519a42f7faa280c71e431eb70425
498d0c7a9e1a23427d6eca6800a2a8c094e6f986
refs/heads/master
2021-01-19T11:48:20.292483
2017-03-11T09:55:33
2017-03-11T09:55:33
82,265,607
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
748
java
/* Александр Плотников Практика */ import java.util.*; import java.io.*; import java.lang.*; public class ReadFile { public static void main(String[] args){ try { FileReader file = new FileReader("oscar.txt"); BufferedReader buffer = new BufferedReader(file) ; } catch ( IOException e ) { System.out.println( "Произошла ошибка чтения" ) ; } String line = "" ; while ( ( line = buffer.readLine() ) != null ) { System.out.println( line ) ; buffer.close(); } //Files.lines(Paths.get("oscar.txt"), StandardCharsets.UTF_8).forEach(System.out::println); } }
[ "alexander-pl@mail.ru" ]
alexander-pl@mail.ru
4c00997635d202381fd8f3c9781d6b5cb1a0c8f5
6474a5958c3d7727f830fc230cdc2040f0eec627
/src/java/product/controller/addProductServlet.java
ab964ae551fda5d0ba24d7ee2891f365320c8b84
[]
no_license
GeetaPriyanka/Product-Maintenance
ad2b854ec14a1ea70611130e313be75d5a29f6a1
8dc20769ea91df65ba71089ead1bf5f65501a671
refs/heads/master
2020-03-29T01:18:26.462497
2017-11-04T16:22:32
2017-11-04T16:22:32
94,638,779
0
0
null
null
null
null
UTF-8
Java
false
false
3,204
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package product.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import product.business.Product; import product.data.ProductDB; import product.data.ProductIO; @WebServlet(name = "addProduct", urlPatterns = {"/addProduct"}) public class addProductServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestURI = request.getRequestURI(); if (requestURI.endsWith("/addProduct")) { String url = "/addProduct.jsp"; getServletContext() .getRequestDispatcher(url) .forward(request, response); } } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("button"); String url,message; String productCode = null,productDesc = null; double productPrice = 0; if (action.equals("Update Product")) { try { productCode = request.getParameter("code"); productDesc = request.getParameter("description"); productPrice = Double.parseDouble(request.getParameter("price")); message = ""; url = "/productMaint.jsp"; if(productCode.isEmpty()||productDesc.isEmpty()||request.getParameter("price").isEmpty()) { message = "Please enter a valid value in all three text boxes."; request.setAttribute("message",message); url = "/addProduct.jsp"; } else{ Product product=new Product(); product.setCode(productCode); product.setDescription(productDesc); product.setPrice(productPrice); ProductDB.insert(product); HttpSession session = request.getSession(); ArrayList<Product> products = ProductDB.selectProducts(); session.setAttribute("productList",products); } } catch(NumberFormatException e ) { message = "Please enter a valid value in all three text boxes"; request.setAttribute("message",message); url = "/addProduct.jsp"; } getServletContext() .getRequestDispatcher(url) .forward(request, response); } } }
[ "gjanapar@uncc.edu" ]
gjanapar@uncc.edu
3edacda85fcdbe30629cc235e4b7d43dbd01f200
9500aa3becad4a840630d5213d9a2acd1c4f0a7d
/src/LifeCycleServlet.java
91c927ba6e24dbeec0d3cdad33bf29c2de7dc39e
[]
no_license
wilson1745/TestServlet
c014d697a079014ce840dab3f88cc96ce70c3bec
ec850059746832c19a2e3a442ee96f4135246f9e
refs/heads/master
2020-04-03T14:53:41.708335
2018-11-25T04:28:54
2018-11-25T04:28:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,662
java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LifeCycleServlet */ public class LifeCycleServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static double startPoint = 0; public LifeCycleServlet() { super(); // TODO Auto-generated constructor stub } @Override public void init() throws ServletException { this.log("執行 init() 方法 ... "); ServletConfig conf = this.getServletConfig(); startPoint = Double.parseDouble(conf.getInitParameter("startPoint")); } @Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { this.log("執行 service() 方法 ... "); super.service(arg0, arg1); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.log("執行 doGet() 方法 ... "); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<link rel='stylesheet' type='text/css' href='../css/style.css'>"); out.println("<HTML><HEAD><TITLE>個人所得稅計算</TITLE></HEAD>"); out.println("<div align='center'><br/><fieldset style=width:90%><legend>個稅計算器</legend><br/>"); out.println("<form method='post' action='LifeCycleServlet'>"); out.println("<div style='line'>"); out.println(" <div class='leftDiv'>您的薪水為</div><div align='left' class='rightDiv'><input type='text' name='income'> 單位:元</div>"); out.println("</div><br/>"); out.println("<div style='line'>"); out.println(" <div class='leftDiv'></div><div align='left' class='rightDiv'><input type='submit' value=' 計算個稅 ' class=button></div>"); out.println("</div>"); out.println("</form>"); out.println("<BODY>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.log("執行 doPost() 方法 ... "); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML><HEAD><TITLE>個人所得稅計算</TITLE></HEAD>"); out.println("<link rel='stylesheet' type='text/css' href='../css/style.css'>"); out.println("<BODY>"); out.println("<div align='center'><br/><fieldset style=width:90%><legend>個稅計算器</legend><br/>"); try { // 從參數中獲得的薪水數目 double income = new Double(request.getParameter("income")); // 應納稅部分 double charge = income - startPoint; // 繳稅 double tax = 0; if (charge <= 0) tax = 0; if (charge > 0 && charge <= 500) tax = charge * 0.05; if (charge > 500 && charge <= 2000) tax = charge * 0.1 - 25; if (charge > 2000 && charge <= 5000) tax = charge * 0.15 - 125; if (charge > 5000 && charge <= 20000) tax = charge * 0.2 - 375; if (charge > 20000 && charge <= 40000) tax = charge * 0.25 - 1375; if (charge > 40000 && charge <= 60000) tax = charge * 0.30 - 3375; if (charge > 60000 && charge <= 80000) tax = charge * 0.35 - 6375; if (charge > 80000 && charge <= 100000) tax = charge * 0.4 - 10375; if (charge > 100000) tax = charge * 0.45 - 15375; out.println("<div style='line'>"); out.println(" <div class='leftDiv'>您的薪水為</div><div class='rightDiv'>" + income + " 元</div>"); out.println("</div>"); out.println("<div style='line'>"); out.println(" <div class='leftDiv'>您應納稅</div><div class='rightDiv'>" + tax + " 元</div>"); out.println("</div><br/>"); out.println("<input type='button' onclick='history.go(-1);' value='納稅光榮 逃稅可恥 傳回' class=button>"); } catch (Exception e) { out.println("請輸入數值類型資料。<input type='button' onclick='history.go(-1);' value='傳回' class=button>"); } out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } @Override public void destroy() { this.log("執行 destroy() 方法 ... "); startPoint = 0; } }
[ "wilson-power0130@hotmail.com" ]
wilson-power0130@hotmail.com
0bcbaa6c10471fc4fd45f4f2f30f8736958f867d
25cace8dff3452739c92132679cce9ee59465b78
/src/test/java/dev/luke10x/fis/offer/OfferApplicationTests.java
3e389df7902ad0cee57b44e3c7b3faf96ef91e73
[]
no_license
luke10x/offer-api
109078fdeacfb744d16d00741011d5da4a6cb5f5
1e8193beffff0b6af3d01bae34f52dd18ed084a4
refs/heads/main
2022-12-23T17:13:01.534833
2020-09-30T19:00:42
2020-09-30T19:00:42
296,680,558
0
0
null
null
null
null
UTF-8
Java
false
false
212
java
package dev.luke10x.fis.offer; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class OfferApplicationTests { @Test void contextLoads() { } }
[ "spam@luke10x.dev" ]
spam@luke10x.dev
0217cf4b9afec9d5e3dc814abf329911fb09948d
434a45b826a2b46dc64ad1562c8236224c6b1884
/AndroidStudioProjects/EjemploFragmento/app/build/generated/source/r/androidTest/debug/es/saladillo/alejandro/ejemplofragmento/test/R.java
21a3cef5545bf3efd10abfb0dd9e2c4864db9ede
[]
no_license
SoulApps/CrossPlatformLearning
66c42b1cb09d69e97c3a1668502b0dd9cc139625
c80d0893621e85b426f0e17410f69e5f825dfa12
refs/heads/master
2021-04-27T06:05:36.794382
2017-12-06T18:17:26
2017-12-06T18:17:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package es.saladillo.alejandro.ejemplofragmento.test; public final class R { public static final class attr { } public static final class string { public static final int app_name=0x7f020000; } }
[ "alejandrosanchezgalvin@gmail.com" ]
alejandrosanchezgalvin@gmail.com
99944537acd75542f6245bc47ed9e9c28b654743
533866e9478b0af48a716da14a7204933aba7aed
/branch/src/com/shougao/Audio/DataBase/FileList.java
812eba6391812f9d730c732f1bd8c1fd1e93f05c
[]
no_license
shougao/audio-player-qingcai
efe2494a6e4b03a3ad220ef8d20372b328ce4b06
16e84a96495d5198dea6385eaad7789bc4acc615
refs/heads/master
2016-09-06T14:02:14.588070
2015-03-15T15:24:45
2015-03-15T15:24:45
32,215,080
0
0
null
null
null
null
GB18030
Java
false
false
2,905
java
package com.shougao.Audio.DataBase; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FileList { /* * 所有id都从0开始计算,在界面显示的歌曲列表从1开始 * * 2011-8-15 */ private static String SD_PATH = "/mnt/udisk"; private ArrayList<String> mp3List = new ArrayList<String>();//用于存放显示的歌曲列表 private HashMap pathMap = new HashMap();//用于存放id - 路径对应表 private HashMap listMap = new HashMap();//用于存放id - 文件内容对象表 private int id = 0; /** * 构造函数只完成默认路径的初始化 * 如果需要改变目录可以使用本类的实例,调用initFileList函数。 */ public FileList(){ initFileList(SD_PATH); } public void initFileList(String path) { mp3List.clear();//每次新的播放列表都清楚原来的就列表 // TODO Auto-generated method stub scanFile(path); for(int i=0; i<mp3List.size(); i++){ System.out.println("file order" + mp3List.get(i)); } orderFile(); } private void orderFile() { // TODO Auto-generated method stub for(int i=0; i<mp3List.size(); i++){ for(int j=1; j<mp3List.size(); j++){ if(mp3List.get(i).compareTo(mp3List.get(j))<0){ }else{ String str = mp3List.get(j); mp3List.set(j, mp3List.get(i)); mp3List.set(i, str); } } } for(int i=0; i<mp3List.size(); i++){ System.out.println("file order:" + mp3List.get(i)); } } private void scanFile(String path) { File file = new File(path); if (!file.exists()) { return; } if (file.canRead()) { if (file.isDirectory()) { String list[] = file.list(); for (int i = 0; i < list.length; ++i) { scanFile(file.getPath() + File.separator + list[i]); } } else if (file.isFile()) { if (file.getName().endsWith("mp3") || file.getName().endsWith("MP3")) { for(String music: mp3List){ if(music.equals(file.getName())) return; } FileContent fc = new FileContent(); fc.setFileName(file.getName()); // mp3List.add((id+1) + "." + file.getName()); mp3List.add(file.getName()); fc.setFilePath(file.getAbsolutePath()); fc.setParentsPath(file.getParent()); listMap.put(id,fc); pathMap.put(id, file.getAbsolutePath()); id++; } } } file = null; } public ArrayList<String> getFileNameList() { return mp3List; } public int fileNum(){ return mp3List.size(); } public String getFilePath(int index) { // TODO Auto-generated method stub FileContent localFileContent = (FileContent) listMap.get(index); String filePath = localFileContent.getFilePath(); System.out.println(filePath); return filePath; } }
[ "zhangqingcai0815@gmail.com@f776371a-a297-3d5d-be45-683a56f9ef12" ]
zhangqingcai0815@gmail.com@f776371a-a297-3d5d-be45-683a56f9ef12
cd7acac259abf147dc97ad0fbb616d713a30c491
67af752356d60a95fb44e3e453e406271e06c76b
/AuthService/src/main/java/com/auth/controller/UserController.java
dca2454fc1405d10a00eee94fe6723fde1fe1b2a
[]
no_license
prasadkandubothu/ProductReviewMicroService
68e427fdc3fe0f4b5ecb351d19dd842a70c92254
e260bdf0a2bec4a426b9784c4e80fe6aa2a1e13d
refs/heads/master
2020-05-15T15:17:54.687402
2019-05-07T02:58:10
2019-05-07T02:58:10
182,369,365
0
0
null
null
null
null
UTF-8
Java
false
false
806
java
package com.auth.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.auth.domain.User; import com.auth.repository.UserRepository; @RestController @RequestMapping("/user") public class UserController { @Autowired BCryptPasswordEncoder encoder; @Autowired UserRepository userRepo; @PostMapping("/register") public void saveUser(@RequestBody User user) { user.setPassword(encoder.encode(user.getPassword())); userRepo.save(user); } }
[ "prasad.kandubothu@outlook.com" ]
prasad.kandubothu@outlook.com
10d0bd84a321c74f435a6f70a90ab89663816593
2ce3d1a1963dbff7eeb856b5536587f3a90ff389
/SensingCarRemoteWebControl/src/main/java/com/mycompany/myapp/controller/HomeController.java
57398eb07267bfea08fd07733207c9f261030bcb
[]
no_license
kyeongsikkim/TestRepositroy
9c3301ed137b955a913a6db95d1e9c5115f7e9ca
9bf34b4f32543976b9173846b2573971014e6a23
refs/heads/master
2021-01-20T00:51:27.566291
2017-06-26T00:08:02
2017-06-26T00:08:02
89,197,677
0
0
null
null
null
null
UTF-8
Java
false
false
10,236
java
package com.mycompany.myapp.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.eclipse.californium.core.CoapClient; import org.eclipse.californium.core.CoapResponse; import org.eclipse.californium.core.coap.MediaTypeRegistry; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping("/") public String home(Model model) { CoapClient coapClient = new CoapClient(); JSONObject jsonObject = null; String json = null; CoapResponse coapResponse = null; //---------------------카메라----------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/camera"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("leftright", jsonObject.getString("leftright")); model.addAttribute("updown", jsonObject.getString("updown")); //---------------------------rgbled---------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/rgbled"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("red", jsonObject.getString("red")); model.addAttribute("green", jsonObject.getString("green")); model.addAttribute("blue", jsonObject.getString("blue")); //----------------------------------laser-------------------------------------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/laseremitter"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("laseremitterStatus", jsonObject.getString("status")); //model.addAttribute("cameraUrl", "http://192.168.3.9:50001?action=stream"); coapClient.shutdown(); //------------------------------ultrasonicsensor------------------------------------------------ jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/ultrasonicsensor"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("ultrasonicsensorAngle", jsonObject.getString("angle")); model.addAttribute("ultrasonicsensorDistance", jsonObject.getString("distance")); //model.addAttribute("cameraUrl", "http://192.168.3.9:50001?action=stream"); coapClient.shutdown(); //---------------------LCD---------------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/lcd"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("lcdline0", jsonObject.getString("line0")); model.addAttribute("lcdline1", jsonObject.getString("line1")); //model.addAttribute("cameraUrl", "http://192.168.3.9:50001?action=stream"); coapClient.shutdown(); //--------------frontTire---------------------------------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/fronttire"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("fronttireAngle", jsonObject.getString("angle")); //---------------backTire----------------------------------------------------- jsonObject = new JSONObject(); jsonObject.put("command", "status"); json = jsonObject.toString(); coapClient.setURI("coap://192.168.3.34/backtire"); coapResponse = coapClient.post(json, MediaTypeRegistry.APPLICATION_JSON); json = coapResponse.getResponseText(); jsonObject = new JSONObject(json); model.addAttribute("backtireSpeed",jsonObject.getString("speed")); model.addAttribute("backtireDirection",jsonObject.getString("direction")); return "controlpanel"; } @RequestMapping("/camera") public void camera(String command, String leftright, String updown, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("leftright", leftright); jsonObject.put("updown", updown); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/camera"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/rgbled") public void rgbled(String command, String red, String green, String blue, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("red", red); jsonObject.put("green", green); jsonObject.put("blue", blue); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/rgbled"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/laseremitter") public void laseremitter(String command,String status,HttpServletResponse response) throws IOException{ JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("status", status); String reqJson = jsonObject.toString(); logger.info(reqJson); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/laseremitter"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/ultrasonicsensor") public void ultrasonicsensor(String command, String angle, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("angle", angle); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/ultrasonicsensor"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/lcd") public void lcd(String command, String line0, String line1, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("line0", line0); jsonObject.put("line1", line1); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/lcd"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/fronttire") public void fronttire(String command, String angle, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("angle", angle); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/fronttire"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } @RequestMapping("/backtire") public void backtire(String command, String speed,String direction, HttpServletResponse response) throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put("command", command); jsonObject.put("speed", speed); jsonObject.put("direction", direction); String reqJson = jsonObject.toString(); CoapClient coapClient = new CoapClient(); coapClient.setURI("coap://192.168.3.34/backtire"); CoapResponse coapResponse = coapClient.post(reqJson, MediaTypeRegistry.APPLICATION_JSON); String resJson = coapResponse.getResponseText(); coapClient.shutdown(); response.setContentType("application/json; charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(resJson); pw.flush(); pw.close(); } }
[ "kimks3131@naver.com" ]
kimks3131@naver.com
460c623f9f9dc19befb7dffe849363b9003ba887
60ff41249d03cad283514c58127349d0fa2086f8
/authorization_server/src/main/java/com/yclt/authorization_server/AuthorizationServerApplication.java
ced93a9cde8d4ea2607f656421250cb55a393358
[]
no_license
jgk9380/cloud_app
ad38635b8f322f39a13263287d23a63490bb4bba
6e360fc5fb81c1090bed811493c5fe01d25fbc03
refs/heads/master
2021-08-24T13:43:26.635362
2017-11-21T08:35:24
2017-11-21T08:35:24
111,521,531
0
0
null
null
null
null
UTF-8
Java
false
false
347
java
package com.yclt.authorization_server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthorizationServerApplication { public static void main(String[] args) { SpringApplication.run(AuthorizationServerApplication.class, args); } }
[ "jgk9380@sian.com" ]
jgk9380@sian.com
5ae82c757b95bd79fd430c8312f1b5336c57af7c
71d0ed0495add6d188d32e0571098405e6237c08
/src/main/java/com/balaz/PathToString.java
ed9b9b95f5e01d75d0e1133e0a22f4852bb7d462
[]
no_license
anbalaz/pantheon-find-path-task
f536bffab2c88699e2b2cfaac8b4af076f0f7c5f
24bf5b22649f277aaa5c527e70f5e3609361761c
refs/heads/master
2020-04-11T04:51:01.393764
2019-01-11T07:24:42
2019-01-11T07:24:42
161,528,815
0
0
null
2019-04-24T06:25:26
2018-12-12T18:29:03
Java
UTF-8
Java
false
false
1,104
java
package com.balaz; import java.awt.*; /** * This class changes pointers through subtraction to strings. */ public class PathToString { private static final String DIRECTION_LEFT = "l"; private static final String DIRECTION_RIGHT = "r"; private static final String DIRECTION_UP = "u"; private static final String DIRECTION_DOWN = "d"; public String directionResolver(Point sourcePoint, Point movePoint) { String direction; Point subtractPoint = (subtract(sourcePoint, movePoint)); if (subtractPoint.x == 0) { if (subtractPoint.y == 1) { direction = DIRECTION_LEFT; } else { direction = DIRECTION_RIGHT; } } else { if (subtractPoint.x == 1) { direction = DIRECTION_UP; } else { direction = DIRECTION_DOWN; } } return direction; } private Point subtract(Point sourcePoint, Point movePoint) { return new Point(sourcePoint.x - movePoint.x, sourcePoint.y - movePoint.y); } }
[ "anbalaz@gmail.com" ]
anbalaz@gmail.com
090af1e3005140b8d54026e9c5784673202bf8bd
cf5c59ca2e7f547dbbe61f296eefe944e9b91a3b
/mifosng-provider/src/main/java/org/mifosplatform/portfolio/subscription/domain/SubscriptionCommandValidator.java
cd74f83cf197e9cb42acd32fa76c081d7d49177a
[]
no_license
mujeeb1238/myfos
bf634ee161e5682859762330e699d72ae06d57cd
a6434b35b23336c705c8ca7b2796ca6478924ed0
refs/heads/master
2020-05-26T01:18:20.049668
2013-04-23T11:44:00
2013-04-23T11:44:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,483
java
package org.mifosplatform.portfolio.subscription.domain; import java.util.ArrayList; import java.util.List; import org.mifosplatform.infrastructure.core.data.ApiParameterError; import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; import org.mifosplatform.portfolio.subscription.commands.SubscriptionCommand; public class SubscriptionCommandValidator { private final SubscriptionCommand command; public SubscriptionCommandValidator(final SubscriptionCommand command) { this.command=command; } public void validateForCreate() { List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("subscription"); baseDataValidator.reset().parameter("subscriptionPeriod").value(command.getSubscriptionPeriod()).notBlank().notNull(); //baseDataValidator.reset().parameter("subscription_type").value(command.getSubscription_type()).notBlank().notNull(); baseDataValidator.reset().parameter("units").value(command.getUnits()).notBlank().notNull(); baseDataValidator.reset().parameter("subscriptionType").value(command.getsubscriptionType()); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } }
[ "mujeeb1238@gmail.com" ]
mujeeb1238@gmail.com
de699bf33c2e95efb65c1b3eb411e34bcd809df6
c6a59f6eb34184b62dbfc442bf2710a6d726867f
/src/main/java/com/example/accessingdata/User.java
1f602f3915818385f30ccc923c48c4fb881479b9
[]
no_license
dawoori/accessing-data
06a6d60bfa17b6d30a8c40b8ac1f62fdd55c9a38
42b7a00a7fa49272d77f4b3957444214985e5efa
refs/heads/master
2022-09-10T16:58:43.975929
2020-05-28T13:09:57
2020-05-28T13:09:57
264,232,558
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package com.example.accessingdata; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Getter @Setter @Entity public class User { @Id @GeneratedValue private Integer id; private String name; private String email; }
[ "daul@kookmin.ac.kr" ]
daul@kookmin.ac.kr
967f5b10b3fbfe56886df29e3b0c07ceef1f00aa
f378ddd47c8b7de6e9cf1d4228c84f73e9dc59f1
/projetos/Damolog/src/main/java/de/hwr/damolog/view/implementation/dialogs/GamerDialog.java
61d65521ba215629e07d8b34beaea18dc6947499
[]
no_license
charles-marques/dataset-375
29e2f99ac1ba323f8cb78bf80107963fc180487c
51583daaf58d5669c69d8208b8c4ed4e009001a5
refs/heads/master
2023-01-20T07:23:09.445693
2020-11-27T22:35:49
2020-11-27T22:35:49
283,315,149
0
1
null
null
null
null
ISO-8859-1
Java
false
false
9,638
java
/** * */ package de.hwr.damolog.view.implementation.dialogs; import java.util.List; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import de.hwr.damolog.constants.Strings; import de.hwr.damolog.model.Player; import de.hwr.damolog.view.implementation.PlayerTable; /** * @author nsmeenk * */ public class GamerDialog extends Dialog { private Player _selectedPlayer; private Button _addButton; private Text _nameText; private Combo _aiCombo; private Text _winText; private Text _remiText; private Text _loseText; private Button _resetButton; private Button _closeButton; private Button _deleteButton; private PlayerTable _playerTable; /** * @param pParent * @param pStyle */ public GamerDialog(Shell pParent, int pStyle) { super(pParent, pStyle); } /** * @param pParent */ public GamerDialog(Shell pParent) { super(pParent); } public int open(final List<Player> pPlayer) { _selectedPlayer = null; Shell parent = getParent(); Display display = parent.getDisplay(); final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.CLOSE); shell.setText(Strings.GAMER_DIALOG_TITLE); shell.setImage(de.hwr.damolog.constants.Images.GAMER_ICON); shell.setLayout(new GridLayout(2, true)); _playerTable = new PlayerTable(shell, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); _playerTable.getTable().setHeaderVisible(true); _playerTable.getTable().setLinesVisible(true); _playerTable.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); _playerTable.setContentProvider(ArrayContentProvider.getInstance()); _playerTable.setInput(pPlayer); Composite selectionComposite = new Composite(shell, SWT.NONE); selectionComposite.setLayout(new GridLayout(3, true)); _addButton = new Button(selectionComposite, SWT.PUSH); _addButton.setText("Neuen Spieler erstellen"); _addButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _addButton.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent pE) { Player newPlayer = new Player("Neuer Spieler", 0, 0, 0); _playerTable.add(newPlayer); pPlayer.add(newPlayer); _playerTable.setSelection(new StructuredSelection(newPlayer)); } }); Label nameLabel = new Label(selectionComposite, SWT.NONE); nameLabel.setText("Name"); nameLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _nameText = new Text(selectionComposite, SWT.BORDER); _nameText.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _nameText.setEnabled(false); _nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent pArg0) { if (_selectedPlayer != null) { _selectedPlayer.setName(_nameText.getText()); update(); } } }); Label aiLabel = new Label(selectionComposite, SWT.NONE); aiLabel.setText("Computerspieler?"); aiLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 2, 1)); _aiCombo = new Combo(selectionComposite, SWT.BORDER | SWT.READ_ONLY); _aiCombo.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 1, 1)); _aiCombo.setEnabled(false); String[] items = { "Ja", "Nein" }; _aiCombo.setItems(items); _aiCombo.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent pE) { if (_selectedPlayer != null) { if (_aiCombo.getItem(_aiCombo.getSelectionIndex()).equals("Ja")) { _selectedPlayer.setAI(true); } else { _selectedPlayer.setAI(false); } update(); } } }); Label winLabel = new Label(selectionComposite, SWT.NONE); winLabel.setText("Gewonnen"); Label remiLabel = new Label(selectionComposite, SWT.NONE); remiLabel.setText("Unentschieden"); Label loseLabel = new Label(selectionComposite, SWT.NONE); loseLabel.setText("Verloren"); _winText = new Text(selectionComposite, SWT.BORDER | SWT.READ_ONLY); _winText.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); _winText.setEnabled(false); _remiText = new Text(selectionComposite, SWT.BORDER | SWT.READ_ONLY); _remiText.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); _remiText.setEnabled(false); _loseText = new Text(selectionComposite, SWT.BORDER | SWT.READ_ONLY); _loseText.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); _loseText.setEnabled(false); _resetButton = new Button(selectionComposite, SWT.PUSH); _resetButton.setText("Zurücksetzen"); _resetButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _resetButton.setEnabled(false); _resetButton.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent pE) { _selectedPlayer.resetStats(); _winText.setText(_selectedPlayer.getWinns() + ""); _remiText.setText(_selectedPlayer.getRemis() + ""); _loseText.setText(_selectedPlayer.getRemis() + ""); if (_selectedPlayer.getWinns() != 0 || _selectedPlayer.getRemis() != 0 || _selectedPlayer.getLoses() != 0) { _resetButton.setEnabled(true); } else { _resetButton.setEnabled(false); } update(); } }); _deleteButton = new Button(selectionComposite, SWT.PUSH); _deleteButton.setText("Spieler löschen"); _deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _deleteButton.setEnabled(false); _deleteButton.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent pE) { _playerTable.remove(_selectedPlayer); pPlayer.remove(_selectedPlayer); } }); _closeButton = new Button(selectionComposite, SWT.PUSH); _closeButton.setText("Schließen"); _closeButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 3, 1)); _closeButton.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent pE) { shell.close(); } }); new Label(selectionComposite, SWT.NONE); _playerTable.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent pArg0) { StructuredSelection selection = (StructuredSelection) _playerTable.getSelection(); _selectedPlayer = (Player) selection.getFirstElement(); resetSelection(); } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return SWT.OK; } /** * */ private void resetSelection() { if (_selectedPlayer != null) { _nameText.setText(_selectedPlayer.getName()); _nameText.setEnabled(true); if (_selectedPlayer.isAI()) { _aiCombo.select(_aiCombo.indexOf("Ja")); } else { _aiCombo.select(_aiCombo.indexOf("Nein")); } _aiCombo.setEnabled(true); _winText.setText(_selectedPlayer.getWinns() + ""); _winText.setEnabled(true); _remiText.setText(_selectedPlayer.getRemis() + ""); _remiText.setEnabled(true); _loseText.setText(_selectedPlayer.getLoses() + ""); _loseText.setEnabled(true); if (_selectedPlayer.getWinns() != 0 || _selectedPlayer.getRemis() != 0 || _selectedPlayer.getLoses() != 0) { _resetButton.setEnabled(true); } else { _resetButton.setEnabled(false); } _deleteButton.setEnabled(true); } else { _nameText.setText(""); _nameText.setEnabled(false); _aiCombo.select(-1); _aiCombo.setEnabled(false); _winText.setText(""); _winText.setEnabled(false); _remiText.setText(""); _remiText.setEnabled(false); _loseText.setText(""); _loseText.setEnabled(false); _resetButton.setEnabled(false); _deleteButton.setEnabled(false); } } /** * */ private void update() { _playerTable.refresh(_selectedPlayer); } }
[ "suporte@localhost.localdomain" ]
suporte@localhost.localdomain
06487a052394e3a18f8a25b3e6d6b3fe191e266f
728246e1162547bab13ef13be23ce0b422a18fab
/src/main/java/br/com/idonate/iDonate/service/exception/QuotationNotRegisteredException.java
cb75e9b28929d7bfea34c355e7f343788cfb44b2
[]
no_license
professordezani/iDonate
f05047faa250f883c97e1d39ac3509d1845240ac
75133f9bf7dda3481952b37ad3936c47251bb2f2
refs/heads/master
2023-01-04T21:41:25.319785
2020-11-05T01:55:12
2020-11-05T01:55:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
209
java
package br.com.idonate.iDonate.service.exception; public class QuotationNotRegisteredException extends Exception { public QuotationNotRegisteredException(String message) { super(message); } }
[ "juninho_2509@hotmail.com" ]
juninho_2509@hotmail.com
53ef466bd00013498126ae8f9ae1682e1cd38165
7e512d95c474399d054a165e082c72277f13089b
/legacy-core/src/main/java/corent/djinn/SelectionDjinnButtonFactory.java
1af41f49fd448e8a6b2350cf1708d47579ed2115
[ "Apache-2.0" ]
permissive
greifentor/archimedes-legacy
d8ec4baa38d6c55c1d3e3177cc6964598541ad1e
996ec2a9d97ba684574849472a8b5b28beaa1825
refs/heads/master
2023-09-01T06:08:45.643685
2023-08-29T09:43:33
2023-08-29T09:43:33
214,502,614
0
0
Apache-2.0
2023-08-29T09:43:35
2019-10-11T18:15:48
Java
UTF-8
Java
false
false
824
java
/* * SelectionDjinnButtonFactory.java * * 05.02.2004 * * (c) by O.Lieshoff * */ package corent.djinn; import javax.swing.*; /** * Dieses Interface definiert das Verhalten einer ButtonFactory, die die notwendigen Buttons * f&uuml;r einen SelectionDjinn produzieren kann.<BR> * <HR> * * @author O.Lieshoff * */ public interface SelectionDjinnButtonFactory { /** @return Generiert einen Abbruch-Button. */ public JButton createButtonAbbruch(); /** @return Generiert einen Auswahl-Button. */ public JButton createButtonAuswahl(); /** @return Generiert einen Duplizieren-Button. */ public JButton createButtonDuplizieren(); /** @return Generiert einen Neuanlage-Button. */ public JButton createButtonNeuanlage(); }
[ "lieshoff@gmx.de" ]
lieshoff@gmx.de
b350f6f6ff3ac3c9e05871027767b78d22f6a366
8be5b750e3cfc5bd9dfda861c5bc24720052183e
/cmdb/src/main/java/com/channelsoft/ccod/support/cmdb/service/impl/AppManagerServiceImpl.java
e5015d42599970a3845aa5fe87effe7cb202f8b0
[]
no_license
3284180393/supportDev
c484c5cc2364375c52798198002a9e968d346320
b909d230e21c7d92f7e25392d8f18589c210b9ca
refs/heads/master
2022-06-26T08:10:57.617659
2020-01-17T10:36:49
2020-01-17T10:36:49
221,192,900
0
0
null
2023-09-14T00:05:34
2019-11-12T10:38:38
Java
UTF-8
Java
false
false
160,721
java
package com.channelsoft.ccod.support.cmdb.service.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.channelsoft.ccod.support.cmdb.config.NotCheckCfgApp; import com.channelsoft.ccod.support.cmdb.constant.*; import com.channelsoft.ccod.support.cmdb.dao.*; import com.channelsoft.ccod.support.cmdb.exception.*; import com.channelsoft.ccod.support.cmdb.po.*; import com.channelsoft.ccod.support.cmdb.service.IAppManagerService; import com.channelsoft.ccod.support.cmdb.service.ILJPaasService; import com.channelsoft.ccod.support.cmdb.service.INexusService; import com.channelsoft.ccod.support.cmdb.service.IPlatformAppCollectService; import com.channelsoft.ccod.support.cmdb.vo.*; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import javax.annotation.PostConstruct; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @ClassName: AppManagerServiceImpl * @Author: lanhb * @Description: AppManagerService的实现类 * @Date: 2019/11/20 14:21 * @Version: 1.0 */ @Service public class AppManagerServiceImpl implements IAppManagerService { // @Autowired // AppMapper appMapper; @Value("${nexus.platform-app-cfg-repository}") private String platformAppCfgRepository; @Value("${nexus.app-module-repository}") private String appRepository; @Value("${debug}") private boolean debug; @Value("${nexus.user}") private String nexusUserName; @Value("${nexus.password}") private String nexusPassword; @Value("${nexus.host-url}") private String nexusHostUrl; @Value("${app-publish-nexus.user}") private String publishNexusUserName; @Value("${app-publish-nexus.password}") private String publishNexusPassword; @Value("${app-publish-nexus.host-url}") private String publishNexusHostUrl; @Value("${lj-paas.idle-pool-set-name}") private String paasIdlePoolSetName; @Value("${test.demo-new-create-platform-id}") private String newDemoCreatePlatformId; @Value("${test.demo-new-create-platform-name}") private String newDemoCreatePlatformName; @Value("${ccod.domain-id-regex}") private String domainIdRegex; @Autowired IPlatformAppCollectService platformAppCollectService; @Autowired INexusService nexusService; @Autowired AppMapper appMapper; @Autowired AppCfgFileMapper appCfgFileMapper; @Autowired AppInstallPackageMapper appInstallPackageMapper; @Autowired ServerMapper serverMapper; @Autowired ServerUserMapper serverUserMapper; @Autowired PlatformMapper platformMapper; @Autowired DomainMapper domainMapper; @Autowired PlatformAppMapper platformAppMapper; @Autowired PlatformAppCfgFileMapper platformAppCfgFileMapper; @Autowired AppModuleMapper appModuleMapper; @Autowired PlatformAppDeployDetailMapper platformAppDeployDetailMapper; @Autowired PlatformResourceMapper platformResourceMapper; @Autowired PlatformAppBkModuleMapper platformAppBkModuleMapper; @Autowired PlatformUpdateSchemaMapper platformUpdateSchemaMapper; @Autowired ILJPaasService paasService; @Autowired private NotCheckCfgApp notCheckCfgApp; private boolean isPlatformCheckOngoing = false; private Set<String> notCheckCfgAppSet; private final static Logger logger = LoggerFactory.getLogger(AppManagerServiceImpl.class); private Map<String, PlatformUpdateSchemaInfo> platformUpdateSchemaMap = new ConcurrentHashMap<>(); @PostConstruct void init() throws Exception { this.notCheckCfgAppSet = new HashSet<>(this.notCheckCfgApp.getNotCheckCfgApps()); logger.info(String.format("%s will not check cfg count of app", JSONArray.toJSONString(this.notCheckCfgAppSet))); List<PlatformUpdateSchemaPo> schemaPoList = this.platformUpdateSchemaMapper.select(); for(PlatformUpdateSchemaPo po : schemaPoList) { try { PlatformUpdateSchemaInfo schemaInfo = JSONObject.parseObject(po.getContext(), PlatformUpdateSchemaInfo.class); this.platformUpdateSchemaMap.put(po.getPlatformId(), schemaInfo); } catch (Exception ex) { logger.error(String.format("parse %s platform update schema exception", po.getPlatformId()), ex); } } try { System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); // this.appMapper.selectByPrimaryKey(1); // this.appMapper.select(null, null, null, null); // platformAppCollectService.collectPlatformAppData("shltPA", null, null, null, null); // this.startCollectPlatformAppData("tool", null, null, null, null); // this.appModuleMapper.select("jj","aa", "bb", "kk"); // this.platformAppDeployDetailMapper.select("11", "22", "33", "44", // "55", "66", "77", "88"); // List<AppModuleVo> appList = this.appModuleMapper.select(null, null, null, null); // System.out.println(JSONArray.toJSONString(appList)); // List<PlatformAppDeployDetailVo> deployList = this.platformAppDeployDetailMapper.select(null, null, null, // null, null, null, null, null); // System.out.println(JSONArray.toJSONString(deployList)); // List<PlatformResourceVo> platformResourceList = this.platformResourceMapper.select(); // System.out.println(JSONArray.toJSONString(platformResourceList)); System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); } catch (Exception ex) { ex.printStackTrace(); } } private String getTempSaveDir(String directory) { String saveDir = String.format("%s/downloads/%s", System.getProperty("user.dir"), directory); return saveDir; } @Override public AppModuleVo createNewAppModule(String appName, String appAlias, String version, VersionControl versionControl, String versionControlUrl, AppInstallPackagePo installPackage, AppCfgFilePo[] cfgs, String basePath) throws Exception { return null; } @Override public AppModuleVo[] queryApps(String appName) throws DataAccessException { logger.debug(String.format("begin to query app modules : appName=%s", appName)); List<AppModuleVo> list = this.appModuleMapper.select(null, appName, null, null); logger.info(String.format("query %d app module record with appName=%s", list.size(), appName)); return list.toArray(new AppModuleVo[0]); } @Override public AppModuleVo queryAppByVersion(String appName, String version) throws ParamException, DataAccessException { logger.debug(String.format("begin to query appName=%s and version=%s app module record", appName, version)); if(StringUtils.isBlank(appName)) { logger.error("query FAIL : appName is blank"); throw new ParamException("appName is blank"); } if(StringUtils.isBlank(version)) { logger.error("query FAIL : version is blank"); throw new ParamException("version is blank"); } AppModuleVo moduleVo = this.appModuleMapper.selectByNameAndVersion(appName, version); if(moduleVo == null) { logger.warn(String.format("not find app module with appName=%s and version=%s", appName, version)); } else { logger.info(String.format("query app module[%s] with appName=%s and version=%s", JSONObject.toJSONString(moduleVo), appName, version)); } return moduleVo; } @Override public PlatformAppDeployDetailVo[] queryPlatformApps(String platformId, String domainId, String hostIp) throws DataAccessException { logger.debug(String.format("begin to query platform apps : platformId=%s, domainId=%s, hostIp=%s", platformId, domainId, hostIp)); List<PlatformAppDeployDetailVo> list = this.platformAppDeployDetailMapper.selectPlatformApps(platformId, domainId, hostIp); logger.info(String.format("query %d record with platformId=%s and domainId=%s and hostIp=%s", list.size(), platformId, domainId, hostIp)); return list.toArray(new PlatformAppDeployDetailVo[0]); } @Override public PlatformAppDeployDetailVo[] queryAppDeployDetails(String appName, String platformId, String domainId, String hostIp) throws DataAccessException { logger.debug(String.format("begin to query platform apps : appName=%s, platformId=%s, domainId=%s, hostIp=%s", appName, platformId, domainId, hostIp)); List<PlatformAppDeployDetailVo> list = this.platformAppDeployDetailMapper.selectAppDeployDetails(appName, platformId, domainId, hostIp); logger.info(String.format("query %d record with appName=%s and platformId=%s and domainId=%s and hostIp=%s", list.size(), appName, platformId, domainId, hostIp)); return list.toArray(new PlatformAppDeployDetailVo[0]); } @Override public PlatformAppModuleVo[] startCollectPlatformAppData(String platformId, String platformName, String domainId, String hostIp, String appName, String version) throws ParamException, Exception { PlatformPo platformPo = platformMapper.selectByPrimaryKey(platformId); if(platformPo != null && !platformPo.getPlatformName().equals(platformName)) { logger.error(String.format("platformId=%s platform has been record in database, but its name is %s, not %s", platformId, platformPo.getPlatformName(), platformName)); throw new ParamException(String.format("platformId=%s platform has been record in database, but its name is %s, not %s", platformId, platformPo.getPlatformName(), platformName)); } if(this.isPlatformCheckOngoing) { logger.error(String.format("start platform=%s app data collect FAIL : some collect task is ongoing", platformId)); throw new Exception(String.format("start platform=%s app data collect FAIL : some collect task is ongoing", platformId)); } try { this.isPlatformCheckOngoing = true; List<PlatformAppModuleVo> modules = this.platformAppCollectService.collectPlatformAppData(platformId, platformName, domainId, hostIp, appName, version); Map<String, List<PlatformAppModuleVo>> platformAppModuleMap = modules.stream().collect(Collectors.groupingBy(PlatformAppModuleVo::getPlatformId)); if(platformAppModuleMap.keySet().size() > 1) { logger.error(String.format("platformId=%s client collected data platformId not unique : [%s]", platformId, String.join(",", platformAppModuleMap.keySet()))); throw new ClientCollectDataException(String.format("platformId=%s client collected data platformId not unique : [%s]", platformId, String.join(",", platformAppModuleMap.keySet()))); } else if(!platformAppModuleMap.containsKey(platformId)) { logger.error(String.format("platformId=%s client collected data's platformId is %s", platformId, JSONObject.toJSONString(platformAppModuleMap.keySet()))); throw new ClientCollectDataException(String.format("platformId=%s client collected data's platformId is %s", platformId, JSONObject.toJSONString(platformAppModuleMap.keySet()))); } platformAppModuleMap = modules.stream().collect(Collectors.groupingBy(PlatformAppModuleVo::getPlatformName)); if(platformAppModuleMap.keySet().size() > 1) { logger.error(String.format("platformName=%s client collected data platformName not unique : [%s]", platformName, String.join(",", platformAppModuleMap.keySet()))); throw new ClientCollectDataException(String.format("platformName=%s client collected data platformName not unique : [%s]", platformName, String.join(",", platformAppModuleMap.keySet()))); } else if(!platformAppModuleMap.containsKey(platformName)) { logger.error(String.format("platformName=%s client collected data's platformName is %s", platformName, JSONObject.toJSONString(platformAppModuleMap.keySet()))); throw new ClientCollectDataException(String.format("platformName=%s client collected data's platformName is %s", platformName, JSONObject.toJSONString(platformAppModuleMap.keySet()))); } Map<String, List<PlatformAppModuleVo>> domainAppMap = modules.stream().collect(Collectors.groupingBy(PlatformAppModuleVo::getDomainId)); Map<String, DomainPo> domainMap = domainMapper.select(platformId, null).stream().collect(Collectors.toMap(DomainPo::getDomainId, Function.identity())); for(String reportDomainId : domainAppMap.keySet()) { Map<String, PlatformAppModuleVo> domainNameAppModuleMap = domainAppMap.get(reportDomainId) .stream().collect(Collectors.toMap(PlatformAppModuleVo::getDomainName, Function.identity())); if(domainNameAppModuleMap.size() > 1) { logger.error(String.format("domainId=%s has not unique domainName=[%s]", reportDomainId, String.join(",", domainNameAppModuleMap.keySet()))); throw new ClientCollectDataException(String.format("domainId=%s has not unique domainName=[%s]", reportDomainId, String.join(",", domainNameAppModuleMap.keySet()))); } String reportDomainName = domainAppMap.get(reportDomainId).get(0).getDomainName(); if(domainMap.containsKey(reportDomainId) && domainMap.get(reportDomainId).getDomainName().equals(reportDomainName)) { logger.error(String.format("domainId=%s is record in database, but its name=%s not %s", reportDomainId, domainMap.get(reportDomainId).getDomainName(), reportDomainName)); throw new ClientCollectDataException(String.format("domainId=%s is record in database, but its name=%s not %s", reportDomainId, domainMap.get(reportDomainId).getDomainName(), reportDomainName)); } } if(platformPo == null) { platformPo = modules.get(0).getPlatform(); platformMapper.insert(platformPo); } for(List<PlatformAppModuleVo> domainModules : domainAppMap.values()) { DomainPo domainPo = domainModules.get(0).getDomain(); if(!domainMap.containsKey(domainPo.getDomainId())) { domainMapper.insert(domainPo); } } Map<String, AppModuleVo> appModuleMap = new HashMap<>(); handleCollectedPlatformAppModules(appModuleMap, modules.toArray(new PlatformAppModuleVo[0])); return modules.toArray(new PlatformAppModuleVo[0]); } finally { this.isPlatformCheckOngoing = false; } } @Override public PlatformAppModuleVo[] startCheckPlatformAppData(String platformId, String platformName, String domainName, String hostIp, String appName, String version) throws Exception { if(this.isPlatformCheckOngoing) { logger.error(String.format("start platform=%s app data check FAIL : some collect task is ongoing", platformId)); throw new Exception(String.format("start platform=%s app data check FAIL : some collect task is ongoing", platformId)); } this.isPlatformCheckOngoing = true; List<PlatformAppModuleVo> modules = this.platformAppCollectService.collectPlatformAppData(platformId, platformName, domainName, hostIp, appName, version); this.isPlatformCheckOngoing = false; return modules.toArray(new PlatformAppModuleVo[0]); } /** * 将一组平台应用模块上传到nexus * 如果某个模块对应的component已经在nexus存在则对比安装包的md5,如果md5不一致则报错,该平台应用模块上传失败,否则上传该平台应用模块的配置文件 * 如果component不存在则创建该应用对应的component(appName/appAlias/version),并上传该平台应用的配置文件 * @param modules 需要上传的模块 * @throws Exception */ void handleCollectedPlatformAppModules(Map<String, AppModuleVo> appModuleMap, PlatformAppModuleVo[] modules) throws Exception { Map<String, List<NexusAssetInfo>> appFileAssetMap = new HashMap<>(); for(PlatformAppModuleVo module : modules) { try { boolean handleSucc = handlePlatformAppModule(module, appModuleMap, appFileAssetMap); if(!handleSucc) { logger.error(String.format("handle [%s] FAIL", module.toString())); } } catch (Exception ex) { logger.error(String.format("handle [%s] exception", module.toString()), ex); } } } /** * 处理客户端收集的平台应用信息 * 如果该模块在db中没有记录则需要上传二进制安装包以及配置文件并在数据库创建一条记录 * 归档平台应用的配置文件,并在数据库创建一条平台应用详情记录 * @param module 客户端收集的平台应用信息 * @param appModuleMap 已经处理的应用模块 * @param appFileAssetMap 已经处理的应用模块在nexus的存储记录 * @return 添加后的模块 * @throws DataAccessException 查询数据库异常 * @throws InterfaceCallException 调用nexus接口异常 * @throws NexusException nexus返回调用失败信息或是解析nexus调用结果失败 * @throws DBNexusNotConsistentException cmdb记录的信息和nexus不一致 */ private boolean handlePlatformAppModule(PlatformAppModuleVo module, Map<String, AppModuleVo> appModuleMap, Map<String, List<NexusAssetInfo>> appFileAssetMap) throws DataAccessException, InterfaceCallException, NexusException, DBNexusNotConsistentException { AppPo appPo = module.getAppInfo(); String appName = appPo.getAppName(); String appVersion = appPo.getVersion(); String appDirectory = appPo.getAppNexusDirectory(); AppModuleVo moduleVo; if(appModuleMap.containsKey(appDirectory)) { moduleVo = appModuleMap.get(appDirectory); } else { moduleVo = appModuleMapper.selectByNameAndVersion(appName, appVersion); } List<NexusAssetInfo> appFileAssetList; if(appFileAssetMap.containsKey(appDirectory)) { appFileAssetList = appFileAssetMap.get(appDirectory); } else { String group = String.format("/%s/%s", appName, appVersion); appFileAssetList = this.nexusService.queryGroupAssetMap(this.nexusHostUrl, this.nexusUserName, nexusPassword, this.appRepository, group); } if(moduleVo != null && appFileAssetList.size() == 0) { logger.error(String.format("cmdb data is not matched with nexus : cmdb has appName=%s and version=%s record but nexus has not", appName, appVersion)); throw new DBNexusNotConsistentException(String.format("cmdb data is not matched with nexus : cmdb has appName=%s and version=%s record but nexus has not", appName, appVersion)); } if(moduleVo == null && appFileAssetList.size() > 0) { logger.error(String.format("cmdb data is not matched with nexus : nexus has appName=%s and version=%s record but cmdb has not", appName, appVersion)); throw new DBNexusNotConsistentException(String.format("cmdb data is not matched with nexus : nexus has appName=%s and version=%s record but cmdb has not", appName, appVersion)); } if(appFileAssetList.size() == 0) { appFileAssetList = addAppToNexus(appName, appVersion, module.getInstallPackage(), module.getCfgs(), this.appRepository, appDirectory); appFileAssetMap.put(appDirectory, appFileAssetList); } if(moduleVo == null) { moduleVo = addNewAppToDB(appPo, module.getInstallPackage(), module.getCfgs()); appModuleMap.put(appDirectory, moduleVo); } if(StringUtils.isBlank(module.getInstallPackage().getLocalSavePath())) { logger.error(String.format("handle [%s] FAIL : not receive install package[%s]", module.toString(), module.getInstallPackage().getFileName())); return false; } String compareResult = compareAppFileWithNexusRecord(appName, appVersion, moduleVo.getInstallPackage(), moduleVo.getCfgs(), appFileAssetList); if(StringUtils.isNotBlank(compareResult)) { logger.error(String.format("collected appName=%s and version=%s files is not matched with nexus : %s", appName, appVersion, compareResult)); throw new DBNexusNotConsistentException(String.format("collected appName=%s and version=%s files is not matched with nexus : %s", appName, appVersion, compareResult)); } PlatformAppPo platformApp = module.getPlatformApp(); platformApp.setAppId(appPo.getAppId()); this.platformAppMapper.insert(platformApp); for(DeployFileInfo cfgFilePo : module.getCfgs()) { PlatformAppCfgFilePo po = new PlatformAppCfgFilePo(platformApp.getPlatformAppId(), cfgFilePo); this.platformAppCfgFileMapper.insert(po); } logger.info(String.format("[%s] platform app module handle SUCCESS", module.toString())); return true; } private AppModuleVo addNewAppToDB(AppPo app, DeployFileInfo installPackage, DeployFileInfo[] cfgs) throws DataAccessException { if(debug) { if(StringUtils.isBlank(app.getAppType())) app.setAppType(AppType.CCOD_KERNEL_MODULE.name); if(StringUtils.isBlank(app.getCcodVersion())) app.setCcodVersion("4.5"); } this.appMapper.insert(app); AppInstallPackagePo instPkgPo = new AppInstallPackagePo(app.getAppId(), installPackage); this.appInstallPackageMapper.insert(instPkgPo); List<AppCfgFilePo> cfgList = new ArrayList<>(); for(DeployFileInfo cfg : cfgs) { AppCfgFilePo cfgFilePo = new AppCfgFilePo(app.getAppId(), cfg); this.appCfgFileMapper.insert(cfgFilePo); cfgList.add(cfgFilePo); } AppModuleVo moduleVo = new AppModuleVo(app, instPkgPo, cfgList); return moduleVo; } private List<NexusAssetInfo> addAppToNexus(String appName, String version, DeployFileInfo installPackage, DeployFileInfo[] cfgs, String repository, String directory) throws InterfaceCallException, NexusException { logger.info(String.format("prepare to upload appName=%s and version=%s app to directory=%s at repository=%s", appName, version, directory, repository)); List<DeployFileInfo> uploadFiles = new ArrayList<>(); uploadFiles.add(installPackage); uploadFiles.addAll(Arrays.asList(cfgs)); List<NexusAssetInfo> fileAssetList = this.nexusService.uploadRawComponent(this.nexusHostUrl, this.nexusUserName, this.nexusPassword, repository, directory, uploadFiles.toArray(new DeployFileInfo[0])); return fileAssetList; } /** * 将安装包和配置文件和nexus存储的信息 * @param appName 应用名 * @param version 应用版本 * @param installPackage 安装包 * @param cfgs 配置文件 * @param NexusFileList 该应用存储在nexus的文件信息 * @return 对比结果,如果完全符合返回"" */ private String compareAppFileWithNexusRecord(String appName, String version, AppInstallPackagePo installPackage, List<AppCfgFilePo> cfgs, List<NexusAssetInfo> NexusFileList) { logger.debug(String.format("begin to compare appName=%s and version=%s installPackage and cfgs with nexus record", appName, version)); Map<String, NexusAssetInfo> nexusFileMap = NexusFileList.stream().collect(Collectors.toMap(NexusAssetInfo::getPath, Function.identity())); StringBuffer sb = new StringBuffer(); String path = String.format("%s/%s/%s", appName, version, installPackage.getFileName()); if(!nexusFileMap.containsKey(path)) { sb.append(String.format("installPackageFile=%s not in nexus record,", installPackage.getFileName()));; } else if(!nexusFileMap.get(path).getMd5().equals(installPackage.getMd5())) { sb.append(String.format("installPackage=%s md5=%s is not equal with nexus md5=%s," ,installPackage.getFileName(), installPackage.getMd5(), nexusFileMap.get(path).getMd5()));; } if(!this.notCheckCfgAppSet.contains(appName)) { if(cfgs.size() != nexusFileMap.size() -1) { sb.append(String.format("cfg count is %d but nexus is %d,", cfgs.size(), nexusFileMap.size() -1)); } else { for(AppCfgFilePo cfg : cfgs) { path = String.format("%s/%s/%s", appName, version, cfg.getFileName()); if(!nexusFileMap.containsKey(path)) { sb.append(String.format("cfg=%s not in nexus,", cfg.getFileName())); } } } } logger.info(String.format("the result of files of appName=%s with version=%s compare with nexus is : %s", sb.toString())); return sb.toString().replaceAll(",$", ""); } @Override public void createNewPlatformAppDataCollectTask(String platformId, String platformName, String domainId, String hostIp, String appName, String version) throws Exception { logger.info(String.format("begin to create platformId=%s, domainId=%s, hostIp=%s, appName=%s, version=%s app collect task", platformId, domainId, hostIp, appName, version)); if(this.isPlatformCheckOngoing) { logger.error(String.format("create platform collect task FaIL : some collect task is ongoing")); throw new Exception(String.format("create platform collect task FaIL : some collect task is ongoing")); } ExecutorService executor = Executors.newFixedThreadPool(1); Thread taskThread = new Thread(new Runnable(){ @Override public void run() { try { startCollectPlatformAppData(platformId, platformName, domainId, hostIp, appName, version); } catch (Exception ex) { logger.error(String.format("start platformId=%s, domainId=%s, hostIp=%s, appName=%s, version=%s app collect task exception", platformId, domainId, hostIp, appName, version), ex); } } }); executor.execute(taskThread); executor.shutdown(); } /** * 部署应用到域主机 * @param domain 部署应用的域信息 * @param setId 部署该应用的域归属的set id * @param bkSet 部署该应用的set信息 * @param hostList 平台下面的所有主机列表 * @param deployOperationList 部署的操作 * @param appList 应用记录列表 * @throws InterfaceCallException 调用蓝鲸api失败 * @throws LJPaasException 蓝鲸api返回调用失败或是解析蓝鲸api返回结果 */ private void deployAppsToDomainHost(DomainPo domain, String setId, LJSetInfo bkSet, List<LJHostInfo> hostList, List<AppUpdateOperationInfo> deployOperationList, List<AppModuleVo> appList) throws InterfaceCallException, LJPaasException, NexusException, IOException { logger.debug(String.format("begin to add new %d apps to %s/%s(%s)/%s(%s)", deployOperationList.size(), domain.getPlatformId(), setId, bkSet.getBkSetName(), domain.getDomainId(), domain.getDomainName())); Date now = new Date(); List<PlatformAppPo> deployAppList = new ArrayList<>(); Map<String, LJHostInfo> hostMap = hostList.stream().collect(Collectors.toMap(LJHostInfo::getHostInnerIp, Function.identity())); Map<String, List<AppModuleVo>> appMap = appList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); for(AppUpdateOperationInfo deployOperationInfo : deployOperationList) { Map<String, AppModuleVo> versionMap = appMap.get(deployOperationInfo.getAppName()).stream().collect(Collectors.toMap(AppModuleVo::getVersion, Function.identity())); AppModuleVo appPo = versionMap.get(deployOperationInfo.getTargetVersion()); LJHostInfo bkHost = hostMap.get(deployOperationInfo.getHostIp()); logger.debug(String.format("insert appId=%d to hostIp=%s with appAlias=%s and deployDirectory=%s to database", appPo.getAppId(), bkHost.getHostInnerIp(), deployOperationInfo.getAppAlias(), deployOperationInfo.getBasePath())); PlatformAppPo deployApp = new PlatformAppPo(); deployApp.setAppAlias(deployOperationInfo.getAppAlias()); deployApp.setHostIp(bkHost.getHostInnerIp()); deployApp.setAppRunner(deployOperationInfo.getAppRunner()); deployApp.setDeployTime(now); deployApp.setAppId(appPo.getAppId()); deployApp.setPlatformId(domain.getPlatformId()); deployApp.setBasePath(deployOperationInfo.getBasePath()); deployApp.setDomainId(domain.getDomainId()); platformAppMapper.insert(deployApp); deployAppList.add(deployApp); handlePlatformAppCfgs(deployApp, appPo, deployOperationInfo.getCfgs()); } paasService.bindDeployAppsToBizSet(bkSet.getBkBizId(), setId, bkSet.getBkSetId(), bkSet.getBkSetName(), deployAppList); } /** * 处理平台应用配置文件 * 处理流程:首先下载配置文件,其次将下载的配置文件按一定格式上传到nexus去,最后入库 * @param platformAppPo 平台应用 * @param appPo 该平台应用对应的app详情 * @param cfgs 配置文件信息 * @throws InterfaceCallException 接口调用失败 * @throws NexusException nexus返回失败或是处理nexus返回信息失败 * @throws IOException 保存文件失败 */ private void handlePlatformAppCfgs(PlatformAppPo platformAppPo, AppModuleVo appPo, List<AppFileNexusInfo> cfgs) throws InterfaceCallException, NexusException, IOException { List<DeployFileInfo> fileList = new ArrayList<>(); List<PlatformAppCfgFilePo> cfgFileList = new ArrayList<>(); Date now = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); String directory = platformAppPo.getPlatformAppDirectory(appPo.getAppName(), appPo.getVersion(), platformAppPo); logger.debug(String.format("begin to handle %s cfgs", directory)); String tmpSaveDir = getTempSaveDir(DigestUtils.md5DigestAsHex(directory.getBytes())); for(AppFileNexusInfo cfg : cfgs) { String downloadUrl = cfg.getFileNexusDownloadUrl(this.nexusHostUrl); logger.debug(String.format("download cfg from %s", downloadUrl)); String savePth = nexusService.downloadFile(this.nexusUserName, this.nexusPassword, downloadUrl, tmpSaveDir, cfg.getFileName()); DeployFileInfo fileInfo = new DeployFileInfo(); fileInfo.setExt(cfg.getExt()); fileInfo.setFileMd5(cfg.getMd5()); fileInfo.setLocalSavePath(savePth); fileInfo.setNexusRepository(this.appRepository); fileInfo.setNexusDirectory(directory); fileInfo.setFileSize(cfg.getFileSize()); fileInfo.setFileName(cfg.getFileName()); fileList.add(fileInfo); PlatformAppCfgFilePo cfgFilePo = new PlatformAppCfgFilePo(); cfgFilePo.setMd5(cfg.getMd5()); cfgFilePo.setFileName(cfg.getFileName()); cfgFilePo.setExt(cfg.getExt()); cfgFilePo.setPlatformAppId(platformAppPo.getPlatformAppId()); cfgFilePo.setCreateTime(now); cfgFilePo.setDeployPath(cfg.getDeployPath()); cfgFilePo.setNexusDirectory(directory); cfgFilePo.setNexusRepository(this.platformAppCfgRepository); cfgFileList.add(cfgFilePo); } logger.debug(String.format("upload platform app cfgs to %s/%s/%s", nexusHostUrl, this.platformAppCfgRepository, directory)); Map<String, NexusAssetInfo> assetMap = nexusService.uploadRawComponent(this.nexusHostUrl, this.nexusUserName, this.nexusPassword, this.platformAppCfgRepository, directory, fileList.toArray(new DeployFileInfo[0])) .stream().collect(Collectors.toMap(NexusAssetInfo::getPath, Function.identity())); logger.debug(String.format("delete platformAppId=%d record from platform_app_cfg_file", platformAppPo.getPlatformAppId())); platformAppCfgFileMapper.delete(null, platformAppPo.getPlatformAppId()); for(PlatformAppCfgFilePo cfgFilePo : cfgFileList) { String path = String.format("%s/%s", directory, cfgFilePo.getFileName()); cfgFilePo.setNexusAssetId(assetMap.get(path).getId()); logger.debug(String.format("insert %s cfg into platform_app_cfg_file", path)); this.platformAppCfgFileMapper.insert(cfgFilePo); } logger.info(String.format("handle %s cfgs SUCCESS", directory)); } private void addNewDomainToPlatform(String domainId, String domainName, List<AppUpdateOperationInfo> domainApps, List<AppModuleVo> appList, PlatformPo platform, String setId, LJSetInfo bkSet, List<LJHostInfo> bkHostList) throws InterfaceCallException, LJPaasException, NexusException, IOException { Date now = new Date(); DomainPo newDomain = new DomainPo(); newDomain.setComment(""); newDomain.setDomainId(domainId); newDomain.setPlatformId(platform.getPlatformId()); newDomain.setStatus(1); newDomain.setUpdateTime(now); newDomain.setCreateTime(now); newDomain.setDomainName(domainName); this.domainMapper.insert(newDomain); deployAppsToDomainHost(newDomain, setId, bkSet, bkHostList, domainApps, appList); } /** * 将指定域的一组应用删除 * @param domain 指定删除应用的域 * @param bkSet 该域归属的蓝鲸paas的set * @param deleteOperationList 需要移除的应用操作列表 * @param appBkModuleList 被移除的应用对应的蓝鲸模块关系列表 * @throws ParamException * @throws InterfaceCallException 调用蓝鲸api失败 * @throws LJPaasException 蓝鲸api返回调用失败或是解析蓝鲸api返回结果失败 */ private void removeAppsFromDomainHost(DomainPo domain, LJSetInfo bkSet, List<AppUpdateOperationInfo> deleteOperationList, List<PlatformAppBkModulePo> appBkModuleList) throws ParamException, InterfaceCallException, LJPaasException { logger.debug(String.format("begin to remove %d apps from platformId=%s and domainId=%s", deleteOperationList.size(), domain.getPlatformId(), domain.getDomainId())); List<PlatformAppBkModulePo> removedAppBkModuleList = new ArrayList<>(); Map<Integer, PlatformAppBkModulePo> appBkModuleMap = appBkModuleList.stream().collect(Collectors.toMap(PlatformAppBkModulePo::getPlatformAppId, Function.identity())); for(AppUpdateOperationInfo deleteOperationInfo : deleteOperationList) { removedAppBkModuleList.add(appBkModuleMap.get(deleteOperationInfo.getPlatformAppId())); } this.paasService.disBindDeployAppsToBizSet(bkSet.getBkBizId(), bkSet.getBkSetId(), removedAppBkModuleList); for(AppUpdateOperationInfo deleteOperationInfo : deleteOperationList) { logger.debug(String.format("delete id=%d platform app cfg record", deleteOperationInfo.getPlatformAppId())); platformAppCfgFileMapper.delete(null, deleteOperationInfo.getPlatformAppId()); logger.debug(String.format("delete id=%d platform app record", deleteOperationInfo.getPlatformAppId())); platformAppMapper.delete(deleteOperationInfo.getPlatformAppId(), null, null); } logger.debug(String.format("remove %d apps from platformId=%s and domainId=%s SUCCESS", removedAppBkModuleList.size(), domain.getPlatformId(), domain.getDomainId())); } /** * 检查平台升级计划参数是否合法 * @param schema 需要检查的平台升级计划 * @param domainList 该平台下的所有域 * @param appList 相关的应用列表 * @param deployApps 该平台已经部署的应用 * @param bkSetList 该平台的对应的蓝鲸biz下的所有set列表 * @param bkHostList 该平台下所有主机 * @param appBkModuleList 该平台升级签部署的应用和蓝鲸模块的关系表 * @return 如果检查通过返回空,否则返回检查失败原因 */ private String checkPlatformUpdateTask(PlatformUpdateSchemaInfo schema, List<DomainPo> domainList, List<AppModuleVo> appList, List<PlatformAppPo> deployApps, List<LJSetInfo> bkSetList, List<LJHostInfo> bkHostList, List<PlatformAppBkModulePo> appBkModuleList, Map<String, BizSetDefine> bizSetDefineMap) { if(schema.getDomainUpdatePlanList() == null) { schema.setDomainUpdatePlanList(new ArrayList<>()); } Map<String, DomainPo> domainMap = domainList.stream().collect(Collectors.toMap(DomainPo::getDomainId, Function.identity())); Map<String, DomainPo> domainNameMap = domainList.stream().collect(Collectors.toMap(DomainPo::getDomainName, Function.identity())); Map<String, LJSetInfo> setMap = bkSetList.stream().collect(Collectors.toMap(LJSetInfo::getBkSetName, Function.identity())); PlatformUpdateTaskType taskType = schema.getTaskType(); StringBuffer sb = new StringBuffer(); for(DomainUpdatePlanInfo planInfo : schema.getDomainUpdatePlanList()) { if(StringUtils.isBlank(planInfo.getDomainId()) || StringUtils.isBlank(planInfo.getDomainName())) { return "domainId and domainName of domain update plan can not be blank"; } else if(!Pattern.matches(this.domainIdRegex, planInfo.getDomainId())) { sb.append(String.format("%s,", planInfo.getDomainId())); } } if(StringUtils.isNotBlank(sb.toString())) { return String.format("domainId %s is not regal : only wanted 0-9a-z or - and - can not be beginning or end", sb.toString().replaceAll(",$", "")); } Map<String, List<DomainUpdatePlanInfo>> updateDomainMap = schema.getDomainUpdatePlanList().stream().collect(Collectors.groupingBy(DomainUpdatePlanInfo::getDomainId)); Map<String, List<PlatformAppPo>> domainAppMap = deployApps.stream().collect(Collectors.groupingBy(PlatformAppPo::getDomainId)); for(String domainId : updateDomainMap.keySet()) { if(updateDomainMap.get(domainId).size() > 1) { logger.error(String.format("domainId %s duplicate", domainId)); sb.append(String.format("%s;", domainId)); } } if(StringUtils.isNotBlank(sb.toString())) { return String.format("domainId %s duplicate", sb.toString().replaceAll(";$", "")); } updateDomainMap = schema.getDomainUpdatePlanList().stream().collect(Collectors.groupingBy(DomainUpdatePlanInfo::getDomainName)); for(String domainName : updateDomainMap.keySet()) { if(updateDomainMap.get(domainName).size() > 1) { logger.error(String.format("domainName %s duplicate", domainName)); sb.append(String.format("%s;", domainName)); } } if(StringUtils.isNotBlank(sb.toString())) { return String.format("domainName %s duplicate", sb.toString().replaceAll(";$", "")); } for(DomainUpdatePlanInfo planInfo : schema.getDomainUpdatePlanList()) { DomainUpdateType updateType = planInfo.getUpdateType(); if(updateType == null) { sb.append(String.format("DomainUpdateType of %s is blank;", JSONObject.toJSONString(planInfo))); continue; } switch (updateType) { case ADD: if(domainMap.containsKey(planInfo.getDomainId())) { sb.append(String.format("%s domain %s, but %s exist;", updateType.name, planInfo.getDomainId(), planInfo.getDomainId())); continue; } else if(domainNameMap.containsKey(planInfo.getDomainName())) { sb.append(String.format("%s domain %s, but %s exist;", updateType.name, planInfo.getDomainName(), planInfo.getDomainName())); continue; } break; default: if(!domainMap.containsKey(planInfo.getDomainId())) { sb.append(String.format("%s domain %s, but %s not exist;", updateType.name, planInfo.getDomainId(), planInfo.getDomainId())); continue; } else if(!domainNameMap.containsKey(planInfo.getDomainName())) { sb.append(String.format("%s domain %s, but %s not exist;", updateType.name, planInfo.getDomainName(), planInfo.getDomainName())); continue; } else if(!setMap.containsKey(planInfo.getBkSetName())) { sb.append(String.format("%s %s of %s of domain %s not exist;", updateType.name, planInfo.getDomainId(), planInfo.getBkSetName())); continue; } break; } switch (taskType) { case CREATE: switch (updateType) { case ADD: if(!bizSetDefineMap.containsKey(planInfo.getBkSetName())) { sb.append(String.format("setName %s of new create domain %s not exist", planInfo.getBkSetName(), planInfo.getDomainId())); continue; } break; default: sb.append(String.format("%s of %s only support %s %s, not %s;", taskType.name, schema.getPlatformId(), DomainUpdateType.ADD.name, planInfo.getDomainId(), updateType.name)); continue; } break; case DELETE: switch (updateType) { case DELETE: break; default: sb.append(String.format("%s of %s only support %s %s, not %s;", taskType.name, schema.getPlatformId(), DomainUpdateType.ADD.name, planInfo.getDomainId(), updateType.name)); continue; } break; case UPDATE: switch (updateType) { case ADD: if(!setMap.containsKey(planInfo.getBkSetName())) { sb.append(String.format("bkSetName=%s of domain %s not exist;", planInfo.getBkSetName(), planInfo.getDomainId())); continue; } break; default: break; } break; } if(planInfo.getAppUpdateOperationList() == null || planInfo.getAppUpdateOperationList().size() == 0) { // sb.append(String.format("operation of %s %s is blank;", updateType.name, planInfo.getDomainId())); continue; } List<PlatformAppPo> domainAppList = new ArrayList<>(); if(domainAppMap.containsKey(planInfo.getDomainId())) { domainAppList = domainAppMap.get(planInfo.getDomainId()); } String operationCheckResult = updateOperationCheck(updateType, planInfo.getAppUpdateOperationList(), appList, domainAppList, appBkModuleList, bkHostList); sb.append(operationCheckResult); } // Map<String, List<AppUpdateOperationInfo>> ipAppMap = allOperationList.stream().collect(Collectors.groupingBy(AppUpdateOperationInfo::getHostIp)); // for(String hostIp : ipAppMap.keySet()) // { // Map<String, List<AppUpdateOperationInfo>> appNameMap = ipAppMap.get(hostIp).stream().collect(Collectors.groupingBy(AppUpdateOperationInfo::getAppName)); // for(String appName : appNameMap.keySet()) // { // if(appNameMap.get(appName).size() > 1) // { // Set<String> aliasSet = new HashSet<>(); // for(AppUpdateOperationInfo opt : appNameMap.get(appName)) // { // switch (opt.getOperation()) // { // case ADD: // case CFG_UPDATE: // case VERSION_UPDATE: // if(aliasSet.contains(opt.getAppAlias())) // { // sb.append(String.format("%s at %s alias duplicate;", appName, hostIp)); // } // else // { // aliasSet.add(opt.getAppAlias()); // } // default: // break; // } // } // } // } // } return sb.toString(); } /** * 验证应用升级操作的相关蚕食是否正确 * @param updateType 域升级方案类型 * @param operationList 域升级的应用升级操作明细 * @param appList 当前应用列表 * @param deployApps 域已经部署的应用列表 * @param appBkModuleList 已经部署的应用和蓝鲸模块的关系表 * @param hostList 平台下所有服务器列表 * @return 检查结果,如果为空则表示检查通过,否则返回检查失败原因 */ private String updateOperationCheck(DomainUpdateType updateType, List<AppUpdateOperationInfo> operationList, List<AppModuleVo> appList, List<PlatformAppPo> deployApps, List<PlatformAppBkModulePo> appBkModuleList, List<LJHostInfo> hostList) { Map<String, LJHostInfo> hostMap = hostList.stream().collect(Collectors.toMap(LJHostInfo::getHostInnerIp, Function.identity())); Map<String, List<AppModuleVo>> appMap = appList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); Map<Integer, PlatformAppBkModulePo> appBkModuleMap = appBkModuleList.stream().collect(Collectors.toMap(PlatformAppBkModulePo::getPlatformAppId, Function.identity())); Map<Integer, PlatformAppPo> platformAppMap = deployApps.stream().collect(Collectors.toMap(PlatformAppPo::getPlatformAppId, Function.identity())); StringBuffer sb = new StringBuffer(); Set<String> deployAppSet = new HashSet<>(); for(PlatformAppPo po : deployApps) { if(deployAppSet.contains(po.getAppAlias())) { sb.append(String.format("%s,", po.getAppAlias())); } else { deployAppSet.add(po.getAppAlias()); } } if(StringUtils.isNotBlank(sb.toString())) { return String.format("alias %s duplicate;", sb.toString().replaceAll(",$", "")); } for(AppUpdateOperationInfo operationInfo : operationList) { if(operationInfo.getOperation() == null) { sb.append(String.format("operationType of %s is blank;", JSONObject.toJSONString(operationInfo))); } else if(AppUpdateOperation.START.equals(operationInfo.getOperation()) || AppUpdateOperation.STOP.equals(operationInfo.getOperation())) { sb.append(String.format("%s of %s is not support now", operationInfo.getOperation().name, JSONObject.toJSONString(operationInfo))); } else if(DomainUpdateType.ADD.equals(updateType) && !AppUpdateOperation.ADD.equals(operationInfo.getOperation())) { sb.append(String.format("DomainUpdateType=%s only support AppUpdateOperation=%s, not %s of %s;", DomainUpdateType.ADD.name, AppUpdateOperation.ADD.name, operationInfo.getOperation().name, JSONObject.toJSONString(operationInfo))); } else if(DomainUpdateType.DELETE.equals(updateType) && !AppUpdateOperation.DELETE.equals(operationInfo.getOperation())) { sb.append(String.format("DomainUpdateType=%s only support AppUpdateOperation=%s, not %s of %s;", DomainUpdateType.DELETE.name, AppUpdateOperation.DELETE.name, operationInfo.getOperation().name, JSONObject.toJSONString(operationInfo))); } else if(!appMap.containsKey(operationInfo.getAppName())) { sb.append(String.format("appName %s of %s not exist;", operationInfo.getAppName(), JSONObject.toJSONString(operationInfo))); } else if(StringUtils.isBlank(operationInfo.getHostIp())) { sb.append(String.format("host of %s is blank;", JSONObject.toJSONString(operationInfo))); } else if(!hostMap.containsKey(operationInfo.getHostIp())) { sb.append(String.format("host %s of %s not exist;", operationInfo.getHostIp(), JSONObject.toJSONString(operationInfo))); } else { Map<String, AppModuleVo> versionMap = appMap.get(operationInfo.getAppName()).stream().collect(Collectors.toMap(AppModuleVo::getVersion, Function.identity())); AppUpdateOperation operation = operationInfo.getOperation(); switch (operation) { case ADD: if(StringUtils.isBlank(operationInfo.getTargetVersion())) { sb.append(String.format("%s : version of %s is blank;", operation.name, operationInfo.getAppName())); } else if(!versionMap.containsKey(operationInfo.getTargetVersion())) { sb.append(String.format("%s : version %s of %s not exist;", operation.name, operationInfo.getTargetVersion(), operationInfo.getAppName())); } if(StringUtils.isBlank(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias of %s is blank;", operation.name, operationInfo.getAppName())); } else if(deployAppSet.contains(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias %s duplicate;", operation.name, operationInfo.getAppAlias())); } else { deployAppSet.add(operationInfo.getAppAlias()); } if(StringUtils.isBlank(operationInfo.getBasePath())) { sb.append(String.format("%s : basePath of %s is blank;", operation.name, operationInfo.getAppAlias())); } if(StringUtils.isBlank(operationInfo.getAppRunner())) { sb.append(String.format("%s : appRunner of %s is blank;", operation.name, operationInfo.getAppAlias())); } if(operationInfo.getCfgs() == null || operationInfo.getCfgs().size() == 0) { sb.append(String.format("%s : cfg of %s is 0;", operation.name, operationInfo.getAppAlias())); } else { String compareResult = cfgFileCompare(versionMap.get(operationInfo.getTargetVersion()), operationInfo.getCfgs()); if(StringUtils.isNotBlank(compareResult)) sb.append(String.format("%s : cfg of %s is not match [%s];", operation.name, operationInfo.getAppAlias(), compareResult)); } break; case VERSION_UPDATE: if(!platformAppMap.containsKey(operationInfo.getPlatformAppId())) { sb.append(String.format("%s : platformAppId=%d of %s not exist", operation.name, operationInfo.getPlatformAppId(), operationInfo.getAppName())); } if(StringUtils.isBlank(operationInfo.getTargetVersion())) { sb.append(String.format("%s : target version of %s is blank;", operation.name, operationInfo.getAppName())); } else if(!versionMap.containsKey(operationInfo.getTargetVersion())) { sb.append(String.format("%s : target version %s of %s not exist;", operation.name, operationInfo.getTargetVersion(), operationInfo.getAppName())); } if(StringUtils.isBlank(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version of %s is blank;", operation.name, operationInfo.getAppName())); } else if(!versionMap.containsKey(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version %s of %s not exist;", operation.name, operationInfo.getOriginalVersion(), operationInfo.getAppName())); } if(StringUtils.isBlank(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias of %s is blank;", operation.name, operationInfo.getAppName())); } else if(!deployAppSet.contains(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias of %s not exist;", operation.name, operationInfo.getAppName())); } if(operationInfo.getCfgs() == null || operationInfo.getCfgs().size() == 0) { sb.append(String.format("%s : cfg of %s is 0;", operation.name, JSONObject.toJSONString(operationInfo))); } if(!appBkModuleMap.containsKey(operationInfo.getPlatformAppId())) { sb.append(String.format("%s : platformAppId=%d of %s lj paas module relation not exist;", operation.name, operationInfo.getPlatformAppId(), JSONObject.toJSONString(operationInfo))); } else { String compareResult = cfgFileCompare(versionMap.get(operationInfo.getTargetVersion()), operationInfo.getCfgs()); if(StringUtils.isNotBlank(compareResult)) sb.append(String.format("%s : cfg of %s is not match [%s];", operation.name, JSONObject.toJSONString(operationInfo), compareResult)); } break; case CFG_UPDATE: if(StringUtils.isBlank(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version of %s is blank;", operation.name, operationInfo.getAppName())); } else if(!versionMap.containsKey(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version %s of %s not exist;", operation.name, operationInfo.getOriginalVersion(), operationInfo.getAppName())); } if(StringUtils.isBlank(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias of %s is blank;", operation.name, JSONObject.toJSONString(operationInfo))); } else if(!deployAppSet.contains(operationInfo.getAppAlias())) { sb.append(String.format("%s : %s of %s not exist;", operation.name, operationInfo.getAppAlias(), operationInfo.getAppName())); } if(operationInfo.getCfgs() == null || operationInfo.getCfgs().size() == 0) { sb.append(String.format("%s : cfg of %s is 0;", operation.name, JSONObject.toJSONString(operationInfo))); } if(!appBkModuleMap.containsKey(operationInfo.getPlatformAppId())) { sb.append(String.format("%s : platformAppId=%d of %s lj paas module relation not exist;", operation.name, operationInfo.getPlatformAppId(), JSONObject.toJSONString(operationInfo))); } else { String compareResult = cfgFileCompare(versionMap.get(operationInfo.getOriginalVersion()), operationInfo.getCfgs()); if(StringUtils.isNotBlank(compareResult)) sb.append(String.format("%s : cfg of %s is not match[%s];", operation.name, JSONObject.toJSONString(operationInfo), compareResult)); } break; case DELETE: if(StringUtils.isBlank(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version of %s is blank;", operation.name, JSONObject.toJSONString(operationInfo))); } else if(!versionMap.containsKey(operationInfo.getOriginalVersion())) { sb.append(String.format("%s : original version %s of %s not exist;", operation.name, operationInfo.getOriginalVersion(), JSONObject.toJSONString(operationInfo))); } if(StringUtils.isBlank(operationInfo.getAppAlias())) { sb.append(String.format("%s : alias of %s is blank;", operation.name, JSONObject.toJSONString(operationInfo))); } else if(!deployAppSet.contains(operationInfo.getAppAlias())) { sb.append(String.format("%s : %s of %s not exist;", operation.name, operationInfo.getAppAlias(), operationInfo.getAppName())); } else { deployAppSet.remove(operationInfo.getAppAlias()); } if(!appBkModuleMap.containsKey(operationInfo.getPlatformAppId())) { sb.append(String.format("%s : platformAppId=%d of %s lj paas module relation not exist;", operation.name, operationInfo.getPlatformAppId(), JSONObject.toJSONString(operationInfo))); } break; default: } } } return sb.toString(); } /** * 将平台升级结果保存到数据库并同步给蓝鲸paas * @param schemaInfo 执行完的平台升级计划 * @param platformPo 执行计划的平台信息 * @param domainList 平台下的所有域列表 * @param appList 当前应用列表 * @param deployApps 执行升级计划前部署应用列表 * @param appBkModuleList 执行升级计划前部署应用同蓝鲸paas平台的关系 * @param bkSetList 该平台对应蓝鲸biz下的所有set列表 * @param bkHostList 该平台所有服务器列表 * @throws ParamException * @throws InterfaceCallException 调用蓝鲸api或是nexus的api失败 * @throws LJPaasException 蓝鲸api返回接口调用失败或是解析蓝鲸api返回结果失败 * @throws NexusException nexus api返回调用失败或是解析nexus api的返回结果失败 * @throws IOException 处理文件失败 */ private void recordPlatformUpdateResult(PlatformUpdateSchemaInfo schemaInfo, PlatformPo platformPo, List<DomainPo> domainList, List<AppModuleVo> appList, List<PlatformAppPo> deployApps, List<PlatformAppBkModulePo> appBkModuleList, List<LJSetInfo> bkSetList, List<LJHostInfo> bkHostList) throws ParamException, InterfaceCallException, LJPaasException, NexusException, IOException { Map<String, LJSetInfo> setMap = bkSetList.stream().collect(Collectors.toMap(LJSetInfo::getBkSetName, Function.identity())); Map<String, DomainPo> domainMap = domainList.stream().collect(Collectors.toMap(DomainPo::getDomainId, Function.identity())); Map<Integer, PlatformAppPo> platformAppMap = deployApps.stream().collect(Collectors.toMap(PlatformAppPo::getPlatformAppId, Function.identity())); Map<String, List<AppModuleVo>> appMap = appList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); for(DomainUpdatePlanInfo planInfo : schemaInfo.getDomainUpdatePlanList()) { switch (planInfo.getUpdateType()) { case ADD: addNewDomainToPlatform(planInfo.getDomainId(), planInfo.getDomainName(), planInfo.getAppUpdateOperationList(), appList, platformPo, planInfo.getSetId(), setMap.get(planInfo.getBkSetName()), bkHostList); break; case DELETE: deleteDomainFromPlatform(domainMap.get(planInfo.getDomainId()), setMap.get(planInfo.getBkSetName()), planInfo.getAppUpdateOperationList(), bkHostList); break; default: DomainPo domainPo = domainMap.get(planInfo.getDomainId()); LJSetInfo bkSet = setMap.get(planInfo.getBkSetName()); Map<AppUpdateOperation, List<AppUpdateOperationInfo>> operationMap = planInfo.getAppUpdateOperationList().stream().collect(Collectors.groupingBy(AppUpdateOperationInfo::getOperation)); if(operationMap.containsKey(AppUpdateOperation.DELETE)) { removeAppsFromDomainHost(domainPo, bkSet, operationMap.get(AppUpdateOperation.DELETE), appBkModuleList); } if(operationMap.containsKey(AppUpdateOperation.VERSION_UPDATE)) { for(AppUpdateOperationInfo updateOperationInfo : operationMap.get(AppUpdateOperation.VERSION_UPDATE)) { Map<String, AppModuleVo> versionMap = appMap.get(updateOperationInfo.getAppName()).stream().collect(Collectors.toMap(AppModuleVo::getVersion, Function.identity())); updateDeployAppModuleVersion(updateOperationInfo, platformAppMap.get(updateOperationInfo.getPlatformAppId()), versionMap.get(updateOperationInfo.getOriginalVersion()), versionMap.get(updateOperationInfo.getTargetVersion())); } } if(operationMap.containsKey(AppUpdateOperation.CFG_UPDATE)) { for(AppUpdateOperationInfo cfgOperationInfo : operationMap.get(AppUpdateOperation.CFG_UPDATE)) { Map<String, AppModuleVo> versionMap = appMap.get(cfgOperationInfo.getAppName()).stream().collect(Collectors.toMap(AppModuleVo::getVersion, Function.identity())); modifyDeployAppModuleCfg(cfgOperationInfo, platformAppMap.get(cfgOperationInfo.getPlatformAppId()), versionMap.get(cfgOperationInfo.getOriginalVersion())); } } if(operationMap.containsKey(AppUpdateOperation.ADD)) { deployAppsToDomainHost(domainPo, planInfo.getSetId(), bkSet, bkHostList, operationMap.get(AppUpdateOperation.ADD), appList); } } } } private String cfgFileCompare(AppModuleVo app, List<AppFileNexusInfo> cfgs) { StringBuffer sb = new StringBuffer(); Map<String, AppCfgFilePo> appCfgMap = app.getCfgs().stream().collect(Collectors.toMap(AppCfgFilePo::getFileName, Function.identity())); Map<String, AppFileNexusInfo> comparedCfgMap = cfgs.stream().collect(Collectors.toMap(AppFileNexusInfo::getFileName, Function.identity())); for(String fileName : appCfgMap.keySet()) { if(!comparedCfgMap.containsKey(fileName)) { sb.append(String.format("cfg %s is not exist,", fileName)); } } for(String fileName : comparedCfgMap.keySet()) { if(!appCfgMap.containsKey(fileName)) { sb.append(String.format("%s is not wanted cfg,", fileName)); } } sb.toString().replaceAll(",$", ""); return sb.toString(); } @Override public void updatePlatformUpdateSchema(PlatformUpdateSchemaInfo updateSchema) throws ParamException, InterfaceCallException, LJPaasException, NexusException, IOException { logger.debug(String.format("begin to update platform update schema : %s", JSONObject.toJSONString(updateSchema))); Date now = new Date(); if(StringUtils.isBlank(updateSchema.getPlatformId())) { logger.error(String.format("platformId of update schema is blank")); throw new ParamException(String.format("platformId of update schema is blank")); } else if(StringUtils.isBlank(updateSchema.getPlatformName())) { logger.error(String.format("platformName of update schema is blank")); throw new ParamException(String.format("platformName of update schema is blank")); } else if(updateSchema.getBkBizId() <= 0) { logger.error(String.format("bkBizId of update schema is 0")); throw new ParamException(String.format("not bkBizId of update schema")); } LJBizInfo bkBiz = paasService.queryBizInfoById(updateSchema.getBkBizId()); if(bkBiz == null) { logger.error(String.format("bkBizId=%d biz not exist", updateSchema.getBkBizId())); throw new ParamException(String.format("bkBizId=%d biz not exist", updateSchema.getBkBizId())); } if(!updateSchema.getPlatformName().equals(bkBiz.getBkBizName())) { logger.error(String.format("bkBizName of bizBkId is %s, not %s", updateSchema.getBkBizId(), bkBiz.getBkBizName(), updateSchema.getPlatformName())); throw new ParamException(String.format("bkBizName of bizBkId is %s, not %s", updateSchema.getBkBizId(), bkBiz.getBkBizName(), updateSchema.getPlatformName())); } PlatformPo platformPo = platformMapper.selectByPrimaryKey(updateSchema.getPlatformId()); if(platformPo == null) { if(!updateSchema.getStatus().equals(UpdateStatus.CREATE)) { logger.error(String.format("%s platform %s not exist", updateSchema.getStatus().name, updateSchema.getPlatformId())); throw new ParamException(String.format("%s platform %s not exist", updateSchema.getStatus().name, updateSchema.getPlatformId())); } else { platformPo = new PlatformPo(updateSchema.getPlatformId(), updateSchema.getPlatformName(), updateSchema.getBkBizId(), updateSchema.getBkCloudId(), CCODPlatformStatus.SCHEMA_CREATE_PLATFORM, updateSchema.getCcodVersion(), "create by platform create schema"); if(StringUtils.isNotBlank(updateSchema.getCcodVersion())) { platformPo.setCcodVersion("CCOD4.1"); } this.platformMapper.insert(platformPo); } } if(!platformPo.getPlatformName().equals(updateSchema.getPlatformName())) { logger.error(String.format("platformName of %s is %s, not %s", platformPo.getPlatformId(), platformPo.getPlatformName(), updateSchema.getPlatformName())); throw new ParamException(String.format("bkBizName of bizBkId is %s, not %s", updateSchema.getBkBizId(), bkBiz.getBkBizName(), updateSchema.getPlatformName())); } if(updateSchema.getPlatformId().equals("ccAppTest")) { updateSchema.setStatus(UpdateStatus.SUCCESS); for(DomainUpdatePlanInfo planInfo : updateSchema.getDomainUpdatePlanList()) { planInfo.setStatus(UpdateStatus.SUCCESS); } } CCODPlatformStatus platformStatus = CCODPlatformStatus.getEnumById(platformPo.getStatus()); if(platformStatus == null) { logger.error(String.format("%s status %d is unknown", platformPo.getPlatformId(), platformPo.getStatus())); throw new ParamException(String.format("%s status %d is unknown", platformPo.getPlatformId(), platformPo.getStatus())); } switch (updateSchema.getTaskType()) { case CREATE: switch (platformStatus) { case SCHEMA_CREATE_PLATFORM: if(StringUtils.isBlank(updateSchema.getCcodVersion())) { logger.error(String.format("ccod version of %s is blank", updateSchema.getPlatformId())); throw new ParamException(String.format("ccod version of %s is blank", updateSchema.getPlatformId())); } break; default: logger.error(String.format("not support %s platform %s which status is %s", updateSchema.getTaskType().name, updateSchema.getPlatformId(), platformStatus.name)); throw new ParamException(String.format("not support %s platform %s which status is %s", updateSchema.getTaskType().name, updateSchema.getPlatformId(), platformStatus.name)); } break; case UPDATE: switch (platformStatus) { case WAIT_SYNC_EXIST_PLATFORM_TO_PAAS: case UNKNOWN: case SCHEMA_CREATE_PLATFORM: logger.error(String.format("not support %s platform %s which status is %s", updateSchema.getTaskType().name, updateSchema.getPlatformId(), platformStatus.name)); throw new ParamException(String.format("not support %s platform %s which status is %s", updateSchema.getTaskType().name, updateSchema.getPlatformId(), platformStatus.name)); default: break; } break; default: logger.error(String.format("current version not support %s %s", updateSchema.getTaskType().name, updateSchema.getPlatformId())); throw new ParamException(String.format("current version not support %s %s", updateSchema.getTaskType().name, updateSchema.getPlatformId())); } List<DomainPo> domainList = this.domainMapper.select(updateSchema.getPlatformId(), null); List<AppModuleVo> appList = this.appModuleMapper.select(null, null, null, null); List<PlatformAppPo> deployApps = this.platformAppMapper.select(updateSchema.getPlatformId(), null, null, null, null, null); List<LJSetInfo> bkSetList = this.paasService.queryBkBizSet(updateSchema.getBkBizId()); List<LJHostInfo> bkHostList = this.paasService.queryBKHost(updateSchema.getBkBizId(), null, null, null, null); List<PlatformAppBkModulePo> appBkModuleList = this.platformAppBkModuleMapper.select(updateSchema.getPlatformId(), null, null, null, null, null); Map<String, BizSetDefine> bizSetDefineMap = paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); String schemaCheckResult; logger.debug(String.format("%s %s has been %s", updateSchema.getTaskType().name, updateSchema.getPlatformId(), updateSchema.getStatus().name)); switch (updateSchema.getTaskType()) { case CREATE: switch (updateSchema.getStatus()) { case CANCEL: case FAIL: this.platformUpdateSchemaMap.remove(updateSchema.getPlatformId()); this.platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); this.platformMapper.delete(updateSchema.getPlatformId()); break; case SUCCESS: schemaCheckResult = checkPlatformUpdateTask(updateSchema, domainList, appList, deployApps, bkSetList, bkHostList, appBkModuleList, bizSetDefineMap); if(StringUtils.isNotBlank(schemaCheckResult)) { logger.error(String.format("schema is not legal : %s", schemaCheckResult)); throw new ParamException(String.format("schema is not legal : %s", schemaCheckResult)); } recordPlatformUpdateResult(updateSchema, platformPo, domainList, appList, deployApps, appBkModuleList, bkSetList, bkHostList); if(this.platformUpdateSchemaMap.containsKey(updateSchema.getPlatformId())) this.platformUpdateSchemaMap.remove(updateSchema.getPlatformId()); this.platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); platformPo.setStatus(CCODPlatformStatus.RUNNING.id); platformPo.setUpdateTime(now); this.platformMapper.update(platformPo); break; default: schemaCheckResult = checkPlatformUpdateTask(updateSchema, domainList, appList, deployApps, bkSetList, bkHostList, appBkModuleList, bizSetDefineMap); if(StringUtils.isNotBlank(schemaCheckResult)) { logger.error(String.format("schema is not legal : %s", schemaCheckResult)); throw new ParamException(String.format("schema is not legal : %s", schemaCheckResult)); } this.platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); this.platformUpdateSchemaMap.put(updateSchema.getPlatformId(), updateSchema); PlatformUpdateSchemaPo schemaPo = new PlatformUpdateSchemaPo(); schemaPo.setPlatformId(updateSchema.getPlatformId()); schemaPo.setContext(JSONObject.toJSONString(updateSchema).getBytes()); platformUpdateSchemaMapper.insert(schemaPo); break; } break; case UPDATE: switch (updateSchema.getStatus()) { case CANCEL: case FAIL: this.platformUpdateSchemaMap.remove(updateSchema.getPlatformId()); this.platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); platformPo.setStatus(CCODPlatformStatus.RUNNING.id); platformPo.setUpdateTime(now); this.platformMapper.update(platformPo); break; case SUCCESS: schemaCheckResult = checkPlatformUpdateTask(updateSchema, domainList, appList, deployApps, bkSetList, bkHostList, appBkModuleList, bizSetDefineMap); if(StringUtils.isNotBlank(schemaCheckResult)) { logger.error(String.format("schema is not legal : %s", schemaCheckResult)); throw new ParamException(String.format("schema is not legal : %s", schemaCheckResult)); } recordPlatformUpdateResult(updateSchema, platformPo, domainList, appList, deployApps, appBkModuleList, bkSetList, bkHostList); if(this.platformUpdateSchemaMap.containsKey(updateSchema.getPlatformId())) this.platformUpdateSchemaMap.remove(updateSchema.getPlatformId()); this.platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); platformPo.setStatus(CCODPlatformStatus.RUNNING.id); platformPo.setUpdateTime(now); this.platformMapper.update(platformPo); break; default: schemaCheckResult = checkPlatformUpdateTask(updateSchema, domainList, appList, deployApps, bkSetList, bkHostList, appBkModuleList, bizSetDefineMap); if(StringUtils.isNotBlank(schemaCheckResult)) { logger.error(String.format("schema is not legal : %s", schemaCheckResult)); throw new ParamException(String.format("schema is not legal : %s", schemaCheckResult)); } this.platformUpdateSchemaMap.put(updateSchema.getPlatformId(), updateSchema); platformPo.setStatus(CCODPlatformStatus.SCHEMA_UPDATE_PLATFORM.id); platformPo.setUpdateTime(now); platformMapper.update(platformPo); platformUpdateSchemaMapper.delete(updateSchema.getPlatformId()); PlatformUpdateSchemaPo schemaPo = new PlatformUpdateSchemaPo(); schemaPo.setPlatformId(updateSchema.getPlatformId()); schemaPo.setContext(JSONObject.toJSONString(updateSchema).getBytes()); platformUpdateSchemaMapper.insert(schemaPo); break; } break; default: logger.error(String.format("current version not support platform %s", updateSchema.getTaskType().name)); throw new ParamException(String.format("current version not support platform %s", updateSchema.getTaskType().name)); } } // private DomainUpdatePlanInfo generateDomainUpdatePlan(DomainUpdateType updateType, UpdateStatus updateStatus, AppUpdateOperation operation, int domId, String domainName, String domainId, List<CCODModuleInfo> deployApps, List<AppPo> appList) // { // Date now = new Date(); // DomainUpdatePlanInfo planInfo = new DomainUpdatePlanInfo(); // planInfo.setDomainId(domainId); // planInfo.setDomainName(domainName); // planInfo.setCreateTime(now); // planInfo.setUpdateTime(now); // planInfo.setExecuteTime(now); // List<AppUpdateOperationInfo> operationList = new ArrayList<>(); // Map<String, List<AppPo>> nameAppMap = appList.stream().collect(Collectors.groupingBy(AppPo::getAppName)); // for(CCODModuleInfo deployApp : deployApps) // { // Map<String, AppPo> versionAppMap = nameAppMap.get(deployApp.getModuleName()).stream().collect(Collectors.toMap(AppPo::getVersion, Function.identity())); // AppPo chosenApp = versionAppMap.get(deployApp.getVersion()); // if(!DomainUpdateType.ADD.equals(updateType)) // { // for(String version : versionAppMap.keySet()) // { // if(!version.equals(deployApp.getVersion())) // { // chosenApp = versionAppMap.get(version); // break; // } // } // } // AppUpdateOperationInfo operationInfo = generateAppUpdateOperation(operation, deployApp, chosenApp, updateStatus); // operationList.add(operationInfo); // } // planInfo.setAppUpdateOperationList(operationList); // return planInfo; // } // private AppUpdateOperationInfo generateAppUpdateOperation(AppUpdateOperation operation, CCODModuleInfo deployApp, AppPo targetApp, UpdateStatus updateStatus) // { // Date now = new Date(); // AppUpdateOperationInfo info = new AppUpdateOperationInfo(); //// info.setAppRunner(deployApp.getAppRunner()); //// info.setBasePath(deployApp.getBasePath()); //// info.setHostIp(deployApp.getHostIp()); //// info.setCfgs(new ArrayList<>()); //// for(PlatformAppCfgFilePo cfg : deployApp.getCfgs()) //// { //// AppFileNexusInfo fileInfo = new AppFileNexusInfo(); //// fileInfo.setDeployPath(deployApp.get); //// NexusAssetInfo assetInfo = new NexusAssetInfo(); //// Checksum checksum = new Checksum(); //// checksum.md5 = cfg.getMd5(); //// assetInfo.setChecksum(checksum); //// assetInfo.setId(cfg.getNexusAssetId()); //// assetInfo.setPath(cfg.getNexusDirectory()); //// assetInfo.setRepository(cfg.getNexusRepository()); //// info.getCfgs().add(assetInfo); //// } //// info.setOperation(operation); //// info.setOriginalAppId(deployApp.getAppId()); //// info.setTargetAppId(deployApp.getAppId()); //// switch (operation) //// { //// case ADD: //// info.setOriginalAppId(0); //// break; //// case DELETE: //// info.setTargetAppId(0); //// info.setCfgs(new ArrayList<>()); //// break; //// case CFG_UPDATE: //// info.setTargetAppId(0); //// break; //// default: //// break; //// } // return info; // } /** * 将某个域从平台移除 * @param deleteDomain 需要删除的域 * @param bkSet 该域归属的蓝鲸paas的set * @param bkHostList 该域关联的服务器信息 * @throws InterfaceCallException 调用蓝鲸api异常 * @throws LJPaasException 蓝鲸api返回调用失败或是解析蓝鲸返回消息失败 */ private void deleteDomainFromPlatform(DomainPo deleteDomain, LJSetInfo bkSet, List<AppUpdateOperationInfo> deleteOperationList, List<LJHostInfo> bkHostList) throws ParamException, InterfaceCallException, LJPaasException { logger.debug(String.format("begin to remove domainId=%s and domainName=%s from platformId=%s", deleteDomain.getDomainId(), deleteDomain.getDomainName(), deleteDomain.getPlatformId())); List<PlatformAppBkModulePo> domainBkModuleList = this.platformAppBkModuleMapper.select(deleteDomain.getPlatformId(), deleteDomain.getDomainId(), null, null, null, null); this.removeAppsFromDomainHost(deleteDomain, bkSet, deleteOperationList, domainBkModuleList); logger.debug(String.format("delete all domainId=%s and platformId=%s app record", deleteDomain.getDomainId(), deleteDomain.getPlatformId())); platformAppMapper.delete(null, deleteDomain.getPlatformId(), deleteDomain.getDomainId()); logger.debug(String.format("delete domainId=%s and platformId=%s record from database", deleteDomain.getDomainId(), deleteDomain.getPlatformId())); domainMapper.delete(deleteDomain.getDomainId(), deleteDomain.getPlatformId()); logger.info(String.format("delete domainId=%s from platformId=%s SUCCESS", deleteDomain.getDomainId(), deleteDomain.getPlatformId())); } /** * 升级已有的应用模块 * @param updateApp 模块升级操作信息 * @param deployApp 该模块的部署记录 * @param originalApp 升级前app信息 * @param targetApp 升级后app信息 * @throws DataAccessException cmdb数据库访问异常 * @throws InterfaceCallException 调用蓝鲸api失败 * @throws LJPaasException 蓝鲸api返回调用失败或是解析蓝鲸api返回结果 */ private void updateDeployAppModuleVersion(AppUpdateOperationInfo updateApp, PlatformAppPo deployApp, AppModuleVo originalApp, AppModuleVo targetApp) throws InterfaceCallException, NexusException, IOException { logger.debug(String.format("begin to modify %s version from %s to %s at %s/%s/%s", updateApp.getAppAlias(), originalApp.getVersion(), targetApp.getVersion(), deployApp.getPlatformId(), deployApp.getDomainId(), deployApp.getHostIp())); Date now = new Date(); handlePlatformAppCfgs(deployApp, targetApp, updateApp.getCfgs()); deployApp.setAppId(targetApp.getAppId()); deployApp.setDeployTime(now); logger.debug(String.format("update platformAppId=%d platform_app record", deployApp.getPlatformAppId())); platformAppMapper.update(deployApp); logger.info(String.format("update %s version from %s to %s at %s SUCCESS", updateApp.getAppAlias(), originalApp.getVersion(), targetApp.getVersion(), deployApp.getHostIp())); } /** * 修改已有的应用的配置文件 * @param modifiedCfgApp 修改配置文件的操作信息 * @param deployApp 被修改配置应用部署记录 * @param appModule 被修改配置app记录 * @throws DataAccessException cmdb数据库访问异常 * @throws InterfaceCallException 调用蓝鲸api失败 * @throws LJPaasException 蓝鲸api返回调用失败或是解析蓝鲸api返回结果 */ private void modifyDeployAppModuleCfg(AppUpdateOperationInfo modifiedCfgApp, PlatformAppPo deployApp, AppModuleVo appModule) throws InterfaceCallException, NexusException, IOException { logger.debug(String.format("begin to modify %d %s cfgs at %s/%s/%s", modifiedCfgApp.getCfgs().size(), modifiedCfgApp.getAppAlias(), deployApp.getPlatformId(), deployApp.getDomainId(), deployApp.getHostIp())); handlePlatformAppCfgs(deployApp, appModule, modifiedCfgApp.getCfgs()); Date now = new Date(); deployApp.setDeployTime(now); logger.debug(String.format("update platformAppId=%d platform_app record deployTime", deployApp.getPlatformAppId())); platformAppMapper.update(deployApp); logger.debug(String.format("modify %d %s cfgs at %s/%s/%s SUCCESS", modifiedCfgApp.getCfgs().size(), modifiedCfgApp.getAppAlias(), deployApp.getPlatformId(), deployApp.getDomainId(), deployApp.getHostIp())); } /** * 根据现有数据生成一个demo平台创建计划 * @param bkBizId 需要创建的平台biz id * @param platformId 需要创建的平台id * @param platformName 需要创建的平台名 * @param bkCloudId 该平台服务器对应的cloud id * @return 新创建的demo平台创建计划 * @throws ParamException * @throws InterfaceCallException * @throws LJPaasException */ private PlatformUpdateSchemaInfo generatePlatformCreateDemoSchema(String platformId, String platformName, int bkBizId, int bkCloudId) throws ParamException, InterfaceCallException, LJPaasException { PlatformPo platform = platformMapper.selectByPrimaryKey(platformId); if (platform != null) { logger.error(String.format("create new platform create schema FAIL : %s exist", platformId)); throw new ParamException(String.format("create new platform create schema FAIL : %s exist", platformId)); } platform = platformMapper.selectByNameBizId(platformName, null); if (platform != null) { logger.error(String.format("create new platform create schema FAIL : %s exist", platformName)); throw new ParamException(String.format("create new platform create schema FAIL : %s exist", platformName)); } LJBizInfo bkBiz = paasService.queryBizInfoById(bkBizId); if (bkBiz == null) { logger.error(String.format("create new platform create schema FAIL : bkBizId=%d biz not exist", bkBizId)); throw new ParamException(String.format("create new platform create schema FAIL : bkBizId=%d biz not exist", bkBizId)); } if (!platformName.equals(bkBiz.getBkBizName())) { logger.error(String.format("create new platform create schema FAIL : bkBizId=%d biz name is %s, not %s", bkBizId, bkBiz.getBkBizName(), platformName)); throw new ParamException(String.format(String.format("create new platform create schema FAIL : bkBizId=%d biz name is %s, not %s", bkBizId, bkBiz.getBkBizName(), platformName))); } Date now = new Date(); List<AppModuleVo> appList = this.appModuleMapper.select(null, null, null, null); Map<String, List<AppModuleVo>> appMap = appList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); Map<String, BizSetDefine> setDefineMap = this.paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); List<LJSetInfo> setList = this.paasService.resetExistBiz(bkBizId, new ArrayList<>(setDefineMap.keySet())); platform = new PlatformPo(platformId, platformName, bkBizId, bkCloudId, CCODPlatformStatus.RUNNING, "CCOD4.1", "通过程序自动创建的demo平台"); platformMapper.insert(platform); PlatformUpdateSchemaInfo schema = new PlatformUpdateSchemaInfo(platformId, platformName, bkBizId, bkCloudId, "CCOD4.1", PlatformUpdateTaskType.CREATE, String.format("%s(%s)平台新建计划", platformName, platformId), String.format("通过程序自动创建的%s(%s)平台新建计划")); Random random = new Random(); List<String> hostList = new ArrayList<>(); for(BizSetDefine setDefine : setDefineMap.values()) { if(setDefine.getApps().length == 0) continue; String hostIp = String.format("%d.%d.%d.%d", 173,random.nextInt(10000) % 255, random.nextInt(10000) % 255, random.nextInt(10000) % 255); hostList.add(hostIp); DomainUpdatePlanInfo planInfo = new DomainUpdatePlanInfo(); planInfo.setUpdateType(DomainUpdateType.ADD); planInfo.setStatus(UpdateStatus.CREATE); planInfo.setComment("由程序自动生成的新建域"); String domainId = setDefine.getFixedDomainId(); String domainName = setDefine.getFixedDomainName(); if(StringUtils.isBlank(domainId)) { domainId = "newCreateTestDomain"; domainName = "新建测试域"; } planInfo.setDomainId(domainId); planInfo.setDomainName(domainName); planInfo.setCreateTime(now); planInfo.setUpdateTime(now); planInfo.setExecuteTime(now); planInfo.setAppUpdateOperationList(new ArrayList<>()); planInfo.setBkSetName(setDefine.getName()); planInfo.setSetId(setDefine.getId()); for(String appName : setDefine.getApps()) { AppModuleVo appModuleVo = appMap.get(appName).get(0); AppUpdateOperationInfo addOperationInfo = new AppUpdateOperationInfo(); addOperationInfo.setHostIp(hostIp); addOperationInfo.setOperation(AppUpdateOperation.ADD); addOperationInfo.setCfgs(new ArrayList<>()); for(AppCfgFilePo appCfgFilePo : appModuleVo.getCfgs()) { AppFileNexusInfo info = new AppFileNexusInfo(); info.setDeployPath(appCfgFilePo.getDeployPath()); info.setExt(appCfgFilePo.getExt()); info.setFileName(appCfgFilePo.getFileName()); info.setFileSize(0); info.setMd5(appCfgFilePo.getMd5()); info.setNexusAssetId(appCfgFilePo.getNexusAssetId()); info.setNexusPath(String.format("%s/%s", appCfgFilePo.getNexusDirectory(), appCfgFilePo.getFileName())); info.setNexusRepository(appCfgFilePo.getNexusRepository()); addOperationInfo.getCfgs().add(info); } addOperationInfo.setBasePath(appModuleVo.getBasePath()); addOperationInfo.setAppRunner("qnsoft"); addOperationInfo.setAppAlias(appModuleVo.getAppAlias()); addOperationInfo.setAppName(appModuleVo.getAppName()); addOperationInfo.setTargetVersion(appModuleVo.getVersion()); planInfo.getAppUpdateOperationList().add(addOperationInfo); } schema.getDomainUpdatePlanList().add(planInfo); } LJSetInfo idlePoolSet = setList.stream().collect(Collectors.toMap(LJSetInfo::getBkSetName, Function.identity())).get(this.paasIdlePoolSetName); List<LJHostInfo> bkHostList = this.paasService.addNewHostToIdlePool(bkBizId, idlePoolSet.getBkSetId(), hostList, bkCloudId); Map<String, BizSetDefine> bizSetDefineMap = paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); String planCheckResult = checkPlatformUpdateTask(schema, new ArrayList<>(), appList, new ArrayList<>(), setList, bkHostList, new ArrayList<>(), bizSetDefineMap); if(StringUtils.isNotBlank(planCheckResult)) { logger.error(String.format("check platform update schema FAIL : %s", planCheckResult)); throw new ParamException(String.format("check platform update schema FAIL : %s", planCheckResult)); } return schema; } @Override public PlatformUpdateSchemaInfo createPlatformUpdateSchemaDemo(PlatformUpdateSchemaParamVo paramVo) throws ParamException, InterfaceCallException, LJPaasException { logger.debug(String.format("prepare to create platform update schema demo : params=%s", JSONObject.toJSONString(paramVo))); if(paramVo.getBkBizId() == 0) { logger.error(String.format("create demo schema FAIL : bkBizId=0")); throw new ParamException(String.format("create demo schema FAIL : bkBizId=0")); } else if(StringUtils.isBlank(paramVo.getPlatformId())) { logger.error(String.format("create demo schema FAIL : platformId is blank")); throw new ParamException(String.format("create demo schema FAIL : platformId is blank")); } else if(StringUtils.isBlank(paramVo.getPlatformName())) { logger.error(String.format("create demo schema FAIL : platformName is blank")); throw new ParamException(String.format("create demo schema FAIL : platformName is blank")); } else if(paramVo.getTaskType() == null) { logger.error(String.format("create demo schema FAIL : taskType is blank")); throw new ParamException(String.format("create demo schema FAIL : taskType is blank")); } PlatformUpdateSchemaInfo schemaInfo; if(PlatformUpdateTaskType.CREATE.equals(paramVo.getTaskType())) { schemaInfo = generatePlatformCreateDemoSchema(paramVo.getPlatformId(), paramVo.getPlatformName(), paramVo.getBkBizId(), paramVo.getBkCloudId()); } else { logger.error(String.format("current version not support %s platform update demo schema create", paramVo.getTaskType().name)); throw new ParamException(String.format("current version not support %s platform update demo schema create", paramVo.getTaskType().name)); } platformUpdateSchemaMapper.delete(paramVo.getPlatformId()); PlatformUpdateSchemaPo schemaPo = new PlatformUpdateSchemaPo(); schemaPo.setPlatformId(paramVo.getPlatformId()); schemaPo.setContext(JSONObject.toJSONString(schemaInfo).getBytes()); platformUpdateSchemaMapper.insert(schemaPo); this.platformUpdateSchemaMap.put(paramVo.getPlatformId(), schemaInfo); return schemaInfo; } @Override public List<PlatformUpdateSchemaInfo> queryPlatformUpdateSchema(String platformId) { logger.debug(String.format("begin to query platformId=%s platform update schema", platformId)); List<PlatformUpdateSchemaInfo> schemaList = new ArrayList<>(); if(StringUtils.isBlank(platformId)) { schemaList = new ArrayList<>(this.platformUpdateSchemaMap.values()); } else { if(this.platformUpdateSchemaMap.containsKey(platformId)) { schemaList.add(platformUpdateSchemaMap.get(platformId)); } } return schemaList; } /** * 把通过onlinemanager主动收集上来的ccod应用部署情况同步到paas之前需要给这些应用添加对应的bizId * 确定应用归属的set信息,并根据定义的set-app关系对某些应用归属域重新赋值 * @param bizId 蓝鲸paas的biz id * @param deployApps 需要处理的应用详情 * @return 处理后的结果 * @throws NotSupportAppException 如果应用中存在没有在lj-paas.set-apps节点定义的应用将抛出此异常 */ private List<PlatformAppDeployDetailVo> makeUpBizInfoForDeployApps(int bizId, List<PlatformAppDeployDetailVo> deployApps) throws NotSupportAppException { Map<String, List<BizSetDefine>> appSetRelationMap = this.paasService.getAppBizSetRelation(); for(PlatformAppDeployDetailVo deployApp : deployApps) { if(!appSetRelationMap.containsKey(deployApp.getAppName())) { logger.error(String.format("%s没有在配置文件的lj-paas.set-apps节点中定义", deployApp.getAppName())); throw new NotSupportAppException(String.format("%s未定义所属的set信息", deployApp.getAppName())); } deployApp.setBkBizId(bizId); BizSetDefine sd = appSetRelationMap.get(deployApp.getAppName()).get(0); deployApp.setBkSetName(sd.getName()); if(StringUtils.isNotBlank(sd.getFixedDomainName())) { deployApp.setSetId(sd.getId()); deployApp.setBkSetName(sd.getName()); deployApp.setDomainId(sd.getFixedDomainId()); deployApp.setDomainName(sd.getFixedDomainName()); } } return deployApps; } /** * 根据应用部署详情生成平台的set拓扑结构 * @param deployAppList 平台的应用部署明细 * @return 台的set拓扑结构 * @throws DBPAASDataNotConsistentException * @throws NotSupportAppException */ private List<CCODSetInfo> generateCCODSetInfo(List<PlatformAppDeployDetailVo> deployAppList, List<String> setNames) throws ParamException, NotSupportAppException { Map<String, List<BizSetDefine>> appSetRelationMap = this.paasService.getAppBizSetRelation(); Map<String, BizSetDefine> setDefineMap = this.paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); Map<String, List<PlatformAppDeployDetailVo>> setAppMap = deployAppList.stream().collect(Collectors.groupingBy(PlatformAppDeployDetailVo::getBkSetName)); List<CCODSetInfo> setList = new ArrayList<>(); for(PlatformAppDeployDetailVo deployApp : deployAppList) { if(!appSetRelationMap.containsKey(deployApp.getAppName())) { logger.error(String.format("current version not support %s", deployApp.getAppName())); throw new NotSupportAppException(String.format("current version not support %s", deployApp.getAppName())); } else if(!setDefineMap.containsKey(deployApp.getBkSetName())) { logger.error(String.format("%s is not a legal ccod set name", deployApp.getBkSetName())); throw new ParamException(String.format("%s is not a legal ccod set name", deployApp.getBkSetName())); } } for(String setName : setAppMap.keySet()) { Map<String, List<PlatformAppDeployDetailVo>> domainAppMap = setAppMap.get(setName) .stream().collect(Collectors.groupingBy(PlatformAppDeployDetailVo::getDomainName)); List<CCODDomainInfo> domainList = new ArrayList<>(); for(String domainName : domainAppMap.keySet()) { List<PlatformAppDeployDetailVo> domAppList = domainAppMap.get(domainName); CCODDomainInfo domain = new CCODDomainInfo(domAppList.get(0).getDomainId(), domAppList.get(0).getDomainName()); for(PlatformAppDeployDetailVo deployApp : domAppList) { CCODModuleInfo bkModule = new CCODModuleInfo(deployApp); domain.getModules().add(bkModule); } domainList.add(domain); } CCODSetInfo set = new CCODSetInfo(setName); set.setDomains(domainList); setList.add(set); } for(String setName : setNames) { if(!setAppMap.containsKey(setName)) { CCODSetInfo setInfo = new CCODSetInfo(setName); setList.add(setInfo); } } return setList; } @Override public PlatformTopologyInfo getPlatformTopology(String platformId) throws ParamException, InterfaceCallException, LJPaasException, NotSupportAppException { logger.debug(String.format("begin to query %s platform topology", platformId)); PlatformPo platform = platformMapper.selectByPrimaryKey(platformId); if(platform == null) { logger.error(String.format("%s platform not exist", platformId)); throw new ParamException(String.format("%s platform not exist", platformId)); } PlatformTopologyInfo topology = new PlatformTopologyInfo(platform); if(topology.getStatus() == null) { logger.error(String.format("unknown ccod platform status %d", platform.getStatus())); throw new ParamException(String.format("unknown ccod platform status %d", platform.getStatus())); } List<LJHostInfo> idleHostList; PlatformUpdateSchemaInfo schema; List<CCODSetInfo> setList; Map<String, BizSetDefine> bizSetMap = paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); List<PlatformAppDeployDetailVo> deployAppList; switch (topology.getStatus()) { case SCHEMA_CREATE_PLATFORM: setList = new ArrayList<>(); idleHostList = this.paasService.queryBizIdleHost(platform.getBkBizId()); schema = this.platformUpdateSchemaMap.containsKey(platformId) ? this.platformUpdateSchemaMap.get(platformId) : null; break; case RUNNING: if(this.platformUpdateSchemaMap.containsKey(platformId)) { logger.error(String.format("%s status is %s, but it has an update schema", platformId, topology.getStatus().name)); throw new ParamException(String.format("%s status is %s, but it has an update schema", platformId, topology.getStatus().name)); } deployAppList = this.platformAppDeployDetailMapper.selectPlatformApps(platformId, null, null); setList = generateCCODSetInfo(deployAppList, new ArrayList<>(bizSetMap.keySet())); idleHostList = this.paasService.queryBizIdleHost(platform.getBkBizId()); schema = null; break; case SCHEMA_UPDATE_PLATFORM: if(!this.platformUpdateSchemaMap.containsKey(platformId)) { logger.error(String.format("%s status is %s, but can not find its update schema", platformId, topology.getStatus().name)); throw new ParamException(String.format("%s status is %s, but can not find its update schema", platformId, topology.getStatus().name)); } deployAppList = this.platformAppDeployDetailMapper.selectPlatformApps(platformId, null, null); setList = generateCCODSetInfo(deployAppList, new ArrayList<>(bizSetMap.keySet())); idleHostList = this.paasService.queryBizIdleHost(platform.getBkBizId()); schema = this.platformUpdateSchemaMap.get(platformId); break; case WAIT_SYNC_EXIST_PLATFORM_TO_PAAS: if(this.platformUpdateSchemaMap.containsKey(platformId)) { logger.error(String.format("%s status is %s, but it has an update schema", platformId, topology.getStatus().name)); throw new ParamException(String.format("%s status is %s, but it has an update schema", platformId, topology.getStatus().name)); } deployAppList = this.platformAppDeployDetailMapper.selectPlatformApps(platformId, null, null); deployAppList = makeUpBizInfoForDeployApps(platform.getBkBizId(), deployAppList); setList = generateCCODSetInfo(deployAppList, new ArrayList<>(bizSetMap.keySet())); idleHostList = this.paasService.queryBizIdleHost(platform.getBkBizId()); schema = null; break; default: idleHostList = new ArrayList<>(); setList = new ArrayList<>(); schema = null; } topology.setSetList(setList); topology.setSchema(schema); topology.setIdleHosts(idleHostList); return topology; } @Override public List<PlatformTopologyInfo> queryAllPlatformTopology() throws ParamException, InterfaceCallException, LJPaasException, NotSupportAppException { List<PlatformTopologyInfo> topoList = new ArrayList<>(); List<PlatformPo> platforms = platformMapper.select(null); for(PlatformPo platformPo : platforms) { PlatformTopologyInfo topo = new PlatformTopologyInfo(platformPo); if(topo.getStatus() == null) { logger.error(String.format("%s status %d is unknown", platformPo.getPlatformId(), platformPo.getStatus())); continue; } switch (topo.getStatus()) { case RUNNING: case WAIT_SYNC_EXIST_PLATFORM_TO_PAAS: case SCHEMA_UPDATE_PLATFORM: case SCHEMA_CREATE_PLATFORM: topoList.add(topo); break; default: } } return topoList; } @Override public void registerNewAppModule(AppModuleVo appModule) throws NotSupportAppException, ParamException, InterfaceCallException, NexusException, IOException { logger.debug(String.format("begin to register app=[%s] into cmdb", JSONObject.toJSONString(appModule))); Map<String, List<BizSetDefine>> appSetRelationMap = this.paasService.getAppBizSetRelation(); if (!appSetRelationMap.containsKey(appModule.getAppName())) { logger.error(String.format("appName=%s is not supported by cmdb", appModule.getAppName())); throw new NotSupportAppException(String.format("appName=%s is not supported by cmdb", appModule.getAppName())); } String moduleCheckResult = checkModuleParam(appModule); if (StringUtils.isNotBlank(moduleCheckResult)) { logger.error(String.format("app module params check FAIL %s", moduleCheckResult)); throw new ParamException(String.format("app module params check FAIL %s", moduleCheckResult)); } AppModuleVo oldModuleVo = this.appModuleMapper.selectByNameAndVersion(appModule.getAppName(), appModule.getVersion()); if (oldModuleVo != null) { if(!oldModuleVo.getInstallPackage().getFileName().equals(appModule.getInstallPackage().getFileName())) { logger.error(String.format("%s's version %s has been registered, but old install package fileName is %s and new install package fileName is %s", appModule.getAppName(), appModule.getVersion(), appModule.getInstallPackage().getFileName(), oldModuleVo.getInstallPackage().getFileName())); throw new ParamException(String.format("%s's version %s has been registered, but old install package fileName is %s and new install package fileName is %s", appModule.getAppName(), appModule.getVersion(), appModule.getInstallPackage().getFileName(), oldModuleVo.getInstallPackage().getFileName())); } else if(!oldModuleVo.getInstallPackage().getMd5().equals(appModule.getInstallPackage().getMd5())) { logger.error(String.format("%s's version %s has been registered, but old install package md5 is %s and new install package md5 is %s", appModule.getAppName(), appModule.getVersion(), appModule.getInstallPackage().getFileName(), oldModuleVo.getInstallPackage().getFileName())); throw new ParamException(String.format("%s's version %s has been registered, but old install package fileName is %s and new install package fileName is %s", appModule.getAppName(), appModule.getVersion(), appModule.getInstallPackage().getMd5(), oldModuleVo.getInstallPackage().getMd5())); } else if(oldModuleVo.getCfgs().size() != appModule.getCfgs().size()) { logger.error(String.format("%s's version %s has been registered, but old has %d cfg and new has is %d", appModule.getAppName(), appModule.getVersion(), appModule.getInstallPackage().getFileName(), oldModuleVo.getInstallPackage().getFileName())); throw new ParamException(String.format("%s's version %s has been registered, but old install package fileName is %s and new install package fileName is %s", appModule.getAppName(), appModule.getVersion(), appModule.getCfgs().size(), oldModuleVo.getCfgs().size())); } else { Map<String, AppCfgFilePo> cfgFileMap = oldModuleVo.getCfgs().stream().collect(Collectors.toMap(AppCfgFilePo::getFileName, Function.identity())); for(AppCfgFilePo cfgFilePo : appModule.getCfgs()) { if(!cfgFileMap.containsKey(cfgFilePo.getFileName())) { logger.error(String.format("%s's version %s has been registered, but cfg fileName not equal", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("%s's version %s has been registered, but cfg fileName not equal", appModule.getAppName(), appModule.getVersion())); } else if(!cfgFileMap.get(cfgFilePo.getFileName()).getDeployPath().equals(cfgFilePo.getDeployPath())) { logger.error(String.format("%s's version %s has been registered, but cfg deploy path not equal", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("%s's version %s has been registered, but cfg deploy path not equal", appModule.getAppName(), appModule.getVersion())); } } } logger.error(String.format("%s's version %s has been registered", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("%s's version %s has been registered", appModule.getAppName(), appModule.getVersion())); } String directory = appModule.getAppModuleNexusDirectory(); String tmpSaveDir = getTempSaveDir(DigestUtils.md5DigestAsHex(directory.getBytes())); List<DeployFileInfo> fileList = new ArrayList<>(); String downloadUrl = appModule.getInstallPackage().getFileNexusDownloadUrl(this.publishNexusHostUrl); logger.debug(String.format("download cfg from %s", downloadUrl)); String savePth = nexusService.downloadFile(this.nexusUserName, this.nexusPassword, downloadUrl, tmpSaveDir, appModule.getInstallPackage().getFileName()); String md5 = DigestUtils.md5DigestAsHex(new FileInputStream(savePth)); if(!md5.equals(appModule.getInstallPackage().getMd5())) { logger.error(String.format("install package %s verify md5 FAIL : report=%s and download=%s", appModule.getInstallPackage().getFileName(), appModule.getInstallPackage().getMd5(), md5)); throw new ParamException(String.format("install package %s verify md5 FAIL : report=%s and download=%s", appModule.getInstallPackage().getFileName(), appModule.getInstallPackage().getMd5(), md5)); } DeployFileInfo fileInfo = new DeployFileInfo(); fileInfo.setFileName(appModule.getInstallPackage().getFileName()); fileInfo.setNexusAssetId(appModule.getInstallPackage().getNexusAssetId()); fileInfo.setNexusDirectory(appModule.getInstallPackage().getNexusDirectory()); fileInfo.setNexusRepository(appModule.getInstallPackage().getNexusRepository()); fileInfo.setLocalSavePath(savePth); fileInfo.setFileMd5(appModule.getInstallPackage().getMd5()); fileInfo.setExt(appModule.getInstallPackage().getExt()); fileInfo.setBasePath(appModule.getBasePath()); fileInfo.setDeployPath(appModule.getBasePath()); fileList.add(fileInfo); for(AppCfgFilePo cfg : appModule.getCfgs()) { downloadUrl = cfg.getFileNexusDownloadUrl(this.publishNexusHostUrl); logger.debug(String.format("download cfg from %s", downloadUrl)); savePth = nexusService.downloadFile(this.nexusUserName, this.nexusPassword, downloadUrl, tmpSaveDir, cfg.getFileName()); md5 = DigestUtils.md5DigestAsHex(new FileInputStream(savePth)); if(!md5.equals(cfg.getMd5())) { logger.error(String.format("cfg %s verify md5 FAIL : report=%s and download=%s", cfg.getFileName(), cfg.getMd5(), md5)); throw new ParamException(String.format("cfg %s verify md5 FAIL : report=%s and download=%s", cfg.getFileName(), cfg.getMd5(), md5)); } fileInfo = new DeployFileInfo(); fileInfo.setFileName(cfg.getFileName()); fileInfo.setNexusAssetId(cfg.getNexusAssetId()); fileInfo.setNexusDirectory(directory); fileInfo.setNexusRepository(this.appRepository); fileInfo.setLocalSavePath(savePth); fileInfo.setFileMd5(cfg.getMd5()); fileInfo.setExt(cfg.getExt()); fileInfo.setBasePath(appModule.getBasePath()); fileInfo.setDeployPath(cfg.getDeployPath()); fileList.add(fileInfo); } Map<String, NexusAssetInfo> assetMap = this.nexusService.uploadRawComponent(this.nexusHostUrl, this.nexusUserName, this.nexusPassword, this.appRepository, directory, fileList.toArray(new DeployFileInfo[0])).stream().collect(Collectors.toMap(NexusAssetInfo::getPath, Function.identity())); AppPo appPo = new AppPo(appModule); Date now = new Date(); appPo.setCreateTime(now); appPo.setUpdateTime(now); this.appMapper.insert(appPo); appModule.getInstallPackage().setNexusRepository(this.appRepository); appModule.getInstallPackage().setNexusDirectory(directory); appModule.getInstallPackage().setAppId(appPo.getAppId()); appModule.getInstallPackage().setNexusAssetId(assetMap.get(String.format("%s/%s", directory, appModule.getInstallPackage().getFileName())).getId()); this.appInstallPackageMapper.insert(appModule.getInstallPackage()); for(AppCfgFilePo cfgFilePo : appModule.getCfgs()) { cfgFilePo.setAppId(appPo.getAppId()); cfgFilePo.setNexusDirectory(directory); cfgFilePo.setNexusRepository(this.appRepository); cfgFilePo.setNexusAssetId(assetMap.get(String.format("%s/%s", directory, cfgFilePo.getFileName())).getId()); this.appCfgFileMapper.insert(cfgFilePo); } } @Override public void updateAppModule(AppModuleVo appModule) throws NotSupportAppException, ParamException, InterfaceCallException, NexusException, IOException { logger.debug(String.format("begin to modify cfg of app=[%s] in cmdb", JSONObject.toJSONString(appModule))); if(StringUtils.isBlank(appModule.getAppName())) { logger.error(String.format("app name is blank")); throw new ParamException(String.format("app name is blank")); } if(StringUtils.isBlank(appModule.getVersion())) { logger.error(String.format("version of %s is blank", appModule.getAppName())); throw new ParamException(String.format("version of %s is blank", appModule.getAppName())); } if(appModule.getInstallPackage() == null) { logger.error(String.format("install package of %s version %s is blank", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("install package of %s version %s is blank", appModule.getAppName(), appModule.getVersion())); } if(appModule.getCfgs() == null || appModule.getCfgs().size() == 0) { logger.error(String.format("cfg of %s version %s is blank", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("cfg of %s version %s is blank", appModule.getAppName(), appModule.getVersion())); } Map<String, List<BizSetDefine>> appSetRelationMap = this.paasService.getAppBizSetRelation(); if (!appSetRelationMap.containsKey(appModule.getAppName())) { logger.error(String.format("appName=%s is not supported by cmdb", appModule.getAppName())); throw new NotSupportAppException(String.format("appName=%s is not supported by cmdb", appModule.getAppName())); } AppModuleVo oldModuleVo = this.appModuleMapper.selectByNameAndVersion(appModule.getAppName(), appModule.getVersion()); if (oldModuleVo == null) { logger.error(String.format("%s version %s has not registered", appModule.getAppName(), appModule.getVersion())); throw new ParamException(String.format("%s version %s has not registered", appModule.getAppName(), appModule.getVersion())); } String directory = appModule.getAppModuleNexusDirectory(); String tmpSaveDir = getTempSaveDir(DigestUtils.md5DigestAsHex(directory.getBytes())); List<DeployFileInfo> fileList = new ArrayList<>(); String downloadUrl = appModule.getInstallPackage().getFileNexusDownloadUrl(this.publishNexusHostUrl); logger.debug(String.format("download cfg from %s", downloadUrl)); String savePth = nexusService.downloadFile(this.nexusUserName, this.nexusPassword, downloadUrl, tmpSaveDir, appModule.getInstallPackage().getFileName()); String md5 = DigestUtils.md5DigestAsHex(new FileInputStream(savePth)); if(!md5.equals(appModule.getInstallPackage().getMd5())) { logger.error(String.format("install package %s verify md5 FAIL : report=%s and download=%s", appModule.getInstallPackage().getFileName(), appModule.getInstallPackage().getMd5(), md5)); throw new ParamException(String.format("install package %s verify md5 FAIL : report=%s and download=%s", appModule.getInstallPackage().getFileName(), appModule.getInstallPackage().getMd5(), md5)); } DeployFileInfo fileInfo = new DeployFileInfo(); fileInfo.setFileName(appModule.getInstallPackage().getFileName()); fileInfo.setNexusAssetId(appModule.getInstallPackage().getNexusAssetId()); fileInfo.setNexusDirectory(appModule.getInstallPackage().getNexusDirectory()); fileInfo.setNexusRepository(appModule.getInstallPackage().getNexusRepository()); fileInfo.setLocalSavePath(savePth); fileInfo.setFileMd5(appModule.getInstallPackage().getMd5()); fileInfo.setExt(appModule.getInstallPackage().getExt()); fileInfo.setBasePath(appModule.getBasePath()); fileInfo.setDeployPath(appModule.getBasePath()); fileList.add(fileInfo); for(AppCfgFilePo cfg : appModule.getCfgs()) { downloadUrl = cfg.getFileNexusDownloadUrl(this.publishNexusHostUrl); logger.debug(String.format("download cfg from %s", downloadUrl)); savePth = nexusService.downloadFile(this.nexusUserName, this.nexusPassword, downloadUrl, tmpSaveDir, cfg.getFileName()); md5 = DigestUtils.md5DigestAsHex(new FileInputStream(savePth)); if(!md5.equals(cfg.getMd5())) { logger.error(String.format("cfg %s verify md5 FAIL : report=%s and download=%s", cfg.getFileName(), cfg.getMd5(), md5)); throw new ParamException(String.format("cfg %s verify md5 FAIL : report=%s and download=%s", cfg.getFileName(), cfg.getMd5(), md5)); } fileInfo = new DeployFileInfo(); fileInfo.setFileName(cfg.getFileName()); fileInfo.setNexusAssetId(cfg.getNexusAssetId()); fileInfo.setNexusDirectory(directory); fileInfo.setNexusRepository(this.appRepository); fileInfo.setLocalSavePath(savePth); fileInfo.setFileMd5(cfg.getMd5()); fileInfo.setExt(cfg.getExt()); fileInfo.setBasePath(appModule.getBasePath()); fileInfo.setDeployPath(cfg.getDeployPath()); fileList.add(fileInfo); } Map<String, NexusAssetInfo> assetMap = this.nexusService.uploadRawComponent(this.nexusHostUrl, this.nexusUserName, this.nexusPassword, this.appRepository, directory, fileList.toArray(new DeployFileInfo[0])).stream().collect(Collectors.toMap(NexusAssetInfo::getPath, Function.identity())); logger.debug(String.format("delete old version install package")); this.appInstallPackageMapper.delete(null, oldModuleVo.getAppId()); logger.debug(String.format("delete old version cfgs")); this.appCfgFileMapper.delete(null, oldModuleVo.getAppId()); oldModuleVo.getInstallPackage().setNexusAssetId(assetMap.get(String.format("%s/%s", directory, appModule.getInstallPackage().getFileName())).getId()); this.appInstallPackageMapper.insert(oldModuleVo.getInstallPackage()); for(AppCfgFilePo cfgFilePo : appModule.getCfgs()) { cfgFilePo.setAppId(oldModuleVo.getAppId()); cfgFilePo.setNexusDirectory(directory); cfgFilePo.setNexusRepository(this.appRepository); cfgFilePo.setNexusAssetId(assetMap.get(String.format("%s/%s", directory, cfgFilePo.getFileName())).getId()); this.appCfgFileMapper.insert(cfgFilePo); } } private String checkModuleParam(AppModuleVo appModuleVo) { StringBuffer sb = new StringBuffer(); if(StringUtils.isBlank(appModuleVo.getAppName())) { sb.append("appName is blank,"); } if(StringUtils.isBlank(appModuleVo.getVersion())) { sb.append("appVersion is blank,"); } if(StringUtils.isBlank(appModuleVo.getBasePath())) { sb.append("default base path is blank,"); } if(appModuleVo.getInstallPackage() == null) { sb.append("install package is null,"); } if(appModuleVo.getCfgs() == null || appModuleVo.getCfgs().size() == 0) { sb.append("cfg is null,"); } return sb.toString().replaceAll(",$", ""); } @Override public PlatformUpdateSchemaInfo createDemoNewPlatform(String platformId, String platformName, int bkBizId, int bkCloudId, List<String> planAppList) throws ParamException, InterfaceCallException, LJPaasException { Date now = new Date(); PlatformPo platformPo = this.platformMapper.selectByPrimaryKey(platformId); if(platformPo != null) { logger.error(String.format("demo platform[id=%s, name=%s] exist", platformId, platformName)); throw new ParamException(String.format("demo platform[id=%s, name=%s] exist", platformId, platformName)); } List<LJBizInfo> bizList = paasService.queryAllBiz(); Map<String, LJBizInfo> bizMap = bizList.stream().collect(Collectors.toMap(LJBizInfo::getBkBizName, Function.identity())); if(!bizMap.containsKey(platformName)) { logger.error(String.format("biz %s not exist at lj paas", platformName)); throw new ParamException(String.format("biz %s not exist at lj paas", platformName)); } else if(bizMap.get(platformName).getBkBizId() != bkBizId) { logger.error(String.format("%s bkBizId is %d not %d", bizMap.get(platformName).getBkBizId(), bkBizId)); throw new ParamException(String.format("%s bkBizId is %d not %d", bizMap.get(platformName).getBkBizId(), bkBizId)); } Map<String, List<String>> planAppMap = new HashMap<>(); for(String planApp : planAppList) { String[] arr = planApp.split("##"); if(!planAppMap.containsKey(arr[0])) { planAppMap.put(arr[0], new ArrayList<>()); } planAppMap.get(arr[0]).add(planApp); } List<AppModuleVo> appList = this.appModuleMapper.select(null, null, null, null); Map<String, List<AppModuleVo>> appMap = appList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); PlatformUpdateSchemaInfo schema = new PlatformUpdateSchemaInfo(platformId, platformName, bkBizId, bkCloudId, "CCOD4.1", PlatformUpdateTaskType.CREATE, String.format("%s(%s)平台新建计划", platformName, platformId), String.format("通过程序自动创建的%s(%s)平台新建计划", platformName, platformId)); Set<String> ipSet = new HashSet<>(); Map<String, BizSetDefine> setDefineMap = this.paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); for(BizSetDefine setDefine : setDefineMap.values()) { if(setDefine.getApps().length == 0) continue; DomainUpdatePlanInfo planInfo = new DomainUpdatePlanInfo(); planInfo.setUpdateType(DomainUpdateType.ADD); planInfo.setStatus(UpdateStatus.CREATE); planInfo.setComment("由程序自动生成的新建域"); String domainId = setDefine.getFixedDomainId(); String domainName = setDefine.getFixedDomainName(); if(StringUtils.isBlank(domainId)) { domainId = "new-create-test-domain"; domainName = "新建测试域"; } planInfo.setDomainId(domainId); planInfo.setDomainName(domainName); planInfo.setCreateTime(now); planInfo.setUpdateTime(now); planInfo.setExecuteTime(now); planInfo.setAppUpdateOperationList(new ArrayList<>()); planInfo.setBkSetName(setDefine.getName()); planInfo.setSetId(setDefine.getId()); for(String appName : setDefine.getApps()) { if(planAppMap.containsKey(appName)) { for(String planApp : planAppMap.get(appName)) { String[] arr = planApp.split("##"); String appAlias = arr[1]; String version = arr[2]; String hostIp = arr[3].split("@")[1]; ipSet.add(hostIp); String[] pathArr = arr[3].split("@")[0].replaceAll("^/", "").split("/"); pathArr[1] = appAlias; String basePath = String.format("/%s", String.join("/", pathArr)); Map<String, AppModuleVo> versionMap = appMap.get(appName).stream().collect(Collectors.toMap(AppModuleVo::getVersion, Function.identity())); if(!versionMap.containsKey(version)) { logger.error(String.format("create demo platform create schema FAIL : %s has not version=%s", appName, version)); throw new ParamException(String.format("create demo platform create schema FAIL : %s has not version=%s", appName, version)); } AppModuleVo appModuleVo = versionMap.get(version); AppUpdateOperationInfo addOperationInfo = new AppUpdateOperationInfo(); addOperationInfo.setHostIp(hostIp); addOperationInfo.setOperation(AppUpdateOperation.ADD); addOperationInfo.setCfgs(new ArrayList<>()); for(AppCfgFilePo appCfgFilePo : appModuleVo.getCfgs()) { AppFileNexusInfo info = new AppFileNexusInfo(); info.setDeployPath(appCfgFilePo.getDeployPath()); info.setExt(appCfgFilePo.getExt()); info.setFileName(appCfgFilePo.getFileName()); info.setFileSize(0); info.setMd5(appCfgFilePo.getMd5()); info.setNexusAssetId(appCfgFilePo.getNexusAssetId()); info.setNexusPath(String.format("%s/%s", appCfgFilePo.getNexusDirectory(), appCfgFilePo.getFileName())); info.setNexusRepository(appCfgFilePo.getNexusRepository()); addOperationInfo.getCfgs().add(info); } addOperationInfo.setBasePath(basePath); addOperationInfo.setAppRunner(appAlias); addOperationInfo.setAppAlias(appAlias); addOperationInfo.setAppName(appName); addOperationInfo.setTargetVersion(version); planInfo.getAppUpdateOperationList().add(addOperationInfo); } } } schema.getDomainUpdatePlanList().add(planInfo); } Map<String, LJHostInfo> hostMap = paasService.queryBKHost(bkBizId, null, null, null, null) .stream().collect(Collectors.toMap(LJHostInfo::getHostInnerIp, Function.identity())); for(String hostIp : ipSet) { if(!hostMap.containsKey(hostIp)) { logger.error(String.format("%s has not %s host", platformName, hostIp)); throw new LJPaasException(String.format("%s has not %s host", platformName, hostIp)); } } paasService.resetExistBiz(bkBizId, new ArrayList<>(setDefineMap.keySet())); schema.setBkBizId(bkBizId); platformPo = new PlatformPo(platformId, platformName, bkBizId, bkCloudId, CCODPlatformStatus.SCHEMA_CREATE_PLATFORM, "CCOD4.1", "create by tools for test"); this.platformMapper.insert(platformPo); List<LJSetInfo> setList = this.paasService.queryBkBizSet(bkBizId); List<LJHostInfo> idleHostList = paasService.queryBizIdleHost(bkBizId); Map<String, BizSetDefine> bizSetDefineMap = paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); String checkResult = checkPlatformUpdateTask(schema, new ArrayList<>(), appList, new ArrayList<>(), setList, idleHostList, new ArrayList<>(), bizSetDefineMap); if(StringUtils.isNotBlank(checkResult)) { logger.error(String.format("demo platform generate fail : %s", checkResult)); throw new ParamException(String.format("demo platform generate fail : %s", checkResult)); } PlatformUpdateSchemaPo schemaPo = new PlatformUpdateSchemaPo(); schemaPo.setContext(JSONObject.toJSONString(schema).getBytes()); schemaPo.setPlatformId(platformId); this.platformUpdateSchemaMapper.insert(schemaPo); this.platformUpdateSchemaMap.put(platformId, schema); return schema; } @Override public PlatformUpdateSchemaInfo createDemoUpdatePlatform(String platformId, String platformName, int bkBizId) throws ParamException, InterfaceCallException, LJPaasException { logger.debug(String.format("begin to create demo update platform[platformId=%s,platformName=%s,bkBizId=%d]", platformId, platformName, bkBizId)); Date now = new Date(); PlatformPo platform = platformMapper.selectByPrimaryKey(platformId); if(platform == null) { logger.error(String.format("platformId=%s not exist", platformId)); throw new ParamException(String.format("platformId=%s not exist", platformId)); } if(!platform.getPlatformName().equals(platformName)) { logger.error(String.format("name of platformId=%s is %s not %s", platformId, platform.getPlatformName(), platformName)); throw new ParamException(String.format("name of platformId=%s is %s not %s", platformId, platform.getPlatformName(), platformName)); } LJBizInfo bkBiz = this.paasService.queryBizInfoById(bkBizId); if(bkBiz == null) { logger.error(String.format("bkBizId=%d biz not exist", bkBizId)); throw new ParamException(String.format("bkBizId=%d biz not exist", bkBizId)); } if(!bkBiz.getBkBizName().equals(platformName)) { logger.error(String.format("bkBizId=%d biz name is %s not %s", bkBizId, bkBiz.getBkBizName(), platformName)); throw new ParamException(String.format("bkBizId=%d biz name is %s not %s", bkBizId, bkBiz.getBkBizName(), platformName)); } List<DomainPo> domainList = domainMapper.select(platformId, null); if(domainList.size() == 0) { logger.error(String.format("%s has 0 domain", platformId)); throw new ParamException(String.format("%s has 0 domain", platformId)); } List<PlatformAppDeployDetailVo> deployApps = platformAppDeployDetailMapper.selectPlatformApps(platformId, null, null); if(deployApps.size() == 0) { logger.error(String.format("%s has deployed 0 app", platformId)); throw new ParamException(String.format("%s has deployed 0 app", platformId)); } List<AppModuleVo> appModuleList = appModuleMapper.select(null, null, null, null); Map<String, List<AppModuleVo>> appModuleMap = appModuleList.stream().collect(Collectors.groupingBy(AppModuleVo::getAppName)); List<DomainUpdatePlanInfo> planList = new ArrayList<>(); Map<String, List<PlatformAppDeployDetailVo>> setAppMap = deployApps.stream().collect(Collectors.groupingBy(PlatformAppDeployDetailVo::getBkSetName)); for(String bkSetName : setAppMap.keySet()) { List<PlatformAppDeployDetailVo> setAppList = setAppMap.get(bkSetName); Map<String, List<PlatformAppDeployDetailVo>> domainAppMap = setAppList.stream().collect(Collectors.groupingBy(PlatformAppDeployDetailVo::getDomainId)); int index = 1; for(String domainId : domainAppMap.keySet()) { List<PlatformAppDeployDetailVo> domainAppList = domainAppMap.get(domainId); if("域服务".equals(bkSetName)) { DomainUpdatePlanInfo planInfo = new DomainUpdatePlanInfo(); planInfo.setAppUpdateOperationList(new ArrayList<>()); planInfo.setStatus(UpdateStatus.CREATE); planInfo.setSetId(domainAppList.get(0).getSetId()); planInfo.setBkSetName(bkSetName); planInfo.setExecuteTime(now); planInfo.setUpdateTime(now); planInfo.setCreateTime(now); planInfo.setDomainName(domainAppList.get(0).getDomainName()); planInfo.setDomainId(domainId); planInfo.setComment(String.format("域%s移除方案", domainId)); planInfo.setUpdateType(DomainUpdateType.DELETE); for(PlatformAppDeployDetailVo deployApp : domainAppList) { AppUpdateOperationInfo opt = new AppUpdateOperationInfo(); opt.setAppName(deployApp.getAppName()); opt.setAppAlias(deployApp.getAppAlias()); opt.setOperation(AppUpdateOperation.DELETE); opt.setHostIp(deployApp.getHostIp()); opt.setPlatformAppId(deployApp.getPlatformAppId()); opt.setOriginalVersion(deployApp.getVersion()); planInfo.getAppUpdateOperationList().add(opt); } planList.add(planInfo); planInfo = new DomainUpdatePlanInfo(); planInfo.setAppUpdateOperationList(new ArrayList<>()); planInfo.setStatus(UpdateStatus.CREATE); planInfo.setSetId(domainAppList.get(0).getSetId()); planInfo.setBkSetName(bkSetName); planInfo.setExecuteTime(now); planInfo.setUpdateTime(now); planInfo.setCreateTime(now); planInfo.setDomainName(String.format("新建%s%d", domainAppList.get(0).getDomainName(), index)); planInfo.setDomainId(String.format("new-create-%s-%d", domainAppList.get(0).getDomainId(), index)); index++; planInfo.setComment(String.format("域%s新建方案", planInfo.getDomainId())); planInfo.setUpdateType(DomainUpdateType.ADD); for(PlatformAppDeployDetailVo deployApp : domainAppList) { AppUpdateOperationInfo opt = new AppUpdateOperationInfo(); opt.setCfgs(new ArrayList<>()); for(PlatformAppCfgFilePo cfgFilePo : deployApp.getCfgs()) { AppFileNexusInfo nexusInfo = new AppFileNexusInfo(); nexusInfo.setNexusRepository(cfgFilePo.getNexusRepository()); nexusInfo.setNexusPath(cfgFilePo.getFileNexusSavePath()); nexusInfo.setNexusAssetId(nexusInfo.getNexusAssetId()); nexusInfo.setMd5(cfgFilePo.getMd5()); nexusInfo.setFileSize(0); nexusInfo.setFileName(cfgFilePo.getFileName()); nexusInfo.setExt(cfgFilePo.getExt()); nexusInfo.setDeployPath(cfgFilePo.getDeployPath()); opt.getCfgs().add(nexusInfo); } opt.setHostIp(deployApp.getHostIp()); opt.setOperation(AppUpdateOperation.ADD); opt.setBasePath(deployApp.getBasePath()); opt.setAppRunner(deployApp.getAppRunner()); opt.setAppAlias(deployApp.getAppAlias()); opt.setAppName(deployApp.getAppName()); opt.setTargetVersion(deployApp.getVersion()); planInfo.getAppUpdateOperationList().add(opt); } planList.add(planInfo); } else { DomainUpdatePlanInfo planInfo = new DomainUpdatePlanInfo(); planInfo.setAppUpdateOperationList(new ArrayList<>()); planInfo.setStatus(UpdateStatus.CREATE); planInfo.setSetId(domainAppList.get(0).getSetId()); planInfo.setBkSetName(bkSetName); planInfo.setExecuteTime(now); planInfo.setUpdateTime(now); planInfo.setCreateTime(now); planInfo.setDomainName(domainAppList.get(0).getDomainName()); planInfo.setDomainId(domainId); planInfo.setComment(String.format("域%s升级方案", domainId)); planInfo.setUpdateType(DomainUpdateType.UPDATE); planList.add(planInfo); for(PlatformAppDeployDetailVo deployApp : domainAppList) { if(index % 2 == 1) { if(appModuleMap.get(deployApp.getAppName()).size() > 1) { for(AppModuleVo moduleVo : appModuleMap.get(deployApp.getAppName())) { if(!moduleVo.getVersion().equals(deployApp.getVersion())) { AppUpdateOperationInfo opt = new AppUpdateOperationInfo(); opt.setTargetVersion(moduleVo.getVersion()); opt.setAppName(deployApp.getAppName()); opt.setAppAlias(deployApp.getAppAlias()); opt.setAppRunner(deployApp.getAppRunner()); opt.setBasePath(deployApp.getBasePath()); opt.setOperation(AppUpdateOperation.VERSION_UPDATE); opt.setHostIp(deployApp.getHostIp()); opt.setOriginalVersion(deployApp.getVersion()); opt.setPlatformAppId(deployApp.getPlatformAppId()); opt.setCfgs(new ArrayList<>()); for(AppCfgFilePo cfgFilePo : moduleVo.getCfgs()) { AppFileNexusInfo nexusInfo = new AppFileNexusInfo(); nexusInfo.setNexusRepository(cfgFilePo.getNexusRepository()); nexusInfo.setNexusPath(cfgFilePo.getNexusFileSavePath()); nexusInfo.setNexusAssetId(nexusInfo.getNexusAssetId()); nexusInfo.setMd5(cfgFilePo.getMd5()); nexusInfo.setFileSize(0); nexusInfo.setFileName(cfgFilePo.getFileName()); nexusInfo.setExt(cfgFilePo.getExt()); nexusInfo.setDeployPath(cfgFilePo.getDeployPath()); opt.getCfgs().add(nexusInfo); } planInfo.getAppUpdateOperationList().add(opt); break; } } } else { AppUpdateOperationInfo opt = new AppUpdateOperationInfo(); opt.setPlatformAppId(deployApp.getPlatformAppId()); opt.setOriginalVersion(deployApp.getVersion()); opt.setHostIp(deployApp.getHostIp()); opt.setOperation(AppUpdateOperation.CFG_UPDATE); opt.setBasePath(deployApp.getBasePath()); opt.setAppRunner(deployApp.getAppRunner()); opt.setAppAlias(deployApp.getAppAlias()); opt.setAppName(deployApp.getAppName()); opt.setCfgs(new ArrayList<>()); for(PlatformAppCfgFilePo cfgFilePo : deployApp.getCfgs()) { AppFileNexusInfo nexusInfo = new AppFileNexusInfo(); nexusInfo.setNexusRepository(cfgFilePo.getNexusRepository()); nexusInfo.setNexusPath(cfgFilePo.getFileNexusSavePath()); nexusInfo.setNexusAssetId(nexusInfo.getNexusAssetId()); nexusInfo.setMd5(cfgFilePo.getMd5()); nexusInfo.setFileSize(0); nexusInfo.setFileName(cfgFilePo.getFileName()); nexusInfo.setExt(cfgFilePo.getExt()); nexusInfo.setDeployPath(cfgFilePo.getDeployPath()); opt.getCfgs().add(nexusInfo); } planInfo.getAppUpdateOperationList().add(opt); } } else { AppUpdateOperationInfo opt = new AppUpdateOperationInfo(); opt.setAppName(deployApp.getAppName()); opt.setAppAlias(deployApp.getAppAlias()); opt.setAppRunner(deployApp.getAppRunner()); opt.setBasePath(deployApp.getBasePath()); opt.setOperation(AppUpdateOperation.DELETE); opt.setHostIp(deployApp.getHostIp()); opt.setOriginalVersion(deployApp.getVersion()); opt.setPlatformAppId(deployApp.getPlatformAppId()); planInfo.getAppUpdateOperationList().add(opt); } } } } } PlatformUpdateSchemaInfo schema = new PlatformUpdateSchemaInfo(platformId, platformName, bkBizId, platform.getBkCloudId(), "CCOD4.1", PlatformUpdateTaskType.UPDATE, "create demo update platform", "demo update platform create by program"); schema.setDomainUpdatePlanList(planList); List<PlatformAppPo> platformAppList = platformAppMapper.select(platformId, null, null, null, null, null); List<LJSetInfo> bkSetList = paasService.queryBkBizSet(bkBizId); List<LJHostInfo> bkHostList = paasService.queryBKHost(bkBizId, null, null, null, null); List<PlatformAppBkModulePo> appBkModuleList = platformAppBkModuleMapper.select(platformId, null, null, null, null, null); Map<String, BizSetDefine> bizSetDefineMap = paasService.queryCCODBizSet(false).stream().collect(Collectors.toMap(BizSetDefine::getName, Function.identity())); String schemaCheckResult = checkPlatformUpdateTask(schema, domainList, appModuleList, platformAppList, bkSetList, bkHostList, appBkModuleList, bizSetDefineMap); if(StringUtils.isNotBlank(schemaCheckResult)) { logger.error(String.format("generate schema fail : %s", schemaCheckResult)); throw new ParamException(String.format("generate schema fail : %s", schemaCheckResult)); } PlatformUpdateSchemaPo schemaPo = new PlatformUpdateSchemaPo(); schemaPo.setPlatformId(platformId); schemaPo.setContext(JSONObject.toJSONString(schema).getBytes()); this.platformUpdateSchemaMapper.insert(schemaPo); platform.setStatus(CCODPlatformStatus.SCHEMA_UPDATE_PLATFORM.id); platformMapper.update(platform); this.platformUpdateSchemaMap.put(platformId, schema); return schema; } @Override public void deletePlatformUpdateSchema(String platformId) throws ParamException { logger.debug(String.format("begin to delete platform update schema of %s", platformId)); PlatformPo platformPo = platformMapper.selectByPrimaryKey(platformId); if(platformPo == null) { logger.error(String.format("%s platform not exist", platformId)); throw new ParamException(String.format("%s platform not exist", platformId)); } CCODPlatformStatus status = CCODPlatformStatus.getEnumById(platformPo.getStatus()); if(status == null) { logger.error(String.format("%s status value %d is unknown", platformId, platformPo.getStatus())); throw new ParamException(String.format("%s status value %d is unknown", platformId, platformPo.getStatus())); } if(this.platformUpdateSchemaMap.containsKey(platformId)) { logger.debug(String.format("remove schema of %s from memory", platformId)); this.platformUpdateSchemaMap.remove(platformId); } logger.debug(String.format("delete schema of %s from database", platformId)); this.platformUpdateSchemaMapper.delete(platformId); switch (status) { case SCHEMA_CREATE_PLATFORM: logger.debug(String.format("%s status is %s, so it should be deleted", platformId, status.name)); platformMapper.delete(platformId); break; default: logger.debug(String.format("%s status is %s, so it should be updated to %s", platformId, status.name, CCODPlatformStatus.RUNNING.name)); platformPo.setStatus(CCODPlatformStatus.RUNNING.id); platformMapper.update(platformPo); break; } } @Override public void deletePlatform(String platformId) throws ParamException { logger.debug(String.format("begin to delete %s from cmdb", platformId)); PlatformPo platformPo = platformMapper.selectByPrimaryKey(platformId); if(platformPo == null) { logger.error(String.format("%s not exist", platformId)); throw new ParamException(String.format("%s not exist", platformId)); } if(this.platformUpdateSchemaMap.containsKey(platformId)) { this.platformUpdateSchemaMap.remove(platformId); } this.platformUpdateSchemaMapper.delete(platformId); List<PlatformAppPo> deployApps = platformAppMapper.select(platformId, null, null, null, null, null); this.platformAppBkModuleMapper.delete(null, null, platformId, null); for(PlatformAppPo deployApp : deployApps) { platformAppCfgFileMapper.delete(null, deployApp.getPlatformAppId()); } this.platformAppMapper.delete(null, platformId, null); this.domainMapper.delete(null, platformId); this.platformMapper.delete(platformId); logger.info(String.format("%s delete success", platformId)); } @Test public void schemaParamTest() { PlatformUpdateSchemaParamVo paramVo = new PlatformUpdateSchemaParamVo(); paramVo.setBkBizId(0); paramVo.setBkCloudId(8); paramVo.setPlatformId("ccodDevelopTestPlatform"); paramVo.setPlatformName("ccod开发测试平台"); paramVo.setTaskType(PlatformUpdateTaskType.CREATE); String script = "glsServer##glsServer##ece10ef28dce83ab36e4d79213ec4f69##/home/ccodrunner/Platform@10.130.41.218\n" + "LicenseServer##license##5214##/home/ccodrunner/Platform@10.130.41.218\n" + "configserver##configserver##aca2af60caa0fb9f4af57f37f869dafc90472525##/home/cfs/Platform@10.130.41.218\n" + "gls##gls##10309##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcms##dcms##11110##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmsWebservice##dcmsWebservice##20503##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmsRecord##dcmsRecord##21763##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmsStaticsReport##dcmsStatics##20537##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmsStaticsReport##dcmsStaticsReport##20528##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "safetyMonitor##safetyMonitor##20383##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmssg##dcmsSG##20070##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "customWebservice##customWebservice##19553##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "dcmsx##dcmsx##master_8efabf4##/home/ccodrunner/resin-4.0.13/webapps@10.130.41.218\n" + "slee##slee##3.1.5.0##/home/slee/Platform/slee/ChannelSoft/CsCCP/SoftSwitch/lib@10.130.41.218\n" + "UCGateway##UCGateway##b4c50cc9602c11c9cbfae23d07f134dc##/home/ccodrunner/SmartDialer4.1/Service@10.130.41.218\n" + "AppGateWay##AppGateWay##c03e1e3fedf73f25a1565c602b8e4040##/home/ccodrunner/SmartDialer4.1/Service@10.130.41.218\n" + "DialEngine##DialEngine##24ae5d2c45523ab5c7e0da7b86db4c18##/home/ccodrunner/SmartDialer4.1/Service@10.130.41.218\n" + "cmsserver##cms##4c303e2a4b97a047f63eb01b247303c9306fbda5##/home/channelsoft/Platform@10.130.41.218\n" + "cmsserver##cms##4c303e2a4b97a047f63eb01b247303c9306fbda5##/home/ccodrunner/Platform@10.130.41.218\n" + "UCDServer##ucds##deb3c3c4bf62c5ae5b3f8a467029a03ed95fb39e##/home/ccodrunner/Platform@10.130.41.218\n" + "ucxserver##ucx##1fef2157ea07c483979b424c758192bd709e6c2a##/home/ccodrunner/Platform@10.130.41.218\n" + "DDSServer##dds##150:18722##/home/ccodrunner/Platform@10.130.41.218\n" + "dcs##dcs##155:21974##/home/ccodrunner/Platform@10.130.41.218\n" + "StatSchedule##ss##154:21104##/home/ccodrunner/Platform@10.130.41.218\n" + "EAService##eas##216:11502##/home/ccodrunner/Platform@10.130.41.218\n" + "dcproxy##dcproxy##195:21857##/home/ccodrunner/Platform@10.130.41.218\n" + "daengine##daengine##179:20744##/home/ccodrunner/Platform@10.130.41.218"; paramVo.setPlanAppList(Arrays.asList(script.split("\n"))); System.out.println(JSONObject.toJSONString(paramVo)); } @Test public void splitTest() { String path = "/home/ccodrunner/resin-4.0.13/webapps"; String appAlias = "dcmsx"; path = path.replaceAll("^/", ""); String[] arr = path.split("/"); arr[1] = appAlias; System.out.println(String.join("/", arr)); } }
[ "lanhb@channelsoft.com" ]
lanhb@channelsoft.com
6047c24dca723daa55a27d078fd02cef95c1333b
0ebe0495a2cab4e1c2e942149805d5eb4df053b8
/app/src/main/java/com/xianyu/bookapplication/SplashActivity.java
7f534deaf19b4fbdf967920a195039620260a53f
[]
no_license
SaltedFish-Extreme/BookApplication
fee249944326605157140f70c84455fb224c29a5
e37a29003752cbf3d6ccae4a79fa3369aa6c702e
refs/heads/master
2023-01-24T19:15:26.702966
2020-12-01T09:17:39
2020-12-01T09:17:39
317,483,262
1
0
null
null
null
null
UTF-8
Java
false
false
1,412
java
package com.xianyu.bookapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.TextView; public class SplashActivity extends Activity { protected Handler mHandler = new Handler(Looper.myLooper()); TextView timeText; TextView skipText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); timeText = findViewById(R.id.timeText); skipText = findViewById(R.id.skipText); SkipLoading(); TimeLoading(); } private void SkipLoading() { skipText.setOnClickListener(v -> { startActivity(new Intent(SplashActivity.this, BookListActivity.class)); this.finish(); mHandler.removeCallbacksAndMessages(null); }); } private void TimeLoading() { timeText.postDelayed(() -> timeText.setText("2秒后进入主页"), 1000); timeText.postDelayed(() -> timeText.setText("1秒后进入主页"), 2000); timeText.postDelayed(() -> timeText.setText("0秒后进入主页"), 3000); mHandler.postDelayed(() -> startActivity(new Intent(SplashActivity.this, BookListActivity.class)), 3100); mHandler.postDelayed(SplashActivity.this::finish, 3100); } }
[ "54784104+SaltedFish-Extreme@users.noreply.github.com" ]
54784104+SaltedFish-Extreme@users.noreply.github.com
127e3c7ddcd6c2fa6099bb008d7306c0bd4906ea
ae98eda20039adfd16d988de62b61b36b9182cc3
/src/main/java/testngPackage/Login.java
00cb8ad099f7348ab425d3cd2262cde4dae5abce
[]
no_license
harshap16/practice_Eclipse_Git1
5e9ef0022975386c6ac5fd410742ba6272fbcc74
6b3b7710b82406fde6ff69c94f9f3ae989a87895
refs/heads/master
2023-03-23T18:19:02.317713
2021-03-23T11:00:50
2021-03-23T11:00:50
350,675,119
0
0
null
null
null
null
UTF-8
Java
false
false
3,010
java
package testngPackage; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; public class Login { static{ System.setProperty("webdriver.chrome.driver", "./utilities/chromedriver.exe"); System.setProperty("webdriver.chrome.silentOutput","true"); } @Test public void testValidLogin() { WebDriver driver=new ChromeDriver(); driver.get("https://demo.actitime.com/login.do"); driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin"); driver.findElement(By.xpath("//input[@name='pwd']")).sendKeys("manager"); driver.findElement(By.xpath("//a[@id='loginButton']")).click(); driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS); driver.findElement(By.xpath("//div[@id='container_users']")).click(); driver.findElement(By.xpath("//div[text()='New User']")).click(); //driver.findElement(By.xpath("//input[@id='createUserPanel_firstNameField']")).sendKeys("Harsha"); //driver.findElement(By.xpath("//input[@id='createUserPanel_lastNameField']")).sendKeys("Paga1"); /******************************************************************** wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//fieldset//input[@placeholder = 'Password']"))); WebElement passInput = driver.findElement(By.xpath("//fieldset//input[@placeholder = 'Password']")); // this xPath does the trick passInput.click(); passInput.sendKeys("password"); *****************************************************************/ WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='createUserPanel_firstNameField']"))); WebElement firstName=driver.findElement(By.xpath("//input[@id='createUserPanel_firstNameField']")); firstName.click(); firstName.sendKeys("aRavi1"); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='createUserPanel_lastNameField']"))); WebElement lastName=driver.findElement(By.xpath("//input[@id='createUserPanel_lastNameField']")); lastName.click(); lastName.sendKeys("zKumar1"); driver.findElement(By.xpath("(//input[@name='email'])[2]")).sendKeys("zravi1@gmail.com"); driver.findElement(By.xpath("//div[text()='Save & Send Invitation']")).click(); driver.findElement(By.xpath("(//span[text()='Close'])[1]")).click(); driver.findElement(By.xpath("//div[@id='container_tasks']")).click(); driver.findElement(By.xpath("//div[@class='addNewButton']")).click(); driver.findElement(By.xpath("//div[text()='+ New Tasks']")).click(); driver.findElement(By.xpath("(//div[@class='dropdownButton'])[1]")).click(); driver.findElement(By.xpath("//div[@class='dropdownButton']")).isSelected(); } }
[ "harsha.p16@gmail.com" ]
harsha.p16@gmail.com
13631dae2a9c0ed993e1e1cb32eda2fbd5b15ec5
fd96f4b19c7f2f890ac8bfef9410c93b407dcc3b
/src/com/dagim/jpa/client/JPAOperations.java
56f216af005bef8d1edffabc3445ecc79b5c2113
[]
no_license
getachew015/JPATutExample
5f19b8966576e4f6821d0b80123a7de83002f4b2
4be4748354c66fa56edd921b91a5183598bc3991
refs/heads/master
2023-08-09T23:46:37.183630
2019-05-28T19:11:25
2019-05-28T19:11:25
189,087,900
0
0
null
2023-07-22T06:57:10
2019-05-28T19:10:05
Java
UTF-8
Java
false
false
2,034
java
package com.dagim.jpa.client; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import com.dagim.jpa.entity.UserDetails; public class JPAOperations { public static void main(String[] args) { //1)Find Records List<Integer> userIds = new ArrayList<Integer>(); userIds.add(1001); userIds.add(1002); userIds.add(1003); userIds.add(1004); findRecords(userIds); //2)Delete Records to avoid duplicate deleteRecords(1001); deleteRecords(1002); deleteRecords(1003); deleteRecords(1004); //3)insert records insertRecords(); //4)update Records updateRecords(1001,"Odowuye Nukurmu"); } public static void insertRecords(){ UserDetails user1 = new UserDetails(1001,"Mariyah Butina"); UserDetails user2 = new UserDetails(1002,"George Clooney"); UserDetails user3 = new UserDetails(1003,"Pablo Escobar"); UserDetails user4 = new UserDetails(1004,"Rico Rodrigo"); EntityManager em = JpaUtility.getEntitymanger(); em.getTransaction().begin(); em.persist(user1); em.persist(user2); em.persist(user3); em.persist(user4); em.getTransaction().commit(); em.close(); } public static void deleteRecords(){ } public static void findRecords(List<Integer> userIdList){ List<UserDetails> users = new ArrayList<UserDetails>(); EntityManager em = JpaUtility.getEntitymanger(); userIdList.forEach(id -> users.add(em.find(UserDetails.class, id))); users.forEach(user -> System.out.println(user.toString())); } public static void updateRecords(int id, String name){ EntityManager em = JpaUtility.getEntitymanger(); UserDetails user = em.find(UserDetails.class, id); em.getTransaction().begin(); user.setUserName(name); em.getTransaction().commit(); em.close(); } public static void deleteRecords(int id){ EntityManager em = JpaUtility.getEntitymanger(); UserDetails user = em.find(UserDetails.class, id); em.getTransaction().begin(); em.remove(user); em.getTransaction().commit(); em.close(); } }
[ "getachew015@gmail.com" ]
getachew015@gmail.com
d15c598ed5226ec6317f566dc7d24b4e478216cb
dd3eec242deb434f76d26b4dc0e3c9509c951ce7
/2018-work/yjj/miscroservice_activity/src/main/java/com/e_commerce/miscroservice/activity/service/ChannelUserService.java
bb8df43692e3369ab562044936f522ccb84cc13d
[]
no_license
github4n/other_workplace
1091e6368abc51153b4c7ebbb3742c35fb6a0f4a
7c07e0d078518bb70399e50b35e9f9ca859ba2df
refs/heads/master
2020-05-31T10:12:37.160922
2019-05-25T15:48:54
2019-05-25T15:48:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
package com.e_commerce.miscroservice.activity.service; import com.e_commerce.miscroservice.activity.PO.ChannelOrderRecordVO; import java.util.Map; /** * @author Charlie * @version V1.0 * @date 2018/12/24 9:41 * @Copyright 玖远网络 */ public interface ChannelUserService { void fansPaySuccess(ChannelOrderRecordVO vo); }
[ "nessary@foxmail.com" ]
nessary@foxmail.com
a8e81efd6d77b36b981092e15da729e6a4af2bae
d0e18a66cf2622452c683de8be24ef9e2454b6f6
/core/src/main/java/me/jeeson/android/mvp/core/util/ThirdViewUtil.java
9a0731d08d392c675e960c1af3d86b8bdec04420
[ "Apache-2.0" ]
permissive
smuwjs/android-mvp-architecture
da848bcc4b4c6d12fafffaf92bdb0924a36452b2
7c7bf712031afb16dbf507517133b75a43587a4f
refs/heads/master
2021-01-22T23:53:54.860631
2017-07-06T07:36:15
2017-07-06T07:36:15
85,677,411
1
2
null
null
null
null
UTF-8
Java
false
false
3,006
java
package me.jeeson.android.mvp.core.util; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.zhy.autolayout.AutoFrameLayout; import com.zhy.autolayout.AutoLinearLayout; import com.zhy.autolayout.AutoRelativeLayout; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by zhiyicx on 2016/3/17. */ public class ThirdViewUtil { private final static String LAYOUT_LINEARLAYOUT = "LinearLayout"; private final static String LAYOUT_FRAMELAYOUT = "FrameLayout"; private final static String LAYOUT_RELATIVELAYOUT = "RelativeLayout"; public static int USE_AUTOLAYOUT = -1;//0 说明 AndroidManifest 里面没有使用 AutoLauout 的Meta,即不使用 AutoLayout,1 为有 Meta ,即需要使用 private ThirdViewUtil() { } public static Unbinder bindTarget(Object target, Object source) { if (source instanceof Activity) { return ButterKnife.bind(target, (Activity) source); } else if (source instanceof View) { return ButterKnife.bind(target, (View) source); } else if (source instanceof Dialog) { return ButterKnife.bind(target, (Dialog) source); } else { return Unbinder.EMPTY; } } @Nullable public static View convertAutoView(String name, Context context, AttributeSet attrs) { //本框架并不强制你使用 AutoLayout //如果你不想使用 AutoLayout ,就不要在 AndroidManifest 中声明, AutoLayout 的 Meta属性(design_width,design_height) if (USE_AUTOLAYOUT == -1) { USE_AUTOLAYOUT = 1; PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo; try { applicationInfo = packageManager.getApplicationInfo(context .getPackageName(), PackageManager.GET_META_DATA); if (applicationInfo == null || applicationInfo.metaData == null || !applicationInfo.metaData.containsKey("design_width") || !applicationInfo.metaData.containsKey("design_height")) { USE_AUTOLAYOUT = 0; } } catch (PackageManager.NameNotFoundException e) { USE_AUTOLAYOUT = 0; } } if (USE_AUTOLAYOUT == 0) { return null; } View view = null; if (name.equals(LAYOUT_FRAMELAYOUT)) { view = new AutoFrameLayout(context, attrs); } else if (name.equals(LAYOUT_LINEARLAYOUT)) { view = new AutoLinearLayout(context, attrs); } else if (name.equals(LAYOUT_RELATIVELAYOUT)) { view = new AutoRelativeLayout(context, attrs); } return view; } }
[ "smuwjs@163.com" ]
smuwjs@163.com
bd2a329035357ef950d19de4bb1fecea1be5c5c6
aecf778a055d0c0115d10a0ed63f43a53c2ec5ac
/src/blip/ConnectionTester.java
988400115e4450492d2022df2dc777bf179518ec
[]
no_license
bartenbach/blip
65975baffdd7262847b4c654208bd19c598321e2
308cf80ffd8f8dbffa1274ccf7eedfdaa0a04d4c
refs/heads/master
2021-09-08T03:19:44.836643
2012-03-15T02:03:42
2012-03-15T02:03:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,433
java
/* * blip * Attribute Only (Public) License Version 0.a5, Feb 07, 2012 Copyright (C) 2012 Blake Bartenbach <SeeD419@gmail.com> (@SeeD419) Anyone is allowed to copy and distribute verbatim or modified copies of this license document and altering is allowed as long as you attribute the author(s) of this license document / files. */ package blip; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author seed419 */ public class ConnectionTester extends Thread { private boolean connection; private static boolean lastConnect; private TrayHandler th; private int failedPings; private BlipUI blip; private boolean initialPing; public ConnectionTester(BlipUI blip, TrayHandler th) { this.blip = blip; this.th = th; failedPings = 2; } @Override public void run() { while (true) { try { Log.debug("Testing Connection..."); connection = testConnection(); if(!connection) { if (lastConnect != connection) { Log.info("Not connected."); th.setIconDisconnected(); blip.setProgressLabel("Not connected"); blip.setProgressBar(false); blip.enableDisconnect(false); blip.enableConnection(true); blip.setProgressBar(false); blip.setProgressValue(0); lastConnect = false; } } else { if (lastConnect != connection) { Log.info("Connected."); th.setIconConnected(); blip.enableConnection(false); blip.enableDisconnect(true); if(!blip.getEssid().equals("$$$$$$$$")) { blip.setProgressLabel("Connected to " + blip.getEssid()); } else { blip.setProgressLabel("Connected"); } blip.setProgressBar(false); blip.setProgressValue(100); lastConnect = true; } } Thread.sleep(5000); } catch (Exception ex) { Log.warning("Connection test thread interrupted", ex); } } } public boolean testConnection() { Log.debug("Pinging..."); Executor pinger = new Executor(Command.ping()); pinger.execute(); int status = 0; try { status = pinger.get(); } catch (InterruptedException ex) { Logger.getLogger(ConnectionTester.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Logger.getLogger(ConnectionTester.class.getName()).log(Level.SEVERE, null, ex); } Log.debug("Pinged"); if(status != 0) { failedPings++; if (failedPings > 1) { Log.debug("Not connected"); return false; } else { return true; } } failedPings = 0; Log.debug("Connected"); return true; } }
[ "seed419@gmail.com" ]
seed419@gmail.com
7c35fd9f6bf31bc44cd03059c86725ce325eb9f4
f467410b628427225d7108405403bf580b309202
/src/ie/broadsheet/app/model/json/Post.java
7e9eb9df75e0a7de594e19e4f2ca835fdfb224c4
[ "MIT" ]
permissive
pnagaraju25/Broadsheet.ie-Android
c72edd3aeaee3d9644e2d558576d5e6486aea6a0
21c36a8845b0d9c6173903205759ac6134b78dcc
refs/heads/master
2021-01-24T16:03:48.212605
2013-07-09T16:38:33
2013-07-09T16:38:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,095
java
package ie.broadsheet.app.model.json; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import android.annotation.SuppressLint; import android.text.format.DateUtils; import com.google.api.client.util.Key; public class Post implements Serializable { private static final long serialVersionUID = 1L; @Key private int id; @Key private String type; @Key private String slug; @Key private String url; @Key private String status; @Key private String title; @Key private String title_plain; @Key private String content; @Key private String excerpt; @Key private String date; @Key private String modified; @Key private List<Category> categories; @Key private List<Tag> tags; @Key private Author author; @Key private List<Comment> comments; private List<Comment> sortedComments = null; @Key private int comment_count; @Key private String comment_status; @Key private List<Attachments> attachments; private String relativeTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitle_plain() { return title_plain; } public void setTitle_plain(String title_plain) { this.title_plain = title_plain; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getExcerpt() { return excerpt; } public void setExcerpt(String excerpt) { this.excerpt = excerpt; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public List<Category> getCategories() { return categories; } public void setCategories(List<Category> categories) { this.categories = categories; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public int getComment_count() { return comment_count; } public void setComment_count(int comment_count) { this.comment_count = comment_count; } public String getComment_status() { return comment_status; } public void setComment_status(String comment_status) { this.comment_status = comment_status; } public List<Attachments> getAttachments() { return attachments; } public void setAttachments(List<Attachments> attachments) { this.attachments = attachments; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((attachments == null) ? 0 : attachments.hashCode()); result = prime * result + ((author == null) ? 0 : author.hashCode()); result = prime * result + ((categories == null) ? 0 : categories.hashCode()); result = prime * result + comment_count; result = prime * result + ((comment_status == null) ? 0 : comment_status.hashCode()); result = prime * result + ((comments == null) ? 0 : comments.hashCode()); result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((excerpt == null) ? 0 : excerpt.hashCode()); result = prime * result + id; result = prime * result + ((modified == null) ? 0 : modified.hashCode()); result = prime * result + ((slug == null) ? 0 : slug.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((tags == null) ? 0 : tags.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((title_plain == null) ? 0 : title_plain.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Post other = (Post) obj; if (attachments == null) { if (other.attachments != null) return false; } else if (!attachments.equals(other.attachments)) return false; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (categories == null) { if (other.categories != null) return false; } else if (!categories.equals(other.categories)) return false; if (comment_count != other.comment_count) return false; if (comment_status == null) { if (other.comment_status != null) return false; } else if (!comment_status.equals(other.comment_status)) return false; if (comments == null) { if (other.comments != null) return false; } else if (!comments.equals(other.comments)) return false; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (excerpt == null) { if (other.excerpt != null) return false; } else if (!excerpt.equals(other.excerpt)) return false; if (id != other.id) return false; if (modified == null) { if (other.modified != null) return false; } else if (!modified.equals(other.modified)) return false; if (slug == null) { if (other.slug != null) return false; } else if (!slug.equals(other.slug)) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; if (tags == null) { if (other.tags != null) return false; } else if (!tags.equals(other.tags)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; if (title_plain == null) { if (other.title_plain != null) return false; } else if (!title_plain.equals(other.title_plain)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } @Override public String toString() { return "Post [id=" + id + ", type=" + type + ", slug=" + slug + ", url=" + url + ", status=" + status + ", title=" + title + ", title_plain=" + title_plain + ", content=" + content + ", excerpt=" + excerpt + ", date=" + date + ", modified=" + modified + ", categories=" + categories + ", tags=" + tags + ", author=" + author + ", comments=" + comments + ", comment_count=" + comment_count + ", comment_status=" + comment_status + ", attachments=" + attachments + "]"; } public String getCommentCountString() { String comments; if (comment_count == 0) { comments = "No comments yet"; } else if (comment_count == 1) { comments = "1 comment"; } else { comments = Integer.toString(comment_count) + " comments"; } return comments; } public String getFeaturedImage() { String imageUrl = null; if (attachments.size() > 0) { AttachmentItem image = (AttachmentItem) ((Attachments) attachments.get(0)).getImages(); if (image != null) { Image thumbnail = image.getFull(); if (thumbnail != null) { imageUrl = thumbnail.getUrl(); } } } return imageUrl; } @SuppressLint("SimpleDateFormat") public String getRelativeTime() { if (relativeTime == null) { relativeTime = ""; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date result = null; try { result = df.parse(this.date); relativeTime = (String) DateUtils.getRelativeTimeSpanString(result.getTime(), new Date().getTime(), DateUtils.MINUTE_IN_MILLIS); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return relativeTime; } public List<Comment> getSortedComments() { if (sortedComments == null) { sortComments(); } return sortedComments; } private void sortComments() { TreeMap<String, Comment> allCommentsMap = new TreeMap<String, Comment>(); for (Iterator<Comment> iterator = comments.iterator(); iterator.hasNext();) { Comment item = (Comment) iterator.next(); item.setChildComment(new TreeMap<String, Comment>()); allCommentsMap.put(Integer.toString(item.getId()), item); } TreeMap<String, Comment> commentParents = new TreeMap<String, Comment>(); TreeMap<String, Comment> allComments = new TreeMap<String, Comment>(); SortedSet<String> keys = new TreeSet<String>(allCommentsMap.keySet()); for (String key : keys) { Comment comment = allCommentsMap.get(key); if (comment.getParent() > 0) { Comment parentComment = allCommentsMap.get(Integer.toString(comment.getParent())); if (parentComment != null) { if (parentComment.getChildComment().size() > 0) { parentComment.getChildComment().put(key, comment); } else { TreeMap<String, Comment> childer = new TreeMap<String, Comment>(); childer.put(key, comment); parentComment.setChildComment(childer); } comment.setChildLevel(parentComment.getChildLevel() + 1); allComments.put(Integer.toString(parentComment.getId()), parentComment); } else { commentParents.put(key, comment); } } else { commentParents.put(key, comment); } } sortedComments = new ArrayList<Comment>(); SortedSet<String> parentkeys = new TreeSet<String>(allCommentsMap.keySet()); for (String key : parentkeys) { Comment comment = commentParents.get(key); if (comment != null) { sortedComments.add(comment); if ((comment.getChildComment() != null) && (comment.getChildComment().size() > 0)) { // sortedComments.addAll(flattenComments(comment.getChildComment())); for (Comment addcomment : flattenComments(comment.getChildComment())) { sortedComments.add(addcomment); } } } } } public List<Comment> flattenComments(TreeMap<String, Comment> comments) { List<Comment> flattened = new ArrayList<Comment>(); SortedSet<String> parentkeys = new TreeSet<String>(comments.keySet()); for (String key : parentkeys) { Comment comment = comments.get(key); flattened.add(comment); if (comment.getChildComment().size() > 0) { flattened.addAll(flattenComments(comment.getChildComment())); } } return flattened; } public void addComment(Comment comment) { comments.add(comment); sortComments(); } }
[ "karl.t.monaghan@gmail.com" ]
karl.t.monaghan@gmail.com
c6dbf6c3fcc2be99066dc0b8c5e13ebb7ff6cadc
cab4a3f8fe124ef68c56bab1236bd39fc0f07a37
/weixin4j-qy/src/main/java/com/foxinmy/weixin4j/qy/api/UserApi.java
6eefda57b493d32b6246046e6de3714bd9cc45b6
[ "Apache-2.0" ]
permissive
WangMl/weixin4j
c328aabc17137d1e5565e425251f13a2ebf5f860
535d078e9d44783974387dc568524fa4325a1f17
refs/heads/master
2021-01-18T08:09:47.755704
2015-08-30T10:28:39
2015-08-30T10:28:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,566
java
package com.foxinmy.weixin4j.qy.api; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.qy.model.OUserInfo; import com.foxinmy.weixin4j.qy.model.User; import com.foxinmy.weixin4j.qy.type.InviteType; import com.foxinmy.weixin4j.qy.type.UserStatus; import com.foxinmy.weixin4j.token.TokenHolder; /** * 成员API * * @className UserApi * @author jy * @date 2014年11月19日 * @since JDK 1.7 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98">管理成员说明</a> */ public class UserApi extends QyApi { private final MediaApi mediaApi; private final TokenHolder tokenHolder; public UserApi(TokenHolder tokenHolder) { this.tokenHolder = tokenHolder; this.mediaApi = new MediaApi(tokenHolder); } /** * 创建成员 * * @param user * 成员对象 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E5.88.9B.E5.BB.BA.E6.88.90.E5.91.98">创建成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult createUser(User user) throws WeixinException { String user_create_uri = getRequestUri("user_create_uri"); return excute(user_create_uri, user, null); } /** * 创建成员 * * @param user * 成员对象 * @param avatar * 头像文件 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E5.88.9B.E5.BB.BA.E6.88.90.E5.91.98">创建成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult createUser(User user, InputStream avatar) throws WeixinException { String user_create_uri = getRequestUri("user_create_uri"); return excute(user_create_uri, user, avatar); } /** * 更新用户(如果非必须的字段未指定 则不更新该字段之前的设置值) * * @param user * 成员对象 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E6.9B.B4.E6.96.B0.E6.88.90.E5.91.98">更新成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult updateUser(User user) throws WeixinException { String user_update_uri = getRequestUri("user_update_uri"); return excute(user_update_uri, user, null); } /** * 更新用户(如果非必须的字段未指定 则不更新该字段之前的设置值) * * @param user * 成员对象 * @param avatar * 头像文件 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E6.9B.B4.E6.96.B0.E6.88.90.E5.91.98">更新成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult updateUser(User user, InputStream avatar) throws WeixinException { String user_update_uri = getRequestUri("user_update_uri"); return excute(user_update_uri, user, avatar); } private JsonResult excute(String uri, User user, InputStream avatar) throws WeixinException { JSONObject obj = (JSONObject) JSON.toJSON(user); Object extattr = obj.remove("extattr"); if (extattr != null) { JSONObject attrs = new JSONObject(); attrs.put("attrs", extattr); obj.put("extattr", attrs); } if (avatar != null) { obj.put("avatar_mediaid", mediaApi.uploadMedia(0, avatar, null)); } else { obj.put("avatar_mediaid", obj.remove("avatar")); } Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.post( String.format(uri, token.getAccessToken()), obj.toJSONString()); return response.getAsJsonResult(); } /** * 获取成员 * * @param userid * 成员唯一ID * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E8.8E.B7.E5.8F.96.E6.88.90.E5.91.98">获取成员说明</a> * @return 成员对象 * @throws WeixinException */ public User getUser(String userid) throws WeixinException { String user_get_uri = getRequestUri("user_get_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.get(String.format(user_get_uri, token.getAccessToken(), userid)); JSONObject obj = response.getAsJson(); Object attrs = obj.getJSONObject("extattr").remove("attrs"); if (attrs != null) { obj.put("extattr", attrs); } return JSON.toJavaObject(obj, User.class); } /** * code获取userid(管理员须拥有agent的使用权限;agentid必须和跳转链接时所在的企业应用ID相同。) * * @param code * 通过员工授权获取到的code,每次员工授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期 * @see com.foxinmy.weixin4j.qy.model.User * @return 成员对象 * @see {@link #getUser(String)} * @see {@link #getUserIdByCode(String,int)} * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E8%8E%B7%E5%8F%96code">企业获取code</a> * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E6%A0%B9%E6%8D%AEcode%E8%8E%B7%E5%8F%96%E6%88%90%E5%91%98%E4%BF%A1%E6%81%AF">根据code获取成员信息</a> * @throws WeixinException */ public User getUserByCode(String code) throws WeixinException { return getUser(getUserIdByCode(code).getString("UserId")); } /** * 获取企业号管理员登录信息 * * @param providerToken * 提供商的token * @param authCode * oauth2.0授权企业号管理员登录产生的code * @return 登陆信息 * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E4%BC%81%E4%B8%9A%E7%AE%A1%E7%90%86%E5%91%98%E7%99%BB%E5%BD%95%E4%BF%A1%E6%81%AF">授权获取企业号管理员登录信息</a> * @see com.foxinmy.weixin4j.qy.model.OUserInfo * @throws WeixinException */ public OUserInfo getOUserInfoByCode(String providerToken, String authCode) throws WeixinException { String oauth_logininfo_uri = getRequestUri("oauth_logininfo_uri"); WeixinResponse response = weixinExecutor.post( String.format(oauth_logininfo_uri, providerToken), String.format("{\"auth_code\":\"%s\"}", authCode)); return JSON.parseObject(response.getAsString(), OUserInfo.class); } /** * 根据code获取成员信息 * * @param code * 通过员工授权获取到的code,每次员工授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期 * @return { "UserId":"USERID", "DeviceId":"DEVICEID" } * @see <a * href="http://qydev.weixin.qq.com/wiki/indexo.php?title=%E4%BC%81%E4%B8%9A%E8%8E%B7%E5%8F%96code">企业获取code</a> * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E6%A0%B9%E6%8D%AEcode%E8%8E%B7%E5%8F%96%E6%88%90%E5%91%98%E4%BF%A1%E6%81%AF">根据code获取成员信息</a> * @throws WeixinException */ public JSONObject getUserIdByCode(String code) throws WeixinException { String user_getid_uri = getRequestUri("user_getid_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.get(String.format( user_getid_uri, token.getAccessToken(), code)); return response.getAsJson(); } /** * 获取部门成员 * * @param partyId * 部门ID 必须 * @param fetchChild * 是否递归获取子部门下面的成员 非必须 * @param userStatus * 成员状态 status可叠加 非必须 * @param findDetail * 是否获取详细信息 * @see com.foxinmy.weixin4j.qy.model.User * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E8.8E.B7.E5.8F.96.E9.83.A8.E9.97.A8.E6.88.90.E5.91.98">获取部门成员说明</a> * @return 成员列表 * @throws WeixinException */ public List<User> listUser(int departId, boolean fetchChild, UserStatus userStatus, boolean findDetail) throws WeixinException { String user_list_uri = findDetail ? getRequestUri("user_list_uri") : getRequestUri("user_slist_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.get(String.format( user_list_uri, token.getAccessToken(), departId, fetchChild ? 1 : 0, userStatus.getVal())); List<User> list = null; if (findDetail) { JSONArray arrays = response.getAsJson().getJSONArray("userlist"); list = new ArrayList<User>(arrays.size()); for (int i = 0; i < arrays.size(); i++) { JSONObject obj = arrays.getJSONObject(i); JSONObject ex = obj.getJSONObject("extattr"); Object attrs = null; if (ex != null && (attrs = ex.remove("attrs")) != null) { obj.put("extattr", attrs); } list.add(JSON.toJavaObject(obj, User.class)); } } else { list = JSON.parseArray(response.getAsJson().getString("userlist"), User.class); } return list; } /** * 获取部门下所有状态成员(不进行递归) * * @param departId * 部门ID * @see {@link #listUser(int, boolean,UserStatus)} * @return 成员列表 * @throws WeixinException */ public List<User> listUser(int departId) throws WeixinException { return listUser(departId, false, UserStatus.BOTH, false); } /** * 删除成员 * * @param userid * 成员ID * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E5.88.A0.E9.99.A4.E6.88.90.E5.91.98">删除成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult deleteUser(String userid) throws WeixinException { String user_delete_uri = getRequestUri("user_delete_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.get(String.format( user_delete_uri, token.getAccessToken(), userid)); return response.getAsJsonResult(); } /** * 批量删除成员 * * @param userIds * 成员列表 * @see <a href= * "http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E6.89.B9.E9.87.8F.E5.88.A0.E9.99.A4.E6.88.90.E5.91.98" * >批量删除成员说明</a> * @return 处理结果 * @throws WeixinException */ public JsonResult batchDeleteUser(List<String> userIds) throws WeixinException { JSONObject obj = new JSONObject(); obj.put("useridlist", userIds); String user_delete_uri = getRequestUri("user_batchdelete_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.post(String.format( user_delete_uri, token.getAccessToken(), obj.toJSONString())); return response.getAsJsonResult(); } /** * 开启二次验证成功时调用(管理员须拥有userid对应员工的管理权限) * * @param userid * 成员ID * @return 调用结果 * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%B3%E6%B3%A8%E4%B8%8E%E5%8F%96%E6%B6%88%E5%85%B3%E6%B3%A8">二次验证说明</a> * @throws WeixinException */ public JsonResult authsucc(String userId) throws WeixinException { String user_authsucc_uri = getRequestUri("user_authsucc_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.get(String.format( user_authsucc_uri, token.getAccessToken(), userId)); return response.getAsJsonResult(); } /** * 邀请成员关注(管理员须拥有该成员的查看权限) * * @param userId * 成员ID * @param tips * 推送到微信上的提示语(只有认证号可以使用)。当使用微信推送时,该字段默认为“请关注XXX企业号”,邮件邀请时,该字段无效。 * @return 邀请类型 * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E6%88%90%E5%91%98#.E9.82.80.E8.AF.B7.E6.88.90.E5.91.98.E5.85.B3.E6.B3.A8">邀请成员关注说明</a> * @throws WeixinException */ public InviteType inviteUser(String userId, String tips) throws WeixinException { JSONObject obj = new JSONObject(); obj.put("userid", userId); obj.put("invite_tips", tips); String invite_user_uri = getRequestUri("invite_user_uri"); Token token = tokenHolder.getToken(); WeixinResponse response = weixinExecutor.post( String.format(invite_user_uri, token.getAccessToken()), obj.toJSONString()); int type = response.getAsJson().getIntValue("type"); if (type == 1) { return InviteType.WEIXIN; } else if (type == 2) { return InviteType.EMAIL; } else { return null; } } /** * userid转换成openid:该接口使用场景为微信支付、微信红包和企业转账,企业号用户在使用微信支付的功能时, * 需要自行将企业号的userid转成openid。 在使用微信红包功能时,需要将应用id和userid转成appid和openid才能使用。 * * @param userid * 企业号内的成员id 必填 * @param agentid * 需要发送红包的应用ID,若只是使用微信支付和企业转账,则无需该参数 传入0或负数则忽略 * @return 结果数组 第一个元素为对应的openid 第二个元素则为应用的appid(如果有) * @throws WeixinException * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=Userid%E4%B8%8Eopenid%E4%BA%92%E6%8D%A2%E6%8E%A5%E5%8F%A3">userid转换成openid</a> */ public String[] userid2openid(String userid, int agentid) throws WeixinException { JSONObject obj = new JSONObject(); obj.put("userid", userid); if (agentid > 0) { obj.put("agentid", agentid); } String userid2openid_uri = getRequestUri("userid2openid_uri"); WeixinResponse response = weixinExecutor.post( String.format(userid2openid_uri, tokenHolder.getAccessToken()), obj.toJSONString()); obj = response.getAsJson(); return new String[] { obj.getString("openid"), obj.getString("appid") }; } /** * openid转换成userid:该接口主要应用于使用微信支付、微信红包和企业转账之后的结果查询, * 开发者需要知道某个结果事件的openid对应企业号内成员的信息时,可以通过调用该接口进行转换查询。 * * @param openid * 在使用微信支付、微信红包和企业转账之后,返回结果的openid * @return 该openid在企业号中对应的成员userid * @throws WeixinException * @see <a * href="http://qydev.weixin.qq.com/wiki/index.php?title=Userid%E4%B8%8Eopenid%E4%BA%92%E6%8D%A2%E6%8E%A5%E5%8F%A3">openid转换成userid</a> */ public String openid2userid(String openid) throws WeixinException { String openid2userid_uri = getRequestUri("openid2userid_uri"); WeixinResponse response = weixinExecutor.post( String.format(openid2userid_uri, tokenHolder.getAccessToken()), String.format("{\"openid\": \"%s\"}", openid)); return response.getAsJson().getString("userid"); } }
[ "foxinmy@gmail.com" ]
foxinmy@gmail.com
cdb7f4a7663548ef4cbbd6c303631b83c0b46dd2
d27f81f357eb76a6e14ecbd9523c0568d28f8497
/translator/src/test/java/test/components/PreflightTest.java
adb9608759d93eecf821706fd6c8ebc25a59feba
[]
no_license
frostbytten/translator-annotated-data
2c2c96c170bcd3b6ba5707b51e783a53c1d684cd
d1259eb025e6a76de42c62492cd09f0cf3b4692e
refs/heads/main
2021-12-02T07:05:49.373839
2021-03-18T17:19:34
2021-03-18T17:19:34
194,269,077
0
1
null
null
null
null
UTF-8
Java
false
false
2,264
java
package test.components; import com.google.common.jimfs.Jimfs; import org.agmip.translators.annotated.sidecar2.components.Sc2File; import org.agmip.translators.annotated.sidecar2.parsers.FileParser; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import test.samples.FileGenerator; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; import static test.samples.FileGenerator.FileCheck; import static test.samples.Sidecar2SampleKeys.*; public class PreflightTest { static FileSystem fs; @BeforeAll static void setupFileSystem() throws IOException { fs = Jimfs.newFileSystem(); Path workDir = fs.getPath("work"); Files.createDirectory(workDir); Files.createFile(workDir.resolve(FMFN_XLSX_VAL)); } private static List<Arguments> providesFiles() { return Sc2FileTest.provider; } @ParameterizedTest @MethodSource("providesFiles") void existingPreflightShouldStayValid(FileCheck file) { Sc2File fc = FileParser.parse(file.json); Path workDir = fs.getPath("work"); assumeThat(fc.isValid()).isTrue(); assumeThat(fc.getContentType()).isEqualTo(FMCT_XLSX_VAL); assumeThat(fc.getName()).isPresent(); assertThat(fc.fileReachable(workDir)).isTrue(); assertThat(fc.isValid()).isTrue(); } @ParameterizedTest @MethodSource("providesFiles") void missingPreflightShouldInvalidate(FileCheck file) { Sc2File fc = FileParser.parse(file.json); Path workDir = fs.getPath("work"); assumeThat(fc.isValid()).isTrue(); assumeThat(fc.getContentType()).isEqualTo(FMCT_CSV_VAL); assertThat(fc.fileReachable(workDir)).isFalse(); assertThat(fc.isValid()).isFalse(); assertThat(fc.reasonInvalid()).isEqualTo("Could not read file: example.csv\n"); } }
[ "cvillalobos@ufl.edu" ]
cvillalobos@ufl.edu
03481584cd9e51beaa062b6fed376e37bdaa2578
8382274682762fc55fe23afc9aacf68b1b08c3d4
/src/test/java/testcase/ProjectManagerTest.java
56efa902735f4e99d16442dc79edb1751b365586
[]
no_license
63966367/financeManageSystem
6673210ef8eb600596bd4f17859cefe9838da695
94560827c7d77e9a0f6f9cfc421bf95bca6effb1
refs/heads/master
2023-05-06T20:32:52.472908
2021-06-01T08:40:40
2021-06-01T08:40:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
612
java
package testcase; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import pageHandle.ProjectManegeHandle; public class ProjectManagerTest extends BaseCase{ public ProjectManegeHandle pmh; public ProjectManagerTest() { super("chrome"); this.pmh = new ProjectManegeHandle(baseDriver); } @Test public void test(){ System.out.println(pmh.getTableValues()); } @Test public void test1(){ System.out.println(pmh.getTableValue()); } @AfterTest public void afterTest(){ baseDriver.closeDriver(); } }
[ "2032514156@qq.com" ]
2032514156@qq.com
d843af4cf21ac0a30c5ce34eda0e36282e4fec64
e6f6e691b3b07b7d8c658aa954c2fbd98a7f5d89
/src/main/java/org/green/jelly/CopyingStringBuilder.java
a7f3e3bd0300c73f5b51b2dd075e38c4000083e3
[ "MIT" ]
permissive
allmycode/green-jelly
3da35ed604ad12d4af862ab3044f449ebd794abd
f0a90b423d2de9aeee4132e9e733161c52c6025c
refs/heads/master
2020-07-02T06:59:57.956321
2019-08-09T11:05:33
2019-08-09T11:05:33
201,449,136
0
0
MIT
2019-08-09T10:48:58
2019-08-09T10:48:57
null
UTF-8
Java
false
false
12,633
java
/** * MIT License * * Copyright (c) 2018 Anatoly Gudkov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.green.jelly; public final class CopyingStringBuilder implements JsonStringBuilder { private final StringBuilder buffer = new StringBuilder(); private final boolean rawString; private int escapedUnicodeChar; public CopyingStringBuilder() { this(false); } public CopyingStringBuilder(final boolean rawString) { this.rawString = rawString; } @Override public int length() { return buffer.length(); } @Override public char charAt(final int index) { return buffer.charAt(index); } @Override public void start(final CharSequence data, final int position) { buffer.setLength(0); } @Override public void append(final CharSequence data, final int start, final int len) { buffer.append(data, start, start + len); } @Override public void appendEscape() { if (rawString) { buffer.append('\\'); } } @Override public void appendEscapedQuotationMark() { buffer.append('"'); } @Override public void appendEscapedReverseSolidus() { buffer.append('\\'); } @Override public void appendEscapedSolidus() { buffer.append('/'); } @Override public void appendEscapedBackspace() { if (rawString) { buffer.append('b'); } else { buffer.append((char) 0x08); } } @Override public void appendEscapedFormfeed() { if (rawString) { buffer.append('f'); } else { buffer.append((char) 0x0c); } } @Override public void appendEscapedNewLine() { if (rawString) { buffer.append('n'); } else { buffer.append((char) 0x0a); } } @Override public void appendEscapedCarriageReturn() { if (rawString) { buffer.append('r'); } else { buffer.append((char) 0x0d); } } @Override public void appendEscapedHorisontalTab() { if (rawString) { buffer.append('t'); } else { buffer.append((char) 0x09); } } @Override public void appendEscapedUnicodeU() { if (rawString) { buffer.append('u'); } } @Override public boolean appendEscapedUnicodeChar1(final char c) { if (rawString) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': buffer.append(c); break; default: return false; } } else { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': escapedUnicodeChar = 4096 * (c - '0'); break; case 'A': case 'a': escapedUnicodeChar = 4096 * 10; break; case 'B': case 'b': escapedUnicodeChar = 4096 * 11; break; case 'C': case 'c': escapedUnicodeChar = 4096 * 12; break; case 'D': case 'd': escapedUnicodeChar = 4096 * 13; break; case 'E': case 'e': escapedUnicodeChar = 4096 * 14; break; case 'F': case 'f': escapedUnicodeChar = 4096 * 15; break; default: return false; } } return true; } @Override public boolean appendEscapedUnicodeChar2(final char c) { if (rawString) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': buffer.append(c); break; default: return false; } } else { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': escapedUnicodeChar = escapedUnicodeChar + 256 * (c - '0'); break; case 'A': case 'a': escapedUnicodeChar = escapedUnicodeChar + 256 * 10; break; case 'B': case 'b': escapedUnicodeChar = escapedUnicodeChar + 256 * 11; break; case 'C': case 'c': escapedUnicodeChar = escapedUnicodeChar + 256 * 12; break; case 'D': case 'd': escapedUnicodeChar = escapedUnicodeChar + 256 * 13; break; case 'E': case 'e': escapedUnicodeChar = escapedUnicodeChar + 256 * 14; break; case 'F': case 'f': escapedUnicodeChar = escapedUnicodeChar + 256 * 15; break; default: return false; } } return true; } @Override public boolean appendEscapedUnicodeChar3(final char c) { if (rawString) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': buffer.append(c); break; default: return false; } } else { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': escapedUnicodeChar = escapedUnicodeChar + 16 * (c - '0'); break; case 'A': case 'a': escapedUnicodeChar = escapedUnicodeChar + 16 * 10; break; case 'B': case 'b': escapedUnicodeChar = escapedUnicodeChar + 16 * 11; break; case 'C': case 'c': escapedUnicodeChar = escapedUnicodeChar + 16 * 12; break; case 'D': case 'd': escapedUnicodeChar = escapedUnicodeChar + 16 * 13; break; case 'E': case 'e': escapedUnicodeChar = escapedUnicodeChar + 16 * 14; break; case 'F': case 'f': escapedUnicodeChar = escapedUnicodeChar + 16 * 15; break; default: return false; } } return true; } @Override public boolean appendEscapedUnicodeChar4(final char c) { if (rawString) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': buffer.append(c); break; default: return false; } } else { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': escapedUnicodeChar = escapedUnicodeChar + 1 * (c - '0'); break; case 'A': case 'a': escapedUnicodeChar = escapedUnicodeChar + 1 * 10; break; case 'B': case 'b': escapedUnicodeChar = escapedUnicodeChar + 1 * 11; break; case 'C': case 'c': escapedUnicodeChar = escapedUnicodeChar + 1 * 12; break; case 'D': case 'd': escapedUnicodeChar = escapedUnicodeChar + 1 * 13; break; case 'E': case 'e': escapedUnicodeChar = escapedUnicodeChar + 1 * 14; break; case 'F': case 'f': escapedUnicodeChar = escapedUnicodeChar + 1 * 15; break; default: return false; } buffer.append((char) escapedUnicodeChar); } return true; } @Override public CharSequence subSequence(final int start, final int end) { throw new UnsupportedOperationException(); } @Override public String toString() { return buffer.toString(); } }
[ "agudkov@deltixlab.com" ]
agudkov@deltixlab.com
c1599e4d1836bb185fea047ba0bb54b7271568ad
1dbcd2d7b30a88c7f4212b1350c695ff23104772
/src/com/xt8/service/impl/ExpressServiceImpl.java
561ab7dedeca21987553662b07ad349806eb8160
[]
no_license
xiaoxiwu/xtb
cfaa3e795ddac6db1a17eda01d44d0546ebebe82
1570bdcb0f8b00fdd9e8c9a3663af6f14a9b598b
refs/heads/master
2021-01-20T11:50:44.684181
2015-01-10T08:42:12
2015-01-10T08:42:12
29,015,878
0
0
null
null
null
null
UTF-8
Java
false
false
1,093
java
package com.xt8.service.impl; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.xt8.model.Express; import com.xt8.model.ExpressSite; import com.xt8.service.ExpressService; public class ExpressServiceImpl extends BasicServiceImpl implements ExpressService { @Override public Express findById(Serializable id) { // TODO Auto-generated method stub return (Express) findById(Express.class, id); } @Override public Express insertExpress(Express express) { // TODO Auto-generated method stub Serializable id = super.save(express); return findById(id); } @Override public List<ExpressSite> listExpressSiteById(int expeId) { // TODO Auto-generated method stub Map<String, Object> condition=new HashMap<String, Object>(); condition.put("ExpressId", expeId); return find(ExpressSite.class,condition ); } @Override public List<Express> listExpress() { // TODO Auto-generated method stub return find(Express.class,null ); } }
[ "xiaoxiwu2008@qq.com" ]
xiaoxiwu2008@qq.com
4e3373994814c08f7e0c0f3540df6754270c919a
dc87de18dcf14e2b0de61f050977a4e34b13c839
/Source code fro app/db/UserLoginDao.java
5e3be64cf83f5e3446fdf7e897aecc2dae9624ae
[]
no_license
CecileUCL/Source-code-for-app
594a3ff574567527e42a0f7315271fae356780f8
f61fd3f7e31b23f76b00fe862eb3fc26774224c5
refs/heads/master
2021-01-12T03:31:53.727322
2017-01-06T17:38:50
2017-01-06T17:38:50
78,225,888
0
0
null
null
null
null
UTF-8
Java
false
false
1,636
java
package com.exam2.db; import java.util.ArrayList; import java.util.List; import com.exam2.entity.UserLogin; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class UserLoginDao { private DataBaseHelper helper = null; public UserLoginDao(Context context) { // TODO Auto-generated constructor stub helper = new DataBaseHelper(context); } /** * * user login */ public void insert(UserLogin userLogin){ SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("username", userLogin.getUsername()); values.put("password", userLogin.getPassword()); db.insert("USER_LOGIN", null, values); db.close(); } /* * */ public List<UserLogin> query(String uname, String pwd) throws Exception { List<UserLogin> userLoginList = new ArrayList<UserLogin>(); SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query("USER_LOGIN", null, " username = '" + uname + "' and password = '" + pwd + "' ", null, null, null, "id desc"); while (cursor.moveToNext()) { UserLogin userLogin = new UserLogin(); String username = cursor.getString(cursor .getColumnIndex("username")); String password = cursor.getString(cursor .getColumnIndex("password")); int id = cursor.getInt(cursor.getColumnIndex("id")); userLogin.setUsername(username); userLogin.setPassword(password); userLogin.setId(id); userLoginList.add(userLogin); } cursor.close(); db.close(); return userLoginList; } }
[ "cecile.larralde@gmail.com" ]
cecile.larralde@gmail.com
8b5744af71ffa7457cf01cc0c0dc7069de316c2f
5b51065948518b3fb69a1783fdbd992198013db0
/Practice/src/prac/Area.java
bf08a757a7e34a69fcdcb8bb78277c6c666791a1
[]
no_license
feefifofannie/SapientTraining
23e759ce5322bfcb5e2992d7f87ebc0440a6d223
d9943f50caa213b073ed8b59566be05b80c2a6a0
refs/heads/master
2016-09-05T21:28:55.197758
2015-08-28T09:32:12
2015-08-28T09:32:12
40,964,449
1
0
null
null
null
null
UTF-8
Java
false
false
319
java
package prac; // Compute the area of a circle. /** * * @author dredmo * */ class Area { public static void main(final String[] args) { final double pi = 3.1416; final double radius = 10.8; double area; area = pi * radius * radius; // compute area System.out.println("Area of circle is " + area); } }
[ "thedanielleredmond@gmail.com" ]
thedanielleredmond@gmail.com
ff58eb8de1ddbc19905acdce28ad6f8066be4ce7
7b665a0a61ce5a56b32cdac7f5cf34c0a9955ac3
/src/main/java/cn/lzq/designpatterns/adapter/Target.java
66c2fd748ed14df0f1520e92b14f5b3fa2f4111a
[]
no_license
lianzq/java-design-patterns
df1e361c425c5bc401324f5b51defcf99272354b
43c49b902862be26b21f58d2a387b80d535d4d17
refs/heads/master
2021-01-22T09:56:00.125247
2017-10-19T08:20:32
2017-10-19T08:20:32
102,333,827
1
0
null
null
null
null
UTF-8
Java
false
false
145
java
package cn.lzq.designpatterns.adapter; /** * @author lianzhiqiang * Created in 2017/10/19 */ public interface Target { void request(); }
[ "254663475@qq.com" ]
254663475@qq.com
7e357778a207e3558443d86251fe947d72a1362b
fb241f812f71f03a7cc32e736c5b9ab3b3cb5c3d
/book-spring-boot-actual-combat-swagger/src/main/java/com/learning/spring/boot/dao/UserDao.java
a7858f6589fc26b5e8b97df320c6f70309b6d924
[]
no_license
BerryHang/book-spring-boot-actual-combat
58af3734e255e91946b2d0cb3a217400f41d6f7f
59c819dd568f5165e323e742e869bdb6463a51c9
refs/heads/master
2022-09-03T21:41:28.055643
2020-01-17T08:22:45
2020-01-17T08:22:45
155,185,154
3
0
null
2022-09-01T23:08:29
2018-10-29T09:28:07
JavaScript
UTF-8
Java
false
false
2,562
java
package com.learning.spring.boot.dao; import com.learning.spring.boot.domain.entity.UserEntity; import com.learning.spring.boot.domain.request.UserCreateRequest; import com.learning.spring.boot.domain.request.UserUpdateRequest; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; /** * @Package: com.learning.spring.boot.dao * @ClassName: UserDao * @Author: beibei.huang * @Description: 用户数据操作类 * @Date: 2019/1/21 11:08 */ @Repository public class UserDao { private static List<UserEntity> userEntityList; static { userEntityList = new ArrayList<>(); UserEntity userEntity1 = new UserEntity(1, "李磊", "lilei", 16); UserEntity userEntity2 = new UserEntity(2, "小明", "xiaoming", 16); UserEntity userEntity3 = new UserEntity(3, "汤姆", "tom", 16); UserEntity userEntity4 = new UserEntity(4, "杰森", "Jason", 16); userEntityList.add(userEntity1); userEntityList.add(userEntity2); userEntityList.add(userEntity3); userEntityList.add(userEntity4); } public List<UserEntity> findUserList(){ return userEntityList; } public UserEntity findUser(Integer userId){ for (UserEntity user:userEntityList) { if (user.getUserId().equals(userId)){ return user; } } return null; } public Integer deleteUser(Integer userId){ for (int i=0 ;i<userEntityList.size();i++){ if (userEntityList.get(i).getUserId().equals(userId)) { userEntityList.remove(i--); return 1; } } return 0; } public Integer createUser(UserCreateRequest userInfo){ Integer maxUserId = 0; for (UserEntity user:userEntityList) { if (user.getUserId()>maxUserId){ maxUserId=user.getUserId(); } } UserEntity userEntity = new UserEntity(maxUserId+1, userInfo.getUserName(), userInfo.getPassword(), userInfo.getAge()); userEntityList.add(userEntity); return maxUserId; } public Integer updateUser(UserUpdateRequest userInfo){ for (UserEntity user:userEntityList) { if (user.getUserId()==userInfo.getUserId()){ user.setAge(userInfo.getAge()); user.setPassword(userInfo.getPassword()); user.setUserName(userInfo.getUserName()); return 1; } } return 0; } }
[ "beibei.huang@weimob.com" ]
beibei.huang@weimob.com
cd1e7817d5d57615b05c89e016fe66e7ee7958cc
a7bb5475078b0a4198e457968cbf6ef86fda6647
/pinyougou-order-service/src/main/java/com/pinyougou/order/service/impl/OrderServiceImplHu.java
bbecf87ab8178e8086e55856bc15c176d62c3bb2
[]
no_license
jamie0909/py-gou
37f23832572334883cb9d7a4f6302659095362a9
7ded86fafe16dfe9e1990b8266c8054388d4e25a
refs/heads/master
2022-12-21T05:30:49.334229
2019-07-27T19:42:44
2019-07-27T19:42:44
199,281,533
1
0
null
2022-12-16T07:14:48
2019-07-28T11:57:14
JavaScript
UTF-8
Java
false
false
10,181
java
package com.pinyougou.order.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.pinyougou.mapper.TbOrderItemMapper; import com.pinyougou.mapper.TbOrderMapper; import com.pinyougou.mapper.TbPayLogMapper; import com.pinyougou.order.service.OrderServiceHu; import com.pinyougou.pojo.*; import com.pinyougou.pojo.TbOrderExample.Criteria; import com.pinyougou.pojo.group.Cart; import entity.PageResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.transaction.annotation.Transactional; import util.IdWorker; import java.math.BigDecimal; import java.util.*; /** * 服务实现层 * @author Administrator * */ @Service @Transactional public class OrderServiceImplHu implements OrderServiceHu { @Autowired private TbOrderMapper orderMapper; @Autowired private TbPayLogMapper payLogMapper; /** * 查询全部 */ @Override public List<TbOrder> findAll() { return orderMapper.selectByExample(null); } /** * * @param pageNum * @param pageSize * @param userId * @param * status 1,待付款 2,待发货 3,待收货 4,待评价 * 数据库 状态:1、未付款,2、已付款,3、未发货,4、已发货,5、交易成功,6、交易关闭,7、待评价 * * @return */ @Override public PageResult findPage(int pageNum, int pageSize, String userId, String status) { TbOrderExample example = new TbOrderExample(); Criteria criteria = example.createCriteria(); if ("1".equals(status)){ criteria.andStatusEqualTo("1"); } if ("2".equals(status)){ List<String> list = new ArrayList<String>(); list.add("2"); list.add("3"); criteria.andStatusIn(list); } if ("3".equals(status)){ criteria.andStatusEqualTo("4"); } if ("4".equals(status)){ criteria.andStatusEqualTo("7"); } criteria.andUserIdEqualTo(userId); PageHelper.startPage(pageNum, pageSize); Page<TbOrder> page= (Page<TbOrder>) orderMapper.selectByExample(example); return new PageResult(page.getTotal(), page.getResult()); } @Autowired private RedisTemplate redisTemplate; @Autowired private IdWorker idWorker; @Autowired private TbOrderItemMapper orderItemMapper; /** * 增加 */ @Override public Map add(TbOrder order) { //1.从redis中提取购物车列表 List<Cart> cartList= (List<Cart>) redisTemplate.boundHashOps("cartList").get(order.getUserId()); String out_trade_no = null; List<String> orderIdList=new ArrayList();//订单ID集合 double total_money=0;//总金额 //2.循环购物车列表添加订单 for(Cart cart:cartList){ TbOrder tbOrder=new TbOrder(); long orderId = idWorker.nextId(); //获取ID tbOrder.setOrderId(orderId); order.setOrderId(orderId); tbOrder.setPaymentType(order.getPaymentType());//支付类型 tbOrder.setStatus("1");//未付款 tbOrder.setCreateTime(new Date());//下单时间 tbOrder.setUpdateTime(new Date());//更新时间 tbOrder.setUserId(order.getUserId());//当前用户 tbOrder.setReceiverAreaName(order.getReceiverAreaName());//收货人地址 tbOrder.setReceiverMobile(order.getReceiverMobile());//收货人电话 tbOrder.setReceiver(order.getReceiver());//收货人 tbOrder.setSourceType(order.getSourceType());//订单来源 tbOrder.setSellerId(order.getSellerId());//商家ID double money=0;//合计数 //循环购物车中每条明细记录 for(TbOrderItem orderItem:cart.getOrderItemList() ){ orderItem.setId(idWorker.nextId());//主键 orderItem.setOrderId(orderId);//订单编号 orderItem.setSellerId(cart.getSellerId());//商家ID orderItemMapper.insert(orderItem); money+=orderItem.getTotalFee().doubleValue(); } tbOrder.setPayment(new BigDecimal(money));//合计 orderMapper.insert(tbOrder); orderIdList.add(orderId+""); total_money+=money; } //添加支付日志 if("1".equals(order.getPaymentType())){ TbPayLog payLog=new TbPayLog(); payLog.setOutTradeNo(idWorker.nextId()+"");//支付订单号 out_trade_no = payLog.getOutTradeNo(); payLog.setCreateTime(new Date()); payLog.setUserId(order.getUserId());//用户ID payLog.setOrderList(orderIdList.toString().replace("[", "").replace("]", ""));//订单ID串 payLog.setTotalFee( (long)( total_money*100) );//金额(分) payLog.setTradeState("0");//交易状态 payLog.setPayType("1");//微信 payLog.setStatus("1"); payLogMapper.insert(payLog); System.out.println("==创建payLog,放入数据库和缓存==========="); System.out.println(order.getOrderId()); redisTemplate.boundHashOps("payLog").put(payLog.getOutTradeNo(), payLog);//放入缓存 } //3.清除redis中的购物车 redisTemplate.boundHashOps("cartList").delete(order.getUserId()); Map map = new HashMap(); map.put("out_trade_no",out_trade_no); return map; } /** * 修改 */ @Override public void update(TbOrder order){ orderMapper.updateByPrimaryKey(order); } /** * 根据ID获取实体 * @param id * @return */ @Override public TbOrder findOne(Long id){ return orderMapper.selectByPrimaryKey(id); } /** * 批量删除 */ @Override public void delete(Long[] ids) { for(Long id:ids){ orderMapper.deleteByPrimaryKey(id); } } @Override public PageResult findPage(TbOrder order, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); TbOrderExample example=new TbOrderExample(); Criteria criteria = example.createCriteria(); if(order!=null){ if(order.getPaymentType()!=null && order.getPaymentType().length()>0){ criteria.andPaymentTypeLike("%"+order.getPaymentType()+"%"); } if(order.getPostFee()!=null && order.getPostFee().length()>0){ criteria.andPostFeeLike("%"+order.getPostFee()+"%"); } if(order.getStatus()!=null && order.getStatus().length()>0){ criteria.andStatusLike("%"+order.getStatus()+"%"); } if(order.getShippingName()!=null && order.getShippingName().length()>0){ criteria.andShippingNameLike("%"+order.getShippingName()+"%"); } if(order.getShippingCode()!=null && order.getShippingCode().length()>0){ criteria.andShippingCodeLike("%"+order.getShippingCode()+"%"); } if(order.getUserId()!=null && order.getUserId().length()>0){ criteria.andUserIdLike("%"+order.getUserId()+"%"); } if(order.getBuyerMessage()!=null && order.getBuyerMessage().length()>0){ criteria.andBuyerMessageLike("%"+order.getBuyerMessage()+"%"); } if(order.getBuyerNick()!=null && order.getBuyerNick().length()>0){ criteria.andBuyerNickLike("%"+order.getBuyerNick()+"%"); } if(order.getBuyerRate()!=null && order.getBuyerRate().length()>0){ criteria.andBuyerRateLike("%"+order.getBuyerRate()+"%"); } if(order.getReceiverAreaName()!=null && order.getReceiverAreaName().length()>0){ criteria.andReceiverAreaNameLike("%"+order.getReceiverAreaName()+"%"); } if(order.getReceiverMobile()!=null && order.getReceiverMobile().length()>0){ criteria.andReceiverMobileLike("%"+order.getReceiverMobile()+"%"); } if(order.getReceiverZipCode()!=null && order.getReceiverZipCode().length()>0){ criteria.andReceiverZipCodeLike("%"+order.getReceiverZipCode()+"%"); } if(order.getReceiver()!=null && order.getReceiver().length()>0){ criteria.andReceiverLike("%"+order.getReceiver()+"%"); } if(order.getInvoiceType()!=null && order.getInvoiceType().length()>0){ criteria.andInvoiceTypeLike("%"+order.getInvoiceType()+"%"); } if(order.getSourceType()!=null && order.getSourceType().length()>0){ criteria.andSourceTypeLike("%"+order.getSourceType()+"%"); } if(order.getSellerId()!=null && order.getSellerId().length()>0){ criteria.andSellerIdLike("%"+order.getSellerId()+"%"); } } Page<TbOrder> page= (Page<TbOrder>)orderMapper.selectByExample(example); return new PageResult(page.getTotal(), page.getResult()); } @Override public TbPayLog searchPayLogFromRedis(String out_trade_no) { System.out.println(); return (TbPayLog) redisTemplate.boundHashOps("payLog").get(out_trade_no); } @Override public void updateOrderStatus(String out_trade_no, String transaction_id) { //1.修改支付日志的状态及相关字段 TbPayLog payLog = payLogMapper.selectByPrimaryKey(out_trade_no); payLog.setPayTime(new Date());//支付时间 payLog.setTradeState("1");//交易成功 payLog.setStatus(""); payLog.setTransactionId(transaction_id);//微信的交易流水号 payLogMapper.updateByPrimaryKey(payLog);//修改 //2.修改订单表的状态 String orderList = payLog.getOrderList();// 订单ID 串 String[] orderIds = orderList.split(","); for(String orderId:orderIds){ TbOrder order = orderMapper.selectByPrimaryKey(Long.valueOf(orderId)); order.setStatus("2");//已付款状态 order.setPaymentTime(new Date());//支付时间 orderMapper.updateByPrimaryKey(order); } //3.清除缓存中的payLog redisTemplate.boundHashOps("payLog").delete(out_trade_no); } @Override public void updateStatus(String out_order_no, String status) throws Exception { TbPayLogExample example = new TbPayLogExample(); TbPayLogExample.Criteria criteria = example.createCriteria(); criteria.andOutTradeNoEqualTo(out_order_no); List<TbPayLog> tbPayLogs = payLogMapper.selectByExample(example); String status1 = tbPayLogs.get(0).getStatus(); if ("8".equals(status)){ if ("1".equals(status1)||"6".equals(status1)){ throw new Exception(); } } TbPayLog payLog = new TbPayLog(); payLog.setStatus(status); payLogMapper.updateByExampleSelective(payLog,example); String orderListStr = tbPayLogs.get(0).getOrderList(); String[] orderList = orderListStr.split(", "); for (String orderId : orderList) { TbOrder order = new TbOrder(); order.setOrderId(Long.parseLong(orderId)); order.setStatus(status); orderMapper.updateByPrimaryKeySelective(order); } } }
[ "1421115469@qq.com" ]
1421115469@qq.com
b53f591e08c78c6b47261380ffbfcaf7ebb80275
13b9880699c6041e213c6bb9620c7cda1aa01589
/Arduino/Dev/ArduBlock/ardublock/src/main/java/com/ardublock/translator/block/ConstrainBlock.java
58249d9b4b4eb2fc7b056627f2f6c9f0ce21a53d
[ "Artistic-2.0" ]
permissive
bkkl/TurtleBots
83b1181d4ffcc05a3b1b9e65a17c470a8632eeb5
5f7d0f6880de4848332a6aa11224ed3849b15085
refs/heads/master
2021-01-17T08:25:15.763995
2015-02-01T14:29:43
2015-02-01T14:29:43
18,184,738
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package com.ardublock.translator.block; import com.ardublock.translator.Translator; public class ConstrainBlock extends TranslatorBlock { public ConstrainBlock(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } @Override public String toCode() throws Exception { String ret = "constrain( "; TranslatorBlock tb = this.getRequiredTranslatorBlockAtSocket(0); ret = ret + tb.toCode(); ret = ret + " , "; tb = this.getRequiredTranslatorBlockAtSocket(1); ret = ret + tb.toCode(); ret = ret + " , "; tb = this.getRequiredTranslatorBlockAtSocket(2); ret = ret + tb.toCode(); ret = ret + " ) "; return codePrefix + ret + codeSuffix; } }
[ "andy@dassing.us" ]
andy@dassing.us
d8ed497142037ee2eff5f6e661cbe861a9121f2e
0175a417f4b12b80cc79edbcd5b7a83621ee97e5
/flexodesktop/externalmodels/flexodocxparser/src/main/java/org/openflexo/docxparser/DocxFileParser.java
6b29f039fb1da4408f6247d2ea37267453448292
[]
no_license
agilebirds/openflexo
c1ea42996887a4a171e81ddbd55c7c1e857cbad0
0250fc1061e7ae86c9d51a6f385878df915db20b
refs/heads/master
2022-08-06T05:42:04.617144
2013-05-24T13:15:58
2013-05-24T13:15:58
2,372,131
11
6
null
2022-07-06T19:59:55
2011-09-12T15:44:45
Java
UTF-8
Java
false
false
8,495
java
/* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.docxparser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.openflexo.docxparser.dto.ParsedDocx; import org.openflexo.docxparser.dto.ParsedHtml; import org.openflexo.docxparser.dto.api.IParsedDocx; import org.openflexo.docxparser.dto.api.IParsedFlexoContent; import org.openflexo.docxparser.dto.api.IParsedFlexoDescription; import org.openflexo.docxparser.dto.api.IParsedFlexoName; import org.openflexo.docxparser.dto.api.IParsedFlexoTitle; import org.openflexo.docxparser.flexotag.FlexoContentTag; import org.openflexo.docxparser.flexotag.FlexoDescriptionTag; import org.openflexo.docxparser.flexotag.FlexoEPITag; import org.openflexo.docxparser.flexotag.FlexoNameTag; import org.openflexo.docxparser.flexotag.FlexoTitleTag; public class DocxFileParser { protected static final Logger logger = Logger.getLogger(DocxFileParser.class.getPackage().toString()); private static final List<String> TAGS = Arrays.asList(FlexoDescriptionTag.FLEXODESCRIPTIONTAG, FlexoNameTag.FLEXONAMETAG, FlexoTitleTag.FLEXOTITLETAG, FlexoContentTag.FLEXOCONTENTTAG, FlexoEPITag.EPI_TAG); private static final String XPATH; static { StringBuilder sb = new StringBuilder(); for (String tag : TAGS) { if (sb.length() == 0) { sb.append("//w:sdt/w:sdtPr[not(w:showingPlcHdr)]/w:tag["); } else { sb.append(" or "); } sb.append("starts-with(@w:val, '"); sb.append(tag); sb.append("')"); } sb.append(']'); XPATH = sb.toString(); } private Set<String> availableCssClasses; private String resourcesDirectory; private OPCPackage filePackage; private PackagePart documentPart = null; private Document documentXml = null; public DocxFileParser(byte[] documentBytes, Set<String> availableCssClasses, String resourcesDirectory) throws InvalidFormatException { ByteArrayInputStream in = new ByteArrayInputStream(documentBytes); try { initialize(in, availableCssClasses, resourcesDirectory); } finally { try { in.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public DocxFileParser(InputStream in, Set<String> availableCssClasses, String resourcesDirectory) throws InvalidFormatException { initialize(in, availableCssClasses, resourcesDirectory); } private void initialize(InputStream in, Set<String> availableCssClasses, String resourcesDirectory) throws InvalidFormatException { if (availableCssClasses == null) { this.availableCssClasses = new HashSet<String>(); } else { this.availableCssClasses = availableCssClasses; } this.resourcesDirectory = resourcesDirectory; try { filePackage = OPCPackage.open(in); } catch (IOException e) { throw new RuntimeException(e); } finally { try { in.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public IParsedDocx getParsedDocx() { ParsedDocx parsedDocx = new ParsedDocx(); List<?> resultList = getDocumentXml().selectNodes(XPATH); for (Iterator<?> iterator = resultList.iterator(); iterator.hasNext();) { Element element = (Element) iterator.next(); String tagValue = element.attributeValue(DocxQName.getQName(OpenXmlTag.w_val)); Element sdtElement = element.getParent().getParent(); // On w:sdt Element sdtContentElement = sdtElement.element(DocxQName.getQName(OpenXmlTag.w_sdtContent)); try { if (tagValue.startsWith(FlexoDescriptionTag.FLEXODESCRIPTIONTAG)) { FlexoDescriptionTag descTag = new FlexoDescriptionTag(tagValue); ParsedHtml parsedHtml = OpenXml2Html.getHtml(sdtContentElement, getDocumentPart(), availableCssClasses, resourcesDirectory); IParsedFlexoDescription parsedFlexoDescription = parsedDocx.getOrCreateParsedDescription(descTag.getFlexoId(), descTag.getUserId()); parsedFlexoDescription.addHtmlDescription(descTag.getTarget(), parsedHtml); } else if (tagValue.startsWith(FlexoNameTag.FLEXONAMETAG)) { String text = extractTextContent(sdtContentElement); FlexoNameTag nameTag = new FlexoNameTag(tagValue); if (text.length() > 0) { IParsedFlexoName parsedFlexoName = parsedDocx.getOrCreateParsedName(nameTag.getFlexoId(), nameTag.getUserId()); parsedFlexoName.setFlexoName(text); } } else if (tagValue.startsWith(FlexoTitleTag.FLEXOTITLETAG)) { FlexoTitleTag titleTag = new FlexoTitleTag(tagValue); String text = extractTextContent(sdtContentElement); if (text.length() > 0) { IParsedFlexoTitle parsedFlexoTitle = parsedDocx.getOrCreateParsedTitle(titleTag.getFlexoId(), titleTag.getUserId()); parsedFlexoTitle.setFlexoTitle(text); } } else if (tagValue.startsWith(FlexoEPITag.EPI_TAG)) { FlexoEPITag epiTag = new FlexoEPITag(tagValue); // TODO: Here extract the text under 3 forms: // * one line string // * multi-line string // * styled text // Reinjection shall then choose the appropriate extract according the info // available in VP. String text = extractTextContent(sdtContentElement); if (text.length() > 0) { parsedDocx.createParsedFlexoEPI(epiTag, text); } } else if (tagValue.startsWith(FlexoContentTag.FLEXOCONTENTTAG)) { FlexoContentTag contentTag = new FlexoContentTag(tagValue); ParsedHtml parsedHtml = OpenXml2Html.getHtml(sdtContentElement, getDocumentPart(), availableCssClasses, resourcesDirectory); IParsedFlexoContent parsedFlexoContent = parsedDocx.getOrCreateParsedContent(contentTag.getFlexoId(), contentTag.getUserId()); parsedFlexoContent.setFlexoContent(parsedHtml); } // else if (tagValue.startsWith(FlexoContentTag.FLEXOEPTAG)) } catch (FlexoDescriptionTag.FlexoTagFormatException e) { logger.log(Level.WARNING, "Cannot parse tag from a building block which seems to be a Flexo Tag", e); } } return parsedDocx; } public String extractTextContent(Element sdtContentElement) { StringBuilder sb = new StringBuilder(); /*Iterator<?> iteratorWp = sdtContentElement.selectNodes("descendant::w:p").iterator(); while (iteratorWp.hasNext()) { Element wpElement = (Element) iteratorWp.next();*/ Iterator<?> iteratorWt = sdtContentElement.selectNodes("descendant::w:t").iterator(); while (iteratorWt.hasNext()) { Element textElement = (Element) iteratorWt.next(); sb.append(textElement.getText()); } /*if (iteratorWp.hasNext()) { sb.append(StringUtils.LINE_SEPARATOR); } }*/ return sb.toString().trim(); } public void close() { try { filePackage.close(); } catch (IOException e) { throw new RuntimeException(e); } } public OPCPackage getFilePackage() { return filePackage; } public PackagePart getDocumentPart() { if (documentPart == null) { PackageRelationship documentRelationship = getFilePackage().getRelationshipsByType(DocxXmlUtil.RELATIONSHIPTYPE_COREDOCUMENT) .getRelationship(0); documentPart = getFilePackage().getPart(documentRelationship); } return documentPart; } public Document getDocumentXml() { if (documentXml == null) { try { documentXml = new SAXReader().read(getDocumentPart().getInputStream()); } catch (Exception e) { throw new RuntimeException(e); } } return documentXml; } }
[ "guillaume.polet@gmail.com" ]
guillaume.polet@gmail.com
49092c276697985ca34b25c6ae4919ecae11cc8f
0f2ebb093e81b74916ece7ce591861ab42ba5a8e
/simple/src/definition/LoggedIn.java
51cb6430edcf4d6730d19204b247ea3ebe2fc05a
[]
no_license
Simonassi/SIMPLE
8b0b87f2c0365a630dc6c7a50159921a79dfcbd3
af6df31590210e4576a2e24bd2f618002cc288cf
refs/heads/master
2021-01-10T15:39:19.548458
2016-03-15T21:44:31
2016-03-15T21:44:31
53,698,144
0
0
null
null
null
null
UTF-8
Java
false
false
1,964
java
package definition; import control.Situation; import model.Access; import model.Account; import model.Device; import com.espertech.esper.client.EventBean; public class LoggedIn extends Situation{ private Device device; private Account account; private Access access; public LoggedIn(){ setSitName("LoggedIn"); setEplA("select Access as access, Access.isAcessing as device, Access.isAcessed as account, Access.key as key1 " + "from Access(actived = true) as Access"); setEplD("select Access.key as key1 " + "from " + " LoggedIn.std:unique(id) as LoggedIn, " + " Access.std:lastevent() as Access " + "where" + " LoggedIn.actived = true and " + " LoggedIn.access.key = Access.key " + " and " + " (" + " not(Access.actived = true) " + " )"); } public Device getDevice() { return device; } public void setDevice(Device device) { this.device = device; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public Access getAccess() { return access; } public void setAccess(Access access) { this.access = access; } @Override public Situation createNewSit(EventBean event) { LoggedIn loggedIn = new LoggedIn(); try{ loggedIn.setAccount((Account)event.get("account")); loggedIn.setDevice((Device)event.get("device")); loggedIn.setAccess((Access)event.get("access")); }catch(Exception e){ System.out.println("LoggedIn: " + e); } return loggedIn; } @Override public Object doActionAtCreateDeactivationEvent() { LoggedIn loggedIn = new LoggedIn(); try{ loggedIn.setAccount(this.getAccount()); loggedIn.setDevice(this.getDevice()); loggedIn.setAccess(this.getAccess()); }catch(Exception e){ System.out.println("LoggedIn: " + e); } return loggedIn; } }
[ "simonassiamorim@hotmail.com" ]
simonassiamorim@hotmail.com
499aeb6dff02b42272734b572e6933c9ce53e2f4
b96e43d0b64c86d8278b2c3847530f4815197066
/src/main/java/com/test/controller/UsersController.java
f29474acac83142bed7130a106f408d47095b4fc
[]
no_license
vipjoker/SpringHibernate
b4443254fee2a1e8039ca512b948802dcfee2a62
65b6a9b477be4ffc325fd820167167a798ecc3d4
refs/heads/master
2020-07-04T21:13:28.574650
2016-11-23T13:15:01
2016-11-23T13:15:01
74,138,374
0
0
null
null
null
null
UTF-8
Java
false
false
1,846
java
package com.test.controller; import com.test.model.Item; import com.test.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.logging.Logger; /** * Created by omakhobei on 11/11/2016. */ @Controller public class UsersController { @Autowired private ApplicationContext appContext; @Autowired private ItemService mService; Logger logger = Logger.getLogger(UsersController.class.getName()); @RequestMapping(value="/" , method = RequestMethod.GET) public String helloWorld(Model model){ Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("YYYY-'W'ww-u"); String formattedDate = format.format(date); model.addAttribute("items",mService.listItems()); return "home"; } @PostMapping("/create") public String createUser(Model model,@ModelAttribute("command")Item item){ logger.info("***************name " + item.toString()); mService.addItem(item); List<Item> items = mService.listItems(); model.addAttribute("items",items); return "redirect:/"; } @GetMapping("/create" ) public String createPage(Model model){ Item item = new Item(); model.addAttribute("command",item); logger.info("crete invoked"); return "create"; } @RequestMapping(value = "/items",method = RequestMethod.GET) public String getAllItems(Model model){ model.addAttribute("serverTime" ,"Items list works "); return "home"; } }
[ "tajcig@ya.ru" ]
tajcig@ya.ru
57325d11bcd7f2f1b5c002dd57bd8cf405fdb5e0
e6bd61a48d83cfb2a162c3174e16ccc2b97627c1
/app/controllers/ItensBacklog.java
b201e0b0eaa3b8d8452a7c57137ad893db7f3575
[]
no_license
eudesf/ceut-scrum-project
c068a0e06f6d0bcf33006193fbec639547987e90
150f493459b00f5ab3a9b9ad1c63a2ea0e88a5e5
refs/heads/master
2016-08-06T10:49:11.857033
2013-01-25T23:14:05
2013-01-25T23:14:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,754
java
package controllers; import java.util.ArrayList; import java.util.List; import models.ItemBacklog; import models.Produto; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.backlog.breakItemForm; import views.html.backlog.editForm; import views.html.backlog.index; public class ItensBacklog extends Controller { public static Form<ItemBacklog> formItem = form(ItemBacklog.class); public static String lastOrderBy = "nome asc"; public static final String BREAK_ITEMS_KEY = "break-items"; public static List<ItemBacklog> itensToAdd = new ArrayList<ItemBacklog>(); private static List<ItemBacklog> listaItensBacklog(Long produtoId) { Produto produto = Produto.find.ref(produtoId); return ItemBacklog.find.where().eq("produto", produto).orderBy(lastOrderBy).findList(); } public static Result index(Long produtoId, String orderBy) { lastOrderBy = orderBy; List<ItemBacklog> itens = listaItensBacklog(produtoId); return ok(index.render(produtoId, formItem, itens)); } public static Result create(Long produtoId) { Form<ItemBacklog> formAux = formItem.bindFromRequest(); if (formAux.hasErrors()) { return badRequest(index.render(produtoId, formAux, listaItensBacklog(produtoId))); } else { ItemBacklog item = formAux.get(); item.produto = Produto.find.ref(produtoId); item.save(); return ok(index.render(produtoId, formItem, listaItensBacklog(produtoId))); } } public static Result delete(Long id) { ItemBacklog item = ItemBacklog.find.ref(id); Long produtoId = item.produto.id; item.delete(); return index(produtoId, lastOrderBy); } public static Result editForm(Long id) { return ok(editForm.render(id, formItem.fill(ItemBacklog.find.ref(id)))); } public static Result update(Long id) { Long produtoId = ItemBacklog.find.ref(id).produto.id; Form<ItemBacklog> formAux = formItem.bindFromRequest(); if (formAux.hasErrors()) { return badRequest(editForm.render(id, formAux)); } else { ItemBacklog item = formAux.get(); item.produto = Produto.find.ref(produtoId); item.update(id); return index(produtoId, lastOrderBy); } } public static Result breakItemForm(Long id) { ItemBacklog item = ItemBacklog.find.byId(id); return ok(breakItemForm.render(item, formItem)); } public static Result breakItem(Long id) { ItemBacklog itemBacklog = ItemBacklog.find.byId(id); Produto produto = itemBacklog.produto; BreakItemsForm formItens = form(BreakItemsForm.class).bindFromRequest().get(); for (ItemBacklog item : formItens.itens) { item.produto = produto; item.save(); } itemBacklog.delete(); return ItensBacklog.index(produto.id, lastOrderBy); } public static Result fake() { return TODO; } }
[ "aeudes@gmail.com" ]
aeudes@gmail.com
ffa5889abd01dfb8bc752a9f58563d3232042c29
8e2945928f641820507f89afccce8745e6703aac
/hsqldb-2.2.8/hsqldb/src/org/hsqldb/HsqlDateTime.java
de7d90ba189658b83e85c3d50a4bd2c36ac08249
[]
no_license
IvoCrnkovic/Accelerando
0e765c01162ce1e9245fb9d9b07f25a8abdbf8b2
2d9c72c30d3fc23699228e969941cf7add03b9db
refs/heads/master
2021-01-06T20:38:15.163674
2012-09-02T23:12:36
2012-09-02T23:12:36
4,567,659
2
0
null
null
null
null
UTF-8
Java
false
false
26,736
java
/* Copyright (c) 2001-2011, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.hsqldb.error.Error; import org.hsqldb.error.ErrorCode; import org.hsqldb.lib.ArrayUtil; import org.hsqldb.lib.StringUtil; import org.hsqldb.types.DTIType; import org.hsqldb.types.Types; /** * collection of static methods to convert Date and Timestamp strings * into corresponding Java objects and perform other Calendar related * operation.<p> * * Was reviewed for 1.7.2 resulting in centralising all DATETIME related * operstions.<p> * * From version 2.0.0, HSQLDB supports TIME ZONE with datetime types. The * values are stored internally as UTC seconds from 1970, regardless of the * time zone of the JVM, and converted as and when required, to the local * timezone. * * @author Fred Toussi (fredt@users dot sourceforge.net) * @version 2.2.6 * @since 1.7.0 */ public class HsqlDateTime { /** * A reusable static value for today's date. Should only be accessed * by getToday() */ private static Locale defaultLocale = Locale.UK; private static long currentDateMillis; public static final Calendar tempCalDefault = new GregorianCalendar(); public static final Calendar tempCalGMT = new GregorianCalendar(TimeZone.getTimeZone("GMT"), defaultLocale); private static final Date tempDate = new Date(0); private static final String sdfdPattern = "yyyy-MM-dd"; static SimpleDateFormat sdfd = new SimpleDateFormat(sdfdPattern); private static final String sdftPattern = "HH:mm:ss"; static SimpleDateFormat sdft = new SimpleDateFormat(sdftPattern); private static final String sdftsPattern = "yyyy-MM-dd HH:mm:ss"; static SimpleDateFormat sdfts = new SimpleDateFormat(sdftsPattern); private static final String sdftsSysPattern = "yyyy-MM-dd HH:mm:ss.SSS"; static SimpleDateFormat sdftsSys = new SimpleDateFormat(sdftsSysPattern); static { tempCalGMT.setLenient(false); sdfd.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"), defaultLocale)); sdfd.setLenient(false); sdft.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"), defaultLocale)); sdft.setLenient(false); sdfts.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"), defaultLocale)); sdfts.setLenient(false); } static { currentDateMillis = getNormalisedDate(System.currentTimeMillis()); } public static long getDateSeconds(String s) { try { synchronized (sdfd) { java.util.Date d = sdfd.parse(s); return d.getTime() / 1000; } } catch (Exception e) { throw Error.error(ErrorCode.X_22007); } } public static String getDateString(long seconds) { synchronized (sdfd) { sysDate.setTime(seconds * 1000); return sdfd.format(sysDate); } } public static long getTimestampSeconds(String s) { try { synchronized (sdfts) { java.util.Date d = sdfts.parse(s); return d.getTime() / 1000; } } catch (Exception e) { throw Error.error(ErrorCode.X_22007); } } public static void getTimestampString(StringBuffer sb, long seconds, int nanos, int scale) { synchronized (sdfts) { tempDate.setTime(seconds * 1000); sb.append(sdfts.format(tempDate)); if (scale > 0) { sb.append('.'); sb.append(StringUtil.toZeroPaddedString(nanos, 9, scale)); } } } public static String getTimestampString(long millis) { synchronized (sdfts) { sysDate.setTime(millis); return sdfts.format(sysDate); } } public static synchronized long getCurrentDateMillis(long millis) { if (millis - currentDateMillis >= 24 * 3600 * 1000) { currentDateMillis = getNormalisedDate(millis); } return currentDateMillis; } private static java.util.Date sysDate = new java.util.Date(); public static String getSystemTimeString() { synchronized (sdftsSys) { sysDate.setTime(System.currentTimeMillis()); return sdftsSys.format(sysDate); } } public static void resetToDate(Calendar cal) { cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); } public static void resetToTime(Calendar cal) { cal.set(Calendar.YEAR, 1970); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DATE, 1); cal.set(Calendar.MILLISECOND, 0); } public static long convertMillisToCalendar(Calendar calendar, long millis) { calendar.clear(); synchronized (tempCalGMT) { tempCalGMT.setTimeInMillis(millis); calendar.set(tempCalGMT.get(Calendar.YEAR), tempCalGMT.get(Calendar.MONTH), tempCalGMT.get(Calendar.DAY_OF_MONTH), tempCalGMT.get(Calendar.HOUR_OF_DAY), tempCalGMT.get(Calendar.MINUTE), tempCalGMT.get(Calendar.SECOND)); return calendar.getTimeInMillis(); } } public static long convertMillisFromCalendar(Calendar calendar, long millis) { synchronized (tempCalGMT) { tempCalGMT.clear(); calendar.setTimeInMillis(millis); tempCalGMT.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); return tempCalGMT.getTimeInMillis(); } } /** * Sets the time in the given Calendar using the given milliseconds value; wrapper method to * allow use of more efficient JDK1.4 method on JDK1.4 (was protected in earlier versions). * * @param cal the Calendar * @param millis the time value in milliseconds */ public static void setTimeInMillis(Calendar cal, long millis) { //#ifdef JAVA4 // Use method directly cal.setTimeInMillis(millis); //#else /* // Have to go indirect synchronized (tempDate) { tempDate.setTime(millis); cal.setTime(tempDate); } */ //#endif JAVA4 } /** * Gets the time from the given Calendar as a milliseconds value; wrapper method to * allow use of more efficient JDK1.4 method on JDK1.4 (was protected in earlier versions). * * @param cal the Calendar * @return the time value in milliseconds */ public static long getTimeInMillis(Calendar cal) { //#ifdef JAVA4 // Use method directly return cal.getTimeInMillis(); //#else /* // Have to go indirect return cal.getTime().getTime(); */ //#endif JAVA4 } public static long convertToNormalisedTime(long t) { return convertToNormalisedTime(t, tempCalGMT); } public static long convertToNormalisedTime(long t, Calendar cal) { synchronized (cal) { setTimeInMillis(cal, t); resetToDate(cal); long t1 = getTimeInMillis(cal); return t - t1; } } public static long convertToNormalisedDate(long t, Calendar cal) { synchronized (cal) { setTimeInMillis(cal, t); resetToDate(cal); return getTimeInMillis(cal); } } public static long getNormalisedTime(long t) { Calendar cal = tempCalGMT; synchronized (cal) { setTimeInMillis(cal, t); resetToTime(cal); return getTimeInMillis(cal); } } public static long getNormalisedTime(Calendar cal, long t) { synchronized (cal) { setTimeInMillis(cal, t); resetToTime(cal); return getTimeInMillis(cal); } } public static long getNormalisedDate(long d) { synchronized (tempCalGMT) { setTimeInMillis(tempCalGMT, d); resetToDate(tempCalGMT); return getTimeInMillis(tempCalGMT); } } public static long getNormalisedDate(Calendar cal, long d) { synchronized (cal) { setTimeInMillis(cal, d); resetToDate(cal); return getTimeInMillis(cal); } } public static int getZoneSeconds(Calendar cal) { return (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000; } public static int getZoneMillis(Calendar cal, long millis) { //#ifdef JAVA4 // get zone for the specific date return cal.getTimeZone().getOffset(millis); //#else /* // get zone for the specific date setTimeInMillis(cal, millis); return (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) ); */ //#endif JAVA4 } /** * Returns the indicated part of the given millisecond date object. * @param m the millisecond time value from which to extract the indicated part * @param part an integer code corresponding to the desired date part * @return the indicated part of the given <code>java.util.Date</code> object */ public static int getDateTimePart(long m, int part) { synchronized (tempCalGMT) { tempCalGMT.setTimeInMillis(m); return tempCalGMT.get(part); } } /** * truncates millisecond date object */ public static long getTruncatedPart(long m, int part) { synchronized (tempCalGMT) { tempCalGMT.setTimeInMillis(m); switch (part) { case DTIType.WEEK_OF_YEAR : { int year = tempCalGMT.get(Calendar.YEAR); int week = tempCalGMT.get(Calendar.WEEK_OF_YEAR); tempCalGMT.clear(); tempCalGMT.set(Calendar.YEAR, year); tempCalGMT.set(Calendar.WEEK_OF_YEAR, week); break; } default : { zeroFromPart(tempCalGMT, part); break; } } return tempCalGMT.getTimeInMillis(); } } /** * rounded millisecond date object */ public static long getRoundedPart(long m, int part) { synchronized (tempCalGMT) { tempCalGMT.setTimeInMillis(m); switch (part) { case Types.SQL_INTERVAL_YEAR : if (tempCalGMT.get(Calendar.MONTH) > 6) { tempCalGMT.add(Calendar.YEAR, 1); } break; case Types.SQL_INTERVAL_MONTH : if (tempCalGMT.get(Calendar.DAY_OF_MONTH) > 15) { tempCalGMT.add(Calendar.MONTH, 1); } break; case Types.SQL_INTERVAL_DAY : if (tempCalGMT.get(Calendar.HOUR_OF_DAY) > 11) { tempCalGMT.add(Calendar.DAY_OF_MONTH, 1); } break; case Types.SQL_INTERVAL_HOUR : if (tempCalGMT.get(Calendar.MINUTE) > 29) { tempCalGMT.add(Calendar.HOUR_OF_DAY, 1); } break; case Types.SQL_INTERVAL_MINUTE : if (tempCalGMT.get(Calendar.SECOND) > 29) { tempCalGMT.add(Calendar.MINUTE, 1); } break; case Types.SQL_INTERVAL_SECOND : if (tempCalGMT.get(Calendar.MILLISECOND) > 499) { tempCalGMT.add(Calendar.SECOND, 1); } break; case DTIType.WEEK_OF_YEAR : { int year = tempCalGMT.get(Calendar.YEAR); int week = tempCalGMT.get(Calendar.WEEK_OF_YEAR); int day = tempCalGMT.get(Calendar.DAY_OF_WEEK); if (day > 3) { week++; } tempCalGMT.clear(); tempCalGMT.set(Calendar.YEAR, year); tempCalGMT.set(Calendar.WEEK_OF_YEAR, week); return tempCalGMT.getTimeInMillis(); } } zeroFromPart(tempCalGMT, part); return tempCalGMT.getTimeInMillis(); } } static void zeroFromPart(Calendar cal, int part) { switch (part) { case Types.SQL_INTERVAL_YEAR : cal.set(Calendar.MONTH, 0); case Types.SQL_INTERVAL_MONTH : cal.set(Calendar.DAY_OF_MONTH, 1); case Types.SQL_INTERVAL_DAY : cal.set(Calendar.HOUR_OF_DAY, 0); case Types.SQL_INTERVAL_HOUR : cal.set(Calendar.MINUTE, 0); case Types.SQL_INTERVAL_MINUTE : cal.set(Calendar.SECOND, 0); case Types.SQL_INTERVAL_SECOND : cal.set(Calendar.MILLISECOND, 0); } } //J- private static final char[][] dateTokens = { { 'R', 'R', 'R', 'R' }, { 'I', 'Y', 'Y', 'Y' }, { 'Y', 'Y', 'Y', 'Y' }, { 'I', 'Y' }, { 'Y', 'Y' }, { 'B', 'C' }, { 'B', '.', 'C', '.' }, { 'A', 'D' }, { 'A', '.', 'D', '.' }, { 'M', 'O', 'N' }, { 'M', 'O', 'N', 'T', 'H' }, { 'M', 'M' }, { 'D', 'A', 'Y' }, { 'D', 'Y' }, { 'W', 'W' }, { 'I', 'W' }, { 'D', 'D' }, { 'D', 'D', 'D' }, { 'W' }, { 'H', 'H', '2', '4' }, { 'H', 'H', '1', '2' }, { 'H', 'H' }, { 'M', 'I' }, { 'S', 'S' }, { 'A', 'M' }, { 'P', 'M' }, { 'A', '.', 'M', '.' }, { 'P', '.', 'M', '.' }, { 'F', 'F' } }; private static final String[] javaDateTokens = { "yyyy", "'*IYYY'", "yyyy", "'*IY'", "yy", "G", "G", "G", "G", "MMM", "MMMMM", "MM", "EEEE", "EE", "'*WW'", "w", "dd", "D", "'*W'", "HH", "KK", "KK", "mm", "ss", "aaa", "aaa", "aaa", "aaa", "S" }; private static final int[] sqlIntervalCodes = { -1, -1, Types.SQL_INTERVAL_YEAR, -1, Types.SQL_INTERVAL_YEAR, -1, -1, -1, -1, Types.SQL_INTERVAL_MONTH, Types.SQL_INTERVAL_MONTH, Types.SQL_INTERVAL_MONTH, -1, -1, DTIType.WEEK_OF_YEAR, -1, Types.SQL_INTERVAL_DAY, Types.SQL_INTERVAL_DAY, Types.SQL_INTERVAL_HOUR, -1, Types.SQL_INTERVAL_HOUR, Types.SQL_INTERVAL_MINUTE, Types.SQL_INTERVAL_SECOND, -1,-1,-1,-1, -1 }; //J+ /** Indicates end-of-input */ private static final char e = 0xffff; public static Date toDate(String string, String pattern, SimpleDateFormat format) { Date date; String javaPattern = HsqlDateTime.toJavaDatePattern(pattern); int matchIndex = javaPattern.indexOf("*IY"); if (matchIndex >= 0) { throw Error.error(ErrorCode.X_22511); } matchIndex = javaPattern.indexOf("*WW"); if (matchIndex >= 0) { throw Error.error(ErrorCode.X_22511); } matchIndex = javaPattern.indexOf("*W"); if (matchIndex >= 0) { throw Error.error(ErrorCode.X_22511); } try { format.applyPattern(javaPattern); date = format.parse(string); } catch (Exception e) { throw Error.error(ErrorCode.X_22007, e.toString()); } return date; } public static String toFormattedDate(Date date, String pattern, SimpleDateFormat format) { String javaPattern = HsqlDateTime.toJavaDatePattern(pattern); try { format.applyPattern(javaPattern); } catch (Exception e) { throw Error.error(ErrorCode.X_22511); } String result = format.format(date); int matchIndex = result.indexOf("*IY"); if (matchIndex >= 0) { Calendar cal = format.getCalendar(); int matchLength = 3; int temp = result.indexOf("*IYYY"); if (temp >= 0) { matchLength = 5; matchIndex = temp; } int year = cal.get(Calendar.YEAR); int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); if (weekOfYear == 1 && cal.get(Calendar.DAY_OF_YEAR) > 360) { year++; } String yearString = String.valueOf(year); if (matchLength == 3) { yearString = yearString.substring(yearString.length() - 2); } StringBuilder sb = new StringBuilder(result); sb.replace(matchIndex, matchIndex + matchLength, yearString); result = sb.toString(); } matchIndex = result.indexOf("*WW"); if (matchIndex >= 0) { Calendar cal = format.getCalendar(); int matchLength = 3; int dayOfYear = cal.get(Calendar.DAY_OF_YEAR); int weekOfYear = ((dayOfYear - 1) / 7) + 1; StringBuilder sb = new StringBuilder(result); sb.replace(matchIndex, matchIndex + matchLength, String.valueOf(weekOfYear)); result = sb.toString(); } matchIndex = result.indexOf("*W"); if (matchIndex >= 0) { Calendar cal = format.getCalendar(); int matchLength = 2; int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); int weekOfMonth = ((dayOfMonth - 1) / 7) + 1; StringBuilder sb = new StringBuilder(result); sb.replace(matchIndex, matchIndex + matchLength, String.valueOf(weekOfMonth)); result = sb.toString(); } return result; } /** * Converts the given format into a pattern accepted by <code>java.text.SimpleDataFormat</code> * * @param format */ public static String toJavaDatePattern(String format) { int len = format.length(); char ch; StringBuffer sb = new StringBuffer(len); Tokenizer tokenizer = new Tokenizer(); for (int i = 0; i <= len; i++) { ch = (i == len) ? e : format.charAt(i); if (tokenizer.isInQuotes()) { if (tokenizer.isQuoteChar(ch)) { ch = '\''; } else if (ch == '\'') { // double the single quote sb.append(ch); } sb.append(ch); continue; } if (!tokenizer.next(ch, i)) { if (tokenizer.consumed) { int index = tokenizer.getLastMatch(); sb.append(javaDateTokens[index]); i = tokenizer.matchOffset; } else { if (tokenizer.isQuoteChar(ch)) { ch = '\''; sb.append(ch); } else if (tokenizer.isLiteral(ch)) { sb.append(ch); } else if (ch == e) { // } else { throw Error.error(ErrorCode.X_22007, format.substring(i)); } } tokenizer.reset(); } } if (tokenizer.isInQuotes()) { throw Error.error(ErrorCode.X_22007); } String javaPattern = sb.toString(); return javaPattern; } public static int toStandardIntervalPart(String format) { int len = format.length(); char ch; Tokenizer tokenizer = new Tokenizer(); for (int i = 0; i <= len; i++) { ch = (i == len) ? e : format.charAt(i); if (!tokenizer.next(ch, i)) { int index = tokenizer.getLastMatch(); if (index >= 0) { return sqlIntervalCodes[index]; } return -1; } } return -1; } /** * This class can match 64 tokens at maximum. */ static class Tokenizer { private int lastMatched; private int matchOffset; private int offset; private long state; private boolean consumed; private boolean isInQuotes; private boolean matched; // private final char quoteChar; private final char[] literalChars; private static char[] defaultLiterals = new char[] { ' ', ',', '-', '.', '/', ':', ';' }; char[][] tokens; public Tokenizer() { this.quoteChar = '\"'; this.literalChars = defaultLiterals; tokens = dateTokens; reset(); } /** * Resets for next reuse. * */ public void reset() { lastMatched = -1; offset = -1; state = 0; consumed = false; matched = false; } /** * Returns the length of a token to match. */ public int length() { return offset; } /** * Returns an index of the last matched token. */ public int getLastMatch() { return lastMatched; } /** * Indicates whether the last character has been consumed by the matcher. */ public boolean isConsumed() { return consumed; } /** * Indicates whether the last character has been consumed by the matcher. */ public boolean wasMatched() { return matched; } /** * Indicates if tokenizing a quoted string */ public boolean isInQuotes() { return isInQuotes; } /** * returns true if character is the quote char and sets state */ public boolean isQuoteChar(char ch) { if (quoteChar == ch) { isInQuotes = !isInQuotes; return true; } return false; } /** * Returns true if ch is in the list of literals */ public boolean isLiteral(char ch) { return ArrayUtil.isInSortedArray(ch, literalChars); } /** * Checks whether the specified bit is not set. * * @param bit */ private boolean isZeroBit(int bit) { return (state & (1L << bit)) == 0; } /** * Sets the specified bit. * @param bit */ private void setBit(int bit) { state |= (1L << bit); } /** * Matches the specified character against tokens. * * @param ch * @param tokens */ public boolean next(char ch, int position) { int index = ++offset; int len = offset + 1; int left = 0; matched = false; for (int i = tokens.length; --i >= 0; ) { if (isZeroBit(i)) { if (tokens[i][index] == ch) { if (tokens[i].length == len) { setBit(i); lastMatched = i; consumed = true; matched = true; matchOffset = position; } else { ++left; } } else { setBit(i); } } } return left > 0; } } }
[ "ajuliano@princeton.edu" ]
ajuliano@princeton.edu
bf91354c5dfb73e1a88a6c2b31fe94415e7046e0
98d8b4a24a53aa1ef2d60c7330beda09fdb7bcec
/src/main/java/by/topolev/spring/beans/RenderMessage.java
2f35862a909881eddb1815571800839fea2784e1
[]
no_license
Topolev/ITechArtSpring
d6d6620cf7d7b6f599bfe606b559260c01f747eb
f100e81b17757a54937f9f848119ad2d87adaa98
refs/heads/master
2021-01-11T04:32:18.207238
2016-10-17T18:48:00
2016-10-17T18:48:00
71,170,109
0
0
null
null
null
null
UTF-8
Java
false
false
134
java
package by.topolev.spring.beans; /** * Created by Vladimir on 16.10.2016. */ public interface RenderMessage { void render(); }
[ "i.topolev.vladimir@gmail.com" ]
i.topolev.vladimir@gmail.com