blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
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
689M
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
131 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
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
4217c9bf35519a3b65317576ac05b367eb1cf2ab
38db548fdf7953b2d9e59320f6cd5ab39e21becd
/SecureSMS/app/src/main/java/pt/ulisboa/tecnico/meic/sirs/securesms/MessageExchange/MessageExchangeProtocol.java
3e6ffe6fcc0a3252baa296e8ad365791ced2f6d2
[]
no_license
diogopainho/sirs-ist
590d42dccf2d2a8820fe80b9940875dd5a49c4ea
48713a9967fab02aa4715f511049d00a817c3a2a
refs/heads/master
2021-01-24T23:34:01.839470
2015-12-03T18:22:02
2015-12-03T18:22:02
44,765,159
0
0
null
null
null
null
UTF-8
Java
false
false
5,693
java
package pt.ulisboa.tecnico.meic.sirs.securesms.MessageExchange; import android.util.Log; import com.activeandroid.query.Select; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidParameterSpecException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import pt.ulisboa.tecnico.meic.sirs.securesms.Crypto.AsymCrypto; import pt.ulisboa.tecnico.meic.sirs.securesms.Crypto.KeyHelper; import pt.ulisboa.tecnico.meic.sirs.securesms.Crypto.SymCrypto; import pt.ulisboa.tecnico.meic.sirs.securesms.Models.ContactModel; import pt.ulisboa.tecnico.meic.sirs.securesms.Models.UserModel; import pt.ulisboa.tecnico.meic.sirs.securesms.Sms.SmsEncoding; public class MessageExchangeProtocol { private static final String TAG = MessageExchangeProtocol.class.getSimpleName(); public static final int SESSION_KEY_DURATION = 5 * 24 * 60 * 60 * 1000; // 5 days private static final int INTEGRITY_LENGTH = 128; private static final int CIPHERED_KEY_LENGTH = 128; public static String send(String plainBody, ContactModel destination, BinaryTextEncoding encoding) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidAlgorithmParameterException, InvalidParameterSpecException { UserModel user = new Select().from(UserModel.class).executeSingle(); boolean includeSymmetricKey = false; byte[] plainBodyBytes = plainBody.getBytes(); if (!destination.hasValidSessionKey()) { destination.setSessionKey(KeyHelper.generateSymmetricKey()); destination.save(); includeSymmetricKey = true; } SecretKey sessionKey = destination.getSessionKey(); ByteArrayOutputStream messageComposition = new ByteArrayOutputStream(); if (includeSymmetricKey) { messageComposition.write('k'); byte[] cipheredKey = AsymCrypto.encrypt(sessionKey.getEncoded(), destination.getPublicKey()); Log.d(TAG, "cipheredKey: " + encoding.encode(cipheredKey)); messageComposition.write(cipheredKey); } else { messageComposition.write('0'); } byte[] cipheredBody = SymCrypto.encrypt(plainBodyBytes, sessionKey); Log.d(TAG, "cipheredBody: " + encoding.encode(cipheredBody)); messageComposition.write(cipheredBody); byte[] intermediateMessage = messageComposition.toByteArray(); byte[] integrityPart = AsymCrypto.sign(intermediateMessage, user.getPrivateKey()); Log.d(TAG, "intermediateMessage: " + encoding.encode(intermediateMessage)); Log.d(TAG, "integrityPart: " + encoding.encode(integrityPart)); ByteArrayOutputStream finalMessageComposition = new ByteArrayOutputStream(); finalMessageComposition.write(integrityPart); finalMessageComposition.write(intermediateMessage); String finalMessage = encoding.encode(finalMessageComposition.toByteArray()); Log.d(TAG, "send - finalMessage: " + finalMessage); return finalMessage; } public static String receive(String finalMessageText, ContactModel sender, BinaryTextEncoding encoding) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidAlgorithmParameterException, InvalidParameterSpecException, FailedVerificationException, InvalidSessionKeyException { UserModel user = new Select().from(UserModel.class).executeSingle(); Log.d(TAG, "receive - finalMessageText: " + finalMessageText); byte[] finalMessageBytes = encoding.decode(finalMessageText); byte[] integrityPart = Arrays.copyOfRange(finalMessageBytes, 0, INTEGRITY_LENGTH); byte[] intermediateMessage = Arrays.copyOfRange(finalMessageBytes, INTEGRITY_LENGTH, finalMessageBytes.length); Log.d(TAG, "integrityPart: " + encoding.encode(integrityPart)); Log.d(TAG, "intermediateMessage: " + encoding.encode(intermediateMessage)); if (!AsymCrypto.verify(intermediateMessage, integrityPart, sender.getPublicKey())) throw new FailedVerificationException(); byte[] cipheredBody; if (intermediateMessage[0] == 'k') { byte[] cipheredKeyBytes = Arrays.copyOfRange(intermediateMessage, 1, CIPHERED_KEY_LENGTH + 1); cipheredBody = Arrays.copyOfRange(intermediateMessage, CIPHERED_KEY_LENGTH + 1, intermediateMessage.length); Log.d(TAG, "cipheredKeyBytes: " + encoding.encode(cipheredKeyBytes)); byte[] sessionKeyBytes = AsymCrypto.decrypt(cipheredKeyBytes, user.getPrivateKey()); sender.setSessionKey(KeyHelper.bytesToSecretKey(sessionKeyBytes)); sender.save(); } else { cipheredBody = Arrays.copyOfRange(intermediateMessage, 1, intermediateMessage.length); } Log.d(TAG, "cipheredBody: " + encoding.encode(cipheredBody)); if (!sender.hasValidSessionKey()) { throw new InvalidSessionKeyException(); } SecretKey sessionKey = sender.getSessionKey(); byte[] plainBodyBytes = SymCrypto.decrypt(cipheredBody, sessionKey); return new String(plainBodyBytes); } }
[ "ruimams@gmail.com" ]
ruimams@gmail.com
1c2f7a7ca8fdba9b164880dc8e0c4c13a49cf00a
8bcd464d0eab4fed3a5b13fa64cc46e75e9060dd
/Maze/GridColors.java
fe95efd22f8eb254fd63adba50d7d764939b1ef7
[]
no_license
ahilan-subbaian/Data-Structures
0f11ea43900f8ea4aea2cdcf2151f1bf532c863d
fb6e98a34bc49e87c47f54dfb80989c0f75f3219
refs/heads/main
2023-01-28T21:23:33.909202
2020-12-04T00:46:26
2020-12-04T00:46:26
318,358,658
0
0
null
null
null
null
UTF-8
Java
false
false
345
java
package hw4; import java.awt.Color; /** * An interface for colors *@author Koffman and Wolfgang */ public interface GridColors { Color PATH = Color.green; Color BACKGROUND = Color.white; Color NON_BACKGROUND = Color.red; Color ABNORMAL = NON_BACKGROUND; Color TEMPORARY = Color.black; } /*</exercise>*/
[ "owner@Ahilans-MacBook-Air.local" ]
owner@Ahilans-MacBook-Air.local
d6aecb98895f9ee478e95c392cdc08f91582fc82
25a3bb5976698fb1971bdb9ad39a05aa4401a71d
/app/src/main/java/com/makgyber/vbuys/activities/MapsActivity.java
c5529ab0653ed3198df57224d6f49b1a60d4ec71
[]
no_license
makgyber/vbuy
408d706a47b94d941beaad4a7a9984e272a92290
663d49eecd6f1a8f1c0c9a377eb9b13e2f295463
refs/heads/master
2022-12-04T20:58:22.662249
2020-08-22T18:01:53
2020-08-22T18:01:53
275,303,818
0
0
null
null
null
null
UTF-8
Java
false
false
9,862
java
package com.makgyber.vbuys.activities; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.Status; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.AutocompletePrediction; import com.google.android.libraries.places.api.model.AutocompleteSessionToken; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.model.RectangularBounds; import com.google.android.libraries.places.api.model.TypeFilter; import com.google.android.libraries.places.api.net.FetchPlaceRequest; import com.google.android.libraries.places.api.net.FetchPlaceResponse; import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest; 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.makgyber.vbuys.R; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private static final String TAG = MapsActivity.class.getSimpleName(); private static final int DEFAULT_ZOOM = 15; private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; private boolean mLocationPermissionGranted; private GoogleMap mMap; PlacesClient placesClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); if (!Places.isInitialized()) { String apiKey = getString(R.string.google_api_key); Places.initialize(MapsActivity.this, apiKey); }; placesClient = Places.createClient(MapsActivity.this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng manila = new LatLng(14.6, 120.99); mMap.addMarker(new MarkerOptions().position(manila).title("Marker in Manila")); mMap.moveCamera(CameraUpdateFactory.newLatLng(manila)); mMap.setMinZoomPreference(8.0f); mMap.setMaxZoomPreference(20.0f); mMap.getUiSettings().setMapToolbarEnabled(true); mMap.setMyLocationEnabled(true); mMap.getUiSettings().setCompassEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); // Initialize the AutocompleteSupportFragment. AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment); autocompleteFragment.setCountry("PH"); // Specify the types of place data to return. autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)); // Set up a PlaceSelectionListener to handle the response. autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(@NotNull Place place) { // TODO: Get info about the selected place. Log.i(TAG, "Place: " + place.getName() + ", " + place.getId() + ", " + place.getLatLng()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), DEFAULT_ZOOM)); mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName())); } @Override public void onError(@NotNull Status status) { // TODO: Handle the error. Log.i(TAG, "An error occurred: " + status); } }); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { Toast.makeText(MapsActivity.this, "LatLong: " + latLng.toString(), Toast.LENGTH_SHORT).show(); } }); getLocationPermission(); updateLocationUI(); testPlaces(); } private void testPlaces() { AutocompleteSessionToken token = AutocompleteSessionToken.newInstance(); // Create a RectangularBounds object. // Use the builder to create a FindAutocompletePredictionsRequest. FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder() // Call either setLocationBias() OR setLocationRestriction(). .setCountry("ph") .setTypeFilter(TypeFilter.ADDRESS) .setSessionToken(token) .setQuery("makati") .build(); placesClient.findAutocompletePredictions(request).addOnSuccessListener(response -> { StringBuilder mResult = new StringBuilder(); for (AutocompletePrediction prediction : response.getAutocompletePredictions()) { mResult.append(" ").append(prediction.getFullText(null) + "\n"); Log.i(TAG, prediction.getPlaceId()); Log.i(TAG, prediction.getPrimaryText(null).toString()); Toast.makeText(MapsActivity.this, prediction.getPrimaryText(null) + "-" + prediction.getSecondaryText(null), Toast.LENGTH_SHORT).show(); } }).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; Log.e(TAG, "Place not found: " + apiException.getStatusCode()); } }); } /** * Prompts the user for permission to use the device location. */ private void getLocationPermission() { /* * Request location permission, so that we can get the location of the * device. The result of the permission request is handled by a callback, * onRequestPermissionsResult. */ if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "IAM HERE"); mLocationPermissionGranted = true; } else { Log.d(TAG, "IAM AT ELSE"); ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } } /** * Handles the result of the request for location permissions. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { mLocationPermissionGranted = false; switch (requestCode) { case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; updateLocationUI(); } } } } /** * Updates the map's UI settings based on whether the user has granted location permission. */ private void updateLocationUI() { if (mMap == null) { return; } try { if (mLocationPermissionGranted) { Log.d(TAG, "Permission Granted!"); mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); mMap.getUiSettings().setMapToolbarEnabled(true); } else { Log.d(TAG, "Permission Not Granted"); mMap.setMyLocationEnabled(false); mMap.getUiSettings().setMyLocationButtonEnabled(false); getLocationPermission(); } } catch (SecurityException e) { Log.e("Exception: %s", e.getMessage()); } } }
[ "makgyber@gmail.com" ]
makgyber@gmail.com
b917326dbabdb0b37b9468ac6efcc6ed499989c5
920445dc6c1957774a1a4d620b9fce0ecfaa92d1
/src/test/java/com/shisen/idioms/leetcode/NumberOfLine.java
7628374731b526d2522b16b2b165f6e24c1ceda3
[]
no_license
hub-sen/idioms
96a2237a88aaadb6d7fd7c02cb63f89bbe9c1e72
17142e2a39ead887eee334efce88864d5491895b
refs/heads/master
2023-08-08T14:25:51.257361
2020-12-11T09:35:47
2020-12-11T09:35:47
221,416,654
0
0
null
null
null
null
UTF-8
Java
false
false
803
java
package com.shisen.idioms.leetcode; import org.junit.Test; import java.util.Arrays; /** * <pre> * Description * @author shishi * 2019/12/27 14:20 * </pre> */ public class NumberOfLine { private int[] widths = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; private String S = "abcdefghijklmnopqrstuvwxyz"; @Test public void test_1() { int[] ints = numberOfLines(widths, S); System.out.println("Arrays.toString(ints) = " + Arrays.toString(ints)); } public int[] numberOfLines(int[] widths, String S) { int sum = 100; int line = 1; int temp; for (char c: S.toCharArray()){ temp = widths[c - 'a']; if (sum < temp) { line++; sum = 100; } sum -= temp; } return new int[]{line, 100 - sum}; } }
[ "1107474494@qq.com" ]
1107474494@qq.com
2828ef79eccdaf1b74f059ed9930bb26387c497e
e3c8599326106dce3c15f7dfb81e4019fa74b600
/src/main/java/cn/com/dom4j/web/controller/JQueryController.java
cf47d37fdb3d6dd8f0554308eae4827bf4853d31
[]
no_license
tanzhiyihuijian/kcsj_12_17
996257c6698d6cd817cb2070390407b96d95f595
40ef61323bece87b394bf72a868e2993d66c5973
refs/heads/master
2021-05-14T00:20:00.375983
2018-02-07T03:50:02
2018-02-07T03:50:02
116,536,018
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
package cn.com.dom4j.web.controller; import org.apache.http.protocol.HttpService; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; /** * @author bobo (bo.wang@laowantong.cc) * @date 2018年01月07日 * @desc jquery */ @Controller @RequestMapping("/jquery") public class JQueryController extends BaseController { @RequestMapping("/index") public ModelAndView index(HttpServletRequest request, ModelMap modelMap) { putServerPath(request, modelMap); return new ModelAndView("/jquery/index", modelMap); } }
[ "w15635606382@gmail.com" ]
w15635606382@gmail.com
008145650a1dc5e89dd01569252df4fd544ef01c
7e99a300f1166b0a7fdffeba38ff9e9e82a204ce
/src/main/java/org/codehaus/plexus/maven/plugin/report/Configuration.java
e34f666dffb7b43914e3110e406f8b8e9d58f2e7
[]
no_license
codehaus-plexus/plexus-maven-plugin
f4b2b4206eaa21ee8630f6fc4bfa638775d1e8c2
420793f437711fadb1c70a74caddc689b54e3f36
refs/heads/master
2023-04-29T00:27:06.411738
2018-07-21T21:23:21
2018-07-21T21:23:21
141,845,727
0
0
null
null
null
null
UTF-8
Java
false
false
1,708
java
/* * The MIT License * * Copyright (c) 2006, The Codehaus * * 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.codehaus.plexus.maven.plugin.report; import org.codehaus.doxia.sink.Sink; import org.jdom.Element; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> * @version $Id$ */ public class Configuration { public Configuration( Element element ) { } public void print( Sink sink ) { sink.section4(); sink.sectionTitle4(); sink.text( "Configuration" ); sink.lineBreak(); sink.sectionTitle4_(); sink.section4_(); sink.paragraph(); sink.paragraph_(); } }
[ "hboutemy@apache.org" ]
hboutemy@apache.org
8080616135124f8615ec07e0b6727dda415eaf3f
a8b1ff8fd188b3b04b626c96991a14fd6af255fc
/app/src/main/java/com/example/souma/vedamagic/Question4.java
e31794bd7714ac4d4fc654c9c5bf162a88fa5c71
[]
no_license
SoumakChakraborty/Veda-Magic
7a485fddb68a819196292ae013c16d470e22db57
feb8a89d81beb773657162152c3eca146d64fe51
refs/heads/master
2020-12-30T13:46:47.216968
2017-06-03T13:11:34
2017-06-03T13:11:34
91,256,646
0
2
null
null
null
null
UTF-8
Java
false
false
2,499
java
package com.example.souma.vedamagic; import android.content.DialogInterface; import android.content.Intent; import android.support.annotation.IdRes; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class Question4 extends AppCompatActivity { boolean get; int c; Button b; AlertDialog.Builder al; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question4); } public void check_answer(View view) { get=((RadioButton)view).isChecked(); b=(Button)findViewById(R.id.submit1); switch (view.getId()) { case R.id.q8: if(get) { c=1; } break; case R.id.q9: if(get) { c=2; } break; case R.id.q10: if(get) { c=3; } break; case R.id.q11: if(get) { c=4; } break; } al=new AlertDialog.Builder(this); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(c==4) { al.setMessage("Correct"); al.setTitle("Result"); al.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); al.show(); } else { al.setMessage("Incorrect"); al.setTitle("Result"); al.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); al.show(); } } }); } }
[ "chakrabortysoumak11@gmail.com" ]
chakrabortysoumak11@gmail.com
bc6d52eaa823b39b49aa128e94abe95044ddb0c1
9058ff4f698ced884f6b61e87b76471921823001
/src/main/java/com/renato/delivery/dto/OrderDTO.java
5ac13af6414b41431cc2a40988465c11b70376fc
[]
no_license
Jrenatomt/delivery
fd6227b0cf24baf046f335bc375882b8073591d3
05ee01a8c12e9f875ec952653c7f93ff6400001e
refs/heads/main
2023-06-28T08:03:07.470565
2021-07-16T22:37:10
2021-07-16T22:37:10
384,463,761
0
0
null
null
null
null
UTF-8
Java
false
false
1,843
java
package com.renato.delivery.dto; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.renato.delivery.entities.Order; import com.renato.delivery.enumerations.OrderStatus; public class OrderDTO { private Long id; private String address; private Double latitude; private Double longitude; private Instant moment; private OrderStatus status; private List<ProductDTO> products = new ArrayList<>(); public OrderDTO() { } public OrderDTO(Long id, String address, Double latitude, Double longitude, Instant moment, OrderStatus status) { this.id = id; this.address = address; this.latitude = latitude; this.longitude = longitude; this.moment = moment; this.status = status; } public OrderDTO(Order entity) { id = entity.getId(); address = entity.getAddress(); latitude = entity.getLatitude(); longitude = entity.getLongitude(); moment = entity.getMoment(); status = entity.getStatus(); products = entity.getProducts().stream().map(ProductDTO::new).collect(Collectors.toList()); } public Long getId() { return id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Instant getMoment() { return moment; } public void setMoment(Instant moment) { this.moment = moment; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public List<ProductDTO> getProducts() { return products; } }
[ "jrenatomt@gmail.com" ]
jrenatomt@gmail.com
cd1682fb07174514eebef4300139d9ddea93413c
1fa3faf7dfefab0f5f9489ad8a64d4aeec910722
/DesignPatterns10 - DAO Factory/src/com/caveofprogramming/designpatterns/demo1/model/Log.java
ec41498b17d421b4515a6d36602162f2855ccddd
[]
no_license
neurogirl47/Design-Patterns
6332ab17214a876cfcb25dbbd129a35ccfc4dda5
84cddffa2fa596af494428aa71ae13eb5c848335
refs/heads/master
2020-12-20T18:17:03.215483
2016-07-08T23:43:31
2016-07-08T23:43:31
62,925,572
0
1
null
null
null
null
UTF-8
Java
false
false
81
java
package com.caveofprogramming.designpatterns.demo1.model; public class Log { }
[ "udochio@hotmail.com" ]
udochio@hotmail.com
1b4d994a191863827d2c7063f6cf5fb1e02f1498
9f9328d657c93cda1b375672420d702fff5a55e1
/src/main/java/co/tdude/soen341/projectb/Lexer/Tokens/Token.java
92d435a278c9254c95c30e7fabd301215f7da917
[ "BSD-3-Clause" ]
permissive
karimrhoualem/JavaCrossAssembler
da3c81bf10444fe5c699225b923f6604b6355004
aad3f6cb5a727958fada5d493465a2037b9944cf
refs/heads/main
2023-01-30T22:57:48.096029
2020-12-15T20:29:11
2020-12-15T20:29:11
321,779,078
0
0
null
null
null
null
UTF-8
Java
false
false
854
java
package co.tdude.soen341.projectb.Lexer.Tokens; /** * Stores token values, which are LineStatements items that are parsed within an assembly file. */ abstract public class Token { /** * The string representation of the token that was parsed. */ private String value; /** * The type of the token, chosen from a list of available enum types. */ protected TokenType type; /** * Constructor used to create a Token object. * @param lexeme */ public Token(String lexeme) { value = lexeme; } /** * Gets the string value of the token. * @return Value of the token. */ public String getValue() { return value; } /** * Gets the token type. * @return Enum token type. */ public TokenType getType() { return type; } }
[ "karim.rhoualem@gmail.com" ]
karim.rhoualem@gmail.com
ee6c84b35cfa9abf549f72a4d5f9252ca3970304
f2e744082c66f270d606bfc19d25ecb2510e337c
/sources/com/google/common/base/Objects.java
f3e3c66fd0c46b5379264a5d63bd385871f8250a
[]
no_license
AshutoshSundresh/OnePlusSettings-Java
365c49e178612048451d78ec11474065d44280fa
8015f4badc24494c3931ea99fb834bc2b264919f
refs/heads/master
2023-01-22T12:57:16.272894
2020-11-21T16:30:18
2020-11-21T16:30:18
314,854,903
4
2
null
null
null
null
UTF-8
Java
false
false
352
java
package com.google.common.base; import java.util.Arrays; public final class Objects extends ExtraObjectsMethodsForWeb { public static boolean equal(Object obj, Object obj2) { return obj == obj2 || (obj != null && obj.equals(obj2)); } public static int hashCode(Object... objArr) { return Arrays.hashCode(objArr); } }
[ "ashutoshsundresh@gmail.com" ]
ashutoshsundresh@gmail.com
05042371c537bd00d96dbec4c340144b18f56436
536b937e059bfc73f8243ca531dbef323f71e29c
/src/main/java/org/globsframework/metamodel/annotations/DefaultDoubleAnnotationType.java
1e5de18450f2802b67e7a45265005cab544f64ec
[ "Apache-2.0" ]
permissive
mathieu-chauvet/globsframework
ba6ff9a9986aef2dcdca39e15172fdb0662b4116
fea08ae887e523e3c5fd80a3942921b4541ae868
refs/heads/master
2023-07-12T08:01:26.446605
2021-08-24T13:10:56
2021-08-24T13:10:56
383,212,633
0
0
Apache-2.0
2021-08-23T09:20:57
2021-07-05T17:08:45
Java
UTF-8
Java
false
false
924
java
package org.globsframework.metamodel.annotations; import org.globsframework.metamodel.GlobType; import org.globsframework.metamodel.GlobTypeLoader; import org.globsframework.metamodel.GlobTypeLoaderFactory; import org.globsframework.metamodel.fields.DoubleField; import org.globsframework.model.Glob; import org.globsframework.model.Key; public class DefaultDoubleAnnotationType { public static GlobType DESC; @DefaultFieldValue public static DoubleField DEFAULT_VALUE; @InitUniqueKey public static Key UNIQUE_KEY; public static Glob create(double defaultDouble) { return DESC.instantiate().set(DEFAULT_VALUE, defaultDouble); } static { GlobTypeLoader loader = GlobTypeLoaderFactory.create(DefaultDoubleAnnotationType.class); loader.register(GlobCreateFromAnnotation.class, annotation -> create(((DefaultDouble)annotation).value())) .load(); } }
[ "marc.dudoignon@gmail.com" ]
marc.dudoignon@gmail.com
e99898e27cf4891111d1180bc1e0c699406911b6
914691900e6c037fd67e77c4c1f5af62a1273f62
/src/com/qts/BookEntry.java
85f064a90098f48307b3555999ae40cd40a7595c
[]
no_license
anupnroygithub/BookDataLoadFromExcel
578ccfc1de571a3a4f257d2fe71a2645bc9cf21f
d30864027877c6a220af9a3c90b57549e1fd8139
refs/heads/master
2020-03-21T17:27:24.573700
2018-06-27T05:25:48
2018-06-27T05:25:48
138,832,944
0
0
null
null
null
null
UTF-8
Java
false
false
16,502
java
package com.qts; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.google.zxing.EncodeHintType; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.model.Book; public class BookEntry { private static final String FILE_NAME = "D:\\Work\\SSR\\Data Received From SSR During Visit\\Our edited excels for data loading\\Library Accession_Register_modified.xlsx"; Connection con = null; Statement stmt = null; List<Book> bookList = null; HashSet<String>publisher = new HashSet<>(); HashSet<String>bookAuthor = new HashSet<>(); HashSet<String>title = new HashSet<>(); public static void main(String args[]){ BookEntry entry = new BookEntry(); entry.insertookInDB(entry.readExcel()); } public void insertookInDB(List<Book> bookList){ } public List<Book> readExcel(){ bookList = new ArrayList<Book>(); try{ FileInputStream excelFile = new FileInputStream(new File(FILE_NAME)); Workbook workbook = new XSSFWorkbook(excelFile); Sheet datatypeSheet = workbook.getSheetAt(0); int startRow = datatypeSheet.getFirstRowNum() + 1; int lastRow = datatypeSheet.getLastRowNum(); for(int count = startRow; count <= lastRow; count ++ ) { Book book = new Book(); Row currentRow = datatypeSheet.getRow(count); book.setAccessionNo(new Double(currentRow.getCell(0).getNumericCellValue()).intValue()); //System.out.println(book.getAccessionNo()); book.setAccessionDate(currentRow.getCell(1).getDateCellValue().toString()); //System.out.println(book.getAccessionDate()); book.setAuthor(currentRow.getCell(2).getStringCellValue()); if(null != currentRow.getCell(6).getStringCellValue() || currentRow.getCell(6).getStringCellValue() != ""){ bookAuthor.add(currentRow.getCell(2).getStringCellValue()); } //System.out.println(book.getAuthor()); book.setTitle(currentRow.getCell(3).getStringCellValue()); if(null != currentRow.getCell(3).getStringCellValue() || currentRow.getCell(3).getStringCellValue() != ""){ title.add(currentRow.getCell(3).getStringCellValue()); } //System.out.println(book.getTitle()); book.setPubYear(String.valueOf(currentRow.getCell(4).getNumericCellValue())); //System.out.println(book.getPubYear()); book.setPubPlace(currentRow.getCell(5).getStringCellValue()); //System.out.println(book.getPubPlace()); book.setPublisher(currentRow.getCell(6).getStringCellValue()); if(null != currentRow.getCell(6).getStringCellValue() || currentRow.getCell(6).getStringCellValue() != ""){ publisher.add(currentRow.getCell(6).getStringCellValue()); } //System.out.println(book.getPublisher()); //System.out.println(count); bookList.add(book) ; } // System.out.println("publisher : "+publisher); List<String>publisherList = new ArrayList<>();//for publisher publisherList.addAll(publisher); insertBookPublisher(publisherList); List<String>authorList = new ArrayList<>(); authorList.addAll(bookAuthor); insertAuthor(authorList); //for author insertIntoLibraryCatalogue(bookList); //for libraryCatalogue insertIntoBook(bookList); //for book insertIntoBookAuthor(bookList); //for book author /*for(Book b : bookList){ System.out.println(b.getAccessionNo() + " : " + b.getAccessionDate() + " : " + b.getAuthor() + " : " + b.getTitle() + " : " + b.getPubYear() + " : " + b.getPubPlace() + " : " + b.getPublisher()); }*/ }catch(IOException ex){ ex.printStackTrace(); } return bookList; } public Connection jdbcConnection(){ try { Class.forName("org.postgresql.Driver"); con = DriverManager .getConnection("jdbc:postgresql://localhost:5432/iCAM_SSRewa", "postgres", "postgres"); } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Opened database successfully"); return con; } public void insertBookPublisher(List<String> publisherList){ con = jdbcConnection(); if(null !=con){ try { stmt = con.createStatement(); for(String publisher : publisherList){ String sql = "INSERT INTO book_publisher(rec_id, obj_id, updated_by, updated_on, date_of_creation, book_publisher_code, book_publisher_name, book_publisher_desc)" +"VALUES (uuid_generate_v4(), 'BOOK_PUBLISHER_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()), (select 'PUB'|| '_' ||COALESCE((SELECT MAX(serial_id) FROM book_publisher), 0)+1), '"+publisher+"', '"+publisher+"');"; stmt.addBatch(sql); } stmt.executeBatch(); System.out.println("book publisher inserted"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("failed to insert book publisher"); }finally{ try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void insertAuthor(List<String> authorList){ con = jdbcConnection(); if(null !=con){ try { stmt = con.createStatement(); for(String author : authorList){ String sql = "INSERT INTO author(rec_id, obj_id, updated_by, updated_on, date_of_creation, author_full_name)" +"VALUES (uuid_generate_v4(), 'AUTHOR_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()), '"+author+"');"; //stmt.executeUpdate(sql); stmt.addBatch(sql); } stmt.executeBatch(); System.out.println("author inserted successfully"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("failed to insert author"); }finally{ try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void insertIntoLibraryCatalogue(List<Book> bookList){ con = jdbcConnection(); String title = ""; String publisher = ""; String place = ""; String year = ""; if(null !=con){ try { stmt = con.createStatement(); title = bookList.get(0).getTitle(); publisher = bookList.get(0).getPublisher(); place = bookList.get(0).getPubPlace(); year = bookList.get(0).getPubYear().replace(".0", ""); String sql = "INSERT INTO library_catalogue(rec_id, obj_id, updated_by, updated_on, date_of_creation, item_code, item_name, book_publisher, place, publish_year, type, item_status)" +"VALUES (uuid_generate_v4(), 'LIBRARY_CATALOGUE_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()),(select 'LC'|| '_' ||COALESCE((SELECT MAX(serial_id) FROM library_catalogue), 0)+1),'"+title+"',(SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true),'"+place+"','"+year+"'," + "(SELECT rec_id FROM book_category WHERE book_category_code = 'BOOK_CATEGORY_1' AND is_active = true), (SELECT rec_id FROM status_of_item WHERE status_of_item_code = 'STATUSOFITEM-1' AND is_active = true));"; stmt.executeUpdate(sql); for(Book book : bookList){ title = book.getTitle(); publisher = book.getPublisher(); place = book.getPubPlace(); year = book.getPubYear().replace(".0", ""); String sql1 = "SELECT item_name FROM library_catalogue WHERE item_name = '"+title+"' AND place = '"+place+"' AND publish_year = '"+year+"' AND book_publisher = (SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true);"; ResultSet rs = stmt.executeQuery(sql1); //System.out.println("rs=="+rs); if(rs.next()){ rs.close(); }else { //itemName = rs.getString("item_name"); //System.out.println(itemName); //if(itemName == ""){ //System.out.println("within insert"); String sql2 = "INSERT INTO library_catalogue(rec_id, obj_id, updated_by, updated_on, date_of_creation, item_code, item_name, book_publisher, place, publish_year, type, item_status)" +"VALUES (uuid_generate_v4(), 'LIBRARY_CATALOGUE_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()),(select 'LC'|| '_' ||COALESCE((SELECT MAX(serial_id) FROM library_catalogue), 0)+1),'"+title+"',(SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true),'"+place+"','"+year+"'," + "(SELECT rec_id FROM book_category WHERE book_category_code = 'BOOK_CATEGORY_1' AND is_active = true), (SELECT rec_id FROM status_of_item WHERE status_of_item_code = 'STATUSOFITEM-1' AND is_active = true));"; stmt.executeUpdate(sql2); //} } //rs.close(); } System.out.println("Library catalogue inserted successfully"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("failed to insert library catalogue"); }finally{ try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void insertIntoBook(List<Book> bookList){ con = jdbcConnection(); String title = ""; String publisher = ""; String place = ""; String year = ""; String accNo = ""; String accDate = ""; if(null !=con){ try { stmt = con.createStatement(); for(Book book : bookList){ title = book.getTitle(); publisher = book.getPublisher(); place = book.getPubPlace(); year = book.getPubYear().replace(".0", ""); accNo = book.getAccessionNo()+""; accDate = book.getAccessionDate(); DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy"); Date date = null; try { date = (Date)formatter.parse(accDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(date); String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR); //System.out.println("formatedDate : " + formatedDate); String sql = "INSERT INTO book (rec_id, obj_id, updated_by, updated_on, date_of_creation, book_code, date_of_entry, accession_number,library_catalogue, item_status, total_no_of_copies_available)" +"VALUES(uuid_generate_v4(), 'BOOK_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()),(select 'BOOK'|| '_' ||COALESCE((SELECT MAX(serial_id) FROM book), 0)+1), (SELECT extract(epoch from (SELECT to_timestamp('"+formatedDate+"','DD/MM/YYYY')))) ,'"+accNo+"',(SELECT rec_id FROM library_catalogue WHERE item_name = '"+title+"' AND place = '"+place+"' AND publish_year = '"+year+"' AND book_publisher = (SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true)),(SELECT rec_id FROM status_of_item WHERE status_of_item_code = 'STATUSOFITEM-2' AND is_active = true), 1);"; stmt.executeUpdate(sql); String qrCodeData = accNo; String path = "D:\\Work\\SSR\\iCAM_SSRewa_Repository\\QRCode\\Book\\" + accNo+".png"; File dir = new File(path); boolean isDirCreated = dir.mkdirs(); if (isDirCreated) { System.out.println("created path "+path); }else System.out.println(path+ " already exist"); generateQrCodeForBook(qrCodeData, path, dir); } System.out.println("inserted succesfully in book table"); }catch(SQLException e){ e.printStackTrace(); }finally{ try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void insertIntoBookAuthor(List<Book> bookList){ con = jdbcConnection(); String title = ""; String publisher = ""; String place = ""; String year = ""; String author = ""; if(null !=con){ try { stmt = con.createStatement(); for(Book book : bookList){ title = book.getTitle(); publisher = book.getPublisher(); place = book.getPubPlace(); year = book.getPubYear().replace(".0", ""); author = book.getAuthor(); String sql1 = "SELECT rec_id FROM book_author WHERE author = (SELECT rec_id FROM author WHERE author_full_name = '"+author+"' AND is_active = true) AND catalogue_item = (SELECT rec_id FROM library_catalogue WHERE item_name = '"+title+"' AND place = '"+place+"' AND publish_year = '"+year+"' AND book_publisher = (SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true));"; ResultSet rs = stmt.executeQuery(sql1); //System.out.println("rs=="+rs); if(rs.next()){ rs.close(); }else { String sql = "INSERT INTO book_author (rec_id, obj_id, updated_by, updated_on, date_of_creation, author, catalogue_item)" +"VALUES(uuid_generate_v4(), 'BOOK_AUTHOR_OLD_DATA_OBJ_ID', (SELECT rec_id FROM resource WHERE user_id ilike 'superadmin' AND is_active =true), extract(epoch FROM now()), extract(epoch FROM now()),(SELECT rec_id FROM author WHERE author_full_name = '"+author+"' AND is_active = true),(SELECT rec_id FROM library_catalogue WHERE item_name = '"+title+"' AND place = '"+place+"' AND publish_year = '"+year+"' AND book_publisher = (SELECT rec_id FROM book_publisher WHERE book_publisher_name = '"+publisher+"' AND is_active = true)) );"; //System.out.println(sql); stmt.executeUpdate(sql); } } System.out.println("inserted succesfully in book_author table"); }catch(SQLException e){ System.out.println("failed to insert"); e.printStackTrace(); }finally{ try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void generateQrCodeForBook(String qrCodeData, String path, File dir){ try{ String charset = "UTF-8"; // or "ISO-8859-1" Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeUtility qrUtil = new QRCodeUtility(); qrUtil.createQRCode(qrCodeData, path, charset, dir, hintMap, 200, 200); }catch(Exception e){ e.printStackTrace(); } } }
[ "anupnarayanroy@outlook.com" ]
anupnarayanroy@outlook.com
f03fcc8ca54681d1bad8efd690ddf5194836805c
12c79dce2d6231930988b2a17a95d3f39fc2836a
/1-Spring/spring-09-aop/src/main/java/com/service/UserServiceImp.java
f819db8c1bc72bf6d324cc9872eb99570953c687
[]
no_license
Gaxvin/Java-Study
e514793d1f6bd2b97bb8f1eb70abd9ef11631448
9d9649f16fc6d62dd791e1db9ba2efbfc1cfc7f9
refs/heads/master
2023-09-06T06:40:08.905425
2021-11-05T02:35:09
2021-11-05T02:35:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
358
java
package com.service; public class UserServiceImp implements UserService { public void add() { System.out.println("add"); } public void delete() { System.out.println("delete"); } public void query() { System.out.println("query"); } public void update() { System.out.println("update"); } }
[ "tanzhihan3@gmail.com" ]
tanzhihan3@gmail.com
ff4be6bd587137ad5aa996634f77744ed29321ce
2ee8015e6a95b9f82dd2eccf544b9ab269ad8eea
/namessquare.java
847d42de3860a3d31934a9fc0683d06c26c73145
[]
no_license
wsun0736/Grade-11-Cs
d0650ecd19a09acd6ade9bad36c2a59efb090bd1
3d5b0f92c2e2723117f42d5161216ee3ce6a9b66
refs/heads/master
2022-12-22T03:13:20.052642
2020-09-13T23:50:10
2020-09-13T23:50:10
295,044,253
0
0
null
null
null
null
UTF-8
Java
false
false
1,128
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 javaapplication6; import java.util.Scanner; /** * * @author waynesun */ public class JavaApplication6 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your name"); String name = input.next(); name = name.toUpperCase(); System.out.println(name); String reverse =""; for(int a = name.length()-1;a>=0;a--){ String rev = name.substring(a,a+1); reverse+=rev; } for (int b=0;b<name.length()-2;b++){ String m = name.substring(b+1,b+2); System.out.print(m); for(int c = 0; c<name.length()-2;c++){ System.out.print("*"); } String end = reverse.substring(b+1,b+2); System.out.println(end); } System.out.println(reverse); } }
[ "noreply@github.com" ]
wsun0736.noreply@github.com
30edccb50a2918d824aba49e92230cb7d4e8b77d
399f59832fed21e1eabc1a9181a3ffc4f991015f
/cargo/src/main/java/com/delmar/sysSettings/dao/SysSettingsItemValueDao.java
2ebb664a7b9bc85a26767e698ccd7d6055106029
[]
no_license
DelmarChina/delmar_platform
bb977778cceced17f118e2b54e24923811b2ca28
8799ab3c086d0e4fed6c2f24eda1beee87ffd76f
refs/heads/master
2021-01-22T05:10:48.713184
2016-08-16T14:36:57
2016-08-16T14:36:57
42,499,265
0
1
null
null
null
null
UTF-8
Java
false
false
215
java
package com.delmar.sysSettings.dao; import com.delmar.core.dao.CoreDao; import com.delmar.sysSettings.model.SysSettingsItemValue; public interface SysSettingsItemValueDao extends CoreDao<SysSettingsItemValue>{ }
[ "ldlqdsdcn@gmail.com" ]
ldlqdsdcn@gmail.com
63a1ae5b71a3b0b4b24b204c05f729d4aa40766d
c3ad1c476e791965d0f6422c7b6eeadcaebda014
/ex-poo/src/designpattern/chainofresponsability/exemploDescontos/SemDesconto.java
316218d3faaf122b274a07d8e97b6a1e94a12f09
[]
no_license
brenomonteiro/exercicios-POO
2598c001d534cb81c19476e15d0019566ff226fc
4bf231ab1b8413f53e94f029d5051a7aa2e4816a
refs/heads/master
2021-05-03T10:38:39.652748
2018-05-31T02:06:07
2018-05-31T02:06:07
120,539,634
0
1
null
null
null
null
UTF-8
Java
false
false
190
java
package designpattern.chainofresponsability.exemploDescontos; public class SemDesconto extends ChainDesconto { @Override public double desconto(Orcamento orcamento) { return 0; } }
[ "brennoo.mendesmonteiro@gmail.com" ]
brennoo.mendesmonteiro@gmail.com
1e5529580580f847a3fe11e2cabf34478abfce6b
a9212ee3fce5cd0dba3c97a7257f181ddd5b5e5a
/ImageProcessing/src/AdjustmentOperation.java
8592f945727b489f5bd92af242daa56f1dffe7bb
[]
no_license
3lizabethxu/image-processing
81ebe128a5a7607aded4338d59c009b7b24fa26f
de43dc02c96795478d0cfee44ec36284a1357dcb
refs/heads/master
2022-01-07T00:36:07.552836
2019-05-28T15:04:04
2019-05-28T15:04:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,511
java
/**Dongzheng (Elizabeth)Xu * This operation changes the brightness of each pixel depending on its Euclidean distance from the upper-left * corner of the image. * * Last edited: February 3 2019 **/ import java.awt.Color; public class AdjustmentOperation implements ImageOperation { @Override public Color[][] doOperation(Color[][] imageArray) { int numOfRows = imageArray.length;// num of rows in image int numOfColumns = imageArray[0].length;//num of columns in image Color [][] result = new Color [numOfRows][numOfColumns]; //each element represents one pixel for(int r=0; r<numOfRows; r++) {//run through each pixel in each column and row of the image for(int c=0; c<numOfColumns; c++) { result[r][c]= EuclidDist(r,c,imageArray); //gets pixel with Euclidean adjustment and sets it as a resulting pixel } } return result; } public Color EuclidDist( int x, int y,Color[][] imageArray) { //defines euclidean distance and relation to brightness adjustment double D=Math.sqrt(Math.pow(x,2)+Math.pow(y,2)); double M=Math.sqrt(Math.pow(imageArray.length,2)+Math.pow(imageArray[0].length,2)); double adjustBrightness = D/M; //find pixel colour int red = (int)(imageArray[x][y].getRed()*adjustBrightness); int green =(int) (imageArray[x][y].getGreen()*adjustBrightness); int blue = (int)(imageArray[x][y].getBlue()*adjustBrightness); //set a pixel Color color = new Color (red,green,blue); return color; } }
[ "noreply@github.com" ]
3lizabethxu.noreply@github.com
34ed78de51fa5c24418dc3a9e4630b95276ac5d7
44fba7bc48051f6ad414fb90d2a4ac9b09b74a5a
/shell/src/main/java/com/rjp/shell/network/NetUtils.java
99764268deb953ff4fe22c35c06e5ca820602dd9
[]
no_license
rjpacket/RNStudy
39edb086e23c3f5e59afd26951b474e83305fc83
0221bc40e2f43e5e1d65e42aee6d14bb4ec5c576
refs/heads/master
2021-04-15T10:01:53.988279
2018-04-16T15:35:34
2018-04-16T15:35:34
126,456,362
0
0
null
null
null
null
UTF-8
Java
false
false
5,408
java
package com.rjp.shell.network; /** * author:RJP on 2017/4/20 20:35 * <p> * 请求统一接口 * 默认不显示加载框 */ public class NetUtils { public static boolean DEBUG = false; private static String DOMAIN = DEBUG ? "https://test.dajiang365.com/" : "https://filter.dajiang365.com/"; //测试线 外网:118.26.65.150 | 内网:192.168.2.237 正式线 https://filter.dajiang365.com/ public static final String URL_LOT_SERVER_API = DOMAIN + "lotserver/api/request"; public static final String URL_EURASIAN_API = DOMAIN + "sports/api/v1/"; // (新的欧亚析接口) private NetUtils() { // //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------// // HttpHeaders headers = new HttpHeaders(); // headers.put("commonHeaderKey1", "commonHeaderValue1"); //header不支持中文,不允许有特殊字符 // headers.put("commonHeaderKey2", "commonHeaderValue2"); // HttpParams params = new HttpParams(); // params.put("commonParamsKey1", "commonParamsValue1"); //param支持中文,直接传,不要自己编码 // params.put("commonParamsKey2", "这里支持中文参数"); // //----------------------------------------------------------------------------------------// // // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // //log相关 // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo"); // loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY); //log打印级别,决定了log显示的详细程度 // loggingInterceptor.setColorLevel(Level.INFO); //log颜色级别,决定了log在控制台显示的颜色 // builder.addInterceptor(loggingInterceptor); //添加OkGo默认debug日志 // //第三方的开源库,使用通知显示当前请求的log,不过在做文件下载的时候,这个库好像有问题,对文件判断不准确 // //builder.addInterceptor(new ChuckInterceptor(this)); // // //超时时间设置,默认60秒 // builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的读取超时时间 // builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的写入超时时间 // builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的连接超时时间 // // //自动管理cookie(或者叫session的保持),以下几种任选其一就行 // //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this))); //使用sp保持cookie,如果cookie不过期,则一直有效 // builder.cookieJar(new CookieJarImpl(new DBCookieStore(this))); //使用数据库保持cookie,如果cookie不过期,则一直有效 // //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore())); //使用内存保持cookie,app退出后,cookie消失 // // //https相关设置,以下几种方案根据需要自己设置 // //方法一:信任所有证书,不安全有风险 // HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); // //方法二:自定义信任规则,校验服务端证书 // HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager()); // //方法三:使用预埋证书,校验服务端证书(自签名证书) // //HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer")); // //方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书) // //HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer")); // builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager); // //配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败 // builder.hostnameVerifier(new SafeHostnameVerifier()); // 其他统一的配置 // 详细说明看GitHub文档:https://github.com/jeasonlzy/ // OkGo.getInstance().init(this) //必须调用初始化 // .setOkHttpClient(builder.build()) //建议设置OkHttpClient,不设置会使用默认的 // .setCacheMode(CacheMode.NO_CACHE) //全局统一缓存模式,默认不使用缓存,可以不传 // .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //全局统一缓存时间,默认永不过期,可以不传 // .setRetryCount(3) //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0 // .addCommonHeaders(headers) //全局公共头 // .addCommonParams(params); //全局公共参数 } private static NetUtils mInstance = new NetUtils(); public static NetUtils getInstance() { return mInstance; } }
[ "jimbo922@163.com" ]
jimbo922@163.com
494c63b8de4d59594f5269630ab26cebb71a4f3e
9482d1ec7543ca923602a152f9aee6e9c92191c9
/src/week2/exercise36/Exercise36p3.java
ff0abe82ea68f9641247b3eb9b7171366526c23a
[]
no_license
cribibi/mooc.fi-exercises
724f018e20bed02e38360df78b60f5757f53797c
3a52dddd7368761058d3e9362420e0c82380c3bd
refs/heads/master
2022-11-07T01:31:00.223548
2020-06-25T10:55:49
2020-06-25T10:55:49
237,834,545
0
0
null
null
null
null
UTF-8
Java
false
false
684
java
package week2.exercise36; import java.util.Scanner; public class Exercise36p3 { public static void main(String[] args) { int sum = 0; int counter = 0; Scanner scanner = new Scanner(System.in); System.out.println("Type numbers: "); while (true) { int no = Integer.parseInt(scanner.nextLine()); if (no == -1) { break; } else { sum += no; counter += 1; } } System.out.println("Thank you and see you later!"); System.out.println("The sum is: " + sum); System.out.println("How many numbers: " + counter); } }
[ "cricler_bianca_melania@yahoo.com" ]
cricler_bianca_melania@yahoo.com
5d57ae80849f9020445a9d1c54dcead4294cc3b9
c15316c0e446c62aed135bc9f5131b1c12735725
/app/src/main/java/com/zsc/zzc/educloud/widget/MyGridView.java
35c33bf6c89d98da7e77c8de5f0cadfc0259ea16
[]
no_license
03040081/EduCloudAndroid
30ed0231c637ddd94f9284c436a9aae21cb06167
46bda45d58ae9697bb17788d99e84d635face0fb
refs/heads/master
2021-04-06T11:25:50.514225
2018-05-04T18:45:47
2018-05-04T18:45:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package com.zsc.zzc.educloud.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class MyGridView extends GridView { public MyGridView(Context context) { super(context); } public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); } public MyGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
[ "936827581@qq.com" ]
936827581@qq.com
ed5be7bebaf7135ecf2ab4a1e91c438e18bef2e0
128da67f3c15563a41b6adec87f62bf501d98f84
/com/emt/proteus/duchampopt/_ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224.java
d77075c38143c3ffce5420b1f4f7040a3c054719
[]
no_license
Creeper20428/PRT-S
60ff3bea6455c705457bcfcc30823d22f08340a4
4f6601fb0dd00d7061ed5ee810a3252dcb2efbc6
refs/heads/master
2020-03-26T03:59:25.725508
2018-08-12T16:05:47
2018-08-12T16:05:47
73,244,383
0
0
null
null
null
null
UTF-8
Java
false
false
2,689
java
/* */ package com.emt.proteus.duchampopt; /* */ /* */ import com.emt.proteus.runtime.api.Env; /* */ import com.emt.proteus.runtime.api.Frame; /* */ import com.emt.proteus.runtime.api.Function; /* */ import com.emt.proteus.runtime.api.ImplementedFunction; /* */ import com.emt.proteus.runtime.api.Jump; /* */ /* */ public final class _ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224 extends ImplementedFunction /* */ { /* */ public static final int FNID = Integer.MAX_VALUE; /* 12 */ public static final Function _instance = new _ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224(); /* 13 */ public final Function resolve() { return _instance; } /* */ /* 15 */ public _ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224() { super("_ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224", 3, false); } /* */ /* */ public int execute(int paramInt1, int paramInt2, int paramInt3) /* */ { /* 19 */ call(paramInt1, paramInt2, paramInt3); /* 20 */ return 0; /* */ } /* */ /* */ public int execute(Env paramEnv, Frame paramFrame, int paramInt1, int paramInt2, int paramInt3, int[] paramArrayOfInt, int paramInt4) /* */ { /* 25 */ int i = paramFrame.getI32(paramArrayOfInt[paramInt4]); /* 26 */ paramInt4 += 2; /* 27 */ paramInt3--; /* 28 */ int j = paramFrame.getI32(paramArrayOfInt[paramInt4]); /* 29 */ paramInt4 += 2; /* 30 */ paramInt3--; /* 31 */ int k = paramFrame.getI32(paramArrayOfInt[paramInt4]); /* 32 */ paramInt4 += 2; /* 33 */ paramInt3--; /* 34 */ call(i, j, k); /* 35 */ return paramInt4; /* */ } /* */ /* */ /* */ /* */ /* */ public static void call(int paramInt1, int paramInt2, int paramInt3) /* */ { /* */ try /* */ { /* 45 */ Jump.label(57693); /* 46 */ if (com.emt.proteus.runtime.api.MainMemory.getI8(paramInt1 + 558) != 0) /* */ { /* */ /* */ /* */ /* 51 */ _ZN11ProgressBar4initEi.call(paramInt3, paramInt2); /* */ } /* */ /* */ /* */ /* */ /* */ /* 58 */ Jump.label(8000000); /* 59 */ return; /* */ } /* */ finally {} /* */ } /* */ } /* Location: /home/jkim13/Desktop/emediatrack/codejar_s.jar!/com/emt/proteus/duchampopt/_ZN7duchamp23searchReconArraySpatialEPlPfS1_RNS_5ParamERN10Statistics14StatsContainerIfEE_224.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "kimjoey79@gmail.com" ]
kimjoey79@gmail.com
56e0dd069bbb6c9a3e556b87ee54eac7c7e03a80
41f9cdad03bf736626318eddeb0a702c9db3a632
/src/FactoryMethod/ChicagoStyleVeggiePizza.java
815b57bd3061e6cf977df13e1238c54a5d511523
[]
no_license
mutonar/patern
de21471653949eedaf3d92f20119a33c3c2e3a85
0f3b8c6ce2c08074a04b0dcd71d7129cbcc8fe54
refs/heads/master
2022-08-10T11:00:05.887493
2022-08-04T14:19:51
2022-08-04T14:19:51
226,075,476
0
0
null
null
null
null
UTF-8
Java
false
false
654
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 FactoryMethod; /** * * @author nazarov */ class ChicagoStyleVeggiePizza extends Pizza { public ChicagoStyleVeggiePizza() { name = "Chicago Style Deep Dish Veggie Pizza"; dough = "Extra Thick Crust Dough"; sauce = "Plum Tomato Sauce"; toppings.add("Double tomato."); // Shredded - Измельченный } @Override void cut() { System.out.println("Cutting the pizza into square slices"); } }
[ "mutonar@gmail.com" ]
mutonar@gmail.com
2335f6f4645bd546a84977abc72dad38f2369222
1324fe8ab20d60a7b20bb4824f1a0fac8e5363de
/src/main/java/com/drsoft/JEE/dao/UserDao.java
2d0c5d458584196d5bf70154ba78d3e19e141b8a
[]
no_license
dongrui1048033466/jee
73170fc1586529bc454dad8a598b8d5190e35517
057ed2fa822f12d05001241b0064346137c2026f
refs/heads/master
2020-04-08T01:31:57.104566
2018-11-24T03:36:02
2018-11-24T03:36:15
158,898,817
0
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
package com.drsoft.JEE.dao; import com.drsoft.JEE.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserDao { // 通过账号和密码查用户 public User findUser(@Param("loginName") String loginName, @Param("loginPwd") String loginPwd); // 通过账号和密码查用户 public User findUsers(@Param("loginName") String loginName, @Param("loginPwd") String loginPwd); // 查总数 public int querycount(); //全查用户 public List<User> queryAll(); //更新用户 public int update(User user); //删除用户 public int delete(@Param("id") int id); //添加用户 public int add(User User); //通过id查用户 public User queryById(@Param("id") int id); //通过id查用户权限 public User queryjurById(@Param("id") int id); // 通过email查 public User queryByEmail(@Param("value") String email); // 通过loginName查 public User queryByLoginName(@Param("value") String loginName); //模糊查询 public List<User> getUsers(@Param("loginName") String loginName, @Param("userName") String userName); }
[ "1048033466@qq.com" ]
1048033466@qq.com
5e9a960461005b0f3e994b98d1d614b890491332
ea31539cc2f2e449972a5bc1d666f38823c0b8d2
/app/src/main/java/com/adadlab/hamza/a9assama/Roommates.java
cdec2472923ecac6282c87f4520df54e608f5149
[]
no_license
hamzaadad/9assama
dffeebd9940e038371649426aa2dfb22187278b6
4ded7dcf6ee7ae205ff19de407923a38e666feab
refs/heads/master
2020-05-24T21:27:07.969733
2017-03-13T18:37:38
2017-03-13T18:37:38
84,882,225
0
0
null
null
null
null
UTF-8
Java
false
false
111
java
package com.adadlab.hamza.a9assama; /** * Created by DevBlaan on 13/03/2017. */ public class Roommates { }
[ "salami@blaan.ma" ]
salami@blaan.ma
439684a836d2c1324569bc91097157db30fa7747
0560d3f5e33c830cc14b53d38eeeabf97a6e638c
/src/main/java/cn/ksdshpx/user/dao/UserDaoImpl.java
6e1a04b2eea78ae543a3b20952b088dcd6afedea
[]
no_license
ksdshpx/PRegisterLogin
3628fe7b5d596aa3dfd084f8a7344ef7c6b600cc
83a2a892ec79eb6ca3e56b24884d7b1bd4555885
refs/heads/master
2020-03-24T16:57:57.831253
2018-09-14T05:51:25
2018-09-14T05:51:25
142,844,462
0
0
null
null
null
null
UTF-8
Java
false
false
2,717
java
package cn.ksdshpx.user.dao; import cn.ksdshpx.user.domain.User; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; /** * Create with IntelliJ IDEA * Create by peng.x * Date: 2018/7/31 * Time: 10:18 * Description:数据访问类UserDao */ public class UserDaoImpl implements UserDao { private String path = "D:\\users.xml"; /** * 按用户名查询 * @param username * @return */ public User findByUsername(String username){ //1.得到Document //创建解析器 SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(path); //2.通过xpath查询得到Element Element element = (Element) document.selectSingleNode("//user[@username='"+username+"']"); //3.校验element是否为null,如果为null,返回null if (element == null) { return null; } //4.把element的数据封装到User对象中 User user = new User(); String attrUsername = element.attributeValue("username"); String attrPassword = element.attributeValue("password"); user.setUsername(attrUsername); user.setPassword(attrPassword); return user; } catch (DocumentException e) { throw new RuntimeException(e); } } /** * 添加用户 * @param user */ public void add(User user){ //1.得到Document //创建解析器 SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(path); //2.得到根元素 Element root = document.getRootElement(); //3.通过根元素创建新元素 Element userEle = root.addElement("user"); //4.为userEle设置属性 userEle.addAttribute("username",user.getUsername()); userEle.addAttribute("password",user.getPassword()); //保存文档 //创建输出格式化器 OutputFormat outputFormat = new OutputFormat("\t",true);//缩进使用\t,还要换行 outputFormat.setTrimText(true);//清空原有的缩进与换行 XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"),outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { throw new RuntimeException(e); } } }
[ "southeast_px@163.com" ]
southeast_px@163.com
48088daa31cc1bb78f106ca1cd5110d553efc9e9
5a3a37a657d0123a35d1652759621e46d2927b1c
/JwZP/07-vet/src/main/java/uj/jwzp2020/veterinaryclinic/model/appointment/AppointmentLength.java
34ae47ee7b5b846690435fff87c3919014ca491b
[]
no_license
seqre/UJ
edbce3c96d906f91ff105389a7bb68e6333c1c2c
ce9819dab1ea2d8459bf7b2f17de23a4230c9bf8
refs/heads/master
2023-02-24T20:29:02.595163
2021-01-22T15:00:23
2021-01-22T15:00:23
290,614,029
13
2
null
null
null
null
UTF-8
Java
false
false
360
java
package uj.jwzp2020.veterinaryclinic.model.appointment; public enum AppointmentLength { FIFTEEN_MINUTES(15), THIRTY_MINUTES(30), FORTY_FIVE_MINUTES(45), SIXTY_MINUTES(60); private final int minutes; AppointmentLength(int minutes) { this.minutes = minutes; } public int getMinutes() { return minutes; } }
[ "seqre@disroot.org" ]
seqre@disroot.org
d737505af2c4c56cdcc6047e1e2e2ee7edc06528
5eb44d79871ea1ed64bcb455ec4ef718ac08852b
/webservice-parent/webservice-ws/src/main/java/com/oney/archi/webservice/config/WebConfigurer.java
5b80fb306a1bc64ebc61b6a5042bbeae07549ba4
[]
no_license
codeworks17/test
14333379a3b7f5c3251836094df9a9d3648d6e1b
d211458065a1ac43dfb2afa447e00af452222764
refs/heads/master
2021-07-16T22:44:10.519199
2017-10-25T11:20:02
2017-10-25T11:20:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,157
java
package com.oney.archi.webservice.config; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.servlet.InstrumentedFilter; import com.codahale.metrics.servlets.MetricsServlet; import com.oney.archi.webservice.web.filter.CachingHttpHeadersFilter; import com.oney.archi.webservice.web.filter.MDCFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.context.embedded.MimeMappings; import org.springframework.boot.context.embedded.ServletContextInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import java.io.File; import java.nio.file.Paths; import java.util.*; import javax.inject.Inject; import javax.servlet.*; /** * Configuration of web application with Servlet 3.0 APIs. */ @Configuration public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); @Inject private Environment env; @Inject private JHipsterProperties jHipsterProperties; @Autowired(required = false) private MetricRegistry metricRegistry; @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles())); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); // Keep the initialisation of this filter **first**. initSlf4jMDC(servletContext, disps); initMetrics(servletContext, disps); if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } log.info("Web application fully configured"); } /** * Set up Mime types and, if needed, set the document root. */ @Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 mappings.add("html", "text/html;charset=utf-8"); // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64 mappings.add("json", "text/html;charset=utf-8"); container.setMimeMappings(mappings); // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. setLocationForStaticAssets(container); } private void setLocationForStaticAssets(ConfigurableEmbeddedServletContainer container) { File root; String prefixPath = resolvePathPrefix(); if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) { root = new File(prefixPath + "target/www/"); } else { root = new File(prefixPath + "src/main/webapp/"); } if (root.exists() && root.isDirectory()) { container.setDocumentRoot(root); } } /** * Resolve path prefix to static resources. */ private String resolvePathPrefix() { String fullExecutablePath = this.getClass().getResource("").getPath(); String rootPath = Paths.get(".").toUri().normalize().getPath(); String extractedPath = fullExecutablePath.replace(rootPath, ""); int extractionEndIndex = extractedPath.indexOf("target/"); if(extractionEndIndex <= 0) { return ""; } return extractedPath.substring(0, extractionEndIndex); } /** * Initializes MDC cleaner. */ private void initSlf4jMDC(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Initializing MDC cleanup filter"); FilterRegistration.Dynamic mdcFilter = servletContext.addFilter("slf4jMdcFilter", new MDCFilter()); mdcFilter.addMappingForUrlPatterns(disps, true, "/*"); mdcFilter.setAsyncSupported(false); } /** * Initializes the caching HTTP Headers Filter. */ private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Registering Caching HTTP Headers Filter"); FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter("cachingHttpHeadersFilter", new CachingHttpHeadersFilter(jHipsterProperties)); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*"); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*"); cachingHttpHeadersFilter.setAsyncSupported(true); } /** * Initializes Metrics. */ private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Initializing Metrics registries"); servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry); servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry); log.debug("Registering Metrics Filter"); FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter", new InstrumentedFilter()); metricsFilter.addMappingForUrlPatterns(disps, true, "/*"); metricsFilter.setAsyncSupported(true); log.debug("Registering Metrics Servlet"); ServletRegistration.Dynamic metricsAdminServlet = servletContext.addServlet("metricsServlet", new MetricsServlet()); metricsAdminServlet.addMapping("/management/jhipster/metrics/*"); metricsAdminServlet.setAsyncSupported(true); metricsAdminServlet.setLoadOnStartup(2); } @Bean @ConditionalOnProperty(name = "jhipster.cors.allowed-origins") public CorsFilter corsFilter() { log.debug("Registering CORS filter"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/v2/api-docs", config); source.registerCorsConfiguration("/oauth/**", config); return new CorsFilter(source); } }
[ "ruffin.alexandre@gmail.com" ]
ruffin.alexandre@gmail.com
46661e3fc186c742ccfebbdd8ff8e69af0fa6120
d200641a5274e1cb97517c5fcab1a832c799a775
/Computer-database/client/src/main/java/com/excilys/malbert/client/service/IClientService.java
5039a3a76623c4f1a508ca564121fcb7dfa80b1e
[]
no_license
amatthieu/Computer-database
df37c4c2141c4dfb1e11759c4ef73854cad101a2
07a19bc51af9ffc63ab0a845a0e08cdbbb2d41c8
refs/heads/master
2021-05-29T10:06:25.550276
2015-05-29T12:40:43
2015-05-29T12:40:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
639
java
package com.excilys.malbert.client.service; import java.util.List; import com.excilys.malbert.core.model.Company; import com.excilys.malbert.core.model.Computer; /** * Interface of the Service communicating with the web services for CLI * * @author excilys */ public interface IClientService { public List<Computer> getAllComputer(); public Computer findComputer(Long id); public void deleteComputer(Long id); public void createComputer(Computer computer); public void updateComputer(Computer computer); public List<Company> getAllCompany(); public void deleteCompany(Long id); public Company getCompany(Long id); }
[ "malbert.excilys@desktop-0130.ebi.excilys.com" ]
malbert.excilys@desktop-0130.ebi.excilys.com
4a6e5f740b02be42a271e9db0bcc796138a35da4
37c240728f71fd6615de66c79345aad4926e2509
/USACO Training/Chapter 2/Section 1/frac1.java
a1153a2d996ecedb76b5cee8f62a39aff795da37
[]
no_license
samasetty/USACO-Solutions
54eb6fc98733cc423033c5b2878beaf7a602e187
a214030441893f724445d787ba5200a6221bdf51
refs/heads/master
2020-08-21T21:53:34.658308
2020-07-08T23:41:55
2020-07-08T23:41:55
216,255,094
0
0
null
null
null
null
UTF-8
Java
false
false
2,250
java
/* ID: settysa1 LANG: JAVA TASK: frac1 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; public class frac1 { static int n; static ArrayList<Fraction> fracs; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("frac1.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("frac1.out")),true); n = Integer.parseInt(f.readLine()); //n = 160; fracs = new ArrayList<Fraction>(); // generating our fractions fracs.add(new Fraction()); fracs.add(new Fraction(1, 1)); Fraction b; for (int i = 2; i < n + 1; i++) { b = new Fraction(0, i); for (int j = 0; j < i - 1; j++) { b.add(); if (b.reduced()) fracs.add(b.copyOf()); } } Collections.sort(fracs); for (Fraction fra : fracs) { out.println(fra); } out.close(); f.close(); } } class Fraction implements Comparable<Fraction> { int numerator; int denominator; public Fraction() { numerator = 0; denominator = 1; } public Fraction(int num, int denom) { numerator = num; denominator = denom; } public void add() { numerator = numerator + 1; } public String toString() { return numerator + "/" + denominator; } public boolean equals(Fraction rhs) { return (numerator == rhs.numerator) && (denominator == rhs.denominator); } public boolean reduced() { for (int i = 2; i <= numerator; i++) { if (numerator % i == 0 && denominator % i == 0) return false; } return true; } @Override public int compareTo(Fraction o) { if(denominator == o.denominator) { if (numerator < o.numerator) { return -1; } else if (numerator > o.numerator) { return 1; } else { return 0; } } if (numerator * o.denominator > o.numerator * denominator) { return 1; } else if (numerator * o.denominator < o.numerator * denominator) { return -1; } else { return 0; } } public Fraction copyOf() { return new Fraction(numerator, denominator); } }
[ "noreply@github.com" ]
samasetty.noreply@github.com
496a878513b140b6621a5557912dc54ab62c46ad
12ddc05ac1700b62c83c31d142cbf0aa47060b93
/SMS SENDING APPLICATION/src/SendSmsPanel.java
a80c5491189d187789e50ec9cf2448ff5d12daf6
[]
no_license
natcobbinah/BULK-SMS-DESKTOP-APP
66953fd2b1df6cee62049b822e71705f1d6e2ffc
de773f241c4da4fba0e49a2dc70a6fdca3855d8a
refs/heads/master
2021-06-12T20:31:30.941445
2020-04-09T14:27:23
2020-04-09T14:27:23
254,392,212
0
0
null
null
null
null
UTF-8
Java
false
false
7,125
java
import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.teknikindustries.bulksms.SMS; public class SendSmsPanel extends JPanel { /** * */ private static final long serialVersionUID = 6003481406975592068L; private JLabel msglbl; private JLabel recipientlbl; private JLabel urllbl; private JLabel maxcharslbl; public JTextField msgtxfd; private JComboBox countrycodescbo; public JTextField phonenumtxtfd; private JComboBox urlcbo; private JButton sendbtn; private JButton clearbtn; // private String userName = "Natcobbinah"; // private String password = "@BYStrVMH"; /* * public String userName = "henhak"; public String password = * "3Accountability"; */ public String userName = ""; public String password = ""; // ----------------------------------------- // ----------------------------------------- public SendSmsPanel() { SendSmsPanelLayoutDesign(); } private void SendSmsPanelLayoutDesign() { setLayout(new GridBagLayout()); msglbl = new JLabel("Message"); recipientlbl = new JLabel("Recipient"); urllbl = new JLabel("URL"); maxcharslbl = new JLabel("(maximum: 160 characters)"); msgtxfd = new JTextField(30); phonenumtxtfd = new JTextField(20); urlcbo = new JComboBox(); DefaultComboBoxModel urlModel = new DefaultComboBoxModel(); urlModel.addElement("https://bulksms.vsms.net/eapi/submission/send_sms/2/2.0"); urlcbo.setModel(urlModel); urlcbo.setEditable(true); sendbtn = new JButton("Send"); clearbtn = new JButton("Clear"); String[] countryCodes = { "+93", "+355", "+213", "+684", "+376", "+244", "+809", "+268", "+54", "+374", "+297", "+247", "+61", "+672", "+43", "+994", "+242", "+246", "+973", "+880", "+375", "+32", "+501", "+229", "+809", "+975", "+284", "+591", "+387", "+267", "+55", "+284", "+673", "+359", "+226", "+257", "+855", "+237", "+1", "+238", "+345", "+238", "+236", "+235", "+56", "+86", "+886", "+57", "+269", "+242", "+682", "+506", "+385", "+53", "+357", "+420", "+45", "+246", "+767", "+809", "+253", "+593", "+20", "+503", "+240", "+291", "+372", "+251", "+500", "+298", "+679", "+358", "+33", "+596", "+594", "+241", "+220", "+995", "+49", "+233", "+350", "+30", "+299", "+473", "+67", "+502", "+224", "+245", "+592", "+509", "+504", "+852", "+36", "+354", "+91", "+62", "+98", "+964", "+353", "+972", "+39", "+225", "+876", "+81", "+962", "+7", "+254", "+855", "+686", "+82", "+850", "+965", "+996", "+371", "+856", "+961", "+266", " + 231", " + 370", " + 218 ", "+ 423", " + 352", " + 853", " + 389", " + 261", " + 265", " + 60 ", "+ 960", " + 223", " + 356", " + 692", " + 596", "+ 222", " + 230", " + 269", " + 52", " + 691", " + 373", " + 33", " + 976", " + 473", " + 212", " + 258", " + 95", " + 264", " + 674", " + 977", " + 31", "+ 599 ", "+ 869", " + 687", " + 64", " + 505", " + 227", " + 234 ", "+ 683 ", "+ 850 ", "+ 1670 ", "+ 47 ", "+ 968 ", "+ 92 ", "+ 680 ", "+ 507 ", "+ 675", "+ 595 ", "+ 51 ", "+ 63 ", "+ 48 ", "+ 351 ", "+ 1787 ", "+ 974 ", "+ 262 ", "+ 40 ", "+ 7 ", "+ 250", " + 670", " + 378", " + 239", " + 966 ", "+ 221", " + 381", "+ 248", " + 232", " + 65", " + 421", " + 386", " + 677", " + 252", " + 27 ", "+ 34", " + 94", " + 290", " + 869", " + 508", " + 249", " + 597", " + 268", " + 46", "+ 41", " + 963 ", "+ 689 ", "+ 886", " + 7", " + 255 ", "+ 66", " + 228", " + 690 ", "+ 676 ", "+ 1868 ", "+ 216", " + 90 ", "+ 993 ", "+ 688 ", "+ 256", "+ 380 ", "+ 971 ", "+ 44 ", "+ 598 ", "+ 1 ", "+ 7 ", "+ 678 ", "+ 39 ", "+ 58 ", "+ 84 ", "+ 1340 ", "+ 681 ", "+ 685 ", "+ 381 ", "+ 967 ", "+ 381 ", "+ 243", "+260", "+26" }; countrycodescbo = new JComboBox(countryCodes); countrycodescbo.setEditable(true); sendbtn = new JButton("Send"); clearbtn = new JButton("Clear"); JPanel savePanel = new JPanel(); savePanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); savePanel.setBorder(BorderFactory.createEtchedBorder()); savePanel.add(sendbtn); savePanel.add(clearbtn); // ----------------------------------------------------------------- JPanel recipientPanel = new JPanel(); recipientPanel.setLayout(new GridBagLayout()); GridBagConstraints rgc = new GridBagConstraints(); rgc.gridx = 0; rgc.gridy = 0; rgc.ipadx = 12; rgc.ipady = 12; rgc.insets = new Insets(2, 2, 2, 2); rgc.anchor = GridBagConstraints.NORTHWEST; recipientPanel.add(countrycodescbo, rgc); rgc.gridx = 1; rgc.gridy = 0; rgc.anchor = GridBagConstraints.NORTHWEST; recipientPanel.add(phonenumtxtfd, rgc); // ------------------------------------------------------------------- JPanel allgcPanel = new JPanel(); allgcPanel.setLayout(new GridBagLayout()); allgcPanel.setBorder(BorderFactory.createTitledBorder("Send SMS [Single Receipient]")); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.ipadx = 12; gc.ipady = 12; gc.insets = new Insets(15,15 ,15,15); allgcPanel.add(msglbl, gc); gc.gridx = 1; gc.gridy = 0; allgcPanel.add(msgtxfd, gc); gc.gridx = 2; gc.gridy = 0; allgcPanel.add(maxcharslbl, gc); gc.gridx = 0; gc.gridy = 1; allgcPanel.add(recipientlbl, gc); gc.gridx = 1; gc.gridy = 1; gc.anchor = GridBagConstraints.NORTHWEST; allgcPanel.add(recipientPanel, gc); gc.gridx = 0; gc.gridy = 2; allgcPanel.add(urllbl, gc); gc.gridx = 1; gc.gridy = 2; gc.anchor = GridBagConstraints.NORTHWEST; allgcPanel.add(urlcbo, gc); gc.gridx = 1; gc.gridy = 3; gc.anchor = GridBagConstraints.NORTHEAST; allgcPanel.add(savePanel, gc); // ----------------------------------------------------------- GridBagConstraints gcmain = new GridBagConstraints(); gcmain.gridx = 0; gcmain.gridy = 0; add(allgcPanel, gcmain); // --------------------SMS CODES---------------------------- SMS smsSample = new SMS(); // --------------------------------------------------------- sendbtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message = msgtxfd.getText(); String phonenumcode = (String) countrycodescbo.getSelectedItem(); String phonenum = phonenumtxtfd.getText(); String fullphonenum = phonenumcode + phonenum; String url = (String) urlcbo.getSelectedItem(); smsSample.SendSMS(userName, password, message, fullphonenum, url); } }); clearbtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { msgtxfd.setText(""); phonenumtxtfd.setText(""); } }); } }
[ "noreply@github.com" ]
natcobbinah.noreply@github.com
b7ddd768421dff62b53600de281954eaca8fdae9
50954e28cda402c5ec6d198711bffe3c50b0f7c7
/JavaSE/src/main/resources/src/org/omg/PortableInterceptor/AdapterManagerIdHelper.java
fef49a710cc2ff41fa645ef30fcde607a3b03560
[]
no_license
bulusky/Note
f7b4a76a4ea5d1f10a122152afacd23a4aed4fd6
73c60b2fccac89d48a7566a265217e601c8fcb79
refs/heads/master
2023-01-03T10:03:29.615608
2020-10-24T09:38:45
2020-10-24T09:38:45
303,957,641
2
0
null
null
null
null
UTF-8
Java
false
false
1,967
java
package org.omg.PortableInterceptor; /** * org/omg/PortableInterceptor/AdapterManagerIdHelper.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/jenkins/workspace/8-2-build-windows-amd64-cygwin/jdk8u251/737/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl * Thursday, March 12, 2020 6:33:10 AM UTC */ /** Adapter manager identifier. Every object adapter has an adapter manager, * indicated in this API only through the ID. A group of object adapter * instances may share the same adapter manager, in which case state transitions * reported for the adapter manager are observed by all object adapters with the * same adapter manager ID. */ abstract public class AdapterManagerIdHelper { private static String _id = "IDL:omg.org/PortableInterceptor/AdapterManagerId:1.0"; public static void insert (org.omg.CORBA.Any a, int 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 int extract (org.omg.CORBA.Any a) { return read (a.create_input_stream ()); } private static org.omg.CORBA.TypeCode __typeCode = null; synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.PortableInterceptor.AdapterManagerIdHelper.id (), "AdapterManagerId", __typeCode); } return __typeCode; } public static String id () { return _id; } public static int read (org.omg.CORBA.portable.InputStream istream) { int value = (int)0; value = istream.read_long (); return value; } public static void write (org.omg.CORBA.portable.OutputStream ostream, int value) { ostream.write_long (value); } }
[ "814192772@qq.com" ]
814192772@qq.com
bb72df022a75605fc4aac2249a0b06f6fcec5898
3c399558fe348ee8d14a005bd571273bb3861df8
/src/main/java/com/soundlab/web/music/MusicCtrl.java
bccaff92d5563c501c931ab463316f0ea697fb6f
[]
no_license
wldms0828/SL
89a3c6ce6a40e6ab910b6a17d21c28e6e5cc81ec
4f150b87548498c759637a628157a070709ade91
refs/heads/master
2020-04-02T05:23:08.980087
2018-10-19T10:40:06
2018-10-19T10:40:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,104
java
package com.soundlab.web.music; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.soundlab.web.cmm.Util; @RestController @RequestMapping("/music") public class MusicCtrl { static final Logger logger = LoggerFactory.getLogger(MusicCtrl.class); @Autowired MusicMapper musMapper; @Autowired HashMap<String, Object> map; @GetMapping("/top50/{x}") private @ResponseBody List<Map<String, Object>> top50(@PathVariable String x) { Util.log.accept(":: MusicCtrl :: list() :: page :: " ); List<Map<String, Object>> topList = null; Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String todayDate= new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //오늘 cal.add(Calendar.DATE, -1); //어제 String yesterDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); cal.add(Calendar.DATE, 1 - cal.get(Calendar.DAY_OF_WEEK)-7); //주간 String week1 = simpleDateFormat.format(cal.getTime()); cal.add(Calendar.DATE, 7 - cal.get(Calendar.DAY_OF_WEEK)); String week2 = simpleDateFormat.format(cal.getTime()); if(x.equals("realChart") ) { map.put("todayDate",todayDate); topList = musMapper.realChart(map); }else if (x.equals("dayChart")){ map.put("yesterDate",yesterDate); topList = musMapper.dayChart(map); }else if (x.equals("weekChart") ){ map.put("week1",week1); map.put("week2",week2); topList = musMapper.weekChart(map); } return topList; } }
[ "lina900904@gmail.com" ]
lina900904@gmail.com
66a629bdcb449e07f84642298606aa2ecad58d55
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_ac55d303682c3e030f04daa4ff3d5a5af1bdecc5/ECollegeApplication/17_ac55d303682c3e030f04daa4ff3d5a5af1bdecc5_ECollegeApplication_t.java
0d5d5c53b14763d3a97650e946f37a7df60c57fb
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
7,117
java
package com.ecollege.android; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import roboguice.application.RoboApplication; import roboguice.inject.SharedPreferencesName; import roboguice.util.Ln; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.widget.Toast; import com.ecollege.android.errors.ECollegeAlertException; import com.ecollege.android.errors.ECollegeException; import com.ecollege.android.errors.ECollegePromptException; import com.ecollege.android.errors.ECollegePromptRetryException; import com.ecollege.android.util.FileCacheManager; import com.ecollege.android.util.VolatileCacheManager; import com.ecollege.android.view.HeaderView; import com.ecollege.api.ECollegeClient; import com.ecollege.api.model.User; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Module; public class ECollegeApplication extends RoboApplication implements UncaughtExceptionHandler { @Inject SharedPreferences prefs; final protected VolatileCacheManager volatileCache = new VolatileCacheManager(); protected Context lastActiveContext; private FileCacheManager serviceCache; public ECollegeApplication() { super(); lastActiveContext = this; Thread.setDefaultUncaughtExceptionHandler(this); //global error handling on UI thread } private ECollegeClient client; public ECollegeClient getClient() { if (client == null) { client = new ECollegeClient(getString(R.string.client_string), getString(R.string.client_id)); } return client; } public String getSessionIdentifier() { String id = getClient().getGrantToken(); return (id == null) ? "" : id; } @Override protected void addApplicationModules(List<Module> modules) { modules.add(new Module() { public void configure(Binder binder) { binder.bindConstant().annotatedWith(SharedPreferencesName.class).to("com.ecollege.android"); //can make a separate module as needed } }); } public void logout() { client = null; currentUser = null; volatileCache.clear(); SharedPreferences.Editor editor = prefs.edit(); editor.remove("grantToken"); editor.commit(); //change to apply if android 2.2 Intent i = new Intent(this,MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } public void putObjectInVolatileCache(String key, Object object) { volatileCache.put(key + "-" + getSessionIdentifier(), object); } public <CachedT> CachedT getObjectOfTypeFromVolatileCache(String key, Class<CachedT> clazz) { CachedT cachedObject = volatileCache.get(key + "-" + getSessionIdentifier(), clazz); return cachedObject; } public FileCacheManager getServiceCache() { if (serviceCache == null) { serviceCache = new FileCacheManager(this, 1000 * 60 * 60); //1 hour cache } return serviceCache; } private int pendingServiceCalls = 0; private User currentUser; private int nextProgressDialogTitleId = -1; private int nextProgressDialogMsgId = -1; public int getPendingServiceCalls() { return pendingServiceCalls; } public synchronized void incrementPendingServiceCalls() { if (pendingServiceCalls == 0) { this.pendingServiceCalls++; updateHeaderProgress(true); } else { this.pendingServiceCalls++; } } public synchronized void decrementPendingServiceCalls() { if (pendingServiceCalls == 1) { this.pendingServiceCalls--; updateHeaderProgress(false); } else { this.pendingServiceCalls--; } } public User getCurrentUser() { return currentUser; } public void setCurrentUser(User currentUser) { this.currentUser = currentUser; } public int getNextProgressDialogTitleId() { return nextProgressDialogTitleId; } public void setNextProgressDialogTitleId(int nextProgressDialogTitleId) { this.nextProgressDialogTitleId = nextProgressDialogTitleId; } public int getNextProgressDialogMsgId() { return nextProgressDialogMsgId; } public void setNextProgressDialogMsgId(int nextProgressDialogMsgId) { this.nextProgressDialogMsgId = nextProgressDialogMsgId; } private HashMap<String, WeakReference<Context>> contextObjects = new HashMap<String, WeakReference<Context>>(); public synchronized Context getActiveContext(String className) { WeakReference<Context> ref = contextObjects.get(className); if (ref == null) { return null; } final Context c = ref.get(); if (c == null) // If the WeakReference is no longer valid, ensure it is removed. contextObjects.remove(className); return c; } public synchronized Context getActiveContext() { return lastActiveContext; } public synchronized void setActiveContext(String className, Context context) { if (!(context instanceof ECollegeApplication)) { lastActiveContext = context; } WeakReference<Context> ref = new WeakReference<Context>(context); this.contextObjects.put(className, ref); } public synchronized void resetActiveContext(String className) { contextObjects.remove(className); } private List<WeakReference<HeaderView>> registeredHeaderViews = new ArrayList<WeakReference<HeaderView>>(); public synchronized void updateHeaderProgress(boolean showProgress) { for (int i=registeredHeaderViews.size()-1;i>=0;i--) { HeaderView hv = registeredHeaderViews.get(i).get(); if (hv == null) { registeredHeaderViews.remove(i); } else { hv.setProgressVisibility(showProgress); } } } public synchronized void registerHeaderView(HeaderView hv) { WeakReference<HeaderView> ref = new WeakReference<HeaderView>(hv); registeredHeaderViews.add(ref); hv.setProgressVisibility(pendingServiceCalls > 0); } public synchronized void unregisterHeaderView(HeaderView hv) { for (int i=registeredHeaderViews.size()-1;i>=0;i--) { if (registeredHeaderViews.get(i).get() == hv) { registeredHeaderViews.remove(i); } } } public void reportError(Throwable source) { ECollegeException ex; if (source instanceof ECollegeException){ ex = (ECollegeException)source; } else { ex = new ECollegePromptException(lastActiveContext, source); } if (ex.getSource() != null) { Ln.e(ex.getSource()); } if (ex instanceof ECollegeAlertException) { Toast.makeText(this,ex.getErrorMessageId(),5000).show(); } else if (ex instanceof ECollegePromptException) { ((ECollegePromptException)ex).showErrorDialog(); } else if (ex instanceof ECollegePromptRetryException) { ((ECollegePromptRetryException)ex).showErrorDialog(); } } public void uncaughtException(Thread thread, Throwable ex) { reportError(ex); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
42fcebc327f3b37fe46bc57c1e8a7271fcbfc4a3
0d6d066e8901e93e876b2994b3704fed18ef2b1d
/src/test/java/com/javaee/klenner/springtests/SpringTestsApplicationTests.java
46aeb9034a753f0d0ed17b382e04e95a0abfb9ab
[]
no_license
klenner1/spring-tests
8509ce27becb5ffec12556973887a44af06a900b
5ffe921b341515c557b3952e84cfcfc8406ce877
refs/heads/master
2020-03-22T18:58:38.399499
2018-07-11T00:37:09
2018-07-11T00:37:09
140,495,656
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
package com.javaee.klenner.springtests; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringTestsApplicationTests { @Test public void contextLoads() { } }
[ "klenne.al@gmail.com" ]
klenne.al@gmail.com
b8c619d4600708190b3fa610da551677775e9040
597a6ead9159402bce7bb24a865793971036c884
/MBDF/src/com/redgalaxy/mbdf/Format8Bit.java
0a225b005d4811bb2e14cae88cd118e99251c80d
[ "MIT" ]
permissive
FoxSamu/MBDF
c0e97d87bfcaeea633a4da92d086164a4b3ddd2c
badf7238bd77075f4658f0d18d5db1460d0da4ec
refs/heads/master
2022-11-27T07:27:59.346904
2018-05-23T10:45:40
2018-05-23T10:45:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
619
java
package com.redgalaxy.mbdf; import java.io.IOException; public class Format8Bit { public static String getBinary(String encoded) { return null; } public static String getEncoded(String binary) throws IOException { return new String( getBytesFromBinary(binary), "UTF-8" ); } private static byte[] getBytesFromBinary(String binary) { byte[] ret = new byte[binary.length() / 8]; for (int i = 0; i < ret.length; i++) { String chunk = binary.substring(i * 8, i * 8 + 8); ret[i] = Byte.parseByte(chunk, 2); } return ret; } }
[ "noreply@github.com" ]
FoxSamu.noreply@github.com
fc63bdd88d5c58e6fba344daaa841e75ef1663b5
8295b37493b9c4433385f5c370a36ccb0f53f908
/src/main/java/it/sdkboilerplate/objects/SdkObject.java
d471100178d05f2fc6632c3243e0fe3c8a044bd8
[]
no_license
moveaxlab/sdk-boilerplate-java7
afb68d6b8c232bdfea05dccc49b0ef987ab50741
357aa774ee90fe6b008ee496d8bbc5782f896292
refs/heads/master
2021-07-08T11:08:31.878053
2019-05-11T17:24:50
2019-05-11T17:24:50
183,202,352
0
0
null
null
null
null
UTF-8
Java
false
false
2,132
java
package it.sdkboilerplate.objects; import it.sdkboilerplate.exceptions.MalformedSdkObjectException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; public abstract class SdkObject extends SdkBodyType { public static HashMap<String, Class<? extends SdkBodyType>> getSubObjects() { return new HashMap(); } /** * Helper method to convert an SdkObject into an HashMap * * @return HashMap representation of the sdk object */ public HashMap<String, Object> toHashMap() { HashMap<String, Object> serialization = new HashMap(); // We get every field defined by the object Field[] objectAttributes = this.getClass().getDeclaredFields(); for (Field field : objectAttributes) { field.setAccessible(true); try { Object fieldValue = field.get(this); Object value = null; // If the value is an SdkObject, we call the method recursively to get the HashMap if (fieldValue instanceof SdkObject) { value = fieldValue.getClass().getMethod("toHashMap").invoke(fieldValue); // If the value is an SdkCollection, we call the method recursively to get its array representation } else if (fieldValue instanceof SdkCollection) { value = fieldValue.getClass().getMethod("toArrayList").invoke(fieldValue); } else { // Else we get the value as it is since its a primitive type value = fieldValue; } serialization.put(field.getName(), value); } catch (NoSuchMethodException e) { throw new MalformedSdkObjectException(e.getMessage()); } catch (IllegalAccessException e) { throw new MalformedSdkObjectException(e.getMessage()); } catch (InvocationTargetException e) { throw new MalformedSdkObjectException(e.getMessage()); } } return serialization; } }
[ "francesco.andreozzi90@gmail.com" ]
francesco.andreozzi90@gmail.com
d893055aa64b8b639f8ab734f82d91ceb890e3f6
187d4454ec653fc5ae4ec951f322c858371c9083
/src/main/java/com/sbd12/sewamobil/Pkg_Data_Mobil/DataMobilTableModel.java
8fdc8fbc48b3fcf3e6e4246f045346ac0088008d
[]
no_license
resawafa/sbd-rev
9beecff2370612f5fe38cc1e58fcc69acb1957c4
54e0ed1f92abbe1b302d2474c00583fa0c7ecf7c
refs/heads/master
2021-08-23T15:24:11.107714
2017-12-05T11:57:28
2017-12-05T11:57:28
108,084,493
0
0
null
2017-12-05T11:57:07
2017-10-24T06:11:48
Java
UTF-8
Java
false
false
1,280
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 com.sbd12.sewamobil.Pkg_Data_Mobil; import com.sbd12.sewamobil.Pkg_Merk_Mobil.MerkMobil; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @author resas */ public class DataMobilTableModel extends AbstractTableModel{ private List<DataMobil> data; private String[] nameField={"No Polisi","Merk","Owner"}; public void setData(List<DataMobil> data) { this.data=data; } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return nameField.length; } @Override public Object getValueAt(int baris, int kolom) { DataMobil kst=data.get(baris); switch(kolom) { case 0: return kst.getNo_pol(); case 1: return kst.getNama_mobil(); case 2: return kst.getNama_ow(); default : return null; } } @Override public String getColumnName(int column) { return nameField[column]; } }
[ "resas@RESAWAFA" ]
resas@RESAWAFA
0cfb876a93092fcc2f1b8eac2ee90dd9a0e96502
6169a2a6fa27b4cce3f4d23442f5db4daf87cef4
/Challange/Challenge.java
c996379fcd05addc90a5b85d4ae89a4f9549641e
[]
no_license
Mahesh-Dahiphale/Edac-may-2021
03cf0ae1fd48eb79baca75b2f044fb3ea09a1670
4aad258592e72e78a4251070594cab096528fc10
refs/heads/main
2023-06-01T17:38:23.613081
2021-06-12T14:51:19
2021-06-12T14:51:19
365,246,863
0
0
null
null
null
null
UTF-8
Java
false
false
1,669
java
class Challenge { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } Node Swap(Node node) { if (node == null || node.next == null) { return node; } Node prev = node; Node curr = node.next; node = curr; while (true) { Node next = curr.next; curr.next = prev; if (next == null || next.next == null) { prev.next = next; break; } prev.next = next.next; prev = next; curr = prev.next; } return node; } void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { Challenge list = new Challenge(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); System.out.println("Linked list before calling pairwiseSwap() "); list.printList(head); Node st = list.Swap(head); System.out.println(""); System.out.println("Linked list after calling pairwiseSwap() "); list.printList(st); System.out.println(""); } }
[ "noreply@github.com" ]
Mahesh-Dahiphale.noreply@github.com
0d0d45f869abd60eb1c5501b35792bdbdebf967c
9c3b8064a655796c6e6bc557d03c006b5e12159f
/app/src/main/java/com/se340/smartshoveler/helpers/DatabaseHandler.java
c3b0465eb6c16024b57c2ea786875f24fb8ba7d0
[]
no_license
msandwidi/smart-shoveler
6cc2f09b7514043481d1db5c14522743b6ffbcbc
e4962ee127f7237bd47598de033fb6e2b310eff5
refs/heads/master
2020-08-07T02:52:42.443994
2019-11-20T04:13:23
2019-11-20T04:13:23
213,269,447
2
0
null
2019-10-27T21:19:51
2019-10-07T01:03:30
null
UTF-8
Java
false
false
4,694
java
package com.se340.smartshoveler.helpers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.HashMap; /** * Created by Akshay Raj on 13-03-2016. * Snow Corporation Inc. * www.snowcorp.org */ public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "SmartShoverler"; // Login table name private static final String TABLE_LOGIN = "login"; // Login Table Columns names private static final String KEY_ID = "id"; private static final String KEY_UID = "uid"; private static final String KEY_NAME = "name"; private static final String KEY_EMAIL = "email"; private static final String KEY_CREATED_AT = "created_at"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Table Create Statements private static final String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_UID + " TEXT," + KEY_NAME + " TEXT," + KEY_EMAIL + " TEXT UNIQUE," + KEY_CREATED_AT + " TEXT" + ")"; // Creating Tables @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_LOGIN_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN); // Create tables again onCreate(db); } /** * Storing user details in database */ public void addUser(String uid, String name, String email) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_UID, uid); // uid values.put(KEY_NAME, name); // FirstName values.put(KEY_EMAIL, email); // Email // Inserting Row db.insert(TABLE_LOGIN, null, values); db.close(); // Closing database connection } /** * Storing user details in database * * * public void updateProfile(String fname, String lname, String email, String mobile, String aclass, * String school, String profile_pic, String uid) { * SQLiteDatabase db = this.getWritableDatabase(); * ContentValues updateValues = new ContentValues(); * updateValues.put(KEY_FIRSTNAME, fname); // FirstName * updateValues.put(KEY_LASTNAME, lname); // LastName * updateValues.put(KEY_EMAIL, email); // Email * updateValues.put(KEY_MOBILE, mobile); // Mobile Number * updateValues.put(KEY_CLASS, aclass); // Class * updateValues.put(KEY_SCHOOL, school); // School * updateValues.put(KEY_PROFILE_PIC, profile_pic); * <p> * db.update(TABLE_LOGIN, updateValues, KEY_UID + "=?", new String[] { String.valueOf(uid) }); * db.close(); * } * <p> * /** * Getting user data from database */ public HashMap<String, String> getUserDetails() { HashMap<String, String> user = new HashMap<String, String>(); String selectQuery = "SELECT * FROM " + TABLE_LOGIN; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // Move to first row cursor.moveToFirst(); if (cursor.getCount() > 0) { user.put("uid", cursor.getString(1)); user.put("name", cursor.getString(2)); user.put("email", cursor.getString(3)); user.put("created_at", cursor.getString(4)); } cursor.close(); db.close(); // return user return user; } /** * Getting user login status * return true if rows are there in table */ public int getRowCount() { String countQuery = "SELECT * FROM " + TABLE_LOGIN; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); int rowCount = cursor.getCount(); db.close(); cursor.close(); // return row count return rowCount; } /** * Recreate database * Delete all tables and create them again */ public void resetTables() { SQLiteDatabase db = this.getWritableDatabase(); // Delete All Rows db.delete(TABLE_LOGIN, null, null); db.close(); } }
[ "shoudou@outlook.com" ]
shoudou@outlook.com
57e8e71c0514c481a11c49414bf6fd9bd06a7863
ff2661c28514b31377d4c9c162850f9140dc6baa
/goulifront/Tmall-controller/src/main/java/com/it/controller/ProductCategoryController.java
7fdb4f159dbe59f597b083886a2017aa9e319680
[]
no_license
ya724/shoppingmall
ea6ec3a9a1aadb58dd8af0acec65c166ece34497
18c7502ba43d9d12e2061f4d114796c81e4ad524
refs/heads/master
2023-01-30T05:26:26.054514
2020-12-15T04:39:10
2020-12-15T04:39:10
321,519,914
0
0
null
null
null
null
UTF-8
Java
false
false
4,966
java
package com.it.controller; import com.it.bean.ProductCategory; import com.it.service.ProductCategoryService; import com.it.utils.PageUtil; import com.it.utils.ResultCode; import com.it.utils.ResultCommon; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; @Controller public class ProductCategoryController { @Resource ProductCategoryService productCategoryService; @RequestMapping("/productcategory_page") public String ProductCategoryPage(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(value = "product_category_name", defaultValue = "") String product_category_name, @RequestParam(value = "parent_id", defaultValue = "0") Integer parent_id, Model model) { System.out.println("父id:" + parent_id); Map<String, Object> map = new HashMap<>(); map.put("parent_id", parent_id); int allCount = productCategoryService.GetAllCount(map); map.put("product_category_name", product_category_name); map.put("pageStart", (pageIndex - 1) * pageSize); map.put("pageSize", pageSize); List<ProductCategory> productCategories = productCategoryService.GetPageProductCategorys(map); PageUtil pageUtil = new PageUtil(pageIndex, pageSize, allCount, productCategories); boolean flag3 = false;//是否是三级类目 boolean flag2 = false;//是否是三级类目 //动态生成页面的导航条 StringBuffer sb = new StringBuffer("<span><a href=\"/productcategory_page\">顶级分类</a></span>"); if (!parent_id.toString().equals("0")) { ProductCategory category = productCategoryService.findById(parent_id); String name = category.getProduct_category_name(); String str1 = " > <span><a href=\"/productcategory_page?parent_id=" + category.getProduct_category_id() + "\">" + name + "</a></span>"; Integer parent_id1 = category.getParent_id(); ProductCategory category1 = productCategoryService.findById(parent_id1); flag2=true; if (category1 != null) { String name1 = category1.getProduct_category_name(); String str2 = " > <span><a href=\"/productcategory_page?parent_id=" + category1.getProduct_category_id() + "\">" + name1 + "</a></span>"; sb.append(str2); flag3 = true; //表示已经是第三级类目 } sb.append(str1); } model.addAttribute("flag2", flag2); model.addAttribute("flag3", flag3); model.addAttribute("menus", sb.toString()); model.addAttribute("product_category_name", product_category_name); model.addAttribute("pageUtil", pageUtil); model.addAttribute("parent_id",parent_id); return "productCategoryManagePage"; } @ResponseBody @RequestMapping("/productcategory_add") public ResultCommon ProductcategoryAdd(ProductCategory productCategory){ int count=productCategoryService.ProductCategoryAdd(productCategory); if(count>0){ return ResultCommon.success(ResultCode.SUCCESS); }else { return ResultCommon.fail(ResultCode.FAIL); } } @RequestMapping("/productcategory_toadd2") public String ProductcategoryToAdd2(@RequestParam("parent_id") Integer parent_id,Model model){ ProductCategory productCategory = productCategoryService.findById(parent_id); model.addAttribute("productCategory",productCategory); return "productCategoryAdd2Page"; } @RequestMapping("/productcategory_toadd3") public String ProductcategoryToAdd3(@RequestParam("parent_id") Integer parent_id,Model model){ ProductCategory productCategory = productCategoryService.findById(parent_id); //System.out.println(productCategory); model.addAttribute("productCategory",productCategory); return "productCategoryAdd3Page"; } @ResponseBody @RequestMapping("/productcategory_add3") public ResultCommon ProductcategoryAdd3(ProductCategory productCategory,String[] propertyname){ int count=productCategoryService.ProductCategoryAdd(productCategory,propertyname); if(count>0){ return ResultCommon.success(ResultCode.SUCCESS); }else { return ResultCommon.fail(ResultCode.FAIL); } } }
[ "1018668430@qq.com" ]
1018668430@qq.com
602f7d52202076800da21225b56b85fa52b9916c
d94c51fc3eadbf6de5e18ab02b68111245f9ffb2
/Java/src/gamelogic/nodes/MultiplyIntDoubleNode.java
e3739c9fce4704393068ab9f922fd2e67851b722
[]
no_license
Asbibi/NodalWorld
7d34b3d78dfc67b34bb530631a0a53b3d846de2e
d4aef9c148243c2938c3ddc72ce82ef370965d31
refs/heads/main
2023-09-01T22:35:18.727212
2021-10-21T20:45:05
2021-10-21T20:45:05
406,709,966
0
0
null
null
null
null
UTF-8
Java
false
false
1,044
java
package gamelogic.nodes; import gamelogic.GameManager; import gamelogic.Input; import gamelogic.NetworkIOException; import gamelogic.Node; import gamelogic.Output; /** * This node allows to multiply int with double. <br/> * Its int output is an approximation for the exact result that is available on the double output.<br/> * * Inputs : a, b <br/> * Outputs : a*b, ~a*b * */ public class MultiplyIntDoubleNode extends Node { public MultiplyIntDoubleNode() { super("Multiply : Int-Double"); addInput(new Input("a", Integer.class)); addInput(new Input("b", Double.class)); addOutput(new Output("~a*b", Integer.class)); addOutput(new Output("a*b", Double.class)); } /** * @param game */ @Override public void evaluate(GameManager game) throws NetworkIOException { int a = getInput("a").getData(Integer.class); double b = getInput("b").getData(Double.class); Double ab = a * b; getOutput("a*b").setData(ab); int ab_ = (int)ab.doubleValue(); if (ab - ab_ > 0.5) ab_++; getOutput("~a*b").setData(ab_); } }
[ "66073617+Asbibi@users.noreply.github.com" ]
66073617+Asbibi@users.noreply.github.com
e3f36cfc180eb97281db9c0fd2e5d9c26abb0b91
4feee031cdd32fbc6a07e871b47338ac42f457de
/src/main/java/com/hanafn/openapi/portal/views/controller/StatsController.java
24c16d1f53d235bac91052635dbdd7bed784079e
[]
no_license
wjsgmlwls79/Hanafn_OpenApi_Portal_Server
078c6100603214e1e6d45de1f95139ea4e0e1916
564c89d76b8897a3cae3b2fe2365ae4c8e07cb7e
refs/heads/master
2022-04-08T05:52:35.058789
2020-01-23T14:38:53
2020-01-23T14:38:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,302
java
package com.hanafn.openapi.portal.views.controller; import com.hanafn.openapi.portal.security.CurrentUser; import com.hanafn.openapi.portal.security.UserPrincipal; import com.hanafn.openapi.portal.views.dto.*; import com.hanafn.openapi.portal.views.service.SettingService; import com.hanafn.openapi.portal.views.service.StatsService; import com.hanafn.openapi.portal.views.vo.UseorgVO; import com.hanafn.openapi.portal.views.vo.UserVO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority; 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 javax.validation.Valid; import java.util.Collection; @RestController @RequestMapping("/api") @Slf4j @RequiredArgsConstructor public class StatsController { private final StatsService statsService; private final SettingService settingService; @PostMapping("/dashBoard") public ResponseEntity<?> dashBoard(@CurrentUser UserPrincipal currentUser, @Valid @RequestBody DashBoardRequest request) { Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities(); for(GrantedAuthority ga : authorities) { if(ga.getAuthority() != "ROLE_SYS_ADMIN") { request.setHfnCd(currentUser.getHfnCd()); request.setUserKey(currentUser.getUserKey()); break; } } DashBoardRsponse data = statsService.dashBoard(request); return ResponseEntity.ok(data); } @PostMapping("/userorgDashBoard") public ResponseEntity<?> userorgDashBoard(@CurrentUser UserPrincipal currentUser, @Valid @RequestBody DashBoardRequest.UseorgDashBoardRequest request) { request.setEntrCd(currentUser.getEntrCd()); if ("ORGD".equals(currentUser.getUserType())) { request.setUserKey(request.getEntrCd()); } else { request.setUserKey(currentUser.getUserKey()); } DashBoardRsponse.UseorgDashBoardRsponse data = statsService.useorgDashBoard(request); return ResponseEntity.ok(data); } @PostMapping("/apiStats") public ResponseEntity<?> apiStats(@CurrentUser UserPrincipal currentUser, @Valid @RequestBody StatsRequest request) { StatsRsponse data = statsService.apiStats(request); return ResponseEntity.ok(data); } @PostMapping("/useorgStats") public ResponseEntity<?> useorgStats(@CurrentUser UserPrincipal currentUser, @Valid @RequestBody StatsRequest request) { StatsRsponse.UseorgStatsRsponse data = statsService.useorgStats(request); return ResponseEntity.ok(data); } @PostMapping("/useorgAppDetailStats") public ResponseEntity<?> useorgAppDetailStats(@CurrentUser UserPrincipal currentUser, @Valid @RequestBody StatsRequest.AppDetailStatsRequest request) { StatsRsponse.AppApiDetailStatsRsponse data = statsService.useorgAppDetailStats(request); return ResponseEntity.ok(data); } }
[ "wjsgmlwls79@naver.com" ]
wjsgmlwls79@naver.com
8411971db651c7493ff34331a62a8b1f8e7db59f
d6a696da29573a209da4137045701d893f6069b4
/src/test/java/UsersSmokeTest.java
dee8cc56497fc360fada8d4c42531faec43b32a9
[]
no_license
LeraHaidaienko/homework_31_hillel
2f5e30bb28f9b2dbe479ff1c7345fe7cfb14b34c
b5f6f12c79dad452283d204c98af6db59b9f01ab
refs/heads/main
2023-06-22T15:59:07.047505
2021-07-08T19:55:05
2021-07-08T19:55:05
384,232,349
0
0
null
null
null
null
UTF-8
Java
false
false
2,483
java
import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import java.util.Random; public class UsersSmokeTest { public static WebDriver driver; @Test public void updateOwnProfile() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "/Users/user/Desktop/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); // Login driver.get("http://users.bugred.ru/user/login/index.html"); driver.findElement(By.name("login")).sendKeys("random1@test.com"); driver.findElement(By.xpath("//form[@action='/user/login/index.html']//input[@name='password']")).sendKeys("random1"); driver.findElement(By.xpath("//div[@class='row']//div[@class='col-md-6'][1]//input[@type='submit']")).click(); WebElement addUserButton = driver.findElement(By.xpath("//a[text() = 'Добавить пользователя']")); Assert.assertEquals(true, addUserButton.isDisplayed()); // Update profile String newName = "random11"; driver.findElement(By.xpath("//a[@class='dropdown-toggle']")).click(); driver.findElement(By.xpath("//a[contains(text(),'Личный кабинет')]")).click(); driver.findElement(By.name("name")).clear(); driver.findElement(By.name("name")).sendKeys(newName); new Select(driver.findElement(By.name("gender"))).selectByVisibleText("Женский"); driver.findElement(By.name("birthday")).sendKeys("01011990"); driver.findElement(By.name("date_start")).sendKeys("01012020"); driver.findElement(By.name("hobby")).clear(); driver.findElement(By.name("hobby")).sendKeys("my_new_hobby"); driver.findElement(By.name("inn")).sendKeys("123451234512"); driver.findElement(By.name("act_profile_now")).click(); driver.findElement(By.xpath("//div[@id='main-menu']//li[@class='newlink']//a[@href='/']")).click(); driver.findElement(By.name("q")).sendKeys(newName); driver.findElement(By.xpath("//button[@type='submit']")).click(); int newUserNumber = driver.findElements(By.xpath("//tbody[@class='ajax_load_row']//tr")).size(); Assert.assertEquals(true, newUserNumber > 0); driver.quit(); } }
[ "valeriia.haidaienko@gmail.com" ]
valeriia.haidaienko@gmail.com
70b86b6ce3b1b5fc2659d301a48f71607a31cc40
0aee0b86f03b1daa807031ba4cd413b3daeb01c8
/src/TSPinclinaciones/Individuo.java
24dbaa4102fd1d8a4e4e820b892f325c6d57dbfa
[]
no_license
koke050800/AlgoritmosGeneticos
2be2ba79aae204aa792d47900b34655e294a0bab
f33f3de125848fc237b513c17ca86fc804977dbd
refs/heads/master
2023-05-27T16:21:13.431599
2021-06-16T17:45:12
2021-06-16T17:45:12
348,551,863
0
0
null
null
null
null
UTF-8
Java
false
false
6,208
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 TSPinclinaciones; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /** * * @author KOKE */ public class Individuo { private int[] genotipo; private int fitness; private int fitnessInclinaciones; private double fitnessGeneral; public int[][] distanciasCaminos; public int[] inclinaciones; public Individuo() { } public Individuo(int ciudadInicial, int matrizCargada[][], int[] inclinaciones) { genotipo = new int[matrizCargada[0].length]; genotipo[0] = ciudadInicial; this.distanciasCaminos = matrizCargada; this.inclinaciones = inclinaciones; crearGenotipoAleatorio(); calcularFitness(); calcularFitnessInclinaciones(); calcularFitnessGeneral(); } public Individuo(int genotipo[], int matrizCargada[][], int[] inclinaciones) { this.genotipo = genotipo.clone(); this.distanciasCaminos = matrizCargada; this.inclinaciones = inclinaciones; calcularFitness(); calcularFitnessInclinaciones(); calcularFitnessGeneral(); } public Individuo(int ciudadInicial, int nCiudades, int limiteInclinacion) { genotipo = new int[nCiudades]; genotipo[0] = ciudadInicial; this.distanciasCaminos = HerramientasTSP.inicializaCaminos(nCiudades); HerramientasTSP.generarInclinaciones(nCiudades, limiteInclinacion); this.inclinaciones = HerramientasTSP.getInclinaciones().clone(); crearGenotipoAleatorio(); calcularFitness(); calcularFitnessInclinaciones(); calcularFitnessGeneral(); } public void calcularFitness() { this.fitness = 0; if (distanciasCaminos != null) { this.fitness = 0; for (int j = 1; j < distanciasCaminos.length; j++) { this.fitness += distanciasCaminos[this.genotipo[j - 1]][this.genotipo[j]]; //System.out.println("Sumado: " + distanciasCaminos[this.genotipo[j - 1]][this.genotipo[j]]); } this.fitness += distanciasCaminos[this.genotipo[0]][this.genotipo[distanciasCaminos.length - 1]]; //System.out.println("Sumado: " + distanciasCaminos[this.genotipo[0]][this.genotipo[distanciasCaminos.length - 1]]); //System.out.println("Fitness: " + this.fitness); } } public void calcularFitnessInclinaciones() { // recorrer el individudo y consultamos las inclinaciones for (int x = 0; x < this.genotipo.length - 1; x++) { this.fitnessInclinaciones += inclinaciones[this.genotipo[x]] - inclinaciones[this.genotipo[x + 1]]; } // agregamos la inclinacion de la ultima a la inicial this.fitnessInclinaciones += inclinaciones[this.genotipo[this.genotipo.length - 1]] - inclinaciones[this.genotipo[0]]; } private void calcularFitnessGeneral() { // 1er Forma this.fitnessGeneral = (0.5) * Math.abs(fitness) + (0.5) * Math.abs(fitnessInclinaciones); } public void calcularFitness2() { this.fitness = 0; if (distanciasCaminos != null) { this.fitness = 0; for (int j = 1; j < distanciasCaminos.length; j++) { this.fitness += distanciasCaminos[this.genotipo[j - 1]][this.genotipo[j]]; System.out.println("Sumado: " + distanciasCaminos[this.genotipo[j - 1]][this.genotipo[j]]); } this.fitness += distanciasCaminos[this.genotipo[0]][this.genotipo[distanciasCaminos.length - 1]]; System.out.println("Sumado: " + distanciasCaminos[this.genotipo[0]][this.genotipo[distanciasCaminos.length - 1]]); System.out.println("Fitness: " + this.fitness); } } public void crearGenotipoAleatorio() { ArrayList<Integer> ciudades = new ArrayList<>(); for (int x = 0; x < genotipo.length; x++) { ciudades.add(x); } ciudades.remove(this.genotipo[0]); Random ran = new Random(); // llenar los espacios vacios restantes del genotipo for (int x = 1; x < genotipo.length; x++) { int pos = ran.nextInt(ciudades.size()); int c = ciudades.get(pos); this.genotipo[x] = c; // eliminamos de las ciudades ciudades.remove(pos); } //System.out.println("Gebotipo creado aleatorio-> "+Arrays.toString(genotipo)); } public void actualizarIndividuo(){ calcularFitness(); calcularFitnessInclinaciones(); calcularFitnessGeneral(); } public void setGenotipo(int[] genotipo) { this.genotipo = genotipo; } public void setFitness(int fitness) { this.fitness = fitness; } public void setFitness() { calcularFitness(); } public void setDistanciasCaminos(int[][] distanciasCaminos) { this.distanciasCaminos = distanciasCaminos; } public int[] getGenotipo() { return genotipo; } public int getFitness() { return fitness; } public int[][] getDistanciasCaminos() { return distanciasCaminos; } public int getFitnessInclinaciones() { return fitnessInclinaciones; } public void setFitnessInclinaciones(int fitnessInclinaciones) { this.fitnessInclinaciones = fitnessInclinaciones; } public int[] getInclinaciones() { return inclinaciones; } public void setInclinaciones(int[] inclinaciones) { this.inclinaciones = inclinaciones; } public double getFitnessGeneral() { return fitnessGeneral; } public void setFitnessGeneral(double fitnessGeneral) { this.fitnessGeneral = fitnessGeneral; } }
[ "KOKE@DESKTOP-A3DTITB" ]
KOKE@DESKTOP-A3DTITB
80ed44d6318b3d4eba19075d18ed6ce6f7bcceea
dc38ac4c26b4c642f0ebb78a85060366e7405093
/src/main/java/CalendarPage.java
4c88418c21ba04307213f71517019032783e78f4
[]
no_license
Alatiel/NewC
7c873005fb60275cb41e0ff69bc0e0e29c678e6a
0cd9656715a5200f5642891a93a4467acde9a2a6
refs/heads/master
2021-04-15T15:38:16.513544
2018-03-23T14:59:17
2018-03-23T14:59:17
126,499,078
0
0
null
null
null
null
UTF-8
Java
false
false
30
java
public class CalendarPage { }
[ "NOfate281" ]
NOfate281
a7f0488a5d09d48a98b912bf2f4634889df7e5c5
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project47/src/test/java/org/gradle/test/performance47_2/Test47_118.java
e1bd4d0220a88de274ab1b688b64a070754897ef
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
292
java
package org.gradle.test.performance47_2; import static org.junit.Assert.*; public class Test47_118 { private final Production47_118 production = new Production47_118("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
447e894172282f8aaf37a589b1716636703ae4c0
d5bf67b727abe367b9162b7ec3d9912ddc730c11
/yixin-edu/yixin-edu-model/src/main/java/com/yixin/edu/model/system/SysDictionaryValue.java
35bd39673cc5f5318e0ba7b6e1562db8c748e752
[]
no_license
bingwumeihuo/xcEduService
a9a34ea33ba841e4d63efc7abea924223117509a
338cd33131f022e54b86f1dd602edb22397fbf56
refs/heads/master
2022-12-02T12:35:51.180120
2019-08-21T06:16:32
2019-08-21T06:16:32
202,681,855
0
0
null
2022-11-24T06:26:45
2019-08-16T07:39:15
Java
UTF-8
Java
false
false
386
java
package com.yixin.edu.model.system; import lombok.Data; import lombok.ToString; import org.springframework.data.mongodb.core.mapping.Field; /** * Created by admin on 2018/2/6. */ @Data @ToString public class SysDictionaryValue { @Field("sd_id") private String sdId; @Field("sd_name") private String sdName; @Field("sd_status") private String sdStatus; }
[ "1183223389@qq.com" ]
1183223389@qq.com
a0e9d14bdc5aecf051cf368966327b41feaba928
43e6c5b05eb1ea591e896f1924be37d80ae6e0be
/ticketServer/src/main/java/com/ticket/czc/tickets/service/impl/OrderManageServiceImpl.java
82d62216c7f32b00a4d7b268298e024745f8c71c
[]
no_license
caizhaochen/J2EE_OnlineTickets
70f926d7d1af96c1222856751f72c40078b45f54
8c3f0589c3c9fe6e6f19b7dd46be1c6842855158
refs/heads/master
2020-03-10T17:59:37.368477
2018-07-11T16:05:06
2018-07-11T16:05:06
129,513,876
1
0
null
null
null
null
UTF-8
Java
false
false
13,700
java
package com.ticket.czc.tickets.service.impl; import com.ticket.czc.tickets.common.BackPercent; import com.ticket.czc.tickets.common.Constant; import com.ticket.czc.tickets.dao.OrderDao; import com.ticket.czc.tickets.dao.impl.BaseDaoImpl; import com.ticket.czc.tickets.factory.DaoFactory; import com.ticket.czc.tickets.factory.ServiceFactory; import com.ticket.czc.tickets.model.*; import com.ticket.czc.tickets.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; @Service public class OrderManageServiceImpl implements OrderManageService { private static OrderManageServiceImpl orderManageService=new OrderManageServiceImpl(); public static OrderManageServiceImpl getInstance(){ return orderManageService; } private SeatsManageService seatsManageService= ServiceFactory.getSeatsManageService(); private AccountManageService accountManageService=ServiceFactory.getAccountManageService(); private UsersManageService usersManageService=ServiceFactory.getUserManageService(); private ShowManageService showManageService=ServiceFactory.getShowManageService(); private VenueManageService venueManageService=ServiceFactory.getVenueManageService(); private OrderDao orderDao= DaoFactory.getOrderDao(); // @Autowired // private SeatsManageService seatsManageService; // @Autowired // private AccountManageService accountManageService; // @Autowired // private UsersManageService usersManageService; // @Autowired // private ShowManageService showManageService; // @Autowired // private VenueManageService venueManageService; // @Autowired // private OrderDao orderDao; private ArrayList<OrdersEntity> unCountOrders=new ArrayList<>(); @Override public Integer generateOrder(OrdersEntity ordersEntity) { int orderid=orderDao.saveOrder(ordersEntity); return orderid; } @Override public OrdersEntity getOrder(int orderId) { OrdersEntity order=orderDao.getOrder(orderId); return order; } @Override public void updateOrder(OrdersEntity ordersEntity) { orderDao.updateOrder(ordersEntity); } @Override public void deleteOrder(OrdersEntity ordersEntity) { } @Override public ArrayList<OrdersEntity> getOverDueOrders() { return orderDao.getOverDueOrders(); } @Override public ArrayList<OrdersEntity> getOrdersByUser(String userEmail) { return orderDao.getOrdersByUser(userEmail); } @Override public String backOrder(int orderId) { OrdersEntity order=orderDao.getOrder(orderId); long orderTime=order.getShowtime().getTime(); long nowTime=System.currentTimeMillis(); long min=orderTime-nowTime; double percent= BackPercent.getReducePercent(min); order.setBeforebackprice(order.getTotalprice()); //恢复这笔订单的座位为可以预定的状态 ArrayList<SeatsEntity> seats=seatsManageService.getSeatsByOrder(orderId); for(int i=0;i<seats.size();i++){ seats.get(i).setSeatisbooked(0); } seatsManageService.updateSeats(seats); ShowsEntity showsEntity=showManageService.getShowById(order.getShowid()); showsEntity.setRestseats(showsEntity.getRestseats()+order.getQuantity()); showManageService.updateShow(showsEntity); order.setOrderstatus(3); double oldPrice=order.getTotalprice(); double backMoney=oldPrice*percent; double nowPrice=oldPrice-backMoney; order.setTotalprice(nowPrice); orderDao.updateOrder(order); String userEmail=order.getUseremail(); String accountId=userEmail; UsersEntity user=usersManageService.getUserInfo(userEmail); user.setCredit(user.getCredit()-((int)backMoney+1)); user.setUserconsume(user.getUserconsume()-backMoney); usersManageService.updateUser(user); accountManageService.addMoney(accountId,backMoney); accountManageService.consumeAccount(Constant.ADMIN_ACCOUNT,Constant.ADMIN_PASSWORD,backMoney); return "success"; } @Override public ArrayList<String> checkOrder(int orderId,int venueId) { ArrayList<String> res=new ArrayList<>(); OrdersEntity order=orderDao.getOrder(orderId); if (order==null){ res.add("fail"); res.add("没有此订单!"); return res; } int showId=order.getShowid(); ShowsEntity show=showManageService.getShowById(showId); int venue=show.getVenueid(); if(venue!=venueId){ res.add("fail"); res.add("该订单不是本场馆发布的!"); return res; } if (order.getOrderstatus()==0){ res.add("fail"); res.add("该订单尚未付款!"); return res; } if (order.getOrderstatus()==1){ res.add("fail"); res.add("该订单因未在规定时间内付款已被取消!"); return res; } if (order.getOrderstatus()==3){ res.add("fail"); res.add("该订单已被撤回销毁!"); return res; } if (order.getHascheck().equals("是")){ res.add("fail"); res.add("该订单已被检票过!"); return res; } order.setHascheck("是"); orderDao.updateOrder(order); res.add("success"); return res; } @Override public ArrayList<CountInfo> getCountInfo() { ArrayList<CountInfo> countInfos=new ArrayList<>(); ArrayList<Integer> showIds=orderDao.getUncountShowId(); if(showIds==null||showIds.size()==0){ return null; } for(int i=0;i<showIds.size();i++){ System.out.println("uncountShowId"+showIds.get(i)); ArrayList<OrdersEntity> orders=orderDao.getUnCountOrderByShow(showIds.get(i)); System.out.println(showIds.get(i)); System.out.println(orders.size()); unCountOrders.addAll(orders); CountInfo countInfo=new CountInfo(); int showId=orders.get(0).getShowid(); ShowsEntity show=showManageService.getShowById(showId); countInfo.setShowId(showId); countInfo.setShowName(show.getShowname()); countInfo.setShowDescribe(show.getShowdescribe()); countInfo.setShowPostTime(show.getPosttime()); countInfo.setShowTime(show.getShowtime()); countInfo.setShowType(show.getShowtype()); int venueId=show.getVenueid(); VenuesEntity venue=venueManageService.getVenueInfo(venueId); countInfo.setVenueName(venue.getVenuename()); double origin=0.0; double venueM=0.0; double adminM=0.0; for(int j=0;j<orders.size();j++){ double price=orders.get(j).getTotalprice(); origin=origin+price; } venueM=venueM+origin*Constant.BENIFIT; adminM=adminM+origin-venueM; countInfo.setOriginMoney(origin); countInfo.setVenueGet(venueM); countInfo.setAdminGet(adminM); countInfos.add(countInfo); } return countInfos; } @Override public ArrayList<String> payForVenue(int showId,double venueM,double adminM) { ArrayList<String> res=new ArrayList<>(); if (unCountOrders==null||unCountOrders.size()==0){ res.add("fail"); res.add("操作失败,请刷新界面!"); return res; } double percent=Constant.BENIFIT; ArrayList<OrdersEntity> orders=new ArrayList<>(); for(int i=0;i<unCountOrders.size();i++){ if(unCountOrders.get(i).getShowid()==showId && unCountOrders.get(i).getIscount()==0){ System.out.println("即将结算的orderId"+unCountOrders.get(i).getOrderid()); unCountOrders.get(i).setIscount(1); // unCountOrders.get(i).setVenueget(unCountOrders.get(i).getTotalprice()* percent); orders.add(unCountOrders.get(i)); } } if(orders==null||orders.size()==0){ res.add("success"); return res; } ShowsEntity show=showManageService.getShowById(showId); show.setVenueget(show.getVenueget()+venueM); show.setAdminget(show.getAdminget()+adminM); showManageService.updateShow(show); orderDao.updateOrders(orders); accountManageService.consumeAccount(Constant.ADMIN_ACCOUNT,Constant.ADMIN_PASSWORD,venueM); res.add("success"); return res; } @Override public ArrayList<VenueShowInfo> getVenueShowByVenue(int venueId) { ArrayList<VenueShowInfo> venueShowInfos=new ArrayList<>(); ArrayList<ShowsEntity> shows=showManageService.getAllShowByVenue(venueId); if(shows==null){ return null; } for(int i=0;i<shows.size();i++){ VenueShowInfo venueShowInfo=new VenueShowInfo(); venueShowInfo.setShow(shows.get(i)); int showId=shows.get(i).getShowid(); int checkOrders=0; int checkSeats=0; ArrayList<OrdersEntity> onlineOrders=orderDao.getPayOnlineOrdersByShow(showId); if(onlineOrders==null){ venueShowInfo.setOnlinePayNum(0); venueShowInfo.setOnlinePayIncome(0.0); }else{ venueShowInfo.setOnlinePayNum(onlineOrders.size()); double onlinePay=0.0; for(int j=0;j<onlineOrders.size();j++){ onlinePay=onlinePay+onlineOrders.get(j).getTotalprice()*Constant.BENIFIT; if(onlineOrders.get(j).getHascheck().equals("是")){ checkOrders++; checkSeats=checkSeats+onlineOrders.get(j).getQuantity(); } } venueShowInfo.setOnlinePayIncome(onlinePay); } ArrayList<OrdersEntity> realOrders=orderDao.getPayRealOrdersByShow(showId); if(realOrders==null){ venueShowInfo.setRealPayNum(0); venueShowInfo.setRealPayIncome(0.0); } else { venueShowInfo.setRealPayNum(realOrders.size()); double realPay=0.0; for(int j=0;j<realOrders.size();j++){ realPay=realPay+realOrders.get(j).getTotalprice(); if(realOrders.get(j).getHascheck().equals("是")){ checkOrders++; checkSeats=checkSeats+realOrders.get(j).getQuantity(); } } venueShowInfo.setRealPayIncome(realPay); } venueShowInfo.setCheckOrders(checkOrders); venueShowInfo.setCheckSeats(checkSeats); ArrayList<OrdersEntity> backOrders=orderDao.getBackOrderByShow(showId); if (backOrders==null){ venueShowInfo.setBackNum(0); venueShowInfo.setBackIncome(0.0); }else { venueShowInfo.setBackNum(backOrders.size()); double backPay=0.0; for(int j=0;j<backOrders.size();j++){ backPay=backPay+backOrders.get(j).getTotalprice()*Constant.BENIFIT; } venueShowInfo.setBackIncome(backPay); } venueShowInfos.add(venueShowInfo); } return venueShowInfos; } @Override public TicketsOrderInfo getTicketsOrderInfo() { ArrayList<OrdersEntity> onlineOrders=orderDao.getAllOnlineOrders(); ArrayList<OrdersEntity> realOrders=orderDao.getAllRealOrders(); ArrayList<OrdersEntity> backOrders=orderDao.getAllBackOrders(); double onlineOrderPrice=0.0; double realOrderPrice=0.0; double backOrderPrice=0.0; int onlineOrderNum=0; int realorderNum=0; int backOrderNum=0; if(onlineOrders!=null){ onlineOrderNum=onlineOrders.size(); for(int i=0;i<onlineOrderNum;i++){ onlineOrderPrice=onlineOrderPrice+onlineOrders.get(i).getTotalprice(); } } if(realOrders!=null){ realorderNum=realOrders.size(); for(int i=0;i<realorderNum;i++){ realOrderPrice=realOrderPrice+realOrders.get(i).getTotalprice(); } } if(backOrders!=null){ backOrderNum=backOrders.size(); for (int i=0;i<backOrderNum;i++){ backOrderPrice=backOrderPrice+backOrders.get(i).getTotalprice(); } } TicketsOrderInfo ticketsOrderInfo=new TicketsOrderInfo(); ticketsOrderInfo.setOnlineOrderNum(onlineOrderNum); ticketsOrderInfo.setOnlineOrderPrice(onlineOrderPrice); ticketsOrderInfo.setOnlineOrderBenifit(onlineOrderPrice-onlineOrderPrice*Constant.BENIFIT); ticketsOrderInfo.setRealOrderNum(realorderNum); ticketsOrderInfo.setRealOrderPrice(realOrderPrice); ticketsOrderInfo.setRealOrderBenifit(0.0); ticketsOrderInfo.setBackOrderNum(backOrderNum); ticketsOrderInfo.setBackOrderPrice(backOrderPrice); ticketsOrderInfo.setBackOrderBenifit(backOrderPrice-backOrderPrice*Constant.BENIFIT); return ticketsOrderInfo; } public static void main(String[] args){ } }
[ "731744067@qq.com" ]
731744067@qq.com
ea989c57423c80416af8f7fb9c9ba6ab771f3cb0
9d537912eec1337eeab520ce80645f315904b90e
/src/main/java/com/concesionario3/config/LiquibaseConfiguration.java
3ef4b993058e6b7cde7b2034a68d39c99a006506
[]
no_license
Fireful/concesionario3
63b7fea625dd3d36b873c7449d30257d74cdbade
96fc0e8088bea9a6eb003524797b1206a51089e7
refs/heads/master
2023-01-28T08:19:13.175806
2020-12-02T23:45:07
2020-12-02T23:45:07
303,700,192
0
0
null
null
null
null
UTF-8
Java
false
false
3,209
java
package com.concesionario3.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.liquibase.SpringLiquibaseUtil; import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import javax.sql.DataSource; import java.util.concurrent.Executor; @Configuration public class LiquibaseConfiguration { private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); private final Environment env; public LiquibaseConfiguration(Environment env) { this.env = env; } @Bean public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor, @LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, LiquibaseProperties liquibaseProperties, ObjectProvider<DataSource> dataSource, DataSourceProperties dataSourceProperties) { // If you don't want Liquibase to start asynchronously, substitute by this: // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema()); liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace()); liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); liquibase.setLabels(liquibaseProperties.getLabels()); liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) { liquibase.setShouldRun(false); } else { liquibase.setShouldRun(liquibaseProperties.isEnabled()); log.debug("Configuring Liquibase"); } return liquibase; } }
[ "firefuldaw@gmail.com" ]
firefuldaw@gmail.com
b58d4987f6b5e7b0a37a04e5aa631c21c5c1393d
fe66593bc27c0ab9ffb93c4cf06f1f3076bd28ab
/TwT/src/main/java/com/fp/twt/common/social/NaverLoginBO.java
10e494adeb4606ae37d76b5e5b69ebbf4a9688b4
[]
no_license
SUJIIIIII/FinalProject-TwT
92ef1de2112804999d522bb24c578a4525786074
c05325bb3ca11265e9f3a8c92f12a846ad829d71
refs/heads/master
2022-10-20T06:16:21.480723
2020-03-19T11:29:23
2020-03-19T11:29:23
238,854,815
0
1
null
2022-10-19T02:04:24
2020-02-07T06:02:15
Java
UTF-8
Java
false
false
3,967
java
package com.fp.twt.common.social; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import javax.servlet.http.HttpSession; import org.springframework.util.StringUtils; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth.OAuth20Service; public class NaverLoginBO { /* 인증 요청문을 구성하는 파라미터 */ // client_id: 애플리케이션 등록 후 발급받은 클라이언트 아이디 // response_type: 인증 과정에 대한 구분값. code로 값이 고정돼 있습니다. // redirect_uri: 네이버 로그인 인증의 결과를 전달받을 콜백 URL(URL 인코딩). 애플리케이션을 등록할 때 Callback // URL에 설정한 정보입니다. // state: 애플리케이션이 생성한 상태 토큰 private final static String CLIENT_ID = "zzMGtw5m1Q8z50jqKKAq"; private final static String CLIENT_SECRET = "cC62mbwUTm"; private final static String REDIRECT_URI = "http://localhost:8787/twt/callback.do"; private final static String SESSION_STATE = "oauth_state"; /* 프로필 조회 API URL */ private final static String PROFILE_API_URL = "https://openapi.naver.com/v1/nid/me"; /* 네이버 아이디로 인증 URL 생성 Method */ public String getAuthorizationUrl(HttpSession session) { /* 세션 유효성 검증을 위하여 난수를 생성 */ String state = generateRandomString(); /* 생성한 난수 값을 session에 저장 */ setSession(session, state); /* Scribe에서 제공하는 인증 URL 생성 기능을 이용하여 네아로 인증 URL 생성 */ OAuth20Service oauthService = new ServiceBuilder().apiKey(CLIENT_ID).apiSecret(CLIENT_SECRET) .callback(REDIRECT_URI).state(state) // 앞서 생성한 난수값을 인증 URL생성시 사용함 .build(NaverLoginApi.instance()); return oauthService.getAuthorizationUrl(); } /* 네이버아이디로 Callback 처리 및 AccessToken 획득 Method */ public OAuth2AccessToken getAccessToken(HttpSession session, String code, String state) throws IOException { /* Callback으로 전달받은 세선검증용 난수값과 세션에 저장되어있는 값이 일치하는지 확인 */ String sessionState = getSession(session); if (StringUtils.pathEquals(sessionState, state)) { OAuth20Service oauthService = new ServiceBuilder().apiKey(CLIENT_ID).apiSecret(CLIENT_SECRET) .callback(REDIRECT_URI).state(state).build(NaverLoginApi.instance()); /* Scribe에서 제공하는 AccessToken 획득 기능으로 네아로 Access Token을 획득 */ OAuth2AccessToken accessToken = oauthService.getAccessToken(code); return accessToken; } return null; } /* 세션 유효성 검증을 위한 난수 생성기 */ private String generateRandomString() { return UUID.randomUUID().toString(); } /* http session에 데이터 저장 */ private void setSession(HttpSession session, String state) { session.setAttribute(SESSION_STATE, state); } /* http session에서 데이터 가져오기 */ private String getSession(HttpSession session) { return (String) session.getAttribute(SESSION_STATE); } /* Access Token을 이용하여 네이버 사용자 프로필 API를 호출 */ public String getUserProfile(OAuth2AccessToken oauthToken) throws IOException { OAuth20Service oauthService = new ServiceBuilder().apiKey(CLIENT_ID).apiSecret(CLIENT_SECRET) .callback(REDIRECT_URI).build(NaverLoginApi.instance()); OAuthRequest request = new OAuthRequest(Verb.GET, PROFILE_API_URL, oauthService); oauthService.signRequest(oauthToken, request); Response response = request.send(); return response.getBody(); } }
[ "56878724+bxxmi@users.noreply.github.com" ]
56878724+bxxmi@users.noreply.github.com
f3844b482c27de8f486507a7451b98cce6f9bcb9
b20a86ce19e01d30f0260de6512e037b59e2ecd0
/iGrid/modules/tools/boot/src/sorcer/provider/boot/PlatformLoader.java
80308c22a5d6397c619d1e7bba22d1a3f0269a52
[]
no_license
mwsobol/iGrid
0ea729b69d417320d6d9233784ab2919df42ec03
b6c6384deb32e570f476c215cb93a5191084b366
refs/heads/master
2021-01-23T13:22:28.149192
2014-07-14T12:53:37
2014-07-14T12:53:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,595
java
/* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.provider.boot; import java.io.File; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import sorcer.core.provider.util.PropertyHelper; /** * Parses platform configuration documents * * @author Dennis Reedy */ public class PlatformLoader { static final String COMPONENT = "sorcer.provider.boot"; static final Logger logger = Logger.getLogger(COMPONENT); /** * Parse the platform * * @param directory The directory to search for XML configuration documents * * @return An array of Capability objects * * @throws Exception if there are errors parsing the configuration files */ public Capability[] parsePlatform(String directory) throws Exception { if(directory == null) throw new IllegalArgumentException("directory is null"); List<Capability> platformList = new ArrayList<Capability>(); File dir = new File(directory); if(dir.exists()) { if(dir.isDirectory()) { if(dir.canRead()) { File[] files = dir.listFiles(); for (File file : files) { if (file.getName().endsWith("xml") || file.getName().endsWith("XML")) { try { platformList.addAll( parsePlatform(file.toURI().toURL())); } catch (Exception e) { logger.log(Level.WARNING, "Could not parse ["+file.getAbsolutePath()+"], " + "continue building platform", e); } } } } else { logger.warning("No read permissions for platform " + "directory ["+directory+"]"); } } else { logger.warning("Platform directory ["+dir+"] " + "is not a directory"); } } else { logger.warning("Platform directory ["+directory+"] not found"); } Capability[] caps = platformList.toArray(new Capability[platformList.size()]); logger.finer("Platform capabilities: " + Arrays.toString(caps)); return caps; } /* * Parse the platform */ Collection<Capability> parsePlatform(URL configURL) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream is = configURL.openStream(); Collection<Capability> caps = new ArrayList<Capability>(); try { Document document = builder.parse(is); Element element = document.getDocumentElement(); if ((element != null) && element.getTagName().equals("platform")) { caps.addAll(visitElement_platform(element, configURL.toExternalForm())); } } finally { is.close(); } return(caps); } /* * Scan through Element named platform. */ Collection<Capability> visitElement_platform(Element element, String configFile) { List<Capability> capabilities = new ArrayList<Capability>(); NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if(node.getNodeType()==Node.ELEMENT_NODE) { Element nodeElement = (Element)node; if (nodeElement.getTagName().equals("capability")) { Capability cap = visitElement_capability(nodeElement); if(cap.getPath()!=null) { File file = new File(cap.getPath()); if(file.exists()) capabilities.add(cap); else logger.warning("Platform configuration " + "for ["+cap+"] not loaded, " + "the path ["+cap.getPath()+"] " + "does not exist. Make sure the " + "configuration file " + "["+configFile+"] " + "is correct, or delete the file " + "if it no longer references a " + "valid capability"); } else if(cap.getClasspath()!=null) { String[] classpath = cap.getClasspath(); boolean okay = true; String failedClassPathEntry = null; for(String s : classpath) { File file = new File(s); if(!file.exists()) { failedClassPathEntry = file.getName(); okay = false; break; } } if(okay) capabilities.add(cap); else { StringBuffer sb = new StringBuffer(); for(String s : cap.getClasspath()) { if(sb.length()>0) sb.append(" "); sb.append(s); } logger.warning("Platform configuration " + "for ["+cap+"] not loaded, " + "could not locate classpath " + "entry ["+failedClassPathEntry+"]. The "+ "classpath ["+sb.toString()+"] " + "is invalid. Make sure the " + "configuration file " + "["+configFile+"] is " + "correct, or delete the file " + "if it no longer references a " + "valid capability"); } } else { capabilities.add(cap); } } } } return(capabilities); } /* * Scan through Element named capability. */ Capability visitElement_capability(Element element) { // <capability> // element.getValue(); Capability cap = new Capability(); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr)attrs.item(i); if (attr.getName().equals("common")) { // <capability common="???"> cap.setCommon(attr.getValue()); } if (attr.getName().equals("name")) { // <capability name="???"> cap.setName(attr.getValue()); } if (attr.getName().equals("class")) { // <capability class="???"> cap.setPlatformClass(attr.getValue()); } } NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if(node.getNodeType()==Node.ELEMENT_NODE) { Element nodeElement = (Element)node; if(nodeElement.getTagName().equals("description")) { cap.setDescription(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("version")) { cap.setVersion(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("manufacturer")) { cap.setManufacturer(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("classpath")) { cap.setClasspath(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("path")) { cap.setPath(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("native")) { cap.setNativeLib(getTextValue(nodeElement)); } if(nodeElement.getTagName().equals("costmodel")) { cap.setCostModelClass(getTextValue(nodeElement)); } } } return(cap); } /** * Get the text value for a node * * @param node The Node to get the text value for * @return The text value for the Node, or a zero-length String if * the Node is not recognized */ String getTextValue(Node node) { NodeList eList = node.getChildNodes(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < eList.getLength(); i++) { Node n = eList.item(i); if (n.getNodeType() == Node.ENTITY_REFERENCE_NODE) { sb.append(getTextValue(n)); } else if (n.getNodeType() == Node.TEXT_NODE) { sb.append(n.getNodeValue()); } } return(replaceProperties(sb.toString().trim())); } String replaceProperties(String arg) { return(PropertyHelper.expandProperties(arg, PropertyHelper.PARSETIME)); } URL getURL(String location) throws MalformedURLException { URL url; if(location.startsWith("http") || location.startsWith("file:")) { url = new URL(location); } else { url = new File(location).toURI().toURL(); } return(url); } /** * Get the default platform configuration * * @return An array of Capability objects returned from parsing the * default configuration META-INF/platform.xml * * @throws Exception if there are errors parsing and/or processing the * default configuration */ public Capability[] getDefaultPlatform() throws Exception { URL platformConfig = PlatformLoader.class.getClassLoader().getResource("META-INF/platform.xml"); if(platformConfig==null) { throw new RuntimeException("META-INF/platform.xml not found"); } Collection<Capability> c = parsePlatform(platformConfig); return(c.toArray(new Capability[c.size()])); } /** * Contains attributes for a platform capability. */ public static class Capability { String name; String description; String manufacturer; String version; String classpath; String path; String nativeLib; String common="false"; static String DEFAULT_PLATFORM_CLASS = "sorcer.provider.system.capability.software.SoftwareSupport"; String platformClass =DEFAULT_PLATFORM_CLASS; String costModelClass; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String[] getClasspath() { if(classpath==null) return(new String[0]); StringTokenizer st = new StringTokenizer(classpath); String[] paths = new String[st.countTokens()]; int n=0; while (st.hasMoreTokens ()) { paths[n++] = st.nextToken(); } return paths; } public URL[] getClasspathURLs() throws MalformedURLException { String[] classpath = getClasspath(); return(Booter.toURLs(classpath)); } public void setClasspath(String classpath) { this.classpath = classpath; } public String getNativeLib() { return nativeLib; } public void setNativeLib(String nativeLib) { this.nativeLib = nativeLib; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public boolean getCommon() { return Boolean.parseBoolean(common.equals("yes")?"true":"false"); } public void setCommon(String common) { this.common = common; } public String getPlatformClass() { return platformClass; } public void setPlatformClass(String platformClass) { this.platformClass = platformClass; } public String geCostModelClass() { return costModelClass; } public void setCostModelClass(String costModelClass) { this.costModelClass = costModelClass; } public String toString() { return "Capability{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", manufacturer='" + manufacturer + '\'' + ", version='" + version + '\'' + ", classpath='" + classpath + '\'' + ", path='" + path + '\'' + ", native='" + nativeLib + '\'' + ", common='" + common + '\'' + ", platformClass='" + platformClass + '\'' + ", costModelClass='" + costModelClass + '\'' + '}'; } } }
[ "sobol@sorcersoft.org" ]
sobol@sorcersoft.org
0f551178551276065fc262a59e242abdd11d459d
cab46e3fc74d0f2d1f5731219bb6b12d884d837e
/leetcode/src/com/ran/leetcode/domain/TreeNode.java
b3fdc4d2bd617d54b723675db67618aa3406fc9d
[]
no_license
rancetao/Leetcode
34f7b09ccf88c5dc1cf212da5688aa578ad9bd67
5910ff1d95714e15ef6d4863c93b9ac9ddff3d21
refs/heads/master
2021-01-22T07:27:12.815338
2014-11-03T07:43:13
2014-11-03T07:43:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package com.ran.leetcode.domain; public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
[ "tao.rance@gmail.com" ]
tao.rance@gmail.com
ba18e392ea82522065f246055924a71c261958dd
eacbddcfa0dcf729dd552e808350448726a5c865
/uo.diesels.model/src-gen/uo/diesels/model/modelDsl/MethodAllModelReturn.java
aa78ca4d517fd068bdec51147c0cf5300cb17113
[]
no_license
carlosord/DieselsPlus
3b088781825ff0608543b22782b25cc1286b827b
a68aabd124ddee0b2f0fcb8cb261d117ca045a54
refs/heads/master
2021-01-23T00:39:53.336238
2017-11-01T20:55:16
2017-11-01T20:55:16
92,829,563
0
0
null
null
null
null
UTF-8
Java
false
false
1,531
java
/** * generated by Xtext 2.10.0 */ package uo.diesels.model.modelDsl; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Method All Model Return</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link uo.diesels.model.modelDsl.MethodAllModelReturn#getReturnType <em>Return Type</em>}</li> * </ul> * * @see uo.diesels.model.modelDsl.ModelDslPackage#getMethodAllModelReturn() * @model * @generated */ public interface MethodAllModelReturn extends Method { /** * Returns the value of the '<em><b>Return Type</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Return Type</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Return Type</em>' reference. * @see #setReturnType(AllModelType) * @see uo.diesels.model.modelDsl.ModelDslPackage#getMethodAllModelReturn_ReturnType() * @model * @generated */ AllModelType getReturnType(); /** * Sets the value of the '{@link uo.diesels.model.modelDsl.MethodAllModelReturn#getReturnType <em>Return Type</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Return Type</em>' reference. * @see #getReturnType() * @generated */ void setReturnType(AllModelType value); } // MethodAllModelReturn
[ "Jato@DESKTOP-S76222N" ]
Jato@DESKTOP-S76222N
3e2508fce641ce652a0b5c4fee294c31c158a15a
e8a751f7618f7111800ad50f6eed2c46aae58a33
/Leetcode_Java/src/main/java/leetcode/MaximumNumberOfEventsThatCanBeAttended_1353.java
2e82056bfd11b4598571e348f9ae13dc1ccd8abb
[]
no_license
jiweiyu/LC
2bd1bf2ee0d3fffeb38bf7e9518ca1849cc1da1b
cad086a55dd8b762c35770cca8a85e773f5983ac
refs/heads/master
2023-06-17T06:00:09.423604
2021-07-13T23:32:33
2021-07-13T23:32:33
385,759,541
0
0
null
null
null
null
UTF-8
Java
false
false
905
java
package leetcode; import java.util.PriorityQueue; import java.util.Arrays; public class MaximumNumberOfEventsThatCanBeAttended_1353 { public int maxEvents(int[][] events) { PriorityQueue<Integer> pq = new PriorityQueue<>(); // minHeap Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0])); //sort events increasing by start time int i = 0, res = 0, n = events.length; for(int d =1; d<=100000; d++){ while(!pq.isEmpty() && pq.peek() < d){ pq.poll(); // remove events that are already closed } while(i < n && events[i][0] == d){ pq.offer(events[i++][1]); //Add new events that can attend on day d } if(!pq.isEmpty()){ res++; pq.poll(); // use day d to attend to the event close earlier } } return res; } }
[ "ivy.jw.yu@gmail.com" ]
ivy.jw.yu@gmail.com
b05fadaf1c52ac1c8322bd22699e2adb9a920f20
bdafbba233bbb2c85212555af125eec2ea0825ec
/배열/10818.java
a391cda9b6a68588399bd4179effe09d3df8e2f2
[]
no_license
own1019/baekJoon
5cdf38f63e7cb346b7ae29105795c7ee9280cb3b
42274118f3fc5d1a02fb965c60788465ee3084ae
refs/heads/master
2023-06-30T11:58:54.269951
2021-08-06T08:02:06
2021-08-06T08:02:06
372,765,094
0
0
null
null
null
null
UTF-8
Java
false
false
1,373
java
package 배열; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class Main10818 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int a = 0; // 값의 비교가 될 처음 값 int b = 0; // 값의 비교가 될 처음 값 String[] arr = new String[n]; // n만큼 배열생성 // 배열에 입력값 입력 for(int i=0; i<n; i++) { arr[i] = st.nextToken(); } // 비교값 기준 - 배열의 첫번째 값 a = Integer.parseInt(arr[0]); b = Integer.parseInt(arr[0]); for(int i=0; i<n; i++) { if(a >= Integer.parseInt(arr[i])) { // i번째 배열이 비교기준보다 작거나 같다면 a = Integer.parseInt(arr[i]); //해당 배열값을 a에 입력 } else if(b <= Integer.parseInt(arr[i])) { // i번째 배열이 비교기준보다 크거나 같다면 b = Integer.parseInt(arr[i]); //해당 배열값을 b에 입력 } } System.out.println(a + " " + b); br.close(); } }
[ "own1019@naver.com" ]
own1019@naver.com
5a91ec564ec4d10c52d6faf96d4c704d4ecc9827
8c1b0ed3dadb19573fe34fa19aae29fea654ef52
/kie-wb-common-forms/kie-wb-common-forms-core/kie-wb-common-forms-fields/src/main/java/org/kie/workbench/common/forms/fields/shared/fieldTypes/basic/slider/definition/DoubleSliderDefinition.java
25243d7e7763317f40924b1537211d3e7ac6a6f9
[ "Apache-2.0" ]
permissive
pefernan/kie-wb-common
d86b1f045c789bf2ac2d915355e1afc67edc2b1b
567bf6d1c3d1923af6b4be52276354d16f615f62
refs/heads/master
2022-01-29T13:27:30.346208
2017-02-27T16:35:23
2017-02-27T16:35:23
47,341,249
0
1
null
2018-02-23T12:08:31
2015-12-03T15:35:49
Java
UTF-8
Java
false
false
3,098
java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.forms.fields.shared.fieldTypes.basic.slider.definition; import org.jboss.errai.common.client.api.annotations.Portable; import org.jboss.errai.databinding.client.api.Bindable; import org.kie.workbench.common.forms.adf.definitions.annotations.FormDefinition; import org.kie.workbench.common.forms.adf.definitions.annotations.FormField; import org.kie.workbench.common.forms.adf.definitions.annotations.i18n.I18nSettings; import org.kie.workbench.common.forms.model.FieldDefinition; @Portable @Bindable @FormDefinition( i18n = @I18nSettings(keyPreffix = "FieldProperties.slider"), startElement = "label" ) public class DoubleSliderDefinition extends SliderBaseDefinition<Double> { @FormField( labelKey = "min", afterElement = "label" ) protected Double min; @FormField( labelKey = "max", afterElement = "min" ) protected Double max; @FormField( labelKey = "precision", afterElement = "max" ) protected Double precision; @FormField( labelKey = "step", afterElement = "precision" ) protected Double step; public DoubleSliderDefinition() { min = new Double(0.0); max = new Double(50.0); precision = new Double(1.0); step = new Double(1.0); } @Override public Double getMin() { return min; } @Override public void setMin(Double min) { this.min = min; } @Override public Double getMax() { return max; } @Override public void setMax(Double max) { this.max = max; } @Override public Double getPrecision() { return precision; } @Override public void setPrecision(Double precision) { this.precision = precision; } @Override public Double getStep() { return step; } @Override public void setStep(Double step) { this.step = step; } @Override protected void doCopyFrom(FieldDefinition other) { if (other instanceof SliderBaseDefinition) { SliderBaseDefinition otherSlider = (SliderBaseDefinition) other; min = otherSlider.getMin().doubleValue(); max = otherSlider.getMax().doubleValue(); precision = otherSlider.getPrecision().doubleValue(); step = otherSlider.getStep().doubleValue(); } } }
[ "christian.sadilek@gmail.com" ]
christian.sadilek@gmail.com
e009ee7b51c989e813d7fff853cbb74cb5281c25
13cbb329807224bd736ff0ac38fd731eb6739389
/org/omg/CORBA/IMP_LIMIT.java
4eac930ccda729d38a133ab4168a79923a023ce2
[]
no_license
ZhipingLi/rt-source
5e2537ed5f25d9ba9a0f8009ff8eeca33930564c
1a70a036a07b2c6b8a2aac6f71964192c89aae3c
refs/heads/master
2023-07-14T15:00:33.100256
2021-09-01T04:49:04
2021-09-01T04:49:04
401,933,858
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package org.omg.CORBA; public final class IMP_LIMIT extends SystemException { public IMP_LIMIT() { this(""); } public IMP_LIMIT(String paramString) { this(paramString, 0, CompletionStatus.COMPLETED_NO); } public IMP_LIMIT(int paramInt, CompletionStatus paramCompletionStatus) { this("", paramInt, paramCompletionStatus); } public IMP_LIMIT(String paramString, int paramInt, CompletionStatus paramCompletionStatus) { super(paramString, paramInt, paramCompletionStatus); } } /* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\org\omg\CORBA\IMP_LIMIT.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.0.7 */
[ "michael__lee@yeah.net" ]
michael__lee@yeah.net
4eb8650e6b36109231f42b66503795394c99b04a
982e62110d15c7782172630cc991ad7f5a0e8104
/mall-mbg/src/main/java/com/djmanong/mall/pms/controller/ProductLadderController.java
6363acd2a0b41d0d8c290cca255c8f055589d271
[]
no_license
djmanong/mall
f205d601b9dff095c71b6f33de1247405a8a4d5d
f5cf8beb9f1e13799c4f6625f21fbe4df5af62e8
refs/heads/master
2023-04-19T07:46:43.498703
2021-05-05T16:00:17
2021-05-05T16:00:17
355,555,364
0
0
null
null
null
null
UTF-8
Java
false
false
397
java
package com.djmanong.mall.pms.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 产品阶梯价格表(只针对同商品) 前端控制器 * </p> * * @author djmanong * @since 2021-04-10 */ @RestController @RequestMapping("/pms/product-ladder") public class ProductLadderController { }
[ "djmanong@qq.com" ]
djmanong@qq.com
1282277fe7644eeb140ce57dfae92633fdf13e0f
fc715e05ce0015f115debe4d57caf6c1c2cc9c74
/src/main/java/yanry/lib/java/model/event/Event.java
24b8554ba8899c815b7df160b3f7b5f91d709f57
[]
no_license
gdyanry/CommonLib
4f89900e03f7e69ea954a7bb3959666744dff26f
33664c25a3115d950c9ffb4d2d46da9f28d47f07
refs/heads/master
2022-03-09T04:51:53.106571
2022-02-16T08:51:26
2022-02-16T08:51:26
32,911,878
2
0
null
null
null
null
UTF-8
Java
false
false
882
java
package yanry.lib.java.model.event; import yanry.lib.java.model.log.LogLevel; import yanry.lib.java.model.log.Logger; import java.util.HashMap; import java.util.ListIterator; /** * @author: rongyu.yan * @create: 2020-07-25 16:01 **/ public class Event { HashMap<EventInterceptor, ListIterator> iteratorCache = new HashMap<>(); private Logger logger; private LogLevel logLevel; public void configLogger(Logger logger, LogLevel logLevel) { this.logger = logger; this.logLevel = logLevel; } void log(int skipLevel, Object... logParts) { if (logger != null) { logger.concat(1, skipLevel > 0 ? logLevel : LogLevel.Verbose, logParts); } } /** * 获取当前事件的最大分发深度。 * * @return */ public int getCurrentLevel() { return iteratorCache.size(); } }
[ "rongyu.yan@tcl.com" ]
rongyu.yan@tcl.com
c042f94bc28fa45d0470083bd13a82f671b359d6
2d9ab284faebe6dacef550c8200ed9866df86418
/Lab5-1170301007/src/track/NormalTrack.java
5989bdb42bf05d4c158a61f4c478d71b01f9455e
[]
no_license
szm981120/HIT-SoftwareConstrucutre-Class17Lab
f29b0426611a3f3b02d4514378bb9bf43261e087
7ebe3b0a85055c5bd357e1b76b232ecaa318f9a1
refs/heads/master
2021-07-13T01:13:35.376167
2019-07-09T02:34:04
2019-07-09T02:34:04
195,918,462
2
0
null
2020-10-13T14:27:35
2019-07-09T02:33:38
HTML
UTF-8
Java
false
false
1,320
java
package track; /** * A normal circular track. * * @author Shen * */ public class NormalTrack implements Track { // IMMUTABLE // factory method private final double radius; /* * Abstraction function: AF(radius) = radius of this track * * Representation invariant: radius must be positive * * Safety from rep exposure: All representations are defined private and final. All * representations in Observer are immutable. */ // checkRep private void checkRep() { assert this.radius > 0; } /** * Constructor. * * @param radius radius of track, must be positive. */ public NormalTrack(double radius) { this.radius = radius; checkRep(); } @Override public double getRadius() { double radius = this.radius; checkRep(); return radius; } /** * Two tracks are equals only when they have the same radius. */ @Override public boolean equals(Object track) { return track != null && track.getClass() == NormalTrack.class && Double .doubleToLongBits(this.radius) == Double.doubleToLongBits(((NormalTrack) track).radius); } @Override public int hashCode() { long longbits = Double.doubleToLongBits(this.radius); int hashcode = new Long(longbits).intValue(); checkRep(); return hashcode; } }
[ "2508754153@qq.com" ]
2508754153@qq.com
d31c2cea8ab6b69529e39035f14080ce086c0d22
d78506661e79a6caf85ec51b3c58004eff40759c
/chapter02/s231/Simple/src/rickyxe/simple/attr/ReduceAttr.java
35fa931b07acb4e325dc2003e1c255328588fc77
[]
no_license
ricky9090/ComputationStudy
85f49d2d779668da6db106988097876e683df5a1
7a5bf0e58b882efdf96e74a57d73165dbcdde3c4
refs/heads/master
2020-12-07T20:24:58.769964
2020-01-14T09:36:23
2020-01-14T09:36:23
232,790,026
0
0
null
null
null
null
UTF-8
Java
false
false
208
java
package rickyxe.simple.attr; import rickyxe.simple.XEnvironment; import rickyxe.simple.base.XObject; public interface ReduceAttr { boolean reducible(); XObject reduce(XEnvironment environment); }
[ "unreal_star13@126.com" ]
unreal_star13@126.com
87c3d86e94b9a2c1e0445d1f640ba51766290a1b
b2db476829567dee326ec688dd32acbe1071c5f3
/oauth2Microservices-create-withsecurity/src/main/java/leo/demo/democreate/services/PublishReferenceService.java
7643a470d5bac3c4a6ce2daf2ab3858719341886
[]
no_license
lcojunk/oauth2Microservices
ed6a1f0b3e75c38f6425b9e51d13b3d36a828c4a
18f2a299eb246660d24eebb8faf41fb3598f91b7
refs/heads/master
2021-01-16T23:22:20.330814
2016-07-12T14:11:27
2016-07-12T14:11:27
60,122,896
1
0
null
null
null
null
UTF-8
Java
false
false
5,844
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 leo.demo.democreate.services; import java.security.Principal; import java.util.List; import java.util.Map; import static leo.demo.MicroserviceConfig.gson; import static leo.demo.MicroserviceConfig.gsonPretty; import static leo.demo.MicroserviceConfig.referenceFailbackUrl; import leo.demo.democreate.dto.RestResponse; import leo.demo.democreate.model.Reference; import leo.demo.democreate.model.UserInformation; import leo.demo.democreate.utils.LoadBalancerUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * * @author odzhara-ongom */ @Service public class PublishReferenceService { @Autowired private LoadBalancerUtils loadBalancerUtils; static Logger log = Logger.getLogger(PublishReferenceService.class.getName()); @Autowired private CrudReferenceMySQLService mySQLService; private HttpEntity<String> postWithCookies(String url, Object body, UserInformation userInformation) { HttpEntity<String> result = null; if (userInformation == null) { return null; } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Cookie", "JSESSIONID=" + userInformation.getSessionID()); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.set("X-XSRF-TOKEN", userInformation.getXsrfToken()); httpHeaders.set("Authorization", userInformation.getBearerAuthorization()); log.debug("postWithCookies. Headers: " + gson.toJson(httpHeaders)); HttpEntity request = new HttpEntity(body, httpHeaders); RestTemplate restTemplate = new RestTemplate(); result = restTemplate.exchange(url, HttpMethod.POST, request, String.class); return result; } private HttpEntity<String> getWithCookies(String url, UserInformation userInformation) { HttpEntity<String> result = null; if (userInformation == null) { return null; } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Cookie", "JSESSIONID=" + userInformation.getSessionID() + ";XSRF-TOKEN=" + userInformation.getXsrfToken()); httpHeaders.set("Authorization", userInformation.getBearerAuthorization()); HttpEntity request = new HttpEntity(httpHeaders); log.debug("getWithCookies. Headers: " + gson.toJson(httpHeaders)); RestTemplate restTemplate = new RestTemplate(); result = restTemplate.exchange(url, HttpMethod.GET, request, String.class); return result; } private RestResponse publish(Reference request, UserInformation userInformation) { //RestResponse<List<Reference>, CreateReferenceRequest> response = new RestResponse<>(request); RestResponse response = new RestResponse(); response.setRequest(request); try { Reference reference = null; if (request != null && request.getId() != null && userInformation != null) { reference = mySQLService.read(request.getId()); if (reference == null) { response.setError("Reference with id=" + request.getId() + " not found"); log.warn("Reference with id=" + request.getId() + " not found"); return response; } String url = loadBalancerUtils.getServiceUrl("oauth2-search-withsecurity", referenceFailbackUrl).toString() + "/api/references"; // Object responseObject = restTemplate.postForEntity(url, reference, Object.class); Object responseObject = postWithCookies(url, reference, userInformation); response.setResult(responseObject); response.setSuccess(true); } response.setResult(mySQLService.getAll()); return response; } catch (Exception e) { response.setError(e.toString()); log.error(e.toString()); return response; } } public RestResponse<List<Reference>, Reference> publishReference( String id, Principal principal, Map<String, String> headers) { log.info("publishing reference"); log.info("publish headers:" + gsonPretty.toJson(headers)); Reference request = new Reference(); try { request.setId(Long.parseLong(id)); } catch (Exception e) { log.warn("Error parsing reference id" + e.toString()); RestResponse<List<Reference>, Reference> result = new RestResponse<>(); result.setError("Error parsing reference id" + e.toString()); return result; } UserInformation userInformation = new UserInformation(principal, SecurityContextHolder .getContext() .getAuthentication(), headers); userInformation.setXsrfToken(UserInformation.xsrfToken(headers)); log.info("punlishing request: " + gsonPretty.toJson(request)); log.info("userInformation:" + gsonPretty.toJson(userInformation)); RestResponse<List<Reference>, Reference> result = publish(request, userInformation); log.info("Response:" + gsonPretty.toJson(result)); return result; } }
[ "Odzhara-Ongom@adesso.local" ]
Odzhara-Ongom@adesso.local
ea4bd5219ad295d6b9895b532f59cac926bb6ffc
95f05f0a01406ed0636d59ca8cc62a32d53069db
/app/src/main/java/com/example/zengqiang/mycloud/app/MyApplication.java
666a2f3faeda7eab41e3b5dfd279bd823fafef5d
[]
no_license
155960/MyCloud
f8e0c307b4d772395c8c62264dc2ba7f502e05dd
786d6a9a243c1ee7ef42f548947884accb921a34
refs/heads/master
2021-07-03T19:34:32.243628
2017-09-23T03:19:57
2017-09-23T03:19:57
104,451,964
1
0
null
null
null
null
UTF-8
Java
false
false
915
java
package com.example.zengqiang.mycloud.app; import android.app.Application; import android.content.res.Configuration; import android.content.res.Resources; import com.example.http.HttpUtils; import com.example.zengqiang.mycloud.utils.DebugUtils; /** * Created by zengqiang on 2017/8/20. */ public class MyApplication extends Application { private static MyApplication myApplication; public static MyApplication getInstance(){ return myApplication; } @Override public void onCreate() { super.onCreate(); myApplication=this; HttpUtils.getInstance().init(this, DebugUtils.DEBUG); initTextSize(); } private void initTextSize(){ Resources res=getResources(); Configuration configuration=new Configuration(); configuration.setToDefaults(); res.updateConfiguration(configuration,res.getDisplayMetrics()); } }
[ "1559603546@qq.com" ]
1559603546@qq.com
dc42499e312243cd447933aec6c9fda991282474
01ebbc94cd4d2c63501c2ebd64b8f757ac4b9544
/backend/gxqpt-msgs/gxqpt-msgs-api/src/main/java/com/hengyunsoft/platform/msgs/open/msg/hystrix/BacklogApiHystrix.java
901bcf4514a5df749ec939f3fa044040e55359cb
[]
no_license
KevinAnYuan/gxq
60529e527eadbbe63a8ecbbad6aaa0dea5a61168
9b59f4e82597332a70576f43e3f365c41d5cfbee
refs/heads/main
2023-01-04T19:35:18.615146
2020-10-27T06:24:37
2020-10-27T06:24:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,200
java
//package com.hengyunsoft.platform.msgs.open.msg.hystrix; // //import com.github.pagehelper.PageInfo; //import com.hengyunsoft.base.Result; //import com.hengyunsoft.page.plugins.openapi.OpenApiReq; //import com.hengyunsoft.platform.msgs.dto.msg.BacklogDTO; //import com.hengyunsoft.platform.msgs.dto.msg.BacklogSaveDTO; //import com.hengyunsoft.platform.msgs.dto.msg.BacklogUpdateDTO; //import com.hengyunsoft.platform.msgs.dto.msg.MsgCenterQueryDTO; //import com.hengyunsoft.platform.msgs.open.msg.BacklogApi; // ////@Component //public class BacklogApiHystrix implements BacklogApi{ // // @Override // public Result<PageInfo<BacklogDTO>> pageMoreBacklogList(OpenApiReq<MsgCenterQueryDTO> openApiReq) { // return Result.timeout(); // } // // @Override // public Result<BacklogDTO> addBacklog(BacklogSaveDTO backlogSaveDTO) { // return Result.timeout(); // } // // @Override // public Result<Boolean> deleteBacklog(Long id) { // return Result.timeout(); // } // // @Override // public Result<Boolean> updateBacklog(BacklogUpdateDTO backlogUpdateDTO) { // return Result.timeout(); // } // // @Override // public Result<Boolean> updateBacklogStatus(Long id) { // return Result.timeout(); // } //}
[ "470382668@qq.com" ]
470382668@qq.com
f5e6589e5196bf235cf2e45334552daafbd8db8a
89ab50fbd102df9c1f784e8fb7c8ff74bc265270
/enumerations/src/EnumTest.java
dde0ea159a1ec2aea58796eb30bfc731fb4bd9e8
[]
no_license
ryanh17/Ryan-Huang
09debc36364e2c015b1620c1ee92c24cde905785
d4ac4d6d0b23e805dab0e813737464d64f056476
refs/heads/master
2021-07-16T03:14:30.246391
2020-05-16T04:36:40
2020-05-16T04:36:40
151,289,153
0
0
null
null
null
null
UTF-8
Java
false
false
111
java
public class EnumTest { Worker worker; EnumTest(Worker worker){ this.worker = worker; } }
[ "43790407+ryanh17@users.noreply.github.com" ]
43790407+ryanh17@users.noreply.github.com
4ac2a88949d334a619dfbf78d1dc952b8157fd87
fb9a23f59d996b573b07bee7ce41a1181157c0d8
/app/src/main/java/com/example/taoaoptonghop/progile.java
f84331f445308bdf968d6985929e0207fd8e77ea
[]
no_license
long12378/apptonghopp
9b214fcc05f710ec8c7f2af406ee57f930af17b9
5749391f92113c687a30a57652df33dad16e444a
refs/heads/master
2022-12-29T15:20:47.252885
2020-10-15T16:02:38
2020-10-15T16:02:38
304,377,869
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package com.example.taoaoptonghop; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class progile extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_progile); } }
[ "nduclong7@gmail.com" ]
nduclong7@gmail.com
5f9c1350248b7df6cf1bcbb9bf6510c9570cdd5d
b628569d5437d95671df68a317ac0b17958ad7a9
/practica4/src/gui/swing/InputPanel.java
f8618be2443360db55829c34c87f9733b678cf39
[]
no_license
practicasTp/practicasTp
e3d3c8fa1534e50c2e7a1f8efa773e388e4c029f
a6029d0684114717902797184042dfe2c67448f4
refs/heads/master
2021-01-01T18:37:44.296833
2014-05-29T15:11:33
2014-05-29T15:11:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,697
java
package gui.swing; import java.awt.BorderLayout; import java.awt.Font; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.TitledBorder; import mv.reading.InputMethod; public class InputPanel extends JPanel { /** * */ private static final long serialVersionUID = 1L; private GUIControler guiCtrl; private static JTextArea inputTextArea; private static InputMethod inCurr; private InputMethod inNew; InputPanel (GUIControler guiCtrl) { this.guiCtrl = guiCtrl; initGUI(); } /** * Inicializa el InputPanel incluyendo el inputTextArea. */ private void initGUI() { this.setLayout(new BorderLayout()); this.setBorder(new TitledBorder("Input")); inputTextArea = new JTextArea(5, 5); inputTextArea.setAlignmentX(CENTER_ALIGNMENT); inputTextArea.setFont( new Font("Courier", Font.PLAIN, 16)); inputTextArea.setEditable(false); this.add(new JScrollPane(inputTextArea)); this.setAlignmentX(CENTER_ALIGNMENT); inCurr = guiCtrl.getInStream(); this.inNew = new InStreamGUI(); guiCtrl.setInStream( inNew ); } static class InStreamGUI implements InputMethod { StringBuilder content; int pos; public InStreamGUI() { this.content = new StringBuilder(); this.pos = 0; // 1. leer toda la entrada del old, y construir el StringBuilder content int character = inCurr.readChar(); while (character != -1) { this.content.append((char)character); character = inCurr.readChar(); } // 2. mostrar el contenido de content en el inputTextArea inputTextArea.setText(content.toString()); } /** * No hace nada porque ya se encarga otro método de abrir el archivo. */ public void open() {} // suponemos que old ya está abierto /** * Se encarga de cerrar el archivo de entrada abierto. */ public void close() { inCurr.close(); } // cerrar old también /** * Lee el siguiente caracter guardado y lo devueve. Además actualiza el * inputTextArea para que muestre un * en lugar del caracter obtenido. * @return int */ public int readChar() { int c = -1; // 1. si pos == content.length() entonce ya no hay más caracteres if (this.pos != this.content.length()) { // 2. consultar el carácter c el la posición pos del content c = this.content.codePointAt(this.pos); // 3. si c no es salto de linea (c!=10 y c!=13) lo cambiamos con * en content! if (c != 10 && c != 13) this.content.replace(this.pos, this.pos+1, "*"); } // 4. actualizar el inputTextArea; inputTextArea.setText(content.toString()); // 5. actualizar pos this.pos++; // 6. devolver c; return c; } } }
[ "miguelamv@msn.com" ]
miguelamv@msn.com
69c5e756a8fde2db8747c9c5fed352fa9fb29a92
0cd02cd8df3c82cc4d389786a68858c27910adad
/microservice-Info/src/main/java/sn/codeart/msa/MicroserviceInfoApplication.java
7b7d79994f15baef53881504d0fd874132a86539
[]
no_license
Junior300895/plateforme-recherche
e4032e958d1dc5d58e0c4ab9b9e6a08792267a50
29f03512fcff3aa43f3c6297a89da62019d8b635
refs/heads/master
2021-06-25T18:32:56.112992
2020-02-23T12:52:27
2020-02-23T12:52:27
218,409,114
0
0
null
2020-10-13T17:05:11
2019-10-30T00:22:45
Java
UTF-8
Java
false
false
457
java
package sn.codeart.msa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient(autoRegister = false) @SpringBootApplication public class MicroserviceInfoApplication { public static void main(String[] args) { SpringApplication.run(MicroserviceInfoApplication.class, args); } }
[ "abadaa9518@gmail.com" ]
abadaa9518@gmail.com
a134af6b701e5e62ddc7813ea9dd835e4c214f6d
be0e8535222b601c277a9d29f234e7fa44e13258
/output/com/ankamagames/dofus/network/types/game/character/CharacterMinimalAllianceInformations.java
c8e945eae6e2b13e97d6bca606d7553b49b6d846
[]
no_license
BotanAtomic/ProtocolBuilder
df303b741c701a17b0c61ddbf5253d1bb8e11684
ebb594e3da3adfad0c3f036e064395a037d6d337
refs/heads/master
2021-06-21T00:55:40.479271
2017-08-14T23:59:09
2017-08-14T23:59:24
100,318,625
1
2
null
null
null
null
UTF-8
Java
false
false
2,046
java
package com.ankamagames.dofus.network.types.game.character; import com.ankamagames.jerakine.network.INetworkType; import com.ankamagames.dofus.network.types.game.context.roleplay.BasicAllianceInformations; import com.ankamagames.dofus.network.types.game.look.EntityLook; import com.ankamagames.dofus.network.types.game.context.roleplay.BasicGuildInformations; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.ICustomDataInput; import com.ankamagames.jerakine.network.utils.FuncTree; public class CharacterMinimalAllianceInformations extends CharacterMinimalGuildInformations implements INetworkType { public BasicAllianceInformations alliance; private FuncTree _alliancetree; public static final int protocolId = 444; @Override public void serialize(ICustomDataOutput param1) { if (this.id < 0 || this.id > 9.007199254740992E15) { throw new Exception("Forbidden value (" + this.id + ") on element id."); } param1.writeVarLong(this.id); param1.writeUTF(this.name); if (this.level < 1 || this.level > 206) { throw new Exception("Forbidden value (" + this.level + ") on element level."); } param1.writeByte(this.level); this.entityLook.serializeAs_EntityLook(param1); this.guild.serializeAs_BasicGuildInformations(param1); this.alliance.serializeAs_BasicAllianceInformations(param1); } @Override public void deserialize(ICustomDataInput param1) { this.uid = param1.readUTF(); this.figure = param1.readVarUhShort(); if (this.figure < 0) { throw new Exception( "Forbidden value (" + this.figure + ") on element of KrosmasterFigure.figure."); } this.pedestal = param1.readVarUhShort(); if (this.pedestal < 0) { throw new Exception( "Forbidden value (" + this.pedestal + ") on element of KrosmasterFigure.pedestal."); } this.bound = param1.readBoolean(); this.alliance = new BasicAllianceInformations(); this.alliance.deserialize(param1); } }
[ "ahmed.botan94@gmail.com" ]
ahmed.botan94@gmail.com
0fb0cf44c1cfe370ef0f1e26f04588ffff3a75d5
71bc5b92dac4d4a86d90eb45d68a86bbef3c9a0e
/src/main/java/Airport.java
3cddd86d66ce8e026c18821d009cecdd5e513123
[]
no_license
DafyddLlyr/Homework_Wk11D5_TravelJava
424094e4fbd244543ccea4386307d63772089a54
cea8659f80b84b9d17be0492c21bcac20f9052b9
refs/heads/master
2021-07-11T19:57:51.655989
2019-07-22T09:49:16
2019-07-22T09:49:16
197,743,807
0
0
null
2020-10-13T14:42:20
2019-07-19T09:24:22
Java
UTF-8
Java
false
false
59
java
public enum Airport { GLA, EDI, LAX, SYD }
[ "dafyddllyr@gmail.com" ]
dafyddllyr@gmail.com
f2cf82812b62c50d74af680b5213e9af5936d66b
2adbabb2a4ac59d22ae06fe8a32f2c016f398da7
/app/src/main/java/com/example/hw11/Contract.java
689b4f38081e896f7e8d691c02b5e651f5ae5135
[]
no_license
lsw6684/ToDoList-Application
2ca3c5290e5d1a53d1ebb7c66ff5516061eab889
4241121ae13c74516c583a1b219b741328678d90
refs/heads/master
2022-12-14T22:59:03.126125
2020-09-20T05:25:09
2020-09-20T05:25:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
899
java
package com.example.hw11; public class Contract { private Contract() { } public static final String TABLE_NAME = "todo_list"; public static final String COL_LEC_NAME = "todo_name"; public static final String SQL_CREATE_TBL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " " + "(" + COL_LEC_NAME + " CHAR(20) PRIMARY KEY)" + ")"; //=CREATE TABLE IF NOT EXISTS todo_list (todo_name CHAR(20) PRIMARY KEY) >> for 유지보수 public static final String SQL_DROP_TBL = "DROP TABLE IF EXISTS " + TABLE_NAME; public static final String SQL_SELECT = "SELECT * FROM " + TABLE_NAME; public static final String SQL_INSERT = "INSERT OR REPLACE INTO " + TABLE_NAME + " " + "(" + COL_LEC_NAME + ") VALUES "; public static final String SQL_DELETED = "DELETE FROM " + TABLE_NAME + " WHERE " + COL_LEC_NAME + " = "; }
[ "lsw6684@hanmail.net" ]
lsw6684@hanmail.net
22273f17a8377ccfb8b2186d7c71328465b5c620
fdd01f5a60a5a9a764ad94e43af157c46f21bcb9
/src/main/java/com/example/demo/configs/ListenerConfig.java
1319875afd2ac383e4c3f9b311e01c5cae263aeb
[]
no_license
xiewenya/demo
6efe9ee9dd3d23dfb4beb1296919135bf25c0488
6ceec96f352069047cc05e254ae52f79aaa16a71
refs/heads/master
2021-04-12T09:48:07.129784
2018-03-21T12:06:13
2018-03-21T12:06:13
126,172,715
0
0
null
null
null
null
UTF-8
Java
false
false
741
java
package com.example.demo.configs; import org.opensolaris.opengrok.web.WebappListener; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author bresai */ @Configuration public class ListenerConfig { @Bean public WebappListener webappListener(){ return new WebappListener(); } @Bean public ServletContextInitializer initializer() { return servletContext -> { servletContext.setInitParameter("CONFIGURATION", "/opt/opengrok/etc/configuration.xml"); servletContext.setInitParameter("ConfigAddress", "localhost:9999"); }; } }
[ "bresai@live.cn" ]
bresai@live.cn
2cd1b6146094956bbc662e431565a4c5691f6be0
9d0608ca8a41542359f8ec051e74a35af0352e78
/src/main/java/cn/springmvc/entry/StuRace.java
01546e53bd79c22f6c823b068494263635dd628b
[]
no_license
hapcaper/race
75221239811c82badd2132f881ff2f1ad75d250e
ec2529a78cc94da19887ac554985499cc973bc0c
refs/heads/master
2021-01-21T23:13:32.616001
2018-01-12T04:14:44
2018-01-12T04:14:44
95,212,292
0
0
null
null
null
null
UTF-8
Java
false
false
1,449
java
package cn.springmvc.entry; /** * Created by ASUS on 2017/6/27. */ public class StuRace { private Integer id ; private Integer stuId ; private String stuName ; private Integer RaceId ; private String RaceName ; @Override public String toString() { return "StuRace{" + "id=" + id + ", stuId=" + stuId + ", stuName='" + stuName + '\'' + ", RaceId=" + RaceId + ", RaceName='" + RaceName + '\'' + ", status=" + status + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getStuId() { return stuId; } public void setStuId(Integer stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public Integer getRaceId() { return RaceId; } public void setRaceId(Integer raceId) { RaceId = raceId; } public String getRaceName() { return RaceName; } public void setRaceName(String raceName) { RaceName = raceName; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } private Integer status ; }
[ "lizihaojlex@gmail.com" ]
lizihaojlex@gmail.com
a73ddddfecb6946e53d0f070e4b50b8da5bd6bed
84d11a9302f490d5c69c120ec7774efa4e401d30
/src/main/java/com/mmall/service/SysRoleUserService.java
6ba267348625d9db2ed5a8d7cf0f40c626620fbd
[]
no_license
iamcyzz/permission
62d93312b8ac79df8b01b66fb4445419a7c50df3
cf45214b206f2886a4b9d27db5b7d15e185b4ca8
refs/heads/master
2020-04-07T16:26:10.353690
2018-11-21T10:11:54
2018-11-21T10:11:54
158,529,154
0
0
null
null
null
null
UTF-8
Java
false
false
4,447
java
package com.mmall.service; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mmall.beans.LogType; import com.mmall.common.RequestHolder; import com.mmall.dao.SysLogMapper; import com.mmall.dao.SysRoleUserMapper; import com.mmall.dao.SysUserMapper; import com.mmall.model.SysLogWithBLOBs; import com.mmall.model.SysRoleUser; import com.mmall.model.SysUser; import com.mmall.util.IpUtil; import com.mmall.util.JsonMapper; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.Set; @Service public class SysRoleUserService { @Resource private SysRoleUserMapper sysRoleUserMapper; @Resource private SysUserMapper sysUserMapper; @Resource private SysLogMapper sysLogMapper; //通过角色id查到有哪些用户 public List<SysUser> getListByRoleId(int roleId) { //先从角色用户表查到有哪些用户的id的list List<Integer> userIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId); if (CollectionUtils.isEmpty(userIdList)) { return Lists.newArrayList(); } //通过用户id获取到具体用户信息 return sysUserMapper.getByIdList(userIdList); } //传入角色id,和用户id public void changeRoleUsers(int roleId, List<Integer> userIdList) { //查看这个角色本来有用的用户id List<Integer> originUserIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId); //假如这里list和原来的长度相同,那么他可能什么都没改,需要进去判断下是不是改了用户 if (originUserIdList.size() == userIdList.size()) { //原来用户的id Set<Integer> originUserIdSet = Sets.newHashSet(originUserIdList); //传入进来的用户id Set<Integer> userIdSet = Sets.newHashSet(userIdList); //原来的用户id移除掉传入进来的用户id originUserIdSet.removeAll(userIdSet); //判断移除后是不是为空的列表,为空说明用户和角色的关系没有变化,不进行任何操作,直接返回 if (CollectionUtils.isEmpty(originUserIdSet)) { return; } } //否则进入这里,进行更新 updateRoleUsers(roleId, userIdList); //最后更新操作记录到日志 saveRoleUserLog(roleId, originUserIdList, userIdList); } //调用事务方法,要更新就全部要更新成功 @Transactional public void updateRoleUsers(int roleId, List<Integer> userIdList) { //先把这个这角色原来有的用户关系全部删除了 sysRoleUserMapper.deleteByRoleId(roleId); //然后判断传入进来的是不是为空的用户的idList,说明没有用户分配了这个角色 if (CollectionUtils.isEmpty(userIdList)) { return; } //用户角色关系的list,用来放我们新的对象 List<SysRoleUser> roleUserList = Lists.newArrayList(); for (Integer userId : userIdList) { SysRoleUser roleUser = SysRoleUser.builder().roleId(roleId).userId(userId).operator(RequestHolder.getCurrentUser().getUsername()) .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build(); roleUserList.add(roleUser); } //把我们新的用户与角色关系,对象通过批量插入,给他放到数据库里面去 sysRoleUserMapper.batchInsert(roleUserList); } //操作记录方法 private void saveRoleUserLog(int roleId, List<Integer> before, List<Integer> after) { SysLogWithBLOBs sysLog = new SysLogWithBLOBs(); sysLog.setType(LogType.TYPE_ROLE_USER); sysLog.setTargetId(roleId); sysLog.setOldValue(before == null ? "" : JsonMapper.obj2String(before)); sysLog.setNewValue(after == null ? "" : JsonMapper.obj2String(after)); sysLog.setOperator(RequestHolder.getCurrentUser().getUsername()); sysLog.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())); sysLog.setOperateTime(new Date()); sysLog.setStatus(1); sysLogMapper.insertSelective(sysLog); } }
[ "364753346@qq.com" ]
364753346@qq.com
f3e60b314cfe8f74b5c77438db797b5f8c6b0b89
31f053359eaf6eb02a68b88084a48f4dc50df793
/obdEnergy/src/main/java/com/example/obdenergy/obdenergy/Activities/GraphsFragment.java
afb2c9852c227f0e6e5585b7801dd1e06463a0e3
[]
no_license
sumayyah/OBDEnergy
8a64b665c365992f5caaad406682bf9d7b83e717
5c8e12f5e99a92dd66d0801b05f2bf512d3671e8
refs/heads/master
2020-12-24T08:32:16.956418
2016-08-26T16:56:59
2016-08-26T16:56:59
19,559,908
0
0
null
2015-06-30T20:43:37
2014-05-08T03:56:45
Java
UTF-8
Java
false
false
18,150
java
package com.example.obdenergy.obdenergy.Activities; import android.app.Activity; import android.app.Fragment; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.example.obdenergy.obdenergy.Data.Path; import com.example.obdenergy.obdenergy.Data.Profile; import com.example.obdenergy.obdenergy.MainActivity; import com.example.obdenergy.obdenergy.R; import com.example.obdenergy.obdenergy.Utilities.BluetoothChatService; import com.example.obdenergy.obdenergy.Utilities.Console; import com.example.obdenergy.obdenergy.Utilities.GridAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.util.ArrayList; /** * Created by sumayyah on 5/31/14. * * * This activity is meant to allow the user to see their data across a range of times. It receives * the user's accumulated data in JSON form from the SharedPreferences file, parses it, and stores it in local * variables. These variables supply the data to a Gridview that displays icons representing fuel usage. */ public class GraphsFragment extends Fragment implements View.OnClickListener{ private MainActivity mainActivity; private GridAdapter gridAdapter; private GridView gridView; private TextView fuelUsed; private TextView carbonUsed; private TextView treesUsed; private TextView scale; private Button today; private Button week; private Button month; private ImageView cloudClicker; private ImageView leafClicker; private Integer[] treeList; private final String classID="GraphsFragment "; private long secsInWeek = 604800; private long secsInDay = 86400; private long dayStartRange; private long currentTime; private long weekStartRange; private double dayFuelNum = 0.0; private double dayCarbonNum = 0.0; private double dayTreesNum = 0.0; private double weekFuelNum = 0.0; private double weekCarbonNum = 0.0; private double weekTreesNum = 0.0; private double monthFuelNum = 0.0; private double monthCarbonNum = 0.0; private double monthTreesNum = 0.0; private double adapterNum = 0; private ArrayList<Integer> imagelist; private boolean cloud = true; private boolean leaf = false; private boolean dayPressed = true; private boolean weekPressed = false; private boolean monthPressed = false; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancestate){ Console.log(classID+"State is "+ BluetoothChatService.getState()); View view = inflater.inflate(R.layout.graphs_fragment, container, false); gridView = (GridView)(view.findViewById(R.id.gridView1)); fuelUsed = (TextView)(view.findViewById(R.id.fuelNumber)); carbonUsed = (TextView)(view.findViewById(R.id.carbonUsed)); treesUsed = (TextView)(view.findViewById(R.id.treesUsed)); scale = (TextView)(view.findViewById(R.id.carbonScale)); today = (Button)(view.findViewById(R.id.todayButton)); week = (Button)(view.findViewById(R.id.weekButton)); month = (Button)(view.findViewById(R.id.monthButton)); cloudClicker = (ImageView)(view.findViewById(R.id.cloudClicker)); leafClicker = (ImageView)(view.findViewById(R.id.leafClicker)); today.setOnClickListener(this); week.setOnClickListener(this); month.setOnClickListener(this); cloudClicker.setOnClickListener(this); leafClicker.setOnClickListener(this); fuelUsed.setText(mainActivity.path.gallonsUsed+""); treesUsed.setText(mainActivity.path.treesKilled+""); imagelist = new ArrayList<Integer>(); // Console.log(classID+"Pieces are today: "+todayJSONArray); // Console.log(classID+"Historical "+Profile.pathHistoryJSON); // String holderString = "[{\"initTimestamp\":\"1402414587670\", \"finalMAF\":655.35,\"treesKilled\":7, \"gallonsUsed\":3, \"carbonUsed\":61},{\"initTimestamp\":\"1401896187867\", \"finalMAF\":655.35,\"treesKilled\":1,\"carbonUsed\":5,\"initFuel\":0,\"gallonsUsed\":7,\"initMAF\":406.65,\"averageSpeed\":55.5,\"finalTimestamp\":\"1402365290\",\"finalFuel\":0}, {\"initTimestamp\":\"1402417236395\",\"carbonUsed\":9, \"initFuel\":0,\"initMAF\":406.65,\"finalFuel\":0,\"treesKilled\":3,\"finalMAF\":655.35,\"gallonsUsed\":6}]"; treeList = new Integer[]{R.drawable.tree1leaf, R.drawable.tree2leaves, R.drawable.tree3leaves, R.drawable.tree4leaves, R.drawable.tree5leaves, R.drawable.tree6leaves, R.drawable.tree7leaves, R.drawable.tree8leaves, R.drawable.tree9leaves, R.drawable.tree10leaves}; setDefaults(); return view; } @Override public void onCreate(Bundle savedInstanceState) { Console.log(classID+"onCreate"); setHasOptionsMenu(true); super.onCreate(savedInstanceState); } @Override public void onAttach(Activity activity) { Console.log(classID+"on attach"); super.onAttach(activity); this.mainActivity = (MainActivity) activity; } public void GraphsFragmentDataComm(){ currentTime = System.currentTimeMillis()/1000; dayStartRange = currentTime - secsInDay; weekStartRange = currentTime - secsInWeek; Console.log(classID+"Called from Main and now parsing historical data ONCE"); try { //Go ahead and parse all the previous paths parseJSON(new JSONArray(String.valueOf(Profile.pathHistoryJSON))); } catch (JSONException e) { Console.log(classID+" failed to get JSON array"); e.printStackTrace(); } } public void GraphsFragmentDataComm(Path p){ Console.log(classID+"Adding path, data before, day: "+dayFuelNum+" "+dayCarbonNum+" "+dayTreesNum+" week "+weekFuelNum+" "+weekCarbonNum+" "+weekTreesNum+" month "+monthFuelNum+" "+monthCarbonNum+" "+monthTreesNum); Console.log(classID+"Adding data, fuel carbon trees "+p.gallonsUsed+" "+p.carbonUsed+" "+p.treesKilled); monthFuelNum += p.gallonsUsed; monthCarbonNum += p.carbonUsed; monthTreesNum += p.treesKilled; weekFuelNum += p.gallonsUsed; weekCarbonNum += p.carbonUsed; weekTreesNum += p.treesKilled; dayFuelNum += p.gallonsUsed; dayCarbonNum += p.carbonUsed; dayTreesNum += p.treesKilled; Console.log(classID+"Adding path, data after, day: "+dayFuelNum+" "+dayCarbonNum+" "+dayTreesNum+" week "+weekFuelNum+" "+weekCarbonNum+" "+weekTreesNum+" month "+monthFuelNum+" "+monthCarbonNum+" "+monthTreesNum); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.todayButton: /*Get today's data collected to far - so this is all the paths stored now? no this won't work*/ dayPressed =true;weekPressed = false;monthPressed = false; today.setTextColor(Color.parseColor("#A4C739")); week.setTextColor(Color.WHITE); month.setTextColor(Color.WHITE); displayData(dayPressed, weekPressed, monthPressed, cloud, leaf); break; case R.id.weekButton: dayPressed =false;weekPressed = true;monthPressed = false; week.setTextColor(Color.parseColor("#A4C739")); today.setTextColor(Color.WHITE); month.setTextColor(Color.WHITE); displayData(dayPressed, weekPressed, monthPressed, cloud, leaf); break; case R.id.monthButton: dayPressed =false;weekPressed = false;monthPressed = true; month.setTextColor(Color.parseColor("#A4C739")); today.setTextColor(Color.WHITE); week.setTextColor(Color.WHITE); displayData(dayPressed, weekPressed, monthPressed, cloud, leaf); break; case R.id.cloudClicker: cloud = true;leaf = false; cloudClicker.setImageDrawable(getResources().getDrawable(R.drawable.cloud_icon_green)); carbonUsed.setTextColor(Color.parseColor("#A4C739")); leafClicker.setImageDrawable(getResources().getDrawable(R.drawable.leaf_copy)); treesUsed.setTextColor(Color.WHITE); displayData(dayPressed, weekPressed, monthPressed, cloud, leaf); break; case R.id.leafClicker: cloud = false;leaf = true; cloudClicker.setImageDrawable(getResources().getDrawable(R.drawable.cloud_icon)); carbonUsed.setTextColor(Color.WHITE); leafClicker.setImageDrawable(getResources().getDrawable(R.drawable.leafgreen)); treesUsed.setTextColor(Color.parseColor("#A4C739")); displayData(dayPressed, weekPressed, monthPressed, cloud, leaf); break; default: break; } } private ArrayList<Integer> setImageArray(double imagenumber, int type){ ArrayList<Integer> finalImages = new ArrayList<Integer>(); int wholenum = (int) imagenumber; double decimalportion = imagenumber%1; int finaldecimal = (int)(decimalportion*10); switch(type){ case 1: /*If carbon*/ Console.log(classID+"Carbon"); for(int i=0;i<wholenum;i++){ finalImages.add(R.drawable.cloud_icon_green); } break; case 2: /*If trees*/ Console.log(classID+"Trees"); for(int i=0;i<wholenum;i++){ finalImages.add(treeList[9]); } if(decimalportion > 0 && finaldecimal > 0){ finalImages.add(treeList[finaldecimal - 1]); } else finalImages.add(treeList[0]); break; default: break; } Console.log(classID+"Number of whole images is "+wholenum+" and parts are "+decimalportion+" ie "+finaldecimal); // gridAdapter = new GridAdapter(mainActivity, finalImages, "TREE"); // gridView.setAdapter(gridAdapter); return finalImages; } private void displayData(boolean day, boolean week, boolean month, boolean cloud, boolean leaf){ /*If the user has selected carbon*/ if(cloud && !leaf){ if(day && !week && !month){ fuelUsed.setText(dayFuelNum + ""); carbonUsed.setText(dayCarbonNum + " kilos CO2"); adapterNum = dayCarbonNum; scale.setText("1 cloud per kilo of carbon"); imagelist = setImageArray(adapterNum, 1); // Console.log(classID+"Cloud and day, send number and type "+adapterNum+" "+adapterType); } else if(!day && week && !month){ fuelUsed.setText(weekFuelNum+""); carbonUsed.setText(weekCarbonNum + " kilos CO2"); if(weekCarbonNum<=10) {adapterNum = (int)(weekCarbonNum); scale.setText("1 cloud per kilo of carbon");} else {adapterNum = (weekCarbonNum/10); scale.setText("1 cloud for every 10 kilos of carbon");} imagelist = setImageArray(adapterNum, 1); // Console.log(classID+"Cloud and week send number and type "+adapterNum+" "+adapterType); } else if(!day && !week && month){ fuelUsed.setText(monthFuelNum+""); carbonUsed.setText(monthCarbonNum + " kilos CO2"); if(monthCarbonNum<=10) {adapterNum = (int)(monthCarbonNum); scale.setText("1 cloud per kilo of carbon");} else {adapterNum = (monthCarbonNum/10); scale.setText("1 cloud for every 10 kilos of carbon");} imagelist = setImageArray(adapterNum, 1); // Console.log(classID+"Cloud and month, send number and type "+adapterNum+" "+adapterType); } else Console.log(classID+"Wrong time bool for cloud"); } /*If the user has selected carbon*/ else if(leaf && !cloud){ scale.setText("1 leaf per tree used"); if(day && !week && !month){ fuelUsed.setText(dayFuelNum + ""); carbonUsed.setText(dayCarbonNum + " kilos CO2"); treesUsed.setText(dayTreesNum + " trees used"); scale.setText("1 leaf per 0.1 tree used"); adapterNum = (dayTreesNum); imagelist = setImageArray(adapterNum, 2); // Console.log(classID+"Leaf and day, send number and type "+adapterNum+" "+adapterType); } else if(!day && week && !month){ fuelUsed.setText(weekFuelNum+""); carbonUsed.setText(weekCarbonNum + " kilos CO2"); treesUsed.setText(weekTreesNum + " trees used"); scale.setText("1 leaf per 0.1 tree used"); adapterNum = (weekTreesNum); imagelist = setImageArray(adapterNum, 2); // Console.log(classID+"Leaf and week, send number and type "+adapterNum+" "+adapterType); } else if(!day && !week && month){ fuelUsed.setText(monthFuelNum+""); carbonUsed.setText(monthCarbonNum + " kilos CO2"); treesUsed.setText(monthTreesNum + " trees used"); scale.setText("1 leaf per 0.1 tree used"); adapterNum = (monthTreesNum); imagelist = setImageArray(adapterNum, 2); // Console.log(classID+"Leaf and month, send number and type "+adapterNum+" "+adapterType); } else Console.log(classID+"Wrong time bool for leaf"); } else Console.log(classID+"wrong boolean somewhere"); gridAdapter = new GridAdapter(mainActivity, imagelist); gridView.setAdapter(gridAdapter); } private void parseJSON(JSONArray jsonArray) throws JSONException { Console.log(classID + "Parsing JSON of length "+jsonArray.length()+" "+jsonArray); DecimalFormat df = new DecimalFormat("#.00"); Long objTimestamp; double fuelNum; double carbonNum; double treesNum; for(int i=0;i<jsonArray.length();i++){ if(jsonArray.isNull(i)){ Console.log(classID+"Array is null at index "+i); continue; } JSONObject obj = (JSONObject) jsonArray.get(i); objTimestamp = Long.parseLong(obj.getString("initTimestamp")); /*Get object's data*/ fuelNum = obj.getDouble("gallonsUsed"); carbonNum = obj.getDouble("carbonUsed"); treesNum = obj.getDouble("treesKilled"); Console.log(classID+"Object "+i+" at "+objTimestamp+" Current time " + currentTime+" Data: fuel carbon trees "+fuelNum+" "+carbonNum+" "+treesNum); monthFuelNum += fuelNum; monthCarbonNum += carbonNum; monthTreesNum += treesNum; /*If in range, calculate data for the week*/ if(objTimestamp <= currentTime && objTimestamp >= weekStartRange){ weekFuelNum += fuelNum; weekCarbonNum += carbonNum; weekTreesNum += treesNum; Console.log(classID+" Week from "+weekStartRange+" to "+currentTime+" Data: fuel carbon trees "+weekFuelNum+" "+weekCarbonNum+" "+weekTreesNum); } /*If in range, calculate data for the day*/ if(objTimestamp <= currentTime && objTimestamp >= dayStartRange){ dayFuelNum += fuelNum; dayCarbonNum += carbonNum; dayTreesNum += treesNum; Console.log(classID+" Today from "+dayStartRange+" to "+currentTime+" Data: fuel carbon trees "+dayFuelNum+" "+dayCarbonNum+" "+dayTreesNum); } } dayCarbonNum = Double.parseDouble(df.format(dayCarbonNum)); dayTreesNum = Double.parseDouble(df.format(dayTreesNum)); dayFuelNum = Double.parseDouble(df.format(dayFuelNum)); weekCarbonNum = Double.parseDouble(df.format(weekCarbonNum)); weekTreesNum = Double.parseDouble(df.format(weekTreesNum)); weekFuelNum = Double.parseDouble(df.format(weekFuelNum)); monthCarbonNum = Double.parseDouble(df.format(monthCarbonNum)); monthTreesNum = Double.parseDouble(df.format(monthTreesNum)); monthFuelNum = Double.parseDouble(df.format(monthFuelNum)); printData(); } private void setDefaults(){ fuelUsed.setText(dayFuelNum+""); carbonUsed.setText(dayCarbonNum + " kilos CO2"); treesUsed.setText(dayTreesNum + " trees used"); dayPressed =true;weekPressed = false;monthPressed = false; today.setTextColor(Color.parseColor("#A4C739")); cloudClicker.setImageDrawable(getResources().getDrawable(R.drawable.cloud_icon_green)); carbonUsed.setTextColor(Color.parseColor("#A4C739")); adapterNum = (int)dayCarbonNum; imagelist = setImageArray(adapterNum, 1); gridAdapter = new GridAdapter(mainActivity,imagelist); /*Call grid view when parsing is done*/ gridView.setAdapter(gridAdapter); } private void printData(){ Console.log(classID + "Printing data now at " + currentTime); Console.log("Day " + dayStartRange + " to " + currentTime + " fuel carbon trees " + dayFuelNum + " " + dayCarbonNum + " " + dayTreesNum); Console.log("Week " + weekStartRange + " to " + currentTime + " fuel carbon trees " + weekFuelNum + " " + weekCarbonNum + " " + weekTreesNum); Console.log("Month fuel carbon trees " + monthFuelNum + " " + monthCarbonNum + " " + monthTreesNum); } }
[ "sumayyah16.m@gmail.com" ]
sumayyah16.m@gmail.com
45918550e5d2d60bc3f02a923169878cc64d37e0
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/pai-dsw-20210226/src/main/java/com/aliyun/pai_dsw20210226/models/UpdateV3InstanceByUserResponse.java
f4d1c71f3e7bda1f83b6806ddafb0b44c9f163e9
[ "Apache-2.0" ]
permissive
aliyun/alibabacloud-java-sdk
83a6036a33c7278bca6f1bafccb0180940d58b0b
008923f156adf2e4f4785a0419f60640273854ec
refs/heads/master
2023-09-01T04:10:33.640756
2023-09-01T02:40:45
2023-09-01T02:40:45
288,968,318
40
45
null
2023-06-13T02:47:13
2020-08-20T09:51:08
Java
UTF-8
Java
false
false
1,441
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.pai_dsw20210226.models; import com.aliyun.tea.*; public class UpdateV3InstanceByUserResponse extends TeaModel { @NameInMap("headers") @Validation(required = true) public java.util.Map<String, String> headers; @NameInMap("statusCode") @Validation(required = true) public Integer statusCode; @NameInMap("body") @Validation(required = true) public UpdateV3InstanceByUserResponseBody body; public static UpdateV3InstanceByUserResponse build(java.util.Map<String, ?> map) throws Exception { UpdateV3InstanceByUserResponse self = new UpdateV3InstanceByUserResponse(); return TeaModel.build(map, self); } public UpdateV3InstanceByUserResponse setHeaders(java.util.Map<String, String> headers) { this.headers = headers; return this; } public java.util.Map<String, String> getHeaders() { return this.headers; } public UpdateV3InstanceByUserResponse setStatusCode(Integer statusCode) { this.statusCode = statusCode; return this; } public Integer getStatusCode() { return this.statusCode; } public UpdateV3InstanceByUserResponse setBody(UpdateV3InstanceByUserResponseBody body) { this.body = body; return this; } public UpdateV3InstanceByUserResponseBody getBody() { return this.body; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
10991729f5d349f8524a670bfa277e7c83434fcb
86ce5ab9b5b71b8d61c4d735c6efa362cfa0e9b7
/src/net/dolpen/gae/libs/servlet/Forwards.java
ae581549557873c0ce7a68abbb8f864b945069b6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dolpen/dolpendotnet
f85d1e68b5e6de101c653e5922ad8e7b00f071a3
ef0291f5392387a56a7fc605820378e44c1df25f
refs/heads/master
2021-01-23T08:56:36.542082
2017-11-16T07:03:08
2017-11-16T07:03:08
24,228,369
0
0
null
null
null
null
UTF-8
Java
false
false
1,643
java
package net.dolpen.gae.libs.servlet; import net.dolpen.gae.libs.jpa.JPA; import javax.servlet.http.*; public class Forwards { private static final String JSP_PREFIX = "/WEB-INF/view"; private static final String ERROR_PATH = "/error/503.jsp"; /** * JSPにフォワードします * * @param target 遷移先 * @param req リクエスト * @param resp レスポンス */ public static void forward(String target, HttpServletRequest req, HttpServletResponse resp) { try { req.getRequestDispatcher(JSP_PREFIX + target).forward(req, resp); } catch (Exception e) { e.printStackTrace(); try { req.getRequestDispatcher(JSP_PREFIX + ERROR_PATH).forward(req, resp); } catch (Exception e1) { } } } /** * サーバーエラー * * @param code エラーコード * @param req リクエスト * @param resp レスポンス */ public static void forwardError(int code, HttpServletRequest req, HttpServletResponse resp) { try { req.getRequestDispatcher(JSP_PREFIX + "/error/" + code + ".jsp").forward(req, resp); } catch (Exception e) { } } /** * 別URLにリダイレクトします * * @param target 遷移先 * @param resp レスポンス */ public static void redirect(String target, HttpServletResponse resp) { if(JPA.em()!=null&&JPA.em().isOpen())JPA.em().close(); try { resp.sendRedirect(target); } catch (Exception e) { } } }
[ "_" ]
_
192ee46a37f4bac73759fec35db9176cebd41a38
f2965c37368e855b428e0c03ff6a4c880d22607a
/app/src/main/java/com/example/guardianpolitico/News.java
b4cb4f0b7d347a2fa9d1d879244fa75d91a310a1
[]
no_license
SireME/Guardian-Politico
ea2879c8edf326be5074806d360ebae991a19d85
83de6d8ec20e4f28e49ac386057d57cd564644e7
refs/heads/master
2020-11-29T12:50:46.956802
2019-12-25T14:55:32
2019-12-25T14:55:32
230,112,888
0
0
null
null
null
null
UTF-8
Java
false
false
1,290
java
package com.example.guardianpolitico; public class News { /** * title of the article */ private String mTitle; /** * url link to the article */ private String mUrl; /** * section where the article belongs */ private String mArticleSection; /** * date published */ private String mDate; /** * Create a new Info object. * * @param title is the title of article * @param section is the section where the article belongs * @param date this is the date article was published */ public News(String title, String section, String date, String url) { mTitle = title; mArticleSection = section; mDate = date; mUrl = url; } /** * Get the title of the article */ public String getTitle() { return mTitle; } /** * Get the section where article belongs */ public String getSection() { return mArticleSection; } /** * Get the date published */ public String getDate() { return mDate; } /** * Get the url of the article */ public String getUrl() { return mUrl; } }
[ "noreply@github.com" ]
SireME.noreply@github.com
daeee0f3aa5f4d9d10a6592a3514e0bf1f917d94
7eda96aefde0a67b534ed457b43e31f8e3d30bbf
/http-ndn-daemon/src/main/java/net/named_data/jndn/security/KeyChain.java
61499c13c9d3d6a367603d4f4e4a6ea99cdc3613
[]
no_license
SethRedwine/http-ndn
00a4369a6b662fc106504cd7ddcf0d2da0cdae6c
c35dc8e365687355d5a923af54f29d74f10a38d8
refs/heads/master
2022-12-22T13:01:13.374511
2020-04-26T23:24:07
2020-04-26T23:24:07
247,608,743
0
0
null
2022-12-12T05:33:07
2020-03-16T04:14:04
Java
UTF-8
Java
false
false
101,590
java
/** * Copyright (C) 2014-2019 Regents of the University of California. * @author: Jeff Thompson <jefft0@remap.ucla.edu> * @author: From code in ndn-cxx by Yingdi Yu <yingdi@cs.ucla.edu> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * A copy of the GNU Lesser General Public License is in the file COPYING. */ package net.named_data.jndn.security; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import net.named_data.jndn.ContentType; import net.named_data.jndn.Data; import net.named_data.jndn.DigestSha256Signature; import net.named_data.jndn.Face; import net.named_data.jndn.HmacWithSha256Signature; import net.named_data.jndn.Interest; import net.named_data.jndn.KeyLocator; import net.named_data.jndn.KeyLocatorType; import net.named_data.jndn.Name; import net.named_data.jndn.OnData; import net.named_data.jndn.OnTimeout; import net.named_data.jndn.Sha256WithEcdsaSignature; import net.named_data.jndn.Sha256WithRsaSignature; import net.named_data.jndn.Signature; import net.named_data.jndn.encoding.EncodingException; import net.named_data.jndn.encoding.WireFormat; import net.named_data.jndn.encoding.der.DerDecodingException; import net.named_data.jndn.security.SigningInfo.SignerType; import net.named_data.jndn.security.certificate.IdentityCertificate; import net.named_data.jndn.security.certificate.PublicKey; import net.named_data.jndn.security.identity.BasicIdentityStorage; import net.named_data.jndn.security.identity.IdentityManager; import net.named_data.jndn.security.pib.Pib; import net.named_data.jndn.security.pib.PibIdentity; import net.named_data.jndn.security.pib.PibImpl; import net.named_data.jndn.security.pib.PibKey; import net.named_data.jndn.security.pib.PibMemory; import net.named_data.jndn.security.pib.PibSqlite3; import net.named_data.jndn.security.policy.NoVerifyPolicyManager; import net.named_data.jndn.security.policy.PolicyManager; import net.named_data.jndn.security.tpm.Tpm; import net.named_data.jndn.security.tpm.TpmBackEnd; import net.named_data.jndn.security.tpm.TpmBackEndFile; import net.named_data.jndn.security.tpm.TpmBackEndMemory; import net.named_data.jndn.security.v2.CertificateV2; import net.named_data.jndn.util.Blob; import net.named_data.jndn.util.Common; import net.named_data.jndn.util.ConfigFile; import net.named_data.jndn.util.SignedBlob; /** * KeyChain is the main class of the security library. * * The KeyChain class provides a set of interfaces to the security library such * as identity management, policy configuration and packet signing and * verification. * @note This class is an experimental feature. See the API docs for more * detail at * http://named-data.net/doc/ndn-ccl-api/key-chain.html . */ public class KeyChain { /** * A KeyChain.Error extends Exception and represents an error in KeyChain * processing. * Note that even though this is called "Error" to be consistent with the * other libraries, it extends the Java Exception class, not Error. */ public static class Error extends Exception { public Error(String message) { super(message); } } /** * A KeyChain.InvalidSigningInfoError extends KeyChain.Error to indicate * that the supplied SigningInfo is invalid. */ public static class InvalidSigningInfoError extends KeyChain.Error { public InvalidSigningInfoError(String message) { super(message); } } /** * A KeyChain.LocatorMismatchError extends KeyChain.Error to indicate that * the supplied TPM locator does not match the locator stored in the PIB. */ public static class LocatorMismatchError extends KeyChain.Error { public LocatorMismatchError(String message) { super(message); } } public interface MakePibImpl { PibImpl makePibImpl(String location) throws PibImpl.Error; } public interface MakeTpmBackEnd { TpmBackEnd makeTpmBackEnd(String location); } /** * Create a KeyChain to use the PIB and TPM defined by the given locators. * This creates a security v2 KeyChain that uses CertificateV2, Pib, Tpm and * Validator (instead of v1 Certificate, IdentityStorage, PrivateKeyStorage * and PolicyManager). * @param pibLocator The PIB locator, e.g., "pib-sqlite3:/example/dir". * @param tpmLocator The TPM locator, e.g., "tpm-memory:". * @param allowReset If true, the PIB will be reset when the supplied * tpmLocator mismatches the one in the PIB. * @throws KeyChain.LocatorMismatchError if the supplied TPM locator does not * match the locator stored in the PIB. */ public KeyChain(String pibLocator, String tpmLocator, boolean allowReset) throws KeyChain.Error, PibImpl.Error, SecurityException, IOException { isSecurityV1_ = false; construct(pibLocator, tpmLocator, allowReset); } /** * Create a KeyChain to use the PIB and TPM defined by the given locators. * Don't allow resetting the PIB when the supplied tpmLocator mismatches the * one in the PIB. * This creates a security v2 KeyChain that uses CertificateV2, Pib, Tpm and * Validator (instead of v1 Certificate, IdentityStorage, PrivateKeyStorage * and PolicyManager). * @param pibLocator The PIB locator, e.g., "pib-sqlite3:/example/dir". * @param tpmLocator The TPM locator, e.g., "tpm-memory:". * @throws KeyChain.LocatorMismatchError if the supplied TPM locator does not * match the locator stored in the PIB. */ public KeyChain(String pibLocator, String tpmLocator) throws KeyChain.Error, PibImpl.Error, SecurityException, IOException { isSecurityV1_ = false; construct(pibLocator, tpmLocator, false); } /** * Create a security v2 KeyChain with explicitly-created PIB and TPM objects, * and that still uses the v1 PolicyManager. * @param pibImpl An explicitly-created PIB object of a subclass of PibImpl. * @param tpmBackEnd An explicitly-created TPM object of a subclass of * TpmBackEnd. * @param policyManager An object of a subclass of a security v1 PolicyManager. */ public KeyChain (PibImpl pibImpl, TpmBackEnd tpmBackEnd, PolicyManager policyManager) throws PibImpl.Error { isSecurityV1_ = false; policyManager_ = policyManager; pib_ = new Pib("", "", pibImpl); tpm_ = new Tpm("", "", tpmBackEnd); } /** * Create a security v2 KeyChain with explicitly-created PIB and TPM objects. * This sets the policy manager to a security v1 NoVerifyPolicyManager. * @param pibImpl An explicitly-created PIB object of a subclass of PibImpl. * @param tpmBackEnd An explicitly-created TPM object of a subclass of * TpmBackEnd. */ public KeyChain(PibImpl pibImpl, TpmBackEnd tpmBackEnd) throws PibImpl.Error { isSecurityV1_ = false; policyManager_ = new NoVerifyPolicyManager(); pib_ = new Pib("", "", pibImpl); tpm_ = new Tpm("", "", tpmBackEnd); } /** * Create a new security v1 KeyChain with the given IdentityManager and * PolicyManager. For security v2, use KeyChain(pibLocator, tpmLocator) or the * default constructor if your .ndn folder is already initialized for v2. * @param identityManager An object of a subclass of IdentityManager. * @param policyManager An object of a subclass of PolicyManager. */ public KeyChain (IdentityManager identityManager, PolicyManager policyManager) { isSecurityV1_ = true; identityManager_ = identityManager; policyManager_ = policyManager; } /** * Create a new security v1 KeyChain with the given IdentityManager and a * NoVerifyPolicyManager. For security v2, use KeyChain(pibLocator, tpmLocator) * or the default constructor if your .ndn folder is already initialized for v2. * @param identityManager An object of a subclass of IdentityManager. */ public KeyChain(IdentityManager identityManager) { isSecurityV1_ = true; identityManager_ = identityManager; policyManager_ = new NoVerifyPolicyManager(); } /** * Create a KeyChain with the default PIB and TPM, which are * platform-dependent and can be overridden system-wide or individually by the * user. This creates a security v2 KeyChain that uses CertificateV2, Pib, Tpm * and Validator. However, if the default security v1 database file still * exists, and the default security v2 database file does not yet exists,then * assume that the system is running an older NFD and create a security v1 * KeyChain with the default IdentityManager and a NoVerifyPolicyManager. * Note: To create a security v2 KeyChain on android, you must use the * KeyChain constructor to provide AndroidSqlite3Pib and TpmBackEndFile * objects which are initialized with the explicit directory for the Android * filesDir. */ public KeyChain() throws SecurityException, KeyChain.Error, PibImpl.Error, IOException { isSecurityV1_ = false; if (BasicIdentityStorage.getDefaultDatabaseFilePath().exists() && !PibSqlite3.getDefaultDatabaseFilePath().exists()) { // The security v1 SQLite file still exists and the security v2 does not yet. isSecurityV1_ = true; identityManager_ = new IdentityManager(); policyManager_ = new NoVerifyPolicyManager(); return; } construct("", "", true); } public final Pib getPib() { if (isSecurityV1_) throw new AssertionError("getPib is not supported for security v1"); return pib_; } public final Tpm getTpm() { if (isSecurityV1_) throw new AssertionError("getTpm is not supported for security v1"); return tpm_; } /** * Get the flag set by the constructor if this is a security v1 or v2 KeyChain. * @return True if this is a security v1 KeyChain, false if this is a security * v2 KeyChain. */ public final boolean getIsSecurityV1() { return isSecurityV1_; } // Identity management /** * Create a security V2 identity for identityName. This method will check if * the identity exists in PIB and whether the identity has a default key and * default certificate. If the identity does not exist, this method will * create the identity in PIB. If the identity's default key does not exist, * this method will create a key pair and set it as the identity's default * key. If the key's default certificate is missing, this method will create a * self-signed certificate for the key. If identityName did not exist and no * default identity was selected before, the created identity will be set as * the default identity. * @param identityName The name of the identity. * @param params The key parameters if a key needs to be generated for the * identity. * @return The created PibIdentity instance. */ public final PibIdentity createIdentityV2(Name identityName, KeyParams params) throws PibImpl.Error, Pib.Error, Tpm.Error, TpmBackEnd.Error, Error { PibIdentity id = pib_.addIdentity_(identityName); PibKey key; try { key = id.getDefaultKey(); } catch (Pib.Error ex) { key = createKey(id, params); } try { key.getDefaultCertificate(); } catch (Pib.Error ex) { Logger.getLogger(this.getClass().getName()).log (Level.INFO, "No default cert for " + key.getName() + ", requesting self-signing"); selfSign(key); } return id; } /** * Create a security V2 identity for identityName. This method will check if * the identity exists in PIB and whether the identity has a default key and * default certificate. If the identity does not exist, this method will * create the identity in PIB. If the identity's default key does not exist, * this method will create a key pair using getDefaultKeyParams() and set it * as the identity's default key. If the key's default certificate is missing, * this method will create a self-signed certificate for the key. If * identityName did not exist and no default identity was selected before, the * created identity will be set as the default identity. * @param identityName The name of the identity. * @return The created Identity instance. */ public final PibIdentity createIdentityV2(Name identityName) throws PibImpl.Error, Pib.Error, Tpm.Error, TpmBackEnd.Error, Error { return createIdentityV2(identityName, getDefaultKeyParams()); } /** * Delete the identity. After this operation, the identity is invalid. * @param identity The identity to delete. */ public final void deleteIdentity(PibIdentity identity) throws PibImpl.Error, TpmBackEnd.Error { Name identityName = identity.getName(); ArrayList<Name> keyNames = identity.getKeys_().getKeyNames(); for (Name keyName : keyNames) tpm_.deleteKey_(keyName); pib_.removeIdentity_(identityName); // TODO: Mark identity as invalid. } /** * Set the identity as the default identity. * @param identity The identity to make the default. */ public final void setDefaultIdentity(PibIdentity identity) throws PibImpl.Error, Pib.Error { pib_.setDefaultIdentity_(identity.getName()); } // Key management /** * Create a key for the identity according to params. If the identity had no * default key selected, the created key will be set as the default for this * identity. This method will also create a self-signed certificate for the * created key. * @param identity A valid PibIdentity object. * @param params The key parameters if a key needs to be generated for the * identity. * @return The new PibKey. */ public final PibKey createKey(PibIdentity identity, KeyParams params) throws Tpm.Error, TpmBackEnd.Error, PibImpl.Error, Pib.Error, KeyChain.Error { // Create the key in the TPM. Name keyName = tpm_.createKey_(identity.getName(), params); // Set up the key info in the PIB. Blob publicKey = tpm_.getPublicKey(keyName); PibKey key = identity.addKey_(publicKey.buf(), keyName); Logger.getLogger(this.getClass().getName()).log (Level.INFO, "Requesting self-signing for newly created key " + key.getName().toUri()); selfSign(key); return key; } /** * Create a key for the identity according to getDefaultKeyParams(). If the * identity had no default key selected, the created key will be set as the * default for this identity. This method will also create a self-signed * certificate for the created key. * @param identity A valid PibIdentity object. * @return The new PibKey. */ public final PibKey createKey(PibIdentity identity) throws Tpm.Error, TpmBackEnd.Error, PibImpl.Error, Pib.Error, KeyChain.Error { return createKey(identity, getDefaultKeyParams()); } /** * Delete the given key of the given identity. The key becomes invalid. * @param identity A valid PibIdentity object. * @param key The key to delete. * @throws IllegalArgumentException If the key does not belong to the identity. */ public final void deleteKey(PibIdentity identity, PibKey key) throws PibImpl.Error, TpmBackEnd.Error { Name keyName = key.getName(); if (!identity.getName().equals(key.getIdentityName())) throw new IllegalArgumentException("Identity `" + identity.getName().toUri() + "` does not match key `" + keyName.toUri() + "`"); identity.removeKey_(keyName); tpm_.deleteKey_(keyName); } /** * Set the key as the default key of identity. * @param identity A valid PibIdentity object. * @param key The key to become the default. * @throws IllegalArgumentException If the key does not belong to the identity. */ public final void setDefaultKey(PibIdentity identity, PibKey key) throws Pib.Error, PibImpl.Error { if (!identity.getName().equals(key.getIdentityName())) throw new IllegalArgumentException("Identity `" + identity.getName().toUri() + "` does not match key `" + key.getName().toUri() + "`"); identity.setDefaultKey_(key.getName()); } // Certificate management /** * Add a certificate for the key. If the key had no default certificate * selected, the added certificate will be set as the default certificate for * this key. * @param key A valid PibKey object. * @param certificate The certificate to add. This copies the object. * @note This method overwrites a certificate with the same name, without * considering the implicit digest. * @throws IllegalArgumentException If the key does not match the certificate. */ public final void addCertificate(PibKey key, CertificateV2 certificate) throws CertificateV2.Error, PibImpl.Error { if (!key.getName().equals(certificate.getKeyName()) || !certificate.getContent().equals(key.getPublicKey())) throw new IllegalArgumentException("Key `" + key.getName().toUri() + "` does not match certificate `" + certificate.getKeyName().toUri() + "`"); key.addCertificate_(certificate); } /** * Delete the certificate with the given name from the given key. * If the certificate does not exist, this does nothing. * @param key A valid PibKey object. * @param certificateName The name of the certificate to delete. * @throws IllegalArgumentException If certificateName does not follow * certificate naming conventions. */ public final void deleteCertificate(PibKey key, Name certificateName) throws PibImpl.Error { if (!CertificateV2.isValidName(certificateName)) throw new IllegalArgumentException("Wrong certificate name `" + certificateName.toUri() + "`"); key.removeCertificate_(certificateName); } /** * Set the certificate as the default certificate of the key. The certificate * will be added to the key, potentially overriding an existing certificate if * it has the same name (without considering implicit digest). * @param key A valid PibKey object. * @param certificate The certificate to become the default. This copies the * object. */ public final void setDefaultCertificate(PibKey key, CertificateV2 certificate) throws PibImpl.Error, CertificateV2.Error, Pib.Error { // This replaces the certificate it it exists. addCertificate(key, certificate); key.setDefaultCertificate_(certificate.getName()); } // Signing /** * Wire encode the Data object, sign it according to the supplied signing * parameters, and set its signature. * @param data The Data object to be signed. This replaces its Signature * object based on the type of key and other info in the SigningInfo params, * and updates the wireEncoding. * @param params The signing parameters. * @param wireFormat A WireFormat object used to encode the input. * @throws KeyChain.Error if signing fails. * @throws KeyChain.InvalidSigningInfoError if params is invalid, or if the * identity, key or certificate specified in params does not exist. */ public final void sign(Data data, SigningInfo params, WireFormat wireFormat) throws TpmBackEnd.Error, PibImpl.Error, KeyChain.Error { Name[] keyName = new Name[1]; Signature signatureInfo = prepareSignatureInfo(params, keyName); data.setSignature(signatureInfo); // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); Blob signatureBytes = sign (encoding.signedBuf(), keyName[0], params.getDigestAlgorithm()); data.getSignature().setSignature(signatureBytes); // Encode again to include the signature. data.wireEncode(wireFormat); } /** * Wire encode the Data object, sign it according to the supplied signing * parameters, and set its signature. * Use the default WireFormat.getDefaultWireFormat(). * @param data The Data object to be signed. This replaces its Signature * object based on the type of key and other info in the SigningInfo params, * and updates the wireEncoding. * @param params The signing parameters. * @throws KeyChain.Error if signing fails. * @throws KeyChain.InvalidSigningInfoError if params is invalid, or if the * identity, key or certificate specified in params does not exist. */ public final void sign(Data data, SigningInfo params) throws TpmBackEnd.Error, PibImpl.Error, KeyChain.Error { sign(data, params, WireFormat.getDefaultWireFormat()); } /** * Wire encode the Data object, sign it with the default key of the default * identity, and set its signature. * If this is a security v1 KeyChain then use the IdentityManager to get the * default identity. Otherwise use the PIB. * @param data The Data object to be signed. This replaces its Signature * object based on the type of key of the default identity, and updates the * wireEncoding. * @param wireFormat A WireFormat object used to encode the input. */ public final void sign(Data data, WireFormat wireFormat) throws SecurityException, TpmBackEnd.Error, PibImpl.Error, KeyChain.Error { if (isSecurityV1_) { identityManager_.signByCertificate (data, prepareDefaultCertificateName(), wireFormat); return; } sign(data, defaultSigningInfo_, wireFormat); } /** * Wire encode the Data object, sign it with the default key of the default * identity, and set its signature. * If this is a security v1 KeyChain then use the IdentityManager to get the * default identity. Otherwise use the PIB. * Use the default WireFormat.getDefaultWireFormat(). * @param data The Data object to be signed. This replaces its Signature * object based on the type of key of the default identity, and updates the * wireEncoding. */ public final void sign(Data data) throws SecurityException, TpmBackEnd.Error, PibImpl.Error, KeyChain.Error { sign(data, WireFormat.getDefaultWireFormat()); } /** * Sign the Interest according to the supplied signing parameters. Append a * SignatureInfo to the Interest name, sign the encoded name components and * append a final name component with the signature bits. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param params The signing parameters. * @param wireFormat A WireFormat object used to encode the input and encode * the appended components. * @throws KeyChain.Error if signing fails. * @throws KeyChain.InvalidSigningInfoError if params is invalid, or if the * identity, key or certificate specified in params does not exist. */ public final void sign(Interest interest, SigningInfo params, WireFormat wireFormat) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { Name[] keyName = new Name[1]; Signature signatureInfo = prepareSignatureInfo(params, keyName); // Append the encoded SignatureInfo. interest.getName().append(wireFormat.encodeSignatureInfo(signatureInfo)); // Append an empty signature so that the "signedPortion" is correct. interest.getName().append(new Name.Component()); // Encode once to get the signed portion, and sign. SignedBlob encoding = interest.wireEncode(wireFormat); Blob signatureBytes = sign (encoding.signedBuf(), keyName[0], params.getDigestAlgorithm()); signatureInfo.setSignature(signatureBytes); // Remove the empty signature and append the real one. interest.setName(interest.getName().getPrefix(-1).append (wireFormat.encodeSignatureValue(signatureInfo))); } /** * Sign the Interest according to the supplied signing parameters. Append a * SignatureInfo to the Interest name, sign the encoded name components and * append a final name component with the signature bits. * Use the default WireFormat.getDefaultWireFormat(). * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param params The signing parameters. * @throws KeyChain.Error if signing fails. * @throws KeyChain.InvalidSigningInfoError if params is invalid, or if the * identity, key or certificate specified in params does not exist. */ public final void sign(Interest interest, SigningInfo params) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { sign(interest, params, WireFormat.getDefaultWireFormat()); } /** * Sign the Interest with the default key of the default identity. Append a * SignatureInfo to the Interest name, sign the encoded name components and * append a final name component with the signature bits. * If this is a security v1 KeyChain then use the IdentityManager to get the * default identity. Otherwise use the PIB. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param wireFormat A WireFormat object used to encode the input and encode * the appended components. */ public final void sign(Interest interest, WireFormat wireFormat) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error, SecurityException { if (isSecurityV1_) { identityManager_.signInterestByCertificate (interest, prepareDefaultCertificateName(), wireFormat); return; } sign(interest, defaultSigningInfo_, wireFormat); } /** * Sign the Interest with the default key of the default identity. Append a * SignatureInfo to the Interest name, sign the encoded name components and * append a final name component with the signature bits. * Use the default WireFormat.getDefaultWireFormat(). * If this is a security v1 KeyChain then use the IdentityManager to get the * default identity. Otherwise use the PIB. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. */ public final void sign(Interest interest) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error, SecurityException { sign(interest, WireFormat.getDefaultWireFormat()); } /** * Sign the byte buffer according to the supplied signing parameters. * @param buffer The byte buffer to be signed. * @param params The signing parameters. If params refers to an identity, this * selects the default key of the identity. If params refers to a key or * certificate, this selects the corresponding key. * @return The signature Blob, or an isNull Blob if params.getDigestAlgorithm() * is unrecognized. */ public final Blob sign(ByteBuffer buffer, SigningInfo params) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { Name[] keyName = new Name[1]; Signature signatureInfo = prepareSignatureInfo(params, keyName); return sign(buffer, keyName[0], params.getDigestAlgorithm()); } /** * Sign the byte buffer using the default key of the default identity. * @param buffer The byte buffer to be signed. * @return The signature Blob. */ public final Blob sign(ByteBuffer buffer) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { return sign(buffer, defaultSigningInfo_); } /** * Generate a self-signed certificate for the public key and add it to the * PIB. This creates the certificate name from the key name by appending * "self" and a version based on the current time. If no default certificate * for the key has been set, then set the certificate as the default for the * key. * @param key The PibKey with the key name and public key. * @param wireFormat A WireFormat object used to encode the certificate. * @return The new certificate. */ public final CertificateV2 selfSign(PibKey key, WireFormat wireFormat) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { CertificateV2 certificate = new CertificateV2(); // Set the name. double now = Common.getNowMilliseconds(); Name certificateName = new Name(key.getName()); certificateName.append("self").appendVersion((long)now); certificate.setName(certificateName); // Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY); // Set a one-hour freshness period. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0); // Set the content. certificate.setContent(key.getPublicKey()); // Set the signature-info. SigningInfo signingInfo = new SigningInfo(key); // Set a 20-year validity period. signingInfo.setValidityPeriod (new ValidityPeriod(now, now + 20 * 365 * 24 * 3600 * 1000.0)); sign(certificate, signingInfo, wireFormat); try { key.addCertificate_(certificate); } catch (CertificateV2.Error ex) { // We don't expect this since we just created the certificate. throw new Error("Error encoding certificate: " + ex); } return certificate; } /** * Generate a self-signed certificate for the public key and add it to the * PIB. This creates the certificate name from the key name by appending * "self" and a version based on the current time. If no default certificate * for the key has been set, then set the certificate as the default for the * key. * Use the default WireFormat.getDefaultWireFormat() to encode the certificate. * @param key The PibKey with the key name and public key. * @return The new certificate. */ public final CertificateV2 selfSign(PibKey key) throws PibImpl.Error, KeyChain.Error, TpmBackEnd.Error { return selfSign(key, WireFormat.getDefaultWireFormat()); } // Import and export /** * Export a certificate and its corresponding private key in a SafeBag. * @param certificate The certificate to export. This gets the key from the * TPM using certificate.getKeyName(). * @param password The password for encrypting the private key, which should * have characters in the range of 1 to 127. If the password is supplied, use * it to put a PKCS #8 EncryptedPrivateKeyInfo in the SafeBag. If the password * is null, put an unencrypted PKCS #8 PrivateKeyInfo in the SafeBag. * @return A SafeBag carrying the certificate and private key. * @throws KeyChain.Error certificate.getKeyName() key does not exist, if the * password is null and the TPM does not support exporting an unencrypted * private key, or for other errors exporting the private key. */ public final SafeBag exportSafeBag(CertificateV2 certificate, ByteBuffer password) throws KeyChain.Error { Name keyName = certificate.getKeyName(); Blob encryptedKey; try { encryptedKey = tpm_.exportPrivateKey_(keyName, password); } catch (Throwable ex) { throw new KeyChain.Error("Failed to export private key `" + keyName.toUri() + "`: " + ex); } return new SafeBag(certificate, encryptedKey); } /** * Export a certificate and its corresponding private key in a SafeBag, with a * null password which exports an unencrypted PKCS #8 PrivateKeyInfo. * @param certificate The certificate to export. This gets the key from the * TPM using certificate.getKeyName(). * @return A SafeBag carrying the certificate and private key. * @throws KeyChain.Error certificate.getKeyName() key does not exist, if the * TPM does not support exporting an unencrypted private key, or for other * errors exporting the private key. */ public final SafeBag exportSafeBag(CertificateV2 certificate) throws KeyChain.Error { return exportSafeBag(certificate, null); } /** * Import a certificate and its corresponding private key encapsulated in a * SafeBag. If the certificate and key are imported properly, the default * setting will be updated as if a new key and certificate is added into this * KeyChain. * @param safeBag The SafeBag containing the certificate and private key. This * copies the values from the SafeBag. * @param password The password for decrypting the private key, which should * have characters in the range of 1 to 127. If the password is supplied, use * it to decrypt the PKCS #8 EncryptedPrivateKeyInfo. If the password is null, * import an unencrypted PKCS #8 PrivateKeyInfo. * @throws KeyChain.Error if the private key cannot be imported, or if a * public key or private key of the same name already exists, or if a * certificate of the same name already exists. */ public final void importSafeBag(SafeBag safeBag, ByteBuffer password) throws KeyChain.Error, CertificateV2.Error, TpmBackEnd.Error, PibImpl.Error, Pib.Error { CertificateV2 certificate = new CertificateV2(safeBag.getCertificate()); Name identity = certificate.getIdentity(); Name keyName = certificate.getKeyName(); Blob publicKeyBits = certificate.getPublicKey(); if (tpm_.hasKey(keyName)) throw new KeyChain.Error("Private key `" + keyName.toUri() + "` already exists"); try { PibIdentity existingId = pib_.getIdentity(identity); existingId.getKey(keyName); throw new KeyChain.Error("Public key `" + keyName.toUri() + "` already exists"); } catch (Pib.Error ex) { // Either the identity or the key doesn't exist, so OK to import. } try { tpm_.importPrivateKey_(keyName, safeBag.getPrivateKeyBag().buf(), password); } catch (Exception ex) { throw new KeyChain.Error("Failed to import private key `" + keyName.toUri() + "`: " + ex); } // Check the consistency of the private key and certificate. Blob content = new Blob(new int[] {0x01, 0x02, 0x03, 0x04}); Blob signatureBits; try { signatureBits = tpm_.sign(content.buf(), keyName, DigestAlgorithm.SHA256); } catch (Exception ex) { tpm_.deleteKey_(keyName); throw new KeyChain.Error("Invalid private key `" + keyName.toUri() + "`"); } PublicKey publicKey; try { publicKey = new PublicKey(publicKeyBits); } catch (UnrecognizedKeyFormatException ex) { // Promote to KeyChain.Error. tpm_.deleteKey_(keyName); throw new KeyChain.Error("Error decoding public key " + ex); } if (!VerificationHelpers.verifySignature(content, signatureBits, publicKey)) { tpm_.deleteKey_(keyName); throw new KeyChain.Error("Certificate `" + certificate.getName().toUri() + "` and private key `" + keyName.toUri() + "` do not match"); } // The consistency is verified. Add to the PIB. PibIdentity id = pib_.addIdentity_(identity); PibKey key = id.addKey_(certificate.getPublicKey().buf(), keyName); key.addCertificate_(certificate); } /** * Import a certificate and its corresponding private key encapsulated in a * SafeBag, with a null password which imports an unencrypted PKCS #8 * PrivateKeyInfo. If the certificate and key are imported properly, the * default setting will be updated as if a new key and certificate is added * into this KeyChain. * @param safeBag The SafeBag containing the certificate and private key. This * copies the values from the SafeBag. * @throws KeyChain.Error if the private key cannot be imported, or if a * public key or private key of the same name already exists, or if a * certificate of the same name already exists. */ public final void importSafeBag(SafeBag safeBag) throws KeyChain.Error, CertificateV2.Error, TpmBackEnd.Error, PibImpl.Error, Pib.Error { importSafeBag(safeBag, null); } // PIB & TPM backend registry /** * Add to the PIB factories map where scheme is the key and makePibImpl is the * value. If your application has its own PIB implementations, this must be * called before creating a KeyChain instance which uses your PIB scheme. * @param scheme The PIB scheme. * @param makePibImpl An interface with makePibImpl which takes the PIB * location and returns a new PibImpl instance. */ public static void registerPibBackend(String scheme, MakePibImpl makePibImpl) { getPibFactories().put(scheme, makePibImpl); } /** * Add to the TPM factories map where scheme is the key and makeTpmBackEnd is * the value. If your application has its own TPM implementations, this must * be called before creating a KeyChain instance which uses your TPM scheme. * @param scheme The TPM scheme. * @param makeTpmBackEnd An interface with makeTpmBackEnd which takes the TPM * location and returns a new TpmBackEnd instance. */ public static void registerTpmBackend(String scheme, MakeTpmBackEnd makeTpmBackEnd) { getTpmFactories().put(scheme, makeTpmBackEnd); } // Security v1 methods /***************************************** * Identity Management * *****************************************/ /** * Create a security v1 identity by creating a pair of Key-Signing-Key (KSK) * for this identity and a self-signed certificate of the KSK. If a key pair or * certificate for the identity already exists, use it. * @param identityName The name of the identity. * @param params The key parameters if a key needs to be generated for the * identity. * @return The name of the default certificate of the identity. * @throws SecurityException if the identity has already been created. */ public final Name createIdentityAndCertificate(Name identityName, KeyParams params) throws SecurityException { return identityManager_.createIdentityAndCertificate(identityName, params); } /** * Create a security v1 identity by creating a pair of Key-Signing-Key (KSK) * for this identity and a self-signed certificate of the KSK. Use * getDefaultKeyParams() to create the key if needed. If a key pair or * certificate for the identity already exists, use it. * @param identityName The name of the identity. * @return The name of the default certificate of the identity. * @throws SecurityException if the identity has already been created. */ public final Name createIdentityAndCertificate(Name identityName) throws SecurityException { return createIdentityAndCertificate(identityName, getDefaultKeyParams()); } /** * Create a security v1 identity by creating a pair of Key-Signing-Key (KSK) * for this identity and a self-signed certificate of the KSK. * @deprecated Use createIdentityAndCertificate which returns the * certificate name instead of the key name. * @param identityName The name of the identity. * @param params The key parameters if a key needs to be generated for the * identity. * @return The key name of the auto-generated KSK of the identity. * @throws SecurityException if the identity has already been created. */ public final Name createIdentity(Name identityName, KeyParams params) throws SecurityException { return IdentityCertificate.certificateNameToPublicKeyName (createIdentityAndCertificate(identityName, params)); } /** * Create a security v1 identity by creating a pair of Key-Signing-Key (KSK) * for this identity and a self-signed certificate of the KSK. Use * getDefaultKeyParams() to create the key if needed. * @deprecated Use createIdentityAndCertificate which returns the * certificate name instead of the key name. * @param identityName The name of the identity. * @return The key name of the auto-generated KSK of the identity. * @throws SecurityException if the identity has already been created. */ public final Name createIdentity(Name identityName) throws SecurityException { return IdentityCertificate.certificateNameToPublicKeyName (createIdentityAndCertificate(identityName)); } /** * Delete the identity from the public and private key storage. If the * identity to be deleted is the current default system default, this will not * delete the identity and will return immediately. * @param identityName The name of the identity. */ public final void deleteIdentity(Name identityName) throws SecurityException { if (!isSecurityV1_) { try { deleteIdentity(pib_.getIdentity(identityName)); } catch (Pib.Error ex) { } catch (PibImpl.Error ex) { } catch (TpmBackEnd.Error ex) { } return; } identityManager_.deleteIdentity(identityName); } /** * Get the default identity. * @return The name of default identity. * @throws SecurityException if the default identity is not set. */ public final Name getDefaultIdentity() throws SecurityException { if (!isSecurityV1_) { try { return pib_.getDefaultIdentity().getName(); } catch (PibImpl.Error ex) { throw new SecurityException("Error in getDefaultIdentity: " + ex); } catch (Pib.Error ex) { throw new SecurityException("Error in getDefaultIdentity: " + ex); } } return identityManager_.getDefaultIdentity(); } /** * Get the default certificate name of the default identity. * @return The requested certificate name. * @throws SecurityException if the default identity is not set or the default * key name for the identity is not set or the default certificate name for * the key name is not set. */ public final Name getDefaultCertificateName() throws SecurityException { if (!isSecurityV1_) { try { return pib_.getDefaultIdentity().getDefaultKey().getDefaultCertificate() .getName(); } catch (PibImpl.Error ex) { throw new SecurityException("Error in getDefaultCertificate: " + ex); } catch (Pib.Error ex) { throw new SecurityException("Error in getDefaultCertificate: " + ex); } } return identityManager_.getDefaultCertificateName(); } /** * Generate a pair of RSA keys for the specified identity. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @param keySize The size of the key. * @return The generated key name. */ public final Name generateRSAKeyPair (Name identityName, boolean isKsk, int keySize) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPair(identityName, isKsk, keySize); } /** * Generate a pair of RSA keys for the specified identity and default keySize * 2048. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @return The generated key name. */ public final Name generateRSAKeyPair(Name identityName, boolean isKsk) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPair(identityName, isKsk); } /** * Generate a pair of RSA keys for the specified identity for a * Data-Signing-Key and default keySize 2048. * @param identityName The name of the identity. * @return The generated key name. */ public final Name generateRSAKeyPair(Name identityName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPair(identityName); } /** * Generate a pair of ECDSA keys for the specified identity. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @param keySize The size of the key. * @return The generated key name. */ public final Name generateEcdsaKeyPair (Name identityName, boolean isKsk, int keySize) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPair(identityName, isKsk, keySize); } /** * Generate a pair of ECDSA keys for the specified identity and default keySize * 256. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @return The generated key name. */ public final Name generateEcdsaKeyPair(Name identityName, boolean isKsk) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPair(identityName, isKsk); } /** * Generate a pair of ECDSA keys for the specified identity for a * Data-Signing-Key and default keySize 256. * @param identityName The name of the identity. * @return The generated key name. */ public final Name generateEcdsaKeyPair(Name identityName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPair is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPair(identityName); } /** * Set a key as the default key of an identity. The identity name is inferred * from keyName. * @param keyName The name of the key. * @param identityNameCheck The identity name to check that the keyName * contains the same identity name. If an empty name, it is ignored. */ public final void setDefaultKeyForIdentity(Name keyName, Name identityNameCheck) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("setDefaultKeyForIdentity is not supported for security v2. Use getPib() methods."); identityManager_.setDefaultKeyForIdentity(keyName, identityNameCheck); } /** * Set a key as the default key of an identity. The identity name is inferred * from keyName. * @param keyName The name of the key. */ public final void setDefaultKeyForIdentity(Name keyName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("setDefaultKeyForIdentity is not supported for security v2. Use getPib() methods."); identityManager_.setDefaultKeyForIdentity(keyName); } /** * Generate a pair of RSA keys for the specified identity and set it as the * default key for the identity. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @param keySize The size of the key. * @return The generated key name. */ public final Name generateRSAKeyPairAsDefault (Name identityName, boolean isKsk, int keySize) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPairAsDefault(identityName, isKsk, keySize); } /** * Generate a pair of RSA keys for the specified identity and set it as the * default key for the identity, using the default keySize 2048. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @return The generated key name. */ public final Name generateRSAKeyPairAsDefault(Name identityName, boolean isKsk) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPairAsDefault(identityName, isKsk); } /** * Generate a pair of RSA keys for the specified identity and set it as * default key for the identity for a Data-Signing-Key and using the default * keySize 2048. * @param identityName The name of the identity. * @return The generated key name. */ public final Name generateRSAKeyPairAsDefault(Name identityName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateRSAKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateRSAKeyPairAsDefault(identityName); } /** * Generate a pair of ECDSA keys for the specified identity and set it as * default key for the identity. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @param keySize The size of the key. * @return The generated key name. */ public final Name generateEcdsaKeyPairAsDefault (Name identityName, boolean isKsk, int keySize) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPairAsDefault(identityName, isKsk, keySize); } /** * Generate a pair of ECDSA keys for the specified identity and set it as * default key for the identity, using the default keySize 256. * @param identityName The name of the identity. * @param isKsk true for generating a Key-Signing-Key (KSK), false for a Data-Signing-Key (KSK). * @return The generated key name. */ public final Name generateEcdsaKeyPairAsDefault(Name identityName, boolean isKsk) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPairAsDefault(identityName, isKsk); } /** * Generate a pair of ECDSA keys for the specified identity and set it as * default key for the identity for a Data-Signing-Key and using the default * keySize 256. * @param identityName The name of the identity. * @return The generated key name. */ public final Name generateEcdsaKeyPairAsDefault(Name identityName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("generateEcdsaKeyPairAsDefault is not supported for security v2. Use createIdentityV2."); return identityManager_.generateEcdsaKeyPairAsDefault(identityName); } /** * Create a public key signing request. * @param keyName The name of the key. * @return The signing request data. * @throws SecurityException if the keyName is not found. */ public final Blob createSigningRequest(Name keyName) throws SecurityException { if (!isSecurityV1_) { try { return pib_.getIdentity(PibKey.extractIdentityFromKeyName(keyName)) .getKey(keyName).getPublicKey(); } catch (PibImpl.Error ex) { throw new SecurityException("Error in getKey: " + ex); } catch (Pib.Error ex) { throw new SecurityException("Error in getKey: " + ex); } } return identityManager_.getPublicKey(keyName).getKeyDer(); } /** * Install an identity certificate into the public key identity storage. * @param certificate The certificate to to added. */ public final void installIdentityCertificate(IdentityCertificate certificate) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("installIdentityCertificate is not supported for security v2. Use getPib() methods."); identityManager_.addCertificate(certificate); } /** * Set the certificate as the default for its corresponding key. * @param certificate The certificate. */ public final void setDefaultCertificateForKey(IdentityCertificate certificate) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("setDefaultCertificateForKey is not supported for security v2. Use getPib() methods."); identityManager_.setDefaultCertificateForKey(certificate); } /** * Get a certificate with the specified name. * @param certificateName The name of the requested certificate. * @return The requested certificate. */ public final IdentityCertificate getCertificate(Name certificateName) throws SecurityException, DerDecodingException { if (!isSecurityV1_) throw new SecurityException ("getCertificate is not supported for security v2. Use getPib() methods."); return identityManager_.getCertificate(certificateName); } /** * @deprecated Use getCertificate. */ public final IdentityCertificate getIdentityCertificate(Name certificateName) throws SecurityException, DerDecodingException { if (!isSecurityV1_) throw new SecurityException ("getIdentityCertificate is not supported for security v2. Use getPib() methods."); return identityManager_.getCertificate(certificateName); } /** * Revoke a key. * @param keyName The name of the key that will be revoked. */ public final void revokeKey(Name keyName) { //TODO: Implement } /** * Revoke a certificate. * @param certificateName The name of the certificate that will be revoked. */ public final void revokeCertificate(Name certificateName) { //TODO: Implement } /** * Get the identity manager given to or created by the constructor. * @return The identity manager. */ public final IdentityManager getIdentityManager() { if (!isSecurityV1_) throw new AssertionError ("getIdentityManager is not supported for security v2"); return identityManager_; } /***************************************** * Sign/Verify * *****************************************/ /** * Wire encode the Data object, sign it and set its signature. * @param data The Data object to be signed. This updates its signature and * key locator field and wireEncoding. * @param certificateName The certificate name of the key to use for signing. * @param wireFormat A WireFormat object used to encode the input. */ public final void sign(Data data, Name certificateName, WireFormat wireFormat) throws SecurityException { if (!isSecurityV1_) { SigningInfo signingInfo = new SigningInfo(); signingInfo.setSigningCertificateName(certificateName); try { sign(data, signingInfo, wireFormat); } catch (TpmBackEnd.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (PibImpl.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (Error ex) { throw new SecurityException("Error in sign: " + ex); } return; } identityManager_.signByCertificate(data, certificateName, wireFormat); } /** * Wire encode the Data object, sign it and set its signature. * Use the default WireFormat.getDefaultWireFormat(). * @param data The Data object to be signed. This updates its signature and * key locator field and wireEncoding. * @param certificateName The certificate name of the key to use for signing. */ public final void sign(Data data, Name certificateName) throws SecurityException { sign(data, certificateName, WireFormat.getDefaultWireFormat()); } /** * Append a SignatureInfo to the Interest name, sign the name components and * append a final name component with the signature bits. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param certificateName The certificate name of the key to use for signing. * @param wireFormat A WireFormat object used to encode the input. */ public final void sign(Interest interest, Name certificateName, WireFormat wireFormat) throws SecurityException { if (!isSecurityV1_) { SigningInfo signingInfo = new SigningInfo(); signingInfo.setSigningCertificateName(certificateName); try { sign(interest, signingInfo, wireFormat); } catch (PibImpl.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (TpmBackEnd.Error ex) { throw new SecurityException("Error in sign: " + ex); } return; } identityManager_.signInterestByCertificate (interest, certificateName, wireFormat); } /** * Append a SignatureInfo to the Interest name, sign the name components and * append a final name component with the signature bits. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param certificateName The certificate name of the key to use for signing. */ public final void sign(Interest interest, Name certificateName) throws SecurityException { sign(interest, certificateName, WireFormat.getDefaultWireFormat()); } /** * Sign the byte buffer using a certificate name and return a Signature object. * @param buffer The byte array to be signed. * @param certificateName The certificate name used to get the signing key and which will be put into KeyLocator. * @return The Signature. */ public Signature sign(ByteBuffer buffer, Name certificateName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("sign(buffer, certificateName) is not supported for security v2. Use sign with SigningInfo."); return identityManager_.signByCertificate(buffer, certificateName); } /** * Wire encode the Data object, sign it and set its signature. * @param data The Data object to be signed. This updates its signature and * key locator field and wireEncoding. * @param identityName The identity name for the key to use for signing. * If empty, infer the signing identity from the data packet name. * @param wireFormat A WireFormat object used to encode the input. If omitted, use WireFormat getDefaultWireFormat(). */ public final void signByIdentity (Data data, Name identityName, WireFormat wireFormat) throws SecurityException { if (!isSecurityV1_) { SigningInfo signingInfo = new SigningInfo(); signingInfo.setSigningIdentity(identityName); try { sign(data, signingInfo, wireFormat); } catch (TpmBackEnd.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (PibImpl.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (Error ex) { throw new SecurityException("Error in sign: " + ex); } return; } Name signingCertificateName; if (identityName.size() == 0) { Name inferredIdentity = policyManager_.inferSigningIdentity(data.getName()); if (inferredIdentity.size() == 0) signingCertificateName = identityManager_.getDefaultCertificateName(); else signingCertificateName = identityManager_.getDefaultCertificateNameForIdentity(inferredIdentity); } else signingCertificateName = identityManager_.getDefaultCertificateNameForIdentity(identityName); if (signingCertificateName.size() == 0) throw new SecurityException("No qualified certificate name found!"); if (!policyManager_.checkSigningPolicy(data.getName(), signingCertificateName)) throw new SecurityException ("Signing Cert name does not comply with signing policy"); identityManager_.signByCertificate(data, signingCertificateName, wireFormat); } /** * Wire encode the Data object, sign it and set its signature. * @param data The Data object to be signed. This updates its signature and * key locator field and wireEncoding. * Use the default WireFormat.getDefaultWireFormat(). * @param identityName The identity name for the key to use for signing. * If empty, infer the signing identity from the data packet name. */ public final void signByIdentity(Data data, Name identityName) throws SecurityException { signByIdentity(data, identityName, WireFormat.getDefaultWireFormat()); } /** * Wire encode the Data object, sign it and set its signature. * @param data The Data object to be signed. This updates its signature and * key locator field and wireEncoding. * Infer the signing identity from the data packet name. * Use the default WireFormat.getDefaultWireFormat(). */ public final void signByIdentity(Data data) throws SecurityException { signByIdentity(data, new Name(), WireFormat.getDefaultWireFormat()); } /** * Sign the byte buffer using an identity name and return a Signature object. * @param buffer The byte array to be signed. * @param identityName The identity name. * @return The Signature. */ public Signature signByIdentity(ByteBuffer buffer, Name identityName) throws SecurityException { if (!isSecurityV1_) throw new SecurityException ("signByIdentity(buffer, identityName) is not supported for security v2. Use sign with SigningInfo."); Name signingCertificateName = identityManager_.getDefaultCertificateNameForIdentity(identityName); if (signingCertificateName.size() == 0) throw new SecurityException("No qualified certificate name found!"); return identityManager_.signByCertificate(buffer, signingCertificateName); } /** * Wire encode the Data object, digest it and set its SignatureInfo to * a DigestSha256. * @param data The Data object to be signed. This updates its signature and * wireEncoding. * @param wireFormat A WireFormat object used to encode the input. */ public final void signWithSha256(Data data, WireFormat wireFormat) throws SecurityException { if (!isSecurityV1_) { SigningInfo signingInfo = new SigningInfo(); signingInfo.setSha256Signing(); try { sign(data, signingInfo, wireFormat); } catch (TpmBackEnd.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (PibImpl.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (Error ex) { throw new SecurityException("Error in sign: " + ex); } return; } identityManager_.signWithSha256(data, wireFormat); } /** * Wire encode the Data object, digest it and set its SignatureInfo to * a DigestSha256. * @param data The Data object to be signed. This updates its signature and * wireEncoding. */ public final void signWithSha256(Data data) throws SecurityException { signWithSha256(data, WireFormat.getDefaultWireFormat()); } /** * Append a SignatureInfo for DigestSha256 to the Interest name, digest the * name components and append a final name component with the signature bits * (which is the digest). * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param wireFormat A WireFormat object used to encode the input. */ public final void signWithSha256(Interest interest, WireFormat wireFormat) throws SecurityException { if (!isSecurityV1_) { SigningInfo signingInfo = new SigningInfo(); signingInfo.setSha256Signing(); try { sign(interest, signingInfo, wireFormat); } catch (PibImpl.Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (Error ex) { throw new SecurityException("Error in sign: " + ex); } catch (TpmBackEnd.Error ex) { throw new SecurityException("Error in sign: " + ex); } return; } identityManager_.signInterestWithSha256(interest, wireFormat); } /** * Append a SignatureInfo for DigestSha256 to the Interest name, digest the * name components and append a final name component with the signature bits * (which is the digest). * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. */ public final void signWithSha256(Interest interest) throws SecurityException { signWithSha256(interest, WireFormat.getDefaultWireFormat()); } public final void verifyData (Data data, OnVerified onVerified, OnDataValidationFailed onValidationFailed, int stepCount) throws SecurityException { Logger.getLogger(this.getClass().getName()).log (Level.INFO, "Enter Verify"); if (policyManager_.requireVerify(data)) { ValidationRequest nextStep = policyManager_.checkVerificationPolicy (data, stepCount, onVerified, onValidationFailed); if (nextStep != null) { VerifyCallbacks callbacks = new VerifyCallbacks (nextStep, nextStep.retry_, onValidationFailed, data); try { face_.expressInterest(nextStep.interest_, callbacks, callbacks); } catch (IOException ex) { try { onValidationFailed.onDataValidationFailed (data, "Error calling expressInterest " + ex); } catch (Throwable exception) { logger_.log(Level.SEVERE, "Error in onDataValidationFailed", exception); } } } } else if (policyManager_.skipVerifyAndTrust(data)) { try { onVerified.onVerified(data); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onVerified", ex); } } else { try { onValidationFailed.onDataValidationFailed (data, "The packet has no verify rule but skipVerifyAndTrust is false"); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onDataValidationFailed", ex); } } } /** * Check the signature on the Data object and call either onVerify.onVerify or * onValidationFailed.onDataValidationFailed. * We use callback functions because verify may fetch information to check the * signature. * @param data The Data object with the signature to check. It is an error if * data does not have a wireEncoding. * To set the wireEncoding, you can call data.wireDecode. * @param onVerified If the signature is verified, this calls * onVerified.onVerified(data). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. * @param onValidationFailed If the signature check fails, this calls * onValidationFailed.onDataValidationFailed(data, reason). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. */ public final void verifyData (Data data, OnVerified onVerified, OnDataValidationFailed onValidationFailed) throws SecurityException { verifyData(data, onVerified, onValidationFailed, 0); } /** * Check the signature on the Data object and call either onVerify.onVerify or * onVerifyFailed.onVerifyFailed. * We use callback functions because verify may fetch information to check the * signature. * @deprecated Use verifyData with OnDataValidationFailed. * @param data The Data object with the signature to check. It is an error if * data does not have a wireEncoding. * To set the wireEncoding, you can call data.wireDecode. * @param onVerified If the signature is verified, this calls * onVerified.onVerified(data). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. * @param onVerifyFailed If the signature check fails, this calls * onVerifyFailed.onVerifyFailed(data). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. */ public final void verifyData (Data data, OnVerified onVerified, final OnVerifyFailed onVerifyFailed) throws SecurityException { // Wrap the onVerifyFailed in an OnDataValidationFailed. verifyData (data, onVerified, new OnDataValidationFailed() { public void onDataValidationFailed(Data localData, String reason) { onVerifyFailed.onVerifyFailed(localData); } }); } public final void verifyInterest (Interest interest, OnVerifiedInterest onVerified, OnInterestValidationFailed onValidationFailed, int stepCount) throws SecurityException { Logger.getLogger(this.getClass().getName()).log (Level.INFO, "Enter Verify"); if (policyManager_.requireVerify(interest)) { ValidationRequest nextStep = policyManager_.checkVerificationPolicy (interest, stepCount, onVerified, onValidationFailed); if (nextStep != null) { VerifyCallbacksForVerifyInterest callbacks = new VerifyCallbacksForVerifyInterest (nextStep, nextStep.retry_, onValidationFailed, interest); try { face_.expressInterest(nextStep.interest_, callbacks, callbacks); } catch (IOException ex) { try { onValidationFailed.onInterestValidationFailed (interest, "Error calling expressInterest " + ex); } catch (Throwable exception) { logger_.log(Level.SEVERE, "Error in onInterestValidationFailed", exception); } } } } else if (policyManager_.skipVerifyAndTrust(interest)) { try { onVerified.onVerifiedInterest(interest); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onVerifiedInterest", ex); } } else { try { onValidationFailed.onInterestValidationFailed (interest, "The packet has no verify rule but skipVerifyAndTrust is false"); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onInterestValidationFailed", ex); } } } /** * Check the signature on the signed interest and call either * onVerify.onVerifiedInterest or * onValidationFailed.onInterestValidationFailed. We * use callback functions because verify may fetch information to check the * signature. * @param interest The interest with the signature to check. * @param onVerified If the signature is verified, this calls * onVerified.onVerifiedInterest(interest). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. * @param onValidationFailed If the signature check fails, this calls * onValidationFailed.onInterestValidationFailed(interest, reason). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. */ public final void verifyInterest (Interest interest, OnVerifiedInterest onVerified, OnInterestValidationFailed onValidationFailed) throws SecurityException { verifyInterest(interest, onVerified, onValidationFailed, 0); } /** * Check the signature on the signed interest and call either * onVerify.onVerifiedInterest or onVerifyFailed.onVerifyInterestFailed. We * use callback functions because verify may fetch information to check the * signature. * @deprecated Use verifyInterest with OnInterestValidationFailed. * @param interest The interest with the signature to check. * @param onVerified If the signature is verified, this calls * onVerified.onVerifiedInterest(interest). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. * @param onVerifyFailed If the signature check fails, this calls * onVerifyFailed.onVerifyInterestFailed(interest). * NOTE: The library will log any exceptions thrown by this callback, but for * better error handling the callback should catch and properly handle any * exceptions. */ public final void verifyInterest (Interest interest, OnVerifiedInterest onVerified, final OnVerifyInterestFailed onVerifyFailed) throws SecurityException { // Wrap the onVerifyFailed in an OnInterestValidationFailed. verifyInterest (interest, onVerified, new OnInterestValidationFailed() { public void onInterestValidationFailed (Interest localInterest, String reason) { onVerifyFailed.onVerifyInterestFailed(localInterest); } }); } /** * Set the Face which will be used to fetch required certificates. * @param face The Face object. */ public final void setFace(Face face) { face_ = face; } /** * Wire encode the data packet, compute an HmacWithSha256 and update the * signature value. * @note This method is an experimental feature. The API may change. * @param data The Data object to be signed. This updates its signature. * @param key The key for the HmacWithSha256. * @param wireFormat A WireFormat object used to encode the data packet. */ public static void signWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // Encode once to get the signed portion. SignedBlob encoding = data.wireEncode(wireFormat); byte[] signatureBytes = Common.computeHmacWithSha256 (key.getImmutableArray(), encoding.signedBuf()); data.getSignature().setSignature(new Blob(signatureBytes, false)); } /** * Wire encode the data packet, compute an HmacWithSha256 and update the * signature value. * Use the default WireFormat.getDefaultWireFormat(). * @note This method is an experimental feature. The API may change. * @param data The Data object to be signed. This updates its signature. * @param key The key for the HmacWithSha256. */ public static void signWithHmacWithSha256(Data data, Blob key) { signWithHmacWithSha256(data, key, WireFormat.getDefaultWireFormat()); } /** * Append a SignatureInfo to the Interest name, compute an HmacWithSha256 * signature for the name components and append a final name component with * the signature bits. * @note This method is an experimental feature. The API may change. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param key The key for the HmacWithSha256. * @param keyName The name of the key for the KeyLocator in the SignatureInfo. * @param wireFormat A WireFormat object used to encode the input. */ public static void signWithHmacWithSha256 (Interest interest, Blob key, Name keyName, WireFormat wireFormat) { HmacWithSha256Signature signature = new HmacWithSha256Signature(); signature.getKeyLocator().setType(KeyLocatorType.KEYNAME); signature.getKeyLocator().setKeyName(keyName); // Append the encoded SignatureInfo. interest.getName().append(wireFormat.encodeSignatureInfo(signature)); // Append an empty signature so that the "signedPortion" is correct. interest.getName().append(new Name.Component()); // Encode once to get the signed portion. SignedBlob encoding = interest.wireEncode(wireFormat); byte[] signatureBytes = Common.computeHmacWithSha256 (key.getImmutableArray(), encoding.signedBuf()); signature.setSignature(new Blob(signatureBytes, false)); // Remove the empty signature and append the real one. interest.setName(interest.getName().getPrefix(-1).append (wireFormat.encodeSignatureValue(signature))); } /** * Append a SignatureInfo to the Interest name, compute an HmacWithSha256 * signature for the name components and append a final name component with * the signature bits. * Use the default WireFormat.getDefaultWireFormat(). * @note This method is an experimental feature. The API may change. * @param interest The Interest object to be signed. This appends name * components of SignatureInfo and the signature bits. * @param key The key for the HmacWithSha256. * @param keyName The name of the key for the KeyLocator in the SignatureInfo. */ public static void signWithHmacWithSha256(Interest interest, Blob key, Name keyName) { signWithHmacWithSha256 (interest, key, keyName, WireFormat.getDefaultWireFormat()); } /** * Compute a new HmacWithSha256 for the data packet and verify it against the * signature value. * @note This method is an experimental feature. The API may change. * @param data The Data packet to verify. * @param key The key for the HmacWithSha256. * @param wireFormat A WireFormat object used to encode the data packet. * @return True if the signature verifies, otherwise false. */ public static boolean verifyDataWithHmacWithSha256(Data data, Blob key, WireFormat wireFormat) { // wireEncode returns the cached encoding if available. SignedBlob encoding = data.wireEncode(wireFormat); byte[] newSignatureBytes = Common.computeHmacWithSha256 (key.getImmutableArray(), encoding.signedBuf()); return ByteBuffer.wrap(newSignatureBytes).equals (data.getSignature().getSignature().buf()); } /** * Compute a new HmacWithSha256 for the data packet and verify it against the * signature value. * Use the default WireFormat.getDefaultWireFormat(). * @note This method is an experimental feature. The API may change. * @param data The Data packet to verify. * @param key The key for the HmacWithSha256. * @return True if the signature verifies, otherwise false. */ public static boolean verifyDataWithHmacWithSha256(Data data, Blob key) { return verifyDataWithHmacWithSha256 (data, key, WireFormat.getDefaultWireFormat()); } /** * Compute a new HmacWithSha256 for all but the final name component and * verify it against the signature value in the final name component. * @note This method is an experimental feature. The API may change. * @param interest The Interest object to verify. * @param key The key for the HmacWithSha256. * @param wireFormat A WireFormat object used to encode the input. * @return True if the signature verifies, otherwise false. */ public static boolean verifyInterestWithHmacWithSha256 (Interest interest, Blob key, WireFormat wireFormat) { Signature signature; try { // Decode the last two name components of the signed interest. signature = wireFormat.decodeSignatureInfoAndValue (interest.getName().get(-2).getValue().buf(), interest.getName().get(-1).getValue().buf()); } catch (EncodingException ex) { // Treat a decoding error as a verification failure. return false; } // wireEncode returns the cached encoding if available. SignedBlob encoding = interest.wireEncode(wireFormat); byte[] newSignatureBytes = Common.computeHmacWithSha256 (key.getImmutableArray(), encoding.signedBuf()); return ByteBuffer.wrap(newSignatureBytes).equals (signature.getSignature().buf()); } /** * Compute a new HmacWithSha256 for all but the final name component and * verify it against the signature value in the final name component. * Use the default WireFormat.getDefaultWireFormat(). * @note This method is an experimental feature. The API may change. * @param interest The Interest object to verify. * @param key The key for the HmacWithSha256. * @return True if the signature verifies, otherwise false. */ public static boolean verifyInterestWithHmacWithSha256(Interest interest, Blob key) { return verifyInterestWithHmacWithSha256 (interest, key, WireFormat.getDefaultWireFormat()); } public static KeyParams getDefaultKeyParams() { return defaultKeyParams_; } /** * @deprecated Use getDefaultKeyParams(). */ public static final RsaKeyParams DEFAULT_KEY_PARAMS = new RsaKeyParams(); // Private security v2 methods /** * Do the work of the constructor. */ private void construct(String pibLocator, String tpmLocator, boolean allowReset) throws KeyChain.Error, PibImpl.Error, SecurityException, IOException { ConfigFile config = new ConfigFile(); if (pibLocator.equals("")) pibLocator = getDefaultPibLocator(config); if (tpmLocator.equals("")) tpmLocator = getDefaultTpmLocator(config); // PIB locator. String[] pibScheme = new String[1]; String[] pibLocation = new String[1]; parseAndCheckPibLocator(pibLocator, pibScheme, pibLocation); String canonicalPibLocator = pibScheme[0] + ":" + pibLocation[0]; // Create the PIB. pib_ = createPib(canonicalPibLocator); String oldTpmLocator = ""; try { oldTpmLocator = pib_.getTpmLocator(); } catch (Pib.Error ex) { // The TPM locator is not set in the PIB yet. } // TPM locator. String[] tpmScheme = new String[1]; String[] tpmLocation = new String[1]; parseAndCheckTpmLocator(tpmLocator, tpmScheme, tpmLocation); String canonicalTpmLocator = tpmScheme[0] + ":" + tpmLocation[0]; if (canonicalPibLocator.equals(getDefaultPibLocator(config))) { // The default PIB must use the default TPM. if (!oldTpmLocator.equals("") && !oldTpmLocator.equals(getDefaultTpmLocator(config))) { pib_.reset_(); canonicalTpmLocator = getDefaultTpmLocator(config); } } else { // Check the consistency of the non-default PIB. if (!oldTpmLocator.equals("") && !oldTpmLocator.equals(canonicalTpmLocator)) { if (allowReset) pib_.reset_(); else throw new LocatorMismatchError ("The supplied TPM locator does not match the TPM locator in the PIB: " + oldTpmLocator + " != " + canonicalTpmLocator); } } // Note that a key mismatch may still happen if the TPM locator is initially // set to a wrong one or if the PIB was shared by more than one TPM before. // This is due to the old PIB not having TPM info. The new PIB should not // have this problem. tpm_ = createTpm(canonicalTpmLocator); pib_.setTpmLocator(canonicalTpmLocator); // Provide a default NoVerifyPolicyManager, assuming the application will // use a Validator. policyManager_ = new NoVerifyPolicyManager(); } /** * Get the PIB factories map. On the first call, this initializes the map with * factories for standard PibImpl implementations. * @return A map where the key is the scheme string and the value is the * object implementing makePibImpl. */ private static HashMap<String, MakePibImpl> getPibFactories() { if (pibFactories_ == null) { pibFactories_ = new HashMap<String, MakePibImpl>(); // Add the standard factories. pibFactories_.put(PibSqlite3.getScheme(), new MakePibImpl() { public PibImpl makePibImpl(String location) throws PibImpl.Error { return new PibSqlite3(location); } }); pibFactories_.put(PibMemory.getScheme(), new MakePibImpl() { public PibImpl makePibImpl(String location) throws PibImpl.Error { return new PibMemory(); } }); } return pibFactories_; } /** * Get the TPM factories map. On the first call, this initializes the map with * factories for standard TpmBackEnd implementations. * @return A map where the key is the scheme string and the value is the * object implementing makeTpmBackEnd. */ private static HashMap<String, MakeTpmBackEnd> getTpmFactories() { if (tpmFactories_ == null) { tpmFactories_ = new HashMap<String, MakeTpmBackEnd>(); // Add the standard factories. tpmFactories_.put(TpmBackEndFile.getScheme(), new MakeTpmBackEnd() { public TpmBackEnd makeTpmBackEnd(String location) { return new TpmBackEndFile(location); } }); tpmFactories_.put(TpmBackEndMemory.getScheme(), new MakeTpmBackEnd() { public TpmBackEnd makeTpmBackEnd(String location) { return new TpmBackEndMemory(); } }); } return tpmFactories_; } /** * Parse the uri and set the scheme and location. * @param uri The URI to parse. * @param scheme Set scheme[0] to the scheme. * @param location Set location[0] to the location. */ private static void parseLocatorUri(String uri, String[] scheme, String[] location) { int iColon = uri.indexOf(':'); if (iColon >= 0) { scheme[0] = uri.substring(0, iColon); location[0] = uri.substring(iColon + 1); } else { scheme[0] = uri; location[0] = ""; } } /** * Parse the pibLocator and set the pibScheme and pibLocation. * @param pibLocator The PIB locator to parse. * @param pibScheme Set pibScheme[0] to the PIB scheme. * @param pibLocation Set pibLocation[0] to the PIB location. */ private static void parseAndCheckPibLocator (String pibLocator, String[] pibScheme, String[] pibLocation) throws KeyChain.Error { parseLocatorUri(pibLocator, pibScheme, pibLocation); if (pibScheme[0].equals("")) pibScheme[0] = getDefaultPibScheme(); if (!getPibFactories().containsKey(pibScheme[0])) throw new KeyChain.Error("PIB scheme `" + pibScheme[0] + "` is not supported"); } /** * Parse the tpmLocator and set the tpmScheme and tpmLocation. * @param tpmLocator The TPM locator to parse. * @param tpmScheme Set tpmScheme[0] to the TPM scheme. * @param tpmLocation Set tpmLocation[0] to the TPM location. */ private static void parseAndCheckTpmLocator (String tpmLocator, String[] tpmScheme, String[] tpmLocation) throws SecurityException, Error { parseLocatorUri(tpmLocator, tpmScheme, tpmLocation); if (tpmScheme[0].equals("")) tpmScheme[0] = getDefaultTpmScheme(); if (!getTpmFactories().containsKey(tpmScheme[0])) throw new KeyChain.Error("TPM scheme `" + tpmScheme[0] + "` is not supported"); } private static String getDefaultPibScheme() { return PibSqlite3.getScheme(); } private static String getDefaultTpmScheme() throws SecurityException { if (Common.platformIsOSX()) throw new SecurityException ("TpmBackEndOsx is not implemented yet. You must use tpm-file."); return TpmBackEndFile.getScheme(); } /** * Create a Pib according to the pibLocator * @param pibLocator The PIB locator, e.g., "pib-sqlite3:/example/dir". * @return A new Pib object. */ private static Pib createPib(String pibLocator) throws KeyChain.Error, PibImpl.Error { String[] pibScheme = new String[1]; String[] pibLocation = new String[1]; parseAndCheckPibLocator(pibLocator, pibScheme, pibLocation); MakePibImpl pibFactory = getPibFactories().get(pibScheme[0]); return new Pib (pibScheme[0], pibLocation[0], pibFactory.makePibImpl(pibLocation[0])); } /** * Create a Tpm according to the tpmLocator * @param tpmLocator The TPM locator, e.g., "tpm-memory:". * @return A new Tpm object. */ private static Tpm createTpm(String tpmLocator) throws SecurityException, KeyChain.Error { String[] tpmScheme = new String[1]; String[] tpmLocation = new String[1]; parseAndCheckTpmLocator(tpmLocator, tpmScheme, tpmLocation); MakeTpmBackEnd tpmFactory = getTpmFactories().get(tpmScheme[0]); return new Tpm (tpmScheme[0], tpmLocation[0], tpmFactory.makeTpmBackEnd(tpmLocation[0])); } private static String getDefaultPibLocator(ConfigFile config) throws Error { if (defaultPibLocator_ != null) return defaultPibLocator_; String clientPib = System.getenv("NDN_CLIENT_PIB"); if (clientPib != null && clientPib != "") defaultPibLocator_ = clientPib; else defaultPibLocator_ = config.get("pib", getDefaultPibScheme() + ":"); String[] pibScheme = new String[1]; String[] pibLocation = new String[1]; parseAndCheckPibLocator(defaultPibLocator_, pibScheme, pibLocation); defaultPibLocator_ = pibScheme[0] + ":" + pibLocation[0]; return defaultPibLocator_; } private static String getDefaultTpmLocator(ConfigFile config) throws SecurityException, Error { if (defaultTpmLocator_ != null) return defaultTpmLocator_; String clientTpm = System.getenv("NDN_CLIENT_TPM"); if (clientTpm != null && clientTpm != "") defaultTpmLocator_ = clientTpm; else defaultTpmLocator_ = config.get("tpm", getDefaultTpmScheme() + ":"); String[] tpmScheme = new String[1]; String[] tpmLocation = new String[1]; parseAndCheckTpmLocator(defaultTpmLocator_, tpmScheme, tpmLocation); defaultTpmLocator_ = tpmScheme[0] + ":" + tpmLocation[0]; return defaultTpmLocator_; } /** * Prepare a Signature object according to signingInfo and get the signing key * name. * @param params The signing parameters. * @param keyName Set keyName[0] to the signing key name. * @return A new Signature object with the SignatureInfo. * @throws InvalidSigningInfoError when the requested signing method cannot be * satisfied. */ private Signature prepareSignatureInfo(SigningInfo params, Name[] keyName) throws PibImpl.Error, KeyChain.Error { PibIdentity identity = null; PibKey key = null; if (params.getSignerType() == SignerType.NULL) { try { identity = pib_.getDefaultIdentity(); } catch (Pib.Error ex) { // There is no default identity, so use sha256 for signing. keyName[0] = SigningInfo.getDigestSha256Identity(); return new DigestSha256Signature(); } } else if (params.getSignerType() == SignerType.ID) { identity = params.getPibIdentity(); if (identity == null) { try { identity = pib_.getIdentity(params.getSignerName()); } catch (Pib.Error ex) { throw new InvalidSigningInfoError ("Signing identity `" + params.getSignerName().toUri() + "` does not exist"); } } } else if (params.getSignerType() == SignerType.KEY) { key = params.getPibKey(); if (key == null) { Name identityName = PibKey.extractIdentityFromKeyName (params.getSignerName()); try { identity = pib_.getIdentity(identityName); key = identity.getKey(params.getSignerName()); // We will use the PIB key instance, so reset the identity. identity = null; } catch (Pib.Error ex) { throw new InvalidSigningInfoError ("Signing key `" + params.getSignerName().toUri() + "` does not exist"); } } } else if (params.getSignerType() == SignerType.CERT) { Name identityName = CertificateV2.extractIdentityFromCertName (params.getSignerName()); try { identity = pib_.getIdentity(identityName); key = identity.getKey (CertificateV2.extractKeyNameFromCertName(params.getSignerName())); } catch (Pib.Error ex) { throw new InvalidSigningInfoError ("Signing certificate `" + params.getSignerName().toUri() + "` does not exist"); } } else if (params.getSignerType() == SignerType.SHA256) { keyName[0] = SigningInfo.getDigestSha256Identity(); return new DigestSha256Signature(); } else // We don't expect this to happen. throw new InvalidSigningInfoError("Unrecognized signer type"); if (identity == null && key == null) throw new InvalidSigningInfoError("Cannot determine signing parameters"); if (identity != null && key == null) { try { key = identity.getDefaultKey(); } catch (Pib.Error ex) { throw new InvalidSigningInfoError ("Signing identity `" + identity.getName().toUri() + "` does not have default certificate"); } } Signature signatureInfo; if (key.getKeyType() == KeyType.RSA && params.getDigestAlgorithm() == DigestAlgorithm.SHA256) signatureInfo = new Sha256WithRsaSignature(); else if (key.getKeyType() == KeyType.EC && params.getDigestAlgorithm() == DigestAlgorithm.SHA256) signatureInfo = new Sha256WithEcdsaSignature(); else throw new KeyChain.Error("Unsupported key type"); if (params.getValidityPeriod().hasPeriod() && ValidityPeriod.canGetFromSignature(signatureInfo)) // Set the ValidityPeriod from the SigningInfo params. ValidityPeriod.getFromSignature(signatureInfo).setPeriod (params.getValidityPeriod().getNotBefore(), params.getValidityPeriod().getNotAfter()); KeyLocator keyLocator = KeyLocator.getFromSignature(signatureInfo); keyLocator.setType(KeyLocatorType.KEYNAME); keyLocator.setKeyName(key.getName()); keyName[0] = key.getName(); return signatureInfo; } /** * Sign the byte array using the key with name keyName. * @param buffer The byte buffer to be signed. * @param keyName The name of the key. * @param digestAlgorithm The digest algorithm. * @return The signature Blob, or an isNull Blob if the key does not exist, or * for an unrecognized digestAlgorithm. */ private Blob sign(ByteBuffer buffer, Name keyName, DigestAlgorithm digestAlgorithm) throws TpmBackEnd.Error { if (keyName.equals(SigningInfo.getDigestSha256Identity())) return new Blob(Common.digestSha256(buffer)); return tpm_.sign(buffer, keyName, digestAlgorithm); } // Private security v1 methods /** * A VerifyCallbacks is used for callbacks from verifyData. */ private class VerifyCallbacks implements OnData, OnTimeout { public VerifyCallbacks (ValidationRequest nextStep, int retry, OnDataValidationFailed onValidationFailed, Data originalData) { nextStep_ = nextStep; retry_ = retry; onValidationFailed_ = onValidationFailed; originalData_ = originalData; } public final void onData(Interest interest, Data data) { try { // Try to verify the certificate (data) according to the parameters in // nextStep. verifyData (data, nextStep_.onVerified_, nextStep_.onValidationFailed_, nextStep_.stepCount_); } catch (SecurityException ex) { Logger.getLogger(KeyChain.class.getName()).log(Level.SEVERE, null, ex); } } public final void onTimeout(Interest interest) { if (retry_ > 0) { // Issue the same expressInterest as in verifyData except decrement // retry. VerifyCallbacks callbacks = new VerifyCallbacks (nextStep_, retry_ - 1, onValidationFailed_, originalData_); try { face_.expressInterest(interest, callbacks, callbacks); } catch (IOException ex) { try { onValidationFailed_.onDataValidationFailed (originalData_, "Error in expressInterest to retry after timeout for fetching " + interest.getName().toUri() + ": " + ex); } catch (Throwable exception) { logger_.log(Level.SEVERE, "Error in onDataValidationFailed", exception); } } } else { try { onValidationFailed_.onDataValidationFailed (originalData_, "The retry count is zero after timeout for fetching " + interest.getName().toUri()); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onDataValidationFailed", ex); } } } private final ValidationRequest nextStep_; private final int retry_; private final OnDataValidationFailed onValidationFailed_; private final Data originalData_; } /** * A VerifyCallbacksForVerifyInterest is used for callbacks from verifyInterest. * This is the same as VerifyCallbacks, but we call * onValidationFailed.onInterestValidationFailed(originalInterest, reason) if * we have too many retries. */ private class VerifyCallbacksForVerifyInterest implements OnData, OnTimeout { public VerifyCallbacksForVerifyInterest (ValidationRequest nextStep, int retry, OnInterestValidationFailed onValidationFailed, Interest originalInterest) { nextStep_ = nextStep; retry_ = retry; onValidationFailed_ = onValidationFailed; originalInterest_ = originalInterest; } public final void onData(Interest interest, Data data) { try { // Try to verify the certificate (data) according to the parameters in // nextStep. verifyData (data, nextStep_.onVerified_, nextStep_.onValidationFailed_, nextStep_.stepCount_); } catch (SecurityException ex) { Logger.getLogger(KeyChain.class.getName()).log(Level.SEVERE, null, ex); } } public final void onTimeout(Interest interest) { if (retry_ > 0) { // Issue the same expressInterest as in verifyData except decrement // retry. VerifyCallbacksForVerifyInterest callbacks = new VerifyCallbacksForVerifyInterest (nextStep_, retry_ - 1, onValidationFailed_, originalInterest_); try { face_.expressInterest(interest, callbacks, callbacks); } catch (IOException ex) { try { onValidationFailed_.onInterestValidationFailed (originalInterest_, "Error in expressInterest to retry after timeout for fetching " + interest.getName().toUri() + ": " + ex); } catch (Throwable exception) { logger_.log(Level.SEVERE, "Error in onInterestValidationFailed", exception); } } } else { try { onValidationFailed_.onInterestValidationFailed (originalInterest_, "The retry count is zero after timeout for fetching " + interest.getName().toUri()); } catch (Throwable ex) { logger_.log(Level.SEVERE, "Error in onInterestValidationFailed", ex); } } } private final ValidationRequest nextStep_; private final int retry_; private final OnInterestValidationFailed onValidationFailed_; private final Interest originalInterest_; } /** * Get the default certificate from the identity storage and return its name. * If there is no default identity or default certificate, then create one. * @return The default certificate name. */ private Name prepareDefaultCertificateName() throws SecurityException { IdentityCertificate signingCertificate = identityManager_.getDefaultCertificate(); if (signingCertificate == null) { setDefaultCertificate(); signingCertificate = identityManager_.getDefaultCertificate(); } return signingCertificate.getName(); } /** * Create the default certificate if it is not initialized. If there is no * default identity yet, creating a new tmp-identity. */ private void setDefaultCertificate() throws SecurityException { if (identityManager_.getDefaultCertificate() == null) { Name defaultIdentity; try { defaultIdentity = identityManager_.getDefaultIdentity(); } catch (SecurityException e) { // Create a default identity name. ByteBuffer randomComponent = ByteBuffer.allocate(4); Common.getRandom().nextBytes(randomComponent.array()); defaultIdentity = new Name().append("tmp-identity") .append(new Blob(randomComponent, false)); } createIdentityAndCertificate(defaultIdentity); identityManager_.setDefaultIdentity(defaultIdentity); } } private boolean isSecurityV1_; private IdentityManager identityManager_; // for security v1 private PolicyManager policyManager_; // for security v1 private Face face_ = null; // for security v1 private Pib pib_; private Tpm tpm_; private static String defaultPibLocator_ = null; private static String defaultTpmLocator_ = null; private static HashMap<String, MakePibImpl> pibFactories_ = null; private static HashMap<String, MakeTpmBackEnd> tpmFactories_ = null; private static final SigningInfo defaultSigningInfo_ = new SigningInfo(); private static final KeyParams defaultKeyParams_ = new RsaKeyParams(); private static final Logger logger_ = Logger.getLogger(KeyChain.class.getName()); }
[ "sredwine@unomaha.edu" ]
sredwine@unomaha.edu
4ddd296557c9d84edb2d4845308bafd751758fe9
d58cb54a7c66c55611dbbc5f0c1238a9a5e52713
/hw11/ListSetTask1.java
736973ba7dd0588bcbcc51e872a96bc5ad6eafe8
[]
no_license
anna-k660/Java
34efb0f52d38d93fa8f0f2bfe04105bf60e690e3
5ed70b0a5855df5497b1a40feb1a20e2049e8149
refs/heads/master
2020-11-29T02:08:13.944910
2020-03-09T19:05:13
2020-03-09T19:05:13
229,988,448
0
0
null
null
null
null
UTF-8
Java
false
false
457
java
package hw11; import java.util.*; public class ListSetTask1 { public static void main(String[] arg) { List<Integer> list = new ArrayList<>(); for (int i = 0; i <= 10; i++) { list.add((int) (10 + Math.random() * 10)); } Set set = new HashSet(); set.addAll(list); CopyListTask1 newList = new CopyListTask1(); newList.createCopyList(list); newList.createCopySet(set); } }
[ "annkopa89@gmail.com" ]
annkopa89@gmail.com
9734dc6743cb417497e22b0dfcc143685cddb948
4174ef12830e6c0628b75402e1d62a1867a39f41
/src/main/java/com/bubblecart/product/microservice/repo/ProductRepository.java
e7d3915a7e40cc60abc6dc570c0e36e35198ef44
[]
no_license
ansuman04/product-microservice
1e3f93df5d8c753a3cd69629e57675c02805b615
fb22771267c39e3da11bc987901dc5de62373e29
refs/heads/master
2022-12-14T14:27:47.432664
2020-08-24T20:26:56
2020-08-24T20:26:56
282,401,465
0
1
null
null
null
null
UTF-8
Java
false
false
680
java
package com.bubblecart.product.microservice.repo; import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import com.bubblecart.product.microservice.domain.Product; public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> { //@Query(value = "SELECT * FROM Product p WHERE p.subcategory_id = :subcategoryId",nativeQuery = true) //public List<Product> findAllBySubcategoryId(@Param("subcategoryId") int subcategoryId); public List<Product> findBysubcategoryId(int subcategoryId,Pageable pageable); public Product findByproductId(int productId); }
[ "ansuman04@gmail.com" ]
ansuman04@gmail.com
26ac4735c81275fb2f361ba3b95cd7a363fda240
6746ae4c8bedba06b0dd3030847a76e249333e42
/app/src/androidTest/java/com/example/spinnertask/ExampleInstrumentedTest.java
7e80296d4dfd7a3e0a8ea654c954e418eb8f0f44
[]
no_license
lprabha/SpinnerTask
d183ba8eee050156dc27213a4d6a146fd58534cf
a6241a9d0ed62f21cf59519d9cc852bc2b81e5d5
refs/heads/master
2020-09-07T23:49:46.208498
2019-11-11T10:01:05
2019-11-11T10:01:05
220,948,903
0
0
null
null
null
null
UTF-8
Java
false
false
764
java
package com.example.spinnertask; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented 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() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals( "com.example.spinnertask", appContext.getPackageName() ); } }
[ "lprabha47@gmail.com" ]
lprabha47@gmail.com
b810cde7fe51d5c7b69ce88ff173926a02acce43
54e55c7a7538f072e11ba612f600e65522440aab
/messageBoard/src/com/hyunbin/controller/action/BoardWriteAction.java
398382a15d4ee0fb9c9e17883bf5cdef42a02eda
[]
no_license
hyunbinLee/messageBoard
4f975c07cbad0351172d0d8324fcd14cac887141
d2864650574218283d2428c67ac8d232794fef87
refs/heads/master
2020-12-30T12:44:41.642635
2017-05-15T15:49:43
2017-05-15T15:49:43
91,355,592
0
0
null
null
null
null
UTF-8
Java
false
false
945
java
package com.hyunbin.controller.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hyunbin.dao.BoardDAO; import com.hyunbin.dto.BoardVO; public class BoardWriteAction implements Action { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub BoardVO bVo= new BoardVO(); bVo.setName(request.getParameter("name")); bVo.setPass(request.getParameter("pass")); bVo.setEmail(request.getParameter("email")); bVo.setTitle(request.getParameter("title")); bVo.setContent(request.getParameter("content")); System.out.println("dagad"); BoardDAO bDao = BoardDAO.getInstance(); bDao.insertBoard(bVo); new BoardListAction().execute(request, response); } }
[ "lhb5759@naver.com" ]
lhb5759@naver.com
070269ff5b26a3f713d43bcf70c5b174bb2dd8d2
2e7df99174c3aa05e85a0ffc042dd76c8a9579a8
/app/src/androidTest/java/com/casassg/projectjupiter/ApplicationTest.java
9bf3e5d88f08541d9d0a09e84d85447a85d34858
[]
no_license
casassg/project_jupiter
aeb92eca62525f2e04cb4add76796d3e00d8e3a4
e0ebe5d6a52fc307f543661b77c95c874dd269b7
refs/heads/master
2021-01-20T11:45:26.567938
2015-06-21T15:10:39
2015-06-21T15:10:39
36,975,747
0
0
null
null
null
null
UTF-8
Java
false
false
357
java
package com.casassg.projectjupiter; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "gerard.casas.saez@est.fib.upc.edu" ]
gerard.casas.saez@est.fib.upc.edu
c965f63f5ec4277c17390a114089da7524e6ed34
5f6516b7b85168c2e15f5859e42ca8bee2776929
/app/build/generated/source/r/debug/ca/yorku/eecs/mack/demolayout/R.java
108e63822442bf41f34207526618e2771c73ad32
[]
no_license
gauriwahi/Demo_Layout
c0db559622b225eef6c35d89682a559db13ee0c7
4287d05720225568d71def59dd2f46b5a7600a47
refs/heads/master
2021-08-09T03:04:12.791581
2017-11-12T02:41:07
2017-11-12T02:41:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,301
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 ca.yorku.eecs.mack.demolayout; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int button1=0x7f050001; public static final int button2=0x7f050002; public static final int button3=0x7f050003; public static final int buttonClear=0x7f050004; public static final int buttonExit=0x7f050005; public static final int editText1=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; public static final int buttonClear=0x7f040001; public static final int buttonExit=0x7f040002; public static final int buttonOne=0x7f040003; public static final int buttonThree=0x7f040004; public static final int buttonTwo=0x7f040005; public static final int hello=0x7f040006; } }
[ "gauri9@DESKTOP-7NLE50V.localdomain" ]
gauri9@DESKTOP-7NLE50V.localdomain
71ea0d2097ab66ba8f323250692eba5806d3d1c7
d9b14f351f668b004c4cb05a10d09e7e85243317
/src/BaekJoon/_Before_Tagging/P11024.java
95f142ba3d1a42b180d9f630f75445983956ecc6
[]
no_license
nn98/Algorithm
262cbe20c71ff9b5de292c244b95a2a0c25e5bd7
55b6db19cb9f2aa5c5056f5cabd2b22715b682fd
refs/heads/main
2023-08-17T04:39:41.236707
2023-08-16T13:04:34
2023-08-16T13:04:34
178,701,901
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package BaekJoon._Before_Tagging; import java.util.Scanner; public class P11024 { //4�� public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int n=s.nextInt(); s.nextLine(); for(int i=0;i<n;i++) { String[] arr=s.nextLine().split(" "); int r=0; for(String j:arr) r+=Integer.parseInt(j); System.out.println(r); } } }
[ "jkllhgb@gmail.com" ]
jkllhgb@gmail.com
2cc5baab811f9e68d6627300edf69d91c73fc383
97464977f3fa1e350dbf91e66135d6b2dfb81001
/qjys_android_code/src/com/rmtech/qjys/ui/qjactivity/CaseAbstractActivity.java
9f18ec3b64e315a233af3459ec50b101a650df41
[ "Apache-2.0" ]
permissive
sunjili/QJYS
17135cf7b813356f272e5e72534390b745cde764
8a0b29058dbde2159cacce270d0fc8d39010eda7
refs/heads/master
2021-01-21T04:48:22.631739
2016-06-30T14:41:49
2016-06-30T14:41:49
55,244,439
0
2
null
null
null
null
UTF-8
Java
false
false
3,824
java
package com.rmtech.qjys.ui.qjactivity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.rmtech.qjys.R; import com.rmtech.qjys.model.CaseInfo; import com.rmtech.qjys.model.UserContext; import com.rmtech.qjys.ui.BaseActivity; import com.rmtech.qjys.ui.GroupDetailsActivity; import com.rmtech.qjys.utils.GroupAndCaseListManager; import com.umeng.analytics.MobclickAgent; /*** * 摘要 * * @author Administrator * */ public class CaseAbstractActivity extends CaseWithIdActivity { private TextView tv_content; private ImageView empty_img; private Button btn_add_abs_detail; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentView(R.layout.qj_case_abs_detail); setTitle("病例摘要"); setLeftTitle("返回"); initView(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); if (caseInfo != null) { CaseInfo tempCase = GroupAndCaseListManager.getInstance().getCaseInfoByCaseId(caseInfo.id); if (tempCase != null) { caseInfo = tempCase; } } setValue(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); MobclickAgent.onPause(this); } private void setValue() { if (caseInfo != null && !TextUtils.isEmpty(caseInfo.abs)&& UserContext.getInstance().isMyself(caseInfo.admin_doctor.id)) { tv_content.setText(caseInfo.abs); tv_content.setVisibility(View.VISIBLE); empty_img.setVisibility(View.GONE); btn_add_abs_detail.setVisibility(View.GONE); setRightTitle("编辑", new OnClickListener() { @Override public void onClick(View v) { CaseAbstractEditActivity.show(getActivity(), caseInfo); } }); } else if(caseInfo != null && !TextUtils.isEmpty(caseInfo.abs)&& !UserContext.getInstance().isMyself(caseInfo.admin_doctor.id)){ tv_content.setText(caseInfo.abs); tv_content.setVisibility(View.VISIBLE); empty_img.setVisibility(View.GONE); btn_add_abs_detail.setVisibility(View.GONE); setRightTitle("", null); } else if(caseInfo != null && TextUtils.isEmpty(caseInfo.abs)&& UserContext.getInstance().isMyself(caseInfo.admin_doctor.id)){ tv_content.setVisibility(View.GONE); empty_img.setVisibility(View.VISIBLE); btn_add_abs_detail.setVisibility(View.VISIBLE); setRightTitle("", null); } else if(caseInfo != null && TextUtils.isEmpty(caseInfo.abs)&& !UserContext.getInstance().isMyself(caseInfo.admin_doctor.id)){ tv_content.setVisibility(View.GONE); empty_img.setVisibility(View.VISIBLE); btn_add_abs_detail.setVisibility(View.GONE); setRightTitle("", null); }else if(caseInfo == null){ tv_content.setVisibility(View.GONE); empty_img.setVisibility(View.VISIBLE); btn_add_abs_detail.setVisibility(View.GONE); setRightTitle("", null); } } private void initView() { tv_content = (TextView) findViewById(R.id.content_tv); btn_add_abs_detail = (Button) findViewById(R.id.btn_add_abs_detail); btn_add_abs_detail.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO 添加摘要 CaseAbstractEditActivity.show(getActivity(), caseInfo); } }); empty_img = (ImageView)findViewById(R.id.empty_img); } protected boolean showTitleBar() { return true; } public static void show(Context context, CaseInfo caseInfo) { Intent intent = new Intent(); setCaseInfo(intent, caseInfo); intent.setClass(context, CaseAbstractActivity.class); context.startActivity(intent); } }
[ "sjl599@163.com" ]
sjl599@163.com
aa6797216381c4ad6c20456d8517620c1f430173
78f3d555d60fe4ca31f1eca8cacfbd394adf1ee5
/HelloWorld/src/thread/VolatileExample.java
9b19d2fbe2c8ab6427a534a966253f207c5667c1
[]
no_license
nguyeti/java_training
b06be1434b6e1e338294c2a44926f94fc9311c26
0b11169a2ef7fd598655bf8ee8745d68ab4be8ec
refs/heads/master
2020-12-03T00:34:46.166399
2017-07-05T23:01:09
2017-07-05T23:01:09
96,044,198
0
0
null
null
null
null
UTF-8
Java
false
false
843
java
package thread; import java.util.Scanner; /** * Created by nguyeti on 22/06/2017.* * THREAD SYNCHRONIZATION */ class Processor extends Thread { private volatile boolean running = true; // prevent threads caching variables public void run(){ while(running){ System.out.println("Hellooooo"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public void shutdown(){ running = false; } } public class VolatileExample { public static void main(String[] args){ Processor p1 = new Processor(); p1.start(); System.out.println("Press RETURN to stop."); Scanner sc = new Scanner(System.in); sc.nextLine(); p1.shutdown(); } }
[ "nguyen.timothee@gmail.com" ]
nguyen.timothee@gmail.com
4ef72429e1315c07033476a30c4ecdc57971c3a0
df82807e57a2247ff7bb4e58209188dfa99dfbcf
/src/leetcode/Node.java
b5664e0ce85cd8d29fde10ffc70efcfc76301d63
[]
no_license
mjydata/OfferPractise
11514de2f927be6090626ec9ed7bffe1717bcb89
bf140fbcc47e1f436e96e80916ea6f77906f7c99
refs/heads/master
2021-06-20T12:18:55.762695
2020-12-12T15:51:53
2020-12-12T15:51:53
134,968,015
0
0
null
null
null
null
ISO-8859-7
Java
false
false
100
java
package leetcode; /** * @author T-Cool * @date 2020/12/8 ΟΒΞη11:55 */ public class Node { }
[ "miaojunyu@xiaomi.com" ]
miaojunyu@xiaomi.com
cfbd0192f6de34cbaa6b6f5d29a75d1ae5882001
f49de10c5f3e4201b6a07771bf84a38c6468f1a8
/src/main/java/com/dev/bond/service/impl/EntityLimitServiceImpl.java
054b4aaf98708cae1f2f9a7e82d11d8449936cbf
[]
no_license
darking-sun/bond
cf945f7d77ef0d88dd9a53f76e31e1872c1d85f1
8440275332910099a55f0a55e04d896d39734fed
refs/heads/master
2022-06-24T09:30:24.205822
2020-04-17T14:44:04
2020-04-17T14:44:04
254,273,123
0
0
null
2022-06-17T03:05:08
2020-04-09T04:44:29
Java
UTF-8
Java
false
false
495
java
package com.dev.bond.service.impl; import com.dev.bond.entity.EntityLimit; import com.dev.bond.mapper.EntityLimitMapper; import com.dev.bond.service.IEntityLimitService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author wzj123 * @since 2020-03-16 */ @Service public class EntityLimitServiceImpl extends ServiceImpl<EntityLimitMapper, EntityLimit> implements IEntityLimitService { }
[ "1563024120@qq.com" ]
1563024120@qq.com
f8c471c1df5cf6183ec4fbbd88a2a1483ed29d36
ec570b616e7da5884cff2df4f0e22082fb10410f
/app/src/main/java/com/junerver/testo2oapp/utils/HttpUtils.java
16b70f90a2251c84d08e0c81c4819f426ff5cdc1
[ "Apache-2.0" ]
permissive
lisazhu1993/TestO2OApp
d5a06dd2317c0c98e30ac8afc2f912ebd2239288
476480a4b791a21479dfbc6e8e75bd74200f5750
refs/heads/master
2021-01-22T00:10:37.975394
2015-11-25T12:20:32
2015-11-25T12:20:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,337
java
package com.junerver.testo2oapp.utils; /** * Created by Junerver on 2015/11/12. * Http请求的工具类 * */ import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; /** * * * @author zhy * */ public class HttpUtils { private static final int TIMEOUT_IN_MILLIONS = 5000; public interface CallBack { void onRequestComplete(String result); } /** * 异步的Get请求 * * @param urlStr * @param callBack */ public static void doGetAsyn(final String urlStr, final CallBack callBack) { new Thread() { public void run() { try { String result = doGet(urlStr); if (callBack != null) { callBack.onRequestComplete(result); } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } /** * 异步的Post请求 * @param urlStr * @param params * @param callBack * @throws Exception */ public static void doPostAsyn(final String urlStr, final String params, final CallBack callBack) throws Exception { new Thread() { public void run() { try { String result = doPost(urlStr, params); if (callBack != null) { callBack.onRequestComplete(result); } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } /** * Get请求,获得返回数据 * * @param urlStr * @return * @throws Exception */ public static String doGet(String urlStr) { URL url = null; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null ; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 * @throws Exception */ public static String doPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setUseCaches(false); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); if (param != null && !param.trim().equals("")) { // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); } // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
[ "junerver@gmail.com" ]
junerver@gmail.com
b4effcf8f91393343f99a8d28a2941e89672d29a
ff09c459a1629eaf3cc948e1565e53fc817c516c
/src/main/java/com/vaguehope/cmstoad/Args.java
6d2c5772af53354983f9bfb976b140462434e332
[]
no_license
haku/cmstoad
3f8d25428d7151fc9a280149b4666024b2e5a075
a25e12a6d6eca12376ab359321b0d471ee9b9bbf
refs/heads/master
2016-08-07T01:43:17.173985
2013-07-19T10:39:09
2013-07-19T10:39:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,884
java
package com.vaguehope.cmstoad; import java.io.File; import java.io.IOException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.spi.StopOptionHandler; public class Args { @Argument(index = 0, required = true, metaVar = "<action>", usage = Action.USAGE) private Action action; @Argument(index = 1, multiValued = true, metaVar = "FILE") @Option(name = "--", handler = StopOptionHandler.class) private List<String> filePaths; @Option(name = "--name", aliases = "-n", metaVar = "my_key", usage = "name for the generated keypair") private String name; @Option(name = "--keysize", aliases = "-s", metaVar = "4096", usage = "length of the generated private key") private int keysize; @Option(name = "--publickey", aliases = "-u", metaVar = "my_key.public.pem", multiValued = true, usage = "public key(s) to encrypt file to") private List<String> publicKeyPaths; @Option(name = "--privatekey", aliases = "-i", metaVar = "my_key.private.pem", multiValued = true, usage = "private key(s) to decrypt file with") private List<String> privateKeyPaths; public Action getAction () { return this.action; } public List<File> getFiles (boolean required, boolean mustExist) throws CmdLineException { if (required && (this.filePaths == null || this.filePaths.isEmpty())) throw new CmdLineException(null, "At least one file is required."); List<File> files = pathsToFiles(this.filePaths); if (mustExist) checkFilesExist(files); return files; } public String getName (boolean required) throws CmdLineException { if (required && (this.name == null || this.name.isEmpty())) throw new CmdLineException(null, "Name is required."); return this.name; } public int getKeysize (boolean required) throws CmdLineException { if (required && (this.keysize < C.MIN_KEY_LENGTH)) throw new CmdLineException(null, "Keysize is required and must be at least 1024."); return this.keysize; } public Map<String, PublicKey> getPublicKeys (boolean required) throws CmdLineException, IOException { if (required && (this.publicKeyPaths == null || this.publicKeyPaths.isEmpty())) throw new CmdLineException(null, "At least one public key is required."); return readKeys(PublicKey.class, this.publicKeyPaths); } public Map<String, PrivateKey> getPrivteKeys (boolean required) throws CmdLineException, IOException { if (required && (this.privateKeyPaths == null || this.privateKeyPaths.isEmpty())) throw new CmdLineException(null, "At least one private key is required."); return readKeys(PrivateKey.class, this.privateKeyPaths); } public <T extends Key> Map<String, T> readKeys (Class<T> type, List<String> paths) throws CmdLineException, IOException { List<File> files = pathsToFiles(paths); checkFilesExist(files); return KeyHelper.readKeys(files, type); } private static List<File> pathsToFiles (List<String> paths) { List<File> files = new ArrayList<File>(); for (String path : paths) { files.add(new File(path)); } return files; } private static void checkFilesExist (List<File> files) throws CmdLineException { for (File file : files) { if (!IoHelper.fileExists(file)) { throw new CmdLineException(null, "File not found: " + file.getAbsolutePath()); } } } public static enum Action { HELP, INFO, KEYGEN, ENCRYPT, DECRYPT, BENCHMARK; private static final String USAGE = "" + "help : display this help and exit\n" + "info : display CMS header info for specified files\n" + "keygen : generate a key pair\n" + "encrypt : encrypt files(s)\n" + "decrypt : decrypt files(s)\n" + "benchmark : run performance benchmark"; } }
[ "haku@vaguehope.com" ]
haku@vaguehope.com
9d028ff2b016ca33156a912e0c86311c9d495ddb
a1aaa6be8b6695874cbdbeadd10dc77e27cbd569
/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/test/java/org/apache/nifi/processors/standard/TestHashContent.java
d14683c7e48043727650724b12aab0681642bea8
[ "MIT", "ISC", "Apache-2.0" ]
permissive
wangrenlei/localization_nifi
a5433045795ef051edbd1a05b9a91b369b15f15c
6f8f74186b8b52af35b0e8d229c918db715f2c87
refs/heads/master
2020-03-18T08:20:34.318891
2018-05-23T02:59:35
2018-05-23T02:59:35
134,503,849
32
8
Apache-2.0
2019-01-02T08:42:29
2018-05-23T02:48:34
Java
UTF-8
Java
false
false
2,527
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.standard; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Paths; import org.apache.nifi.util.MockFlowFile; import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunners; import org.junit.Test; public class TestHashContent { @Test public void testMD5() throws IOException { // Expected hash value obtained by running Linux md5sum against the file test("MD5", "65a8e27d8879283831b664bd8b7f0ad4"); } @Test public void testSHA256() throws IOException { // Expected hash value obtained by running Linux sha256sum against the file test("SHA-256", "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"); } @Test public void testSHA1() throws IOException { // Expected hash value obtained by running Linux sha1sum against the file test("SHA", "0a0a9f2a6772942557ab5355d76af442f8f65e01"); } private void test(final String hashAlgorithm, final String expectedHash) throws IOException { final TestRunner runner = TestRunners.newTestRunner(new HashContent()); runner.setProperty(HashContent.ATTRIBUTE_NAME, "hash"); runner.setProperty(HashContent.HASH_ALGORITHM, hashAlgorithm); runner.enqueue(Paths.get("src/test/resources/hello.txt")); runner.run(); runner.assertQueueEmpty(); runner.assertAllFlowFilesTransferred(HashContent.REL_SUCCESS, 1); final MockFlowFile outFile = runner.getFlowFilesForRelationship(HashContent.REL_SUCCESS).get(0); final String hashValue = outFile.getAttribute("hash"); assertEquals(expectedHash, hashValue); } }
[ "joewitt@apache.org" ]
joewitt@apache.org
89cd7a0b5a43ea222aeee35e70209bc6c0867eef
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.qqlite/classes.jar/com/tencent/mobileqq/msf/service/h.java
573b90418917c7a1369b8edc15069d7b4d1b237e
[]
no_license
tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651957
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
2022-01-31T09:46:26
2022-01-31T02:43:22
Java
UTF-8
Java
false
false
31,912
java
package com.tencent.mobileqq.msf.service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.IBinder.DeathRecipient; import android.os.IInterface; import android.os.RemoteException; import com.tencent.mobileqq.msf.core.MsfCore; import com.tencent.mobileqq.msf.core.b.m; import com.tencent.mobileqq.msf.core.push.f; import com.tencent.qphone.base.util.BaseApplication; import com.tencent.qphone.base.util.QLog; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Random; public class h implements IBinder.DeathRecipient { private static final int A = 1; private static final int B = 0; private static final int E = 3600000; public static final int a = 2; public static final int b = 1; public static final int c = 0; private static final int f = 500; private static final String g = "GuardManager"; private static final String h = "gm_history"; private static final int i = 1; private static final int j = 2; private static final int k = 3; private static final int l = 4; private static final int m = 5; private static long t = 720000L; private static long v = 0L; private static final int z = 2; private int C = 0; private int D = 3; public boolean d = false; public volatile boolean e = false; private long[] n = null; private long[] o = null; private long[] p = null; private long[] q = null; private long r = 0L; private int s = 0; private IBinder u; private int w = 1; private long x = 0L; private MsfCore y; public h(MsfCore paramMsfCore) { this.y = paramMsfCore; } private void a(long paramLong, int paramInt1, int paramInt2, boolean paramBoolean, int paramInt3) { if (this.n == null) { b(); } int i3 = this.o.length; if (paramInt1 != i3) { localObject = new long[24]; long[] arrayOfLong1 = new long[24]; long[] arrayOfLong2 = new long[24]; long[] arrayOfLong3 = new long[24]; int i4 = 24 / i3; i1 = 0; int i2; while (i1 < i3) { i2 = 0; while (i2 < i4) { localObject[(i1 * i4 + i2)] = 0L; arrayOfLong1[(i1 * i4 + i2)] = 0L; arrayOfLong2[(i1 * i4 + i2)] = 0L; arrayOfLong3[(i1 * i4 + i2)] = 0L; i2 += 1; } localObject[((int)(this.n[i1] / 3600000L))] = this.n[i1]; arrayOfLong1[((int)(this.n[i1] / 3600000L))] = this.o[i1]; arrayOfLong2[((int)(this.p[i1] / 3600000L))] = this.p[i1]; arrayOfLong3[((int)(this.p[i1] / 3600000L))] = this.q[i1]; i1 += 1; } this.n = new long[paramInt1]; this.o = new long[paramInt1]; this.p = new long[paramInt1]; this.q = new long[paramInt1]; i3 = 24 / paramInt1; i1 = 0; while (i1 < paramInt1) { i2 = 0; while (i2 < i3) { arrayOfLong2 = this.o; arrayOfLong2[i1] += arrayOfLong1[(i1 * i3 + i2)]; arrayOfLong2 = this.n; arrayOfLong2[i1] += localObject[(i1 * i3 + i2)] * arrayOfLong1[(i1 * i3 + i2)]; arrayOfLong2 = this.q; arrayOfLong2[i1] += arrayOfLong1[(i1 * i3 + i2)]; arrayOfLong2 = this.p; arrayOfLong2[i1] += localObject[(i1 * i3 + i2)] * arrayOfLong1[(i1 * i3 + i2)]; i2 += 1; } if (this.o[i1] != 0L) { arrayOfLong2 = this.n; arrayOfLong2[i1] /= this.o[i1]; } if (this.q[i1] != 0L) { arrayOfLong2 = this.p; arrayOfLong2[i1] /= this.q[i1]; } i1 += 1; } } Object localObject = Calendar.getInstance(Locale.getDefault()); ((Calendar)localObject).setTimeInMillis(paramLong - 15000L); int i1 = ((Calendar)localObject).get(7); paramInt1 = ((Calendar)localObject).get(11); paramLong = paramInt1 * 60 * 60 * 1000 + paramLong % 3600000L; long l1; if (this.C == 2) { if (paramBoolean) { localObject = "11"; a("GM_StartTime", paramLong, (String)localObject); paramInt1 /= 24 / this.n.length; if ((i1 == 1) || (i1 == 7)) { break label749; } l1 = this.o[paramInt1] + 1L; paramLong = (this.n[paramInt1] * this.o[paramInt1] + paramLong) / l1; this.n[paramInt1] = paramLong; this.o[paramInt1] = l1; label656: this.D = paramInt2; if (paramInt3 == 0) { break label801; } if (paramInt3 != 2) { break label796; } paramInt1 = 2; this.C = paramInt1; } } label749: while (this.C != 0) { for (;;) { c(); if (this.r != i1) { this.r = i1; this.s = 0; } if (paramBoolean) { this.s += 1; } return; localObject = "10"; break; if (paramBoolean) { localObject = "01"; break; } localObject = "00"; break; l1 = this.q[paramInt1] + 1L; paramLong = (this.p[paramInt1] * this.q[paramInt1] + paramLong) / l1; this.p[paramInt1] = paramLong; this.q[paramInt1] = l1; break label656; paramInt1 = 1; } } label796: label801: if (new Random().nextInt(2) == 0) {} for (paramInt1 = 2;; paramInt1 = 1) { this.C = paramInt1; break; } } private void a(String paramString1, long paramLong, String paramString2) { HashMap localHashMap = null; if (paramString2 != null) { localHashMap = new HashMap(); localHashMap.put("Tag", paramString2); } this.y.getStatReporter().a(paramString1, true, paramLong, 0L, localHashMap, false, false); } /* Error */ private void b() { // Byte code: // 0: iconst_0 // 1: istore_2 // 2: aload_0 // 3: monitorenter // 4: new 171 java/io/ObjectInputStream // 7: dup // 8: invokestatic 177 com/tencent/qphone/base/util/BaseApplication:getContext ()Landroid/content/Context; // 11: ldc 26 // 13: invokevirtual 183 android/content/Context:openFileInput (Ljava/lang/String;)Ljava/io/FileInputStream; // 16: invokespecial 186 java/io/ObjectInputStream:<init> (Ljava/io/InputStream;)V // 19: astore 5 // 21: aload 5 // 23: astore 4 // 25: aload 5 // 27: invokevirtual 190 java/io/ObjectInputStream:readByte ()B // 30: istore_3 // 31: iload_3 // 32: ifeq +88 -> 120 // 35: bipush 24 // 37: iload_3 // 38: irem // 39: ifne +81 -> 120 // 42: aload 5 // 44: astore 4 // 46: iload_3 // 47: newarray long // 49: astore 6 // 51: aload 5 // 53: astore 4 // 55: iload_3 // 56: newarray long // 58: astore 7 // 60: iconst_0 // 61: istore_1 // 62: iload_1 // 63: iload_3 // 64: if_icmpge +36 -> 100 // 67: aload 5 // 69: astore 4 // 71: aload 7 // 73: iload_1 // 74: aload 5 // 76: invokevirtual 194 java/io/ObjectInputStream:readLong ()J // 79: lastore // 80: aload 5 // 82: astore 4 // 84: aload 6 // 86: iload_1 // 87: aload 5 // 89: invokevirtual 194 java/io/ObjectInputStream:readLong ()J // 92: lastore // 93: iload_1 // 94: iconst_1 // 95: iadd // 96: istore_1 // 97: goto -35 -> 62 // 100: aload 5 // 102: astore 4 // 104: aload_0 // 105: aload 6 // 107: putfield 75 com/tencent/mobileqq/msf/service/h:o [J // 110: aload 5 // 112: astore 4 // 114: aload_0 // 115: aload 7 // 117: putfield 73 com/tencent/mobileqq/msf/service/h:n [J // 120: aload 5 // 122: astore 4 // 124: aload_0 // 125: aload 5 // 127: invokevirtual 198 java/io/ObjectInputStream:readInt ()I // 130: putfield 91 com/tencent/mobileqq/msf/service/h:D I // 133: aload 5 // 135: astore 4 // 137: aload_0 // 138: aload 5 // 140: invokevirtual 198 java/io/ObjectInputStream:readInt ()I // 143: putfield 89 com/tencent/mobileqq/msf/service/h:C I // 146: iload_3 // 147: ifeq +88 -> 235 // 150: bipush 24 // 152: iload_3 // 153: irem // 154: ifne +81 -> 235 // 157: aload 5 // 159: astore 4 // 161: iload_3 // 162: newarray long // 164: astore 6 // 166: aload 5 // 168: astore 4 // 170: iload_3 // 171: newarray long // 173: astore 7 // 175: iload_2 // 176: istore_1 // 177: iload_1 // 178: iload_3 // 179: if_icmpge +36 -> 215 // 182: aload 5 // 184: astore 4 // 186: aload 7 // 188: iload_1 // 189: aload 5 // 191: invokevirtual 194 java/io/ObjectInputStream:readLong ()J // 194: lastore // 195: aload 5 // 197: astore 4 // 199: aload 6 // 201: iload_1 // 202: aload 5 // 204: invokevirtual 194 java/io/ObjectInputStream:readLong ()J // 207: lastore // 208: iload_1 // 209: iconst_1 // 210: iadd // 211: istore_1 // 212: goto -35 -> 177 // 215: aload 5 // 217: astore 4 // 219: aload_0 // 220: aload 6 // 222: putfield 79 com/tencent/mobileqq/msf/service/h:q [J // 225: aload 5 // 227: astore 4 // 229: aload_0 // 230: aload 7 // 232: putfield 77 com/tencent/mobileqq/msf/service/h:p [J // 235: aload 5 // 237: ifnull +8 -> 245 // 240: aload 5 // 242: invokevirtual 201 java/io/ObjectInputStream:close ()V // 245: aload_0 // 246: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 249: ifnonnull +17 -> 266 // 252: aload_0 // 253: iconst_1 // 254: newarray long // 256: putfield 75 com/tencent/mobileqq/msf/service/h:o [J // 259: aload_0 // 260: iconst_1 // 261: newarray long // 263: putfield 73 com/tencent/mobileqq/msf/service/h:n [J // 266: aload_0 // 267: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 270: ifnonnull +25 -> 295 // 273: aload_0 // 274: aload_0 // 275: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 278: arraylength // 279: newarray long // 281: putfield 79 com/tencent/mobileqq/msf/service/h:q [J // 284: aload_0 // 285: aload_0 // 286: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 289: arraylength // 290: newarray long // 292: putfield 77 com/tencent/mobileqq/msf/service/h:p [J // 295: aload_0 // 296: monitorexit // 297: return // 298: astore 6 // 300: aconst_null // 301: astore 5 // 303: aload 5 // 305: astore 4 // 307: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 310: ifeq +17 -> 327 // 313: aload 5 // 315: astore 4 // 317: ldc 23 // 319: iconst_2 // 320: ldc 209 // 322: aload 6 // 324: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 327: aload 5 // 329: ifnull -84 -> 245 // 332: aload 5 // 334: invokevirtual 201 java/io/ObjectInputStream:close ()V // 337: goto -92 -> 245 // 340: astore 4 // 342: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 345: ifeq -100 -> 245 // 348: ldc 23 // 350: iconst_2 // 351: ldc 214 // 353: aload 4 // 355: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 358: goto -113 -> 245 // 361: astore 4 // 363: aload_0 // 364: monitorexit // 365: aload 4 // 367: athrow // 368: astore 5 // 370: aconst_null // 371: astore 4 // 373: aload 4 // 375: ifnull +8 -> 383 // 378: aload 4 // 380: invokevirtual 201 java/io/ObjectInputStream:close ()V // 383: aload 5 // 385: athrow // 386: astore 4 // 388: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 391: ifeq -8 -> 383 // 394: ldc 23 // 396: iconst_2 // 397: ldc 214 // 399: aload 4 // 401: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 404: goto -21 -> 383 // 407: astore 4 // 409: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 412: ifeq -167 -> 245 // 415: ldc 23 // 417: iconst_2 // 418: ldc 214 // 420: aload 4 // 422: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 425: goto -180 -> 245 // 428: astore 5 // 430: goto -57 -> 373 // 433: astore 6 // 435: goto -132 -> 303 // Local variable table: // start length slot name signature // 0 438 0 this h // 61 151 1 i1 int // 1 175 2 i2 int // 30 150 3 i3 int // 23 293 4 localObjectInputStream1 java.io.ObjectInputStream // 340 14 4 localIOException1 java.io.IOException // 361 5 4 localObject1 Object // 371 8 4 localObject2 Object // 386 14 4 localIOException2 java.io.IOException // 407 14 4 localIOException3 java.io.IOException // 19 314 5 localObjectInputStream2 java.io.ObjectInputStream // 368 16 5 localObject3 Object // 428 1 5 localObject4 Object // 49 172 6 arrayOfLong1 long[] // 298 25 6 localThrowable1 java.lang.Throwable // 433 1 6 localThrowable2 java.lang.Throwable // 58 173 7 arrayOfLong2 long[] // Exception table: // from to target type // 4 21 298 java/lang/Throwable // 332 337 340 java/io/IOException // 240 245 361 finally // 245 266 361 finally // 266 295 361 finally // 332 337 361 finally // 342 358 361 finally // 378 383 361 finally // 383 386 361 finally // 388 404 361 finally // 409 425 361 finally // 4 21 368 finally // 378 383 386 java/io/IOException // 240 245 407 java/io/IOException // 25 31 428 finally // 46 51 428 finally // 55 60 428 finally // 71 80 428 finally // 84 93 428 finally // 104 110 428 finally // 114 120 428 finally // 124 133 428 finally // 137 146 428 finally // 161 166 428 finally // 170 175 428 finally // 186 195 428 finally // 199 208 428 finally // 219 225 428 finally // 229 235 428 finally // 307 313 428 finally // 317 327 428 finally // 25 31 433 java/lang/Throwable // 46 51 433 java/lang/Throwable // 55 60 433 java/lang/Throwable // 71 80 433 java/lang/Throwable // 84 93 433 java/lang/Throwable // 104 110 433 java/lang/Throwable // 114 120 433 java/lang/Throwable // 124 133 433 java/lang/Throwable // 137 146 433 java/lang/Throwable // 161 166 433 java/lang/Throwable // 170 175 433 java/lang/Throwable // 186 195 433 java/lang/Throwable // 199 208 433 java/lang/Throwable // 219 225 433 java/lang/Throwable // 229 235 433 java/lang/Throwable } /* Error */ private void c() { // Byte code: // 0: iconst_0 // 1: istore_2 // 2: aload_0 // 3: monitorenter // 4: aload_0 // 5: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 8: ifnull +27 -> 35 // 11: aload_0 // 12: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 15: arraylength // 16: iconst_1 // 17: if_icmpne +21 -> 38 // 20: aload_0 // 21: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 24: iconst_0 // 25: laload // 26: lstore 4 // 28: lload 4 // 30: lconst_0 // 31: lcmp // 32: ifne +6 -> 38 // 35: aload_0 // 36: monitorexit // 37: return // 38: new 216 java/io/ObjectOutputStream // 41: dup // 42: invokestatic 177 com/tencent/qphone/base/util/BaseApplication:getContext ()Landroid/content/Context; // 45: ldc 26 // 47: iconst_0 // 48: invokevirtual 220 android/content/Context:openFileOutput (Ljava/lang/String;I)Ljava/io/FileOutputStream; // 51: invokespecial 223 java/io/ObjectOutputStream:<init> (Ljava/io/OutputStream;)V // 54: astore 7 // 56: aload 7 // 58: astore 6 // 60: aload_0 // 61: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 64: arraylength // 65: istore_3 // 66: aload 7 // 68: astore 6 // 70: aload 7 // 72: iload_3 // 73: invokevirtual 227 java/io/ObjectOutputStream:writeByte (I)V // 76: iconst_0 // 77: istore_1 // 78: iload_1 // 79: iload_3 // 80: if_icmpge +40 -> 120 // 83: aload 7 // 85: astore 6 // 87: aload 7 // 89: aload_0 // 90: getfield 73 com/tencent/mobileqq/msf/service/h:n [J // 93: iload_1 // 94: laload // 95: invokevirtual 230 java/io/ObjectOutputStream:writeLong (J)V // 98: aload 7 // 100: astore 6 // 102: aload 7 // 104: aload_0 // 105: getfield 75 com/tencent/mobileqq/msf/service/h:o [J // 108: iload_1 // 109: laload // 110: invokevirtual 230 java/io/ObjectOutputStream:writeLong (J)V // 113: iload_1 // 114: iconst_1 // 115: iadd // 116: istore_1 // 117: goto -39 -> 78 // 120: aload 7 // 122: astore 6 // 124: aload 7 // 126: aload_0 // 127: getfield 91 com/tencent/mobileqq/msf/service/h:D I // 130: invokevirtual 233 java/io/ObjectOutputStream:writeInt (I)V // 133: aload 7 // 135: astore 6 // 137: aload 7 // 139: aload_0 // 140: getfield 89 com/tencent/mobileqq/msf/service/h:C I // 143: invokevirtual 233 java/io/ObjectOutputStream:writeInt (I)V // 146: aload 7 // 148: astore 6 // 150: aload_0 // 151: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 154: ifnull +194 -> 348 // 157: aload 7 // 159: astore 6 // 161: aload_0 // 162: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 165: arraylength // 166: iconst_1 // 167: if_icmpne +18 -> 185 // 170: aload 7 // 172: astore 6 // 174: aload_0 // 175: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 178: iconst_0 // 179: laload // 180: lconst_0 // 181: lcmp // 182: ifeq +166 -> 348 // 185: aload 7 // 187: astore 6 // 189: aload_0 // 190: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 193: arraylength // 194: istore_3 // 195: iload_2 // 196: istore_1 // 197: iload_1 // 198: iload_3 // 199: if_icmpge +149 -> 348 // 202: aload 7 // 204: astore 6 // 206: aload 7 // 208: aload_0 // 209: getfield 77 com/tencent/mobileqq/msf/service/h:p [J // 212: iload_1 // 213: laload // 214: invokevirtual 230 java/io/ObjectOutputStream:writeLong (J)V // 217: aload 7 // 219: astore 6 // 221: aload 7 // 223: aload_0 // 224: getfield 79 com/tencent/mobileqq/msf/service/h:q [J // 227: iload_1 // 228: laload // 229: invokevirtual 230 java/io/ObjectOutputStream:writeLong (J)V // 232: iload_1 // 233: iconst_1 // 234: iadd // 235: istore_1 // 236: goto -39 -> 197 // 239: astore 8 // 241: aconst_null // 242: astore 7 // 244: aload 7 // 246: astore 6 // 248: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 251: ifeq +17 -> 268 // 254: aload 7 // 256: astore 6 // 258: ldc 23 // 260: iconst_2 // 261: ldc 214 // 263: aload 8 // 265: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 268: aload 7 // 270: ifnull -235 -> 35 // 273: aload 7 // 275: invokevirtual 234 java/io/ObjectOutputStream:close ()V // 278: goto -243 -> 35 // 281: astore 6 // 283: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 286: ifeq -251 -> 35 // 289: ldc 23 // 291: iconst_2 // 292: ldc 214 // 294: aload 6 // 296: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 299: goto -264 -> 35 // 302: astore 6 // 304: aload_0 // 305: monitorexit // 306: aload 6 // 308: athrow // 309: astore 7 // 311: aconst_null // 312: astore 6 // 314: aload 6 // 316: ifnull +8 -> 324 // 319: aload 6 // 321: invokevirtual 234 java/io/ObjectOutputStream:close ()V // 324: aload 7 // 326: athrow // 327: astore 6 // 329: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 332: ifeq -8 -> 324 // 335: ldc 23 // 337: iconst_2 // 338: ldc 214 // 340: aload 6 // 342: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 345: goto -21 -> 324 // 348: aload 7 // 350: ifnull -315 -> 35 // 353: aload 7 // 355: invokevirtual 234 java/io/ObjectOutputStream:close ()V // 358: goto -323 -> 35 // 361: astore 6 // 363: invokestatic 207 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 366: ifeq -331 -> 35 // 369: ldc 23 // 371: iconst_2 // 372: ldc 214 // 374: aload 6 // 376: invokestatic 212 com/tencent/qphone/base/util/QLog:d (Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V // 379: goto -344 -> 35 // 382: astore 7 // 384: goto -70 -> 314 // 387: astore 8 // 389: goto -145 -> 244 // Local variable table: // start length slot name signature // 0 392 0 this h // 77 159 1 i1 int // 1 195 2 i2 int // 65 135 3 i3 int // 26 3 4 l1 long // 58 199 6 localObjectOutputStream1 java.io.ObjectOutputStream // 281 14 6 localIOException1 java.io.IOException // 302 5 6 localObject1 Object // 312 8 6 localObject2 Object // 327 14 6 localIOException2 java.io.IOException // 361 14 6 localIOException3 java.io.IOException // 54 220 7 localObjectOutputStream2 java.io.ObjectOutputStream // 309 45 7 localObject3 Object // 382 1 7 localObject4 Object // 239 25 8 localThrowable1 java.lang.Throwable // 387 1 8 localThrowable2 java.lang.Throwable // Exception table: // from to target type // 38 56 239 java/lang/Throwable // 273 278 281 java/io/IOException // 4 28 302 finally // 273 278 302 finally // 283 299 302 finally // 319 324 302 finally // 324 327 302 finally // 329 345 302 finally // 353 358 302 finally // 363 379 302 finally // 38 56 309 finally // 319 324 327 java/io/IOException // 353 358 361 java/io/IOException // 60 66 382 finally // 70 76 382 finally // 87 98 382 finally // 102 113 382 finally // 124 133 382 finally // 137 146 382 finally // 150 157 382 finally // 161 170 382 finally // 174 185 382 finally // 189 195 382 finally // 206 217 382 finally // 221 232 382 finally // 248 254 382 finally // 258 268 382 finally // 60 66 387 java/lang/Throwable // 70 76 387 java/lang/Throwable // 87 98 387 java/lang/Throwable // 102 113 387 java/lang/Throwable // 124 133 387 java/lang/Throwable // 137 146 387 java/lang/Throwable // 150 157 387 java/lang/Throwable // 161 170 387 java/lang/Throwable // 174 185 387 java/lang/Throwable // 189 195 387 java/lang/Throwable // 206 217 387 java/lang/Throwable // 221 232 387 java/lang/Throwable } public void a(int paramInt, long paramLong1, long paramLong2) { if (QLog.isColorLevel()) { QLog.d("GuardManager", 2, "onEvent:" + paramInt + ", " + paramLong1 + ", " + paramLong2); } long l1 = System.currentTimeMillis(); this.x = l1; this.e = true; switch (paramInt) { default: return; case 5: paramInt = (int)(paramLong1 >> 8); int i1 = (int)(0xFF & paramLong1); if ((0xFF & paramLong2) == 1L) {} for (boolean bool = true;; bool = false) { a(l1, paramInt, i1, bool, (int)(paramLong2 >> 8)); return; } case 100: v = l1; this.w = 1; this.e = false; return; case 1: this.w = 2; return; case 3: this.w = 4; return; case 2: this.w = 3; t = paramLong1; return; case 4: this.w = 5; t = paramLong1; return; } MsfService.getCore().pushManager.j(); MsfService.getCore().pushManager.k(); } public void a(IInterface paramIInterface) { IBinder localIBinder; if (paramIInterface != null) { localIBinder = paramIInterface.asBinder(); } for (;;) { if (QLog.isColorLevel()) { QLog.d("GuardManager", 2, "onAppBind with " + paramIInterface); } paramIInterface = this.u; long l1; if (paramIInterface != localIBinder) { l1 = System.currentTimeMillis(); if (paramIInterface != null) { paramIInterface.unlinkToDeath(this, 0); this.u = null; v = l1; this.x = l1; } if ((localIBinder == null) || (!localIBinder.isBinderAlive())) {} } try { localIBinder.linkToDeath(this, 0); this.u = localIBinder; v = l1; return; localIBinder = null; } catch (RemoteException paramIInterface) { while (!QLog.isColorLevel()) {} QLog.d("GuardManager", 2, "onAppBind ", paramIInterface); } } } public boolean a() { IBinder localIBinder = this.u; return (this.e) && (localIBinder != null) && (localIBinder.isBinderAlive()); } public boolean a(int paramInt) { if ((this.d) || ((this.u != null) && (this.u.isBinderAlive())) || ((paramInt != 0) && (this.w == 2)) || ((paramInt != 0) && (this.w == 4))) { return true; } this.d = true; long l4 = System.currentTimeMillis(); long l1 = Math.abs(l4 - v); int i1; if (((paramInt == 1) && (this.e) && (l1 > t)) || ((paramInt == 0) && (l1 > 500L))) { if (QLog.isColorLevel()) { QLog.d("GuardManager", 2, "prestart " + paramInt + ", " + l4 + ", " + v + ", " + t); } localObject = new Intent("com.tencent.qqlite.broadcast.qq"); if (paramInt == 1) { i1 = 1; ((Intent)localObject).putExtra("k_start_mode", i1); BaseApplication.getContext().sendBroadcast((Intent)localObject); v = l4; if (paramInt != 1) { break label240; } localObject = "0"; a("GM_LiteTime", 0L, (String)localObject); } } label240: while ((paramInt != 2) || (l1 <= t)) { for (;;) { return true; i1 = 0; continue; localObject = "1"; } } if (this.o == null) { b(); } Object localObject = Calendar.getInstance(Locale.getDefault()); ((Calendar)localObject).setTimeInMillis(l4); paramInt = ((Calendar)localObject).get(11); long l5 = l4 % 3600000L + paramInt * 60 * 60 * 1000; int i5 = paramInt / (24 / this.o.length); paramInt = this.n.length; int i4 = this.D + this.s; l1 = 0L; long l3; long l2; int i2; int i3; if (this.C != 2) { l3 = this.o[i5] + this.q[i5]; i1 = paramInt; l2 = l3; if (l3 > 7L) { i2 = 0; for (i1 = paramInt; (i2 < paramInt) && (i1 > i4); i1 = i3) { i3 = i1; if (this.o[i2] + this.q[i2] < l3) { i3 = i1 - 1; } i2 += 1; } l1 = (this.n[i5] * this.o[i5] + this.p[i5] * this.q[i5]) / (this.o[i5] + this.q[i5]); l2 = l3; } label494: if ((i1 <= i4) && (l1 - l5 < t) && (l1 - l5 > -t)) { if (QLog.isColorLevel()) { QLog.d("GuardManager", 2, "prestart bgFetch " + i1 + ", " + this.D + ", " + this.s + ", " + l2 + ", " + l5 + ", " + l1 + ", " + l4 + ", " + v + ", " + t); } localObject = new Intent("com.tencent.qqlite.broadcast.qq"); ((Intent)localObject).putExtra("k_start_mode", 2); BaseApplication.getContext().sendBroadcast((Intent)localObject); if (this.C != 2) { break label894; } } } label894: for (localObject = "1";; localObject = "0") { a("GM_PrestartTime", l5, (String)localObject); v = l4; break; i1 = ((Calendar)localObject).get(7); if ((i1 == 7) || (i1 == 1)) { l3 = this.q[i5]; i1 = paramInt; l2 = l3; if (l3 <= 2L) { break label494; } i2 = 0; for (i1 = paramInt; (i2 < paramInt) && (i1 > i4); i1 = i3) { i3 = i1; if (this.q[i2] < l3) { i3 = i1 - 1; } i2 += 1; } l1 = this.p[i5]; l2 = l3; break label494; } l3 = this.o[i5]; i1 = paramInt; l2 = l3; if (l3 <= 5L) { break label494; } i2 = 0; for (i1 = paramInt; (i2 < paramInt) && (i1 > i4); i1 = i3) { i3 = i1; if (this.o[i2] < l3) { i3 = i1 - 1; } i2 += 1; } l1 = this.n[i5]; l2 = l3; break label494; } } public void binderDied() { if (QLog.isColorLevel()) { QLog.d("GuardManager", 2, "binderDied"); } IBinder localIBinder = this.u; if (localIBinder != null) { localIBinder.unlinkToDeath(this, 0); this.u = null; v = System.currentTimeMillis(); long l1 = v - this.x; if ((l1 > 0L) && (l1 < 86400000L)) { a("GM_AliveTime" + this.w, l1, null); } } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.qqlite\classes.jar * Qualified Name: com.tencent.mobileqq.msf.service.h * JD-Core Version: 0.7.0.1 */
[ "98632993+tsuzcx@users.noreply.github.com" ]
98632993+tsuzcx@users.noreply.github.com
fde167f1864f5a8b2baef9135863125d2fe98be6
e3943ade3e804fd20ecad084238b006d8b98e91b
/libraries/cboe-fx/src/main/java/com/paritytrading/juncture/cboe/fx/itch/CboeFXBookFormatter.java
8f80215e185c4d20944f1940409f2e34df02b549
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
rajanprasad-ms/juncture
6035662d1e3a033104dbd60d50070088ed251f2e
046a2dec80def8c4e5095cfee3aa4ac8297f2f5d
refs/heads/master
2023-01-23T21:48:19.301361
2020-12-06T20:32:47
2020-12-06T20:32:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,067
java
/* * Copyright 2015 Juncture authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paritytrading.juncture.cboe.fx.itch; import static com.paritytrading.foundation.ByteBuffers.*; import static com.paritytrading.juncture.cboe.fx.itch.CboeFXBook.*; import com.paritytrading.foundation.ASCII; import java.nio.ByteBuffer; import java.util.Arrays; /** * A formatter for outbound Cboe FX Book Protocol messages. */ public class CboeFXBookFormatter { private State state; /** * Create a formatter for outbound Cboe FX Book Protocol messages. */ public CboeFXBookFormatter() { state = new State(); } /** * Start a Market Snapshot message. * * @param buffer a buffer */ public void marketSnapshotStart(ByteBuffer buffer) { state.reset(); // Message Type buffer.put(MESSAGE_TYPE_MARKET_SNAPSHOT); state.lengthOfMessagePosition = buffer.position(); // Length of Message ASCII.putLongRight(state.lengthOfMessage, 0); buffer.put(state.lengthOfMessage); state.numberOfCurrencyPairsPosition = buffer.position(); } /** * <p>Add an entry to a Market Snapshot message. Subsequent entries must be * grouped by the following fields:</p> * * <ol> * <li>currency pair</li> * <li>buy or sell indicator</li> * <li>price</li> * </ol> * * @param buffer a buffer * @param entry an entry */ public void marketSnapshotEntry(ByteBuffer buffer, MarketSnapshotEntry entry) { if (!Arrays.equals(entry.currencyPair, state.currencyPair)) { if (state.currencyPairs == 0) { // Number of Currency Pairs ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); } state.currencyPairs++; System.arraycopy(entry.currencyPair, 0, state.currencyPair, 0, state.currencyPair.length); // Currency Pair buffer.put(entry.currencyPair); state.buyOrSellIndicator = entry.buyOrSellIndicator; state.numberOfPricesPosition = buffer.position(); // Number of Bid Prices ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); if (entry.buyOrSellIndicator == SELL) { state.numberOfPricesPosition = buffer.position(); // Number of Offer Prices ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); } System.arraycopy(entry.price, 0, state.price, 0, state.price.length); // Bid/Offer Price buffer.put(entry.price); state.numberOfOrdersPosition = buffer.position(); // Number of Bid/Offer Orders ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); state.prices = 1; state.orders = 0; } else if (entry.buyOrSellIndicator != state.buyOrSellIndicator) { // Number of Bid Prices ASCII.putLongRight(state.numberOfItems, state.prices); put(buffer, state.numberOfItems, state.numberOfPricesPosition); // Number of Bid Orders ASCII.putLongRight(state.numberOfItems, state.orders); put(buffer, state.numberOfItems, state.numberOfOrdersPosition); state.numberOfPricesPosition = buffer.position(); state.buyOrSellIndicator = entry.buyOrSellIndicator; // Number of Offer Prices ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); System.arraycopy(entry.price, 0, state.price, 0, state.price.length); // Offer Price buffer.put(entry.price); state.numberOfOrdersPosition = buffer.position(); // Number of Offer Orders ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); state.prices = 1; state.orders = 0; } else if (!Arrays.equals(entry.price, state.price)) { // Number of Bid/Offer Orders ASCII.putLongRight(state.numberOfItems, state.orders); put(buffer, state.numberOfItems, state.numberOfOrdersPosition); // Bid/Offer Price buffer.put(entry.price); state.numberOfOrdersPosition = buffer.position(); // Number of Bid/Offer Orders ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); state.orders = 0; state.prices++; } buffer.put(entry.amount); buffer.put(entry.minqty); buffer.put(entry.lotsize); buffer.put(entry.orderId); state.orders++; } /** * End a Market Snapshot message. * * @param buffer a buffer */ public void marketSnapshotEnd(ByteBuffer buffer) { if (state.currencyPairs > 0) { // Number of Currency Pairs ASCII.putLongRight(state.numberOfItems, state.currencyPairs); put(buffer, state.numberOfItems, state.numberOfCurrencyPairsPosition); } if (state.buyOrSellIndicator == BUY) { // Number Of Offer Prices ASCII.putLongRight(state.numberOfItems, 0); buffer.put(state.numberOfItems); } if (state.prices > 0) { // Number of Bid/Offer Prices ASCII.putLongRight(state.numberOfItems, state.prices); put(buffer, state.numberOfItems, state.numberOfPricesPosition); } if (state.orders > 0) { // Number of Bid/Offer Orders ASCII.putLongRight(state.numberOfItems, state.orders); put(buffer, state.numberOfItems, state.numberOfOrdersPosition); } int endPosition = buffer.position(); int lengthOfMessage = endPosition - state.numberOfCurrencyPairsPosition; // Length of Message ASCII.putLongRight(state.lengthOfMessage, lengthOfMessage); put(buffer, state.lengthOfMessage, state.lengthOfMessagePosition); } private static class State { public byte[] lengthOfMessage; public byte[] numberOfItems; public int lengthOfMessagePosition; public int numberOfCurrencyPairsPosition; public int numberOfPricesPosition; public int numberOfOrdersPosition; public int currencyPairs; public int prices; public int orders; public byte[] currencyPair; public byte buyOrSellIndicator; public byte[] price; public State() { lengthOfMessage = new byte[6]; numberOfItems = new byte[4]; currencyPair = new byte[7]; price = new byte[10]; reset(); } public void reset() { ASCII.putLongRight(lengthOfMessage, 0); ASCII.putLongRight(numberOfItems, 0); lengthOfMessagePosition = -1; numberOfCurrencyPairsPosition = -1; numberOfPricesPosition = -1; numberOfOrdersPosition = -1; currencyPairs = 0; prices = 0; orders = 0; ASCII.putLeft(currencyPair, " "); buyOrSellIndicator = ' '; ASCII.putLeft(price, " "); } } }
[ "jussi.k.virtanen@gmail.com" ]
jussi.k.virtanen@gmail.com
097e160a3765725d29fedfa23c7299eb4f951821
611b899e0b07bc4597f48391a4a8a1b07192dfd5
/netty-research/src/main/java/io/netty/example/study/client/codec/OrderProtocolEncoder.java
43cd657c3b82eac575422668c9e57e1ef7b8d624
[]
no_license
BrendaHub/SpringBoot-loiter-study-gradle
638e21b006705390642c3eb1dc5ddb62b3a09cf1
7d7ccdc1ca05084d3fe721802c22039332d86bd7
refs/heads/master
2022-12-30T12:33:14.652676
2020-09-14T07:05:55
2020-09-14T07:05:55
284,397,704
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package io.netty.example.study.client.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.example.study.common.RequestMessage; import io.netty.handler.codec.MessageToMessageEncoder; import java.util.List; /** * 订单协议编码 */ public class OrderProtocolEncoder extends MessageToMessageEncoder<RequestMessage> { @Override protected void encode(ChannelHandlerContext ctx, RequestMessage requestMessage, List<Object> out) throws Exception { // 通过上下文创建一个byteBuf ByteBuf buffer = ctx.alloc().buffer(); // 将请求内容进行编码 requestMessage.encode(buffer); // 添加到响应的集合中 out.add(buffer); } }
[ "13552666934@139.com" ]
13552666934@139.com
18a609f1e3cfecb47545d1c063c17c7e2f4895a3
4826c18533b0074003eb25cadc99b6f7716eb2cf
/EventBus Library/app/src/main/java/com/example/eventbuslibrary/MessageEvent.java
4c0e6f3055e50358e7073dd18dc27d408a6081c6
[]
no_license
avengerseries101/EventBus
3d54e1ccf8140cb2832b062e9cf00de4809bf399
dcf7f5ce8f96cb5ab4dedb6db9c51425e5da9337
refs/heads/master
2022-11-06T19:40:44.281876
2020-06-29T14:33:55
2020-06-29T14:33:55
275,837,759
0
0
null
null
null
null
UTF-8
Java
false
false
247
java
package com.example.eventbuslibrary; public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } public String getMessage() { return message; } }
[ "avengerseries101@gmail.com" ]
avengerseries101@gmail.com
f665fdae4cc8847df665316f8267f141b670e90f
84daf19073e34bd72dbad758b99efe8fba1387ed
/muck-parent/muck-domain/src/main/java/com/muck/domain/ExcelInputLog.java
59c3048ebd7f8ce0c093a9a732afe1b2158f313c
[]
no_license
gk1996TZ/gk1996TZ.github.io
359f0328474cb8a6e783d03967c03aaac6302900
3739e38e18159bf6fb8f780d162c68178a330d57
refs/heads/master
2020-04-01T17:20:08.275143
2018-11-01T08:34:34
2018-11-01T08:35:00
153,423,909
1
0
null
null
null
null
UTF-8
Java
false
false
291
java
package com.muck.domain; import com.muck.annotation.Table; /** * @Description: 导入Excel表格操作日志实体类 * @version: v1.0.0 * @author: 朱俊亮 * @date: 2018年5月26日 下午4:48:00 */ @Table(name="t_excel_input_log") public class ExcelInputLog extends BaseEntity{ }
[ "gk1996dd@163.com" ]
gk1996dd@163.com
8db31e0e35e2099f8d5d50fccf9bcaa0dc0a9171
d855556d42201990f7534f1529822ed8cfcf1ddb
/Tugas_1/app/src/androidTest/java/com/example/windows10/tugas_1/ExampleInstrumentedTest.java
044061ed6d6b308f5d60d0263666314c22c2e127
[]
no_license
Fanirahmat/Latihan1-android
623ecfe45551222c69747fe8074f649894ce0771
b2b7e876b2b76c6a88a30deb6475206e4c629338
refs/heads/master
2021-03-21T01:59:45.099018
2020-03-14T10:27:19
2020-03-14T10:27:19
247,254,101
0
0
null
null
null
null
UTF-8
Java
false
false
742
java
package com.example.windows10.tugas_1; 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.*; /** * Instrumented 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() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.windows10.tugas_1", appContext.getPackageName()); } }
[ "fanirahmatulloh842@gmail.com" ]
fanirahmatulloh842@gmail.com