blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da3ce1e4c8b9c4f8bd227e24ce27873211715131 | c4909320f6647fcd3f02279501d1f0c9959b13d5 | /src/com/pep/http/HttpExchangeHandler.java | 62754be245a9f6f95bdd1f47f6f40d502b2d7c6b | [] | no_license | LongHuu100/Tu_Code_Java_Http_Server | a9d6ae6608181389b72994b7ecfcc61e0a034b16 | cca89698799eb439dae339bdbc2d607396a690da | refs/heads/master | 2023-08-02T15:58:47.165254 | 2021-10-03T10:04:48 | 2021-10-03T10:04:48 | 405,921,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,142 | java | package com.pep.http;
import com.pep.http.util.MalformedRequestException;
import com.pep.http.util.RoutingException;
import com.pep.http.util.Status;
import java.io.IOException;
/**
* HttpExchangeHandler
*/
public class HttpExchangeHandler implements ExchangeHandler {
private final HttpHandler handler;
public HttpExchangeHandler(HttpHandler handler) {
if (handler == null)
throw new IllegalArgumentException();
this.handler = handler;
}
/* Được gọi từ com.pep.http.Server --> listen */
@Override
public void accept(Exchange exchange) throws IOException {
HttpReader reader = new HttpReader(exchange.in);
HttpWriter writer = new HttpWriter(exchange.out);
try {
handler.accept(reader, writer);
} catch (MalformedRequestException e) {
Status.badRequest().accept(reader, writer);
} catch (RoutingException e) {
Status.notFound().accept(reader, writer);
} catch (Exception e) {
e.printStackTrace();
Status.internalServerError().accept(reader, writer);
}
}
}
| [
"long.huu.100@gmail.com"
] | long.huu.100@gmail.com |
39057d360794640de5b19a71c7efd5ab2a9b3412 | 6e1877e641316d391fcf98332f1a40b881eea7a4 | /app/src/main/java/com/msfthack/crowdcheck/MapActivity.java | a5e81a9801f0ee9f855bfa0d109c945fb61c9c1d | [] | no_license | asaratik/crowdcheck | 1e95b176e16ddb6bf3f630ba68a022821e3e0f0c | 496d9656108f0d7848449011aad3c1a69f1f0885 | refs/heads/master | 2022-11-24T12:17:43.009132 | 2020-07-30T06:55:34 | 2020-07-30T06:55:34 | 283,094,405 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,025 | java | package com.msfthack.crowdcheck;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
// Bing imports
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.microsoft.maps.CustomTileMapLayer;
import com.microsoft.maps.MapElementTappedEventArgs;
import com.microsoft.maps.MapFlyout;
import com.microsoft.maps.MapImage;
import com.microsoft.maps.MapLayer;
import com.microsoft.maps.MapRenderMode;
import com.microsoft.maps.MapTileBitmapRequestedEventArgs;
import com.microsoft.maps.MapView;
import com.microsoft.maps.Geopoint;
import com.microsoft.maps.MapAnimationKind;
import com.microsoft.maps.MapScene;
import com.microsoft.maps.MapElementLayer;
import com.microsoft.maps.MapIcon;
import com.microsoft.maps.OnBitmapRequestedListener;
import com.microsoft.maps.OnMapElementTappedListener;
import com.msfthack.crowdcheck.helpers.Locations;
import com.msfthack.crowdcheck.helpers.POI;
import com.msfthack.crowdcheck.helpers.Utils;
public class MapActivity extends AppCompatActivity{
private MapView mMapView;
private MapElementLayer mPinLayer;
private List<MapIcon> pins;
List<Locations> locations;
private Geopoint LOCATION;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMapView = new MapView(this, MapRenderMode.VECTOR);
mPinLayer = new MapElementLayer();
mPinLayer.addOnMapElementTappedListener(new OnMapElementTappedListener() {
@Override
public boolean onMapElementTapped(MapElementTappedEventArgs mapElementTappedEventArgs) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),
getLocationDetails((int) mapElementTappedEventArgs.mapElements.get(0).getTag()), duration);
toast.show();
return false;
}
});
mMapView.getLayers().add(mPinLayer);
mMapView.setCredentialsKey(BuildConfig.CREDENTIALS_KEY);
((FrameLayout)findViewById(R.id.map_view)).addView(mMapView);
mMapView.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
//Setup the required data for the map view
Intent intent = getIntent();
setupRequiredData(intent.getStringExtra("location"));
mMapView.setScene(
MapScene.createFromLocationAndZoomLevel(LOCATION, 18),
MapAnimationKind.NONE);
addPinsToLayer(pins);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mMapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
private MapIcon getPin(Geopoint geo, String title, int intensity, int uid)
{
MapIcon pushpin = new MapIcon();
pushpin.setLocation(geo);
MapFlyout flyOut = new MapFlyout();
// ImageView iv = new ImageView(getApplicationContext());
// Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
try {
InputStream is;
if(intensity > 75)
{
is = getApplicationContext().getAssets().open("red.png");
flyOut.setDescription("Busy");
}
else if(intensity > 40 && intensity < 75)
{
is = getApplicationContext().getAssets().open("orange.png");
flyOut.setDescription("Moderate");
}
else
{
is = getApplicationContext().getAssets().open("green.png");
flyOut.setDescription("Free");
}
pushpin.setTag(uid);
pushpin.setImage(new MapImage(is));
pushpin.setOpacity(0.5f);
}catch (IOException io)
{
io.printStackTrace();
}
pushpin.setTitle(title);
pushpin.setFlyout(flyOut);
return pushpin;
}
private void addPinsToLayer(List<MapIcon> pins)
{
for(MapIcon pin:pins) {
mPinLayer.getElements().add(pin);
}
}
private void setupRequiredData(String location)
{
String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "data.json");
Gson gson = new Gson();
Type listUserType = new TypeToken<List<Locations>>() { }.getType();
locations = gson.fromJson(jsonFileString, listUserType);
pins = new ArrayList<>();
for (int i = 0; i < locations.size(); i++)
if(locations.get(i).getTitle().equals(location))
{
Log.println(Log.INFO, "TAG", locations.get(i).toString());
LOCATION = new Geopoint(locations.get(i).getLat(), locations.get(i).getLng());
List<POI> list = locations.get(i).getPoi();
for(int j = 0;j<list.size();j++)
pins.add(getPin(new Geopoint(list.get(j).getLat(), list.get(j).getLng()),
list.get(j).getTitle(), list.get(j).getIntensity(), list.get(j).getUid()));
break;
}
}
private String getLocationDetails(int uid)
{
String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "data.json");
Gson gson = new Gson();
Type listUserType = new TypeToken<List<Locations>>() { }.getType();
locations = gson.fromJson(jsonFileString, listUserType);
pins = new ArrayList<>();
for (int i = 0; i < locations.size(); i++) {
List<POI> list = locations.get(i).getPoi();
for(int j = 0;j<list.size();j++)
if ((list.get(j).getUid() == uid))
return list.get(j).getTitle();
}
return "default";
}
}
| [
"ashokaratikatla@gmail.com"
] | ashokaratikatla@gmail.com |
715db68e27b2217cb19276e78849332c0cf00599 | 7229c57245ad7c44a973e5ca12087f6953903e4f | /JavaPractice/src/org/dimigo/oop/SnackTest.java | a4556d84debd0dd8a1402515c0264bb12adb458c | [] | no_license | wp132424/JavaPractice | 0f5070a20bb459147aa7976364448306883e4e53 | b8b07ad80f83b6f72997a9ab945f4fd611b7a0c7 | refs/heads/master | 2020-05-27T08:18:45.931706 | 2015-08-25T08:18:50 | 2015-08-25T08:18:50 | 32,291,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 468 | java | package org.dimigo.oop;
public class SnackTest {
public static void main(String[] args) {
Snack[] SnackArr= new Snack[] {
new Snack("새우깡","농심",1100,2),
new Snack("콘칲","크라운",1200,1),
new Snack("허니버터칩","해태",1500,4)
};
int sum= 0;
for (Snack snack : SnackArr) {
sum += snack.calcPrice();
snack.printSnack();
System.out.println();
}
System.out.println("총합 : " + sum);
}
}
| [
"Junghyun@JHPC"
] | Junghyun@JHPC |
cdf60bce52857eeeedd29a6267dd8ed907113296 | eaf69ea473f4f048ff9c445c39ada42e8fde23bb | /src/main/java/cw19/phone/Telefon.java | a06fdee3ad3a145f4de28f4a4ce466c0031b46cb | [] | no_license | Kasad0r/ppj | b0eaae4087e87e7522834321be277d06a2a543b3 | a66a6a5c954f068b3ff301190d105e51cf764fdd | refs/heads/master | 2020-08-20T13:46:20.681503 | 2020-01-21T14:02:26 | 2020-01-21T14:02:26 | 216,029,847 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 438 | java | package cw19.phone;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Telefon implements Funkcional {
String interfejsKomunikacyjny;
String color;
public void zadzwon(String numer) {
System.out.println("Call to " + numer);
}
@Override
public void wyswietlHistoriePolaczen() {
}
}
| [
"dimon.pokemon99@gmail.com"
] | dimon.pokemon99@gmail.com |
3306cc02362a18f13e5fc6726bd84d97e968701f | 214bdad60d082ede7d3d434afb3f5c9704b9e52e | /StrategyPattern/src/com/agroho/engine/V6CarEngine.java | c6f6b9dd83a16cc7a1a410cf861af55bcad6507c | [] | no_license | aRezaulAlam/DesignPattern | b25a3683215af89102c5b2a7ba45cb97a222e831 | 380fc231caf89cf869e764e25523358926f3569f | refs/heads/master | 2021-01-10T14:41:04.252094 | 2016-03-13T17:57:17 | 2016-03-13T17:57:17 | 53,788,056 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package com.agroho.engine;/*
* Created by rezaul on 2016-03-13.
* Email: arezaulalam@gmail.com
*/
public class V6CarEngine implements EngineStyle {
@Override
public void CheckedEngine() {
System.out.println("This is running wit V6 Engine");
}
}
| [
"arezaulalam@gmail.com"
] | arezaulalam@gmail.com |
63271aacaeecf622c15bf0ff4b4b069dfa81e463 | 2273e9bca8a622ad37f41762fc32fec6e8ed7105 | /heima-leadnews/heima-leadnews-wemedia-gateway/src/main/java/com/heima/wemedia/gateway/WemediaGatewayApplication.java | 9d46ce2acdde3cd4889e5cd3ffe809b7d643b5d2 | [] | no_license | AI96/heima-leadnews | a47652a11d698e2b45f7eaeea63ca9048fac8cfc | 8eadcdd22c248636c8e9eb46108710401026ea64 | refs/heads/master | 2023-05-11T04:38:21.347605 | 2021-05-27T03:13:24 | 2021-05-27T03:13:24 | 370,889,214 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 461 | java | package com.heima.wemedia.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient //开启注册中心
public class WemediaGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(WemediaGatewayApplication.class,args);
}
} | [
"yp@163.com"
] | yp@163.com |
7750158e0a9624432b19c42ba7010f18cb51fc8a | 32ba22aa2ad08088355b906c4ae75e0308390be7 | /JasonImageUtil/src/main/java/com/jason/jasonimageutil/ReadImage.java | 2ce3e009432e736a1fd4af184f04acbfc6af6f22 | [] | no_license | DonyLi/ImageUtil | 21fcd814ccce21a1bd306b1b5382258ffb15c4dc | e8a61b6305470941178be91c55838ef6dd8aa70c | refs/heads/master | 2020-03-19T23:58:08.631059 | 2019-01-08T06:34:52 | 2019-01-08T06:34:52 | 137,026,929 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 141 | java | package com.jason.jasonimageutil;
public interface ReadImage {
ReadImageResult readImage(String path, int widthLim, boolean isGif);
}
| [
"709553941@qq.com"
] | 709553941@qq.com |
b7f9073760680dc2c410135ab72611759138d79f | 28a7ede896b98bf6e2630129d94e9e7afd29dc13 | /src/main/java/com/nsb/practice/designpatterns/visitor/Monitor.java | 38d3fd32fc5fd7903e334b6747219039725938b6 | [
"Apache-2.0"
] | permissive | Dorae132/practice | 8a7da9702074608c04d0b5e1a5358a9aad02eccb | d95221c3dea36720df3f0b0019d171a60c60e114 | refs/heads/master | 2022-11-28T10:43:35.461565 | 2020-09-27T00:51:20 | 2020-09-27T00:51:20 | 135,540,001 | 1 | 1 | Apache-2.0 | 2022-10-18T23:20:51 | 2018-05-31T06:14:03 | Java | UTF-8 | Java | false | false | 227 | java | package com.nsb.practice.designpatterns.visitor;
public class Monitor implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
| [
"nsb_2017@163.com"
] | nsb_2017@163.com |
2bb9c560ff2f612034a3e34a6c4877e64fa5bd65 | 36d7ac13d205b9a5b8c3308a27c4605a1cd7ee56 | /others/AndEngine-GLES2-AnchorCenter/src/org/andengine/audio/sound/SoundManager.java | a24468adf18047b6b34d4d9e97ca5ae94a9f8cdc | [
"Apache-2.0"
] | permissive | renanlr/billyadventures | 92103d6208f2e80644fca38c2c8a4ad6f2b5a7ce | f35384d6355dbbdbc5708b370731d1be1e652f39 | refs/heads/master | 2021-01-20T03:39:09.059791 | 2014-12-09T05:03:33 | 2014-12-09T05:03:33 | 23,578,058 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,142 | java | package org.andengine.audio.sound;
import org.andengine.audio.BaseAudioManager;
import org.andengine.audio.sound.exception.SoundException;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:22:59 - 11.03.2010
*/
public class SoundManager extends BaseAudioManager<Sound> implements OnLoadCompleteListener {
// ===========================================================
// Constants
// ===========================================================
private static final int SOUND_STATUS_OK = 0;
public static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
// ===========================================================
// Fields
// ===========================================================
private final SoundPool mSoundPool;
private final SparseArray<Sound> mSoundMap = new SparseArray<Sound>();
// ===========================================================
// Constructors
// ===========================================================
public SoundManager() {
this(MAX_SIMULTANEOUS_STREAMS_DEFAULT);
}
public SoundManager(final int pMaxSimultaneousStreams) {
this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0);
this.mSoundPool.setOnLoadCompleteListener(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
SoundPool getSoundPool() {
return this.mSoundPool;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void add(final Sound pSound) {
super.add(pSound);
this.mSoundMap.put(pSound.getSoundID(), pSound);
}
@Override
public boolean remove(final Sound pSound) {
final boolean removed = super.remove(pSound);
if (removed) {
this.mSoundMap.remove(pSound.getSoundID());
}
return removed;
}
@Override
public void releaseAll() {
super.releaseAll();
this.mSoundPool.release();
}
@Override
public synchronized void onLoadComplete(final SoundPool pSoundPool, final int pSoundID, final int pStatus) {
if (pStatus == SoundManager.SOUND_STATUS_OK) {
final Sound sound = this.mSoundMap.get(pSoundID);
if (sound == null) {
throw new SoundException("Unexpected soundID: '" + pSoundID + "'.");
} else {
sound.setLoaded(true);
}
}
}
// ===========================================================
// Methods
// ===========================================================
public void onPause() {
this.mSoundPool.autoPause();
}
public void onResume() {
this.mSoundPool.autoResume();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| [
"renan.lobato.rheinboldt@gmail.com"
] | renan.lobato.rheinboldt@gmail.com |
8cd05d37efd811b8cfb9b7a1136cefc73e74e32c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/26/26_940403c7c625d7e4a7073da45784d38e8361b617/InsertReviewFrame/26_940403c7c625d7e4a7073da45784d38e8361b617_InsertReviewFrame_s.java | e9a3b04019843ece8c62b8b1c8eec3af004326b3 | [] | 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 | 6,103 | java | import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.*;
/*
* A review frame where a user can insert a review.
*/
public class InsertReviewFrame extends JFrame
{
private static Connection connection;
private static PreparedStatement preparedStatement = null;
JLabel label1, label2, label3, label4;
JComboBox input1, input2, input3, input4;
JButton saveButton, resetButton;
String[] ratingChoices = {"1 - Dishaster!", "2 - Poor", "3 - Meh", "4 - Good", "5 - Great" };
String restid = "";
public InsertReviewFrame(Connection cn, final int userid)
{
connection = cn;
setTitle("Dishaster! - New Review");
setLayout(new GridLayout(5,2));
setSize(new Dimension(400, 250));
label1 = new JLabel(" Restaurant:");
label2 = new JLabel(" Address:");
label3 = new JLabel(" Dish:");
label4 = new JLabel(" Rating:");
ArrayList<String> names = new ArrayList<String>();
try {
names = GUIFrame.readDataBase("distinct name", 1, 1, "");
} catch (Exception e2) {
e2.printStackTrace();
}
input1 = new JComboBox(names.toArray());
input1.setSelectedItem(null);
input2 = new JComboBox();
input3 = new JComboBox();
input4 = new JComboBox();
input1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
try
{
input2.removeAllItems();
input3.removeAllItems();
String name = (String)input1.getSelectedItem();
name = name.replace("'", "\\'");
String where = "name = '" + name + "'";
ArrayList<String> addresses = GUIFrame.readDataBase("address", 1, 1, where);
for (String address : addresses)
input2.addItem(address);
input2.setSelectedItem(null);
ArrayList<String> foods = GUIFrame.readDataBase("distinct food", 1, 3, where);
for (String food : foods)
input3.addItem(food);
input3.setSelectedItem(null);
}
catch(Exception e) {}
}
});
input2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
try
{
String where = "address = '" + input2.getSelectedItem() + "'";
restid = GUIFrame.readDataBase("restaurant_id", 1, 1, where).get(0);
}
catch(Exception e) {}
}
});
input4 = new JComboBox(ratingChoices);
input4.setSelectedItem(null);
saveButton = new JButton("Add");
resetButton = new JButton("Reset");
add(label1);
add(input1);
add(label2);
add(input2);
add(label3);
add(input3);
add(label4);
add(input4);
add(saveButton);
add(resetButton);
// resets all the fields
resetButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
input1.setSelectedItem(null);
input2.setSelectedItem(null);
input3.setSelectedItem(null);
input4.setSelectedItem(null);
}
});
// insert new review
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String value1 = (String) input1.getSelectedItem();
String value2 = (String) input2.getSelectedItem();
String value3 = (String) input3.getSelectedItem();
String value4 = Integer.toString(input4.getSelectedIndex() + 1);
System.out.println(value1 + value2 + value3 + value4);
try
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String statement = "insert into Review(reviewer_id, restaurant_id, food, rating, created) " +
"values(" + userid + ", " + restid + ", '" + input3.getSelectedItem() + "', " + (input4.getSelectedIndex()+1) + ", '" + dateFormat.format(cal.getTime()) + "')";
System.out.println(statement);
preparedStatement = connection.prepareStatement(statement);
preparedStatement.executeUpdate();
JOptionPane.showMessageDialog(saveButton, "Successfully added.");
// update the review frame table
ReviewFrame.updateTable("SELECT name as restaurant, address, food, rating, created as date " +
"FROM Review NATURAL JOIN Restaurant " +
"WHERE reviewer_id = " + userid + " " +
"ORDER BY created DESC;");
try
{
// update the review archive
CallableStatement cStmt = connection.prepareCall("{call UpdateArchive()}");
//cStmt.setString(1, dateFormat.format(cal.getTime()));
cStmt.execute();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(saveButton,"Error archiving.");
}
dispose();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(saveButton,"You have made this review already. If you wish to change the rating, select 'Update Review'.");
}
}
});
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
fa1b8b54d621b68c17bd0fb03464a1b02621a9d4 | aa86f5c41866b66c1cf1c5f11a4af428ddf3c2b0 | /src/main/java/br/com/vetorsistemas/integradorbw/listas/ListaRepository.java | 60e1c4045a23eaa2ec09207102ed27d4d7eb1516 | [] | no_license | evirson/integradorbw | 83091151be615e143f4341aef588ec14eb08470d | 8b7353e14ec44080d7e09bbdc97878909ae0aebd | refs/heads/master | 2021-05-19T19:15:23.113037 | 2020-04-11T23:12:18 | 2020-04-11T23:12:18 | 252,079,293 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 824 | java | package br.com.vetorsistemas.integradorbw.listas;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ListaRepository extends JpaRepository<Lista, Integer> {
default List<Lista> findAll() {
List<Lista> lista = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
Lista x = new Lista();
x.setId(i);
x.setIndice(1);
switch (i) {
case 1:
x.setDescricao("Clientes");
x.setTipo(1);
break;
case 2:
x.setDescricao("Normal");
x.setTipo(2);
break;
case 3:
x.setDescricao("Oferta");
x.setTipo(2);
break;
default:
x.setDescricao("Não Nominado");
x.setTipo(2);
}
lista.add(x);
}
return lista;
}
}
| [
"evirson@vetorsistemas.com.br"
] | evirson@vetorsistemas.com.br |
6d4b7ed14d05903cfecf6ef3bdfcab59ffd447e7 | cd86541e1265fcd206af6436a01d551c393c3ce8 | /src/Viewer/ImageManager.java | cbca25e6ceeb80d8cfbed2d68f48cd05f059a089 | [] | no_license | Moneil97/Image-Tools | 269bb2d7d683fe66cf4d34758d3a3bf01b008af9 | 8c4e248492173336f3b0b8bcedda798d6ff9d610 | refs/heads/master | 2016-09-07T19:04:07.353216 | 2015-02-21T03:32:41 | 2015-02-21T03:32:41 | 31,000,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,803 | java | package Viewer;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class ImageManager {
private FileFilter filter;
private String extensions[] = {".jpg", ".png", ".gif", ".jpeg", ".bmp", ".wbmp"};
private List<File> photos = new ArrayList<File>();
private int imageNum = 0;
public ImageManager() {
filter = new FileFilter(){
@Override
public boolean accept(File file) {
for (String extension : extensions)
if (file.getName().toLowerCase().endsWith(extension))
return true;
return false;
}
};
}
public void addImages(File file) {
if (file.isDirectory()){
for (File f : file.listFiles(filter))
photos.add(f);
}
else if (file.isFile()){
if (filter.accept(file))
photos.add(file);
}
System.out.println(photos);
}
public BufferedImage nextImage(){
if (imageNum < photos.size())
imageNum ++;
try {
return ImageIO.read(photos.get(imageNum));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public BufferedImage previousImage(){
if (imageNum > 0)
imageNum --;
try {
return ImageIO.read(photos.get(imageNum));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public BufferedImage getFirstImage() {
try {
return ImageIO.read(photos.get(0));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void clear() {
photos.clear();
imageNum = 0;
}
public int getImageCount(){
return photos.size();
}
public int getCurrentImageNum(){
return imageNum;
}
}
| [
"cam8059@yahoo.com"
] | cam8059@yahoo.com |
34d5492ebc6168d16aeaa3d4714988f8afc58b15 | 70fc691535cd0ab0d1de689401867e26a66fc152 | /Ong_Base/main/com/ong/bean/helpers/BeanHelper.java | b1a3242dc8e4316f8a1abda754271e846973cf28 | [] | no_license | vergil-ong/ong_base | eaf9c83352bd4a4483d60cf2ebefdd1316fa821e | e642f3dc8468c076f057bafcc18af8d5ad5b591e | refs/heads/master | 2022-12-19T20:50:59.861943 | 2019-10-21T23:39:19 | 2019-10-21T23:39:19 | 108,228,845 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 10,711 | java | package com.ong.bean.helpers;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ong.log.helpers.Log;
/**
* 对Bean类的帮助类
* @Description: Bean类的帮助类
* @Author: Ong
* @CreateDate: 2017-05-20 12:00:00
* @E-mail: 865208597@qq.com
*/
public class BeanHelper {
private static Log logger = Log.getLog(BeanHelper.class);
private static final String STATICDIR = "D://eclipseworkspace/ong/Ong_Base/STATIC";
private static Class<?> defaultMapClazz = HashMap.class;
private static final String EMPTYSTR = "";
private static final String[] JSONDIR_SUFFIX = {"json","data"};
private static final String[] XML_SUFFIX = {"xml"};
/**
* return if List is null
* @param map
* @return
*/
public static boolean isListNull(List<?> list){
return list == null;
}
/**
* return List is null or empty
* @param map
* @return
*/
public static boolean isListEmpty(List<?> list){
return isListNull(list)||list.isEmpty();
}
/**
* return if map is null
* @param map
* @return
*/
public static boolean isMapNull(Map<?,?> map){
return map == null;
}
/**
* return map is null or empty
* @param map
* @return
*/
public static boolean isMapEmpty(Map<?,?> map){
return isMapNull(map)||map.isEmpty();
}
/**
* get Instance of Map if it`s null
* @param <P>
* @param <T>
* @param map
* @return
*/
public static <T, P> Map<T,P> getInstanceIfNull(Map<T, P> map){
return getInstanceIfNull(map, defaultMapClazz);
}
/**
* get Instance of Map if it`s null
* @param <T>
* @param <P>
* @param map
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T, P> Map<T,P> getInstanceIfNull(Map<T, P> map, Class<?> clazz){
Map<T,P> resultMap = null;
/**
* 1. check if map is null
* 1.1 map is not null
* return map
* 1.2 map is null
* return new Instance Class
*/
//1. check if map is null
if(!isMapNull(map)){
//1.1 map is not null return map
return map;
}
//return new Instance Class
try {
resultMap = (Map<T, P>) clazz.newInstance();
} catch (Exception e1) {
logger.error("newInstance the class {0} ,Exception is {1}",clazz,e1.getMessage());
try {
resultMap = (Map<T, P>) defaultMapClazz.newInstance();
} catch (Exception e2) {
logger.error("newInstance the defaultMapClazz {0} ,Exception is {1}",defaultMapClazz,e2.getMessage());
resultMap = new HashMap<T, P>();
}
}
return resultMap;
}
/**
* Object to String
* @param obj
* @return
*/
public static String getStr(Object obj){
String retStr = EMPTYSTR;
if(obj == null){
return retStr;
}
try{
retStr = (String)obj;
}catch(Exception e){
logger.warn("cast the class {0} ,Exception is {1}",obj,e.getMessage());
retStr = obj.toString();
}
return retStr;
}
/**
* get Map from bean
* @param obj
* @return
*/
public static Map<String,Object> bean2Map(Object obj){
Map<String, Object> map = new HashMap<String, Object>();
Method[] declaredMethods = obj.getClass().getDeclaredMethods();
for(Method decMethod : declaredMethods){
Class<?>[] parameterTypes = decMethod.getParameterTypes();
String methodName = decMethod.getName();
if(!methodName.startsWith("get")||parameterTypes.length!=0){
//filter the method is not start with get
//or parameters is not null
continue;
}
try {
Object[] params = {};
Object getValue = decMethod.invoke(obj, params);
String subName = methodName.substring(3);
String firstChar = subName.substring(0, 1);
subName = subName.replaceFirst(firstChar, firstChar.toLowerCase());
map.put(subName, getValue);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
}
return map;
}
/**
* set map to bean<br/>
* 暂时只支持bean类的无参构造函数,如不存在无参构造,则需手动添加<br/>
* 初步构想使用注解来指定构造函数
* @param <T>
* @param map
* @param clazz
* @return
*/
public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz){
if(isMapEmpty(map)){
return null;
}
try {
T bean = clazz.newInstance();
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method decMethod : declaredMethods){
String methodName = decMethod.getName();
Class<?>[] parameterTypes = decMethod.getParameterTypes();
if(!methodName.startsWith("set") || parameterTypes.length != 1){
continue;
}
String subName = methodName.substring(3, methodName.length());
String firstChar = subName.substring(0, 1);
subName = subName.replaceFirst(firstChar, firstChar.toLowerCase());
Object setValue = map.get(subName);
decMethod.invoke(bean, transferExpectClass(setValue, parameterTypes[0]));
}
return bean;
} catch (InstantiationException e) {
logger.error(e);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
return null;
}
/**
* 将对象转换成期望类型
* @param obj
* @param expectClazz
* @return
*/
public static <T> Object transferExpectClass(Object obj, Class<T> expectClazz){
if(obj.getClass().equals(expectClazz)){
return obj;
}else if(expectClazz.isAssignableFrom(java.lang.String.class)){
return getStr(obj);
}else {
return invokeValueOf(getStr(obj), expectClazz);
}
}
/**
* 执行valueOf 方法
* @param obj
* @param clazz
* @return
*/
public static <T> Object invokeValueOf(Object obj, Class<T> clazz){
try {
Method declaredMethod = clazz.getDeclaredMethod("valueOf", java.lang.String.class);
return declaredMethod.invoke(null, obj);
} catch (NoSuchMethodException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
return obj;
}
/**
* 将BeanA 转换成 BeanB
* @param a
* @param b
* @return
*/
public static <T, P> P transBeanAToBeanB(T a, P b){
if(a == null){
return null;
}
if(b == null){
return null;
}
Class<? extends Object> clazzA = a.getClass();
Class<? extends Object> classB = b.getClass();
Method[] declaredMethods = clazzA.getDeclaredMethods();
for(Method decMethod : declaredMethods){
String methodName = decMethod.getName();
Class<?>[] parameterTypes = decMethod.getParameterTypes();
if(!methodName.startsWith("get") || parameterTypes.length != 0){
continue;
}
Object[] params = {};
try {
Object getValue = decMethod.invoke(a, params);
String setMethodName = methodName.replaceFirst("get", "set");
String fieldName = lowerFirstCase(methodName.replaceFirst("get", ""));
Field declaredField = classB.getDeclaredField(fieldName);
Class<?> type = declaredField.getType();
Method setMethod = classB.getDeclaredMethod(setMethodName, type);
setMethod.invoke(b, getValue);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
} catch (NoSuchFieldException e) {
logger.info(e);
} catch (SecurityException e) {
logger.error(e);
} catch (NoSuchMethodException e) {
logger.info(e);
}
}
return b;
}
/**
* 将BeanA 转换成 BeanB
* @param a
* @param b
* @return
*/
public static <T, P> P transBeanAToBeanB(T a, Class<P> clazzB){
try {
P b = clazzB.newInstance();
return transBeanAToBeanB(a, b);
} catch (InstantiationException | IllegalAccessException e) {
logger.error(e);
}
return null;
}
public static <T, P> List<P> transAListToBeanB(List<T> a, Class<P> clazzB){
if(a == null){
return null;
}
List<P> resultList = new ArrayList<P>(a.size());
for(T t : a){
resultList.add(transBeanAToBeanB(t, clazzB));
}
return resultList;
}
/**
* 首字母大写
* @param str
* @return
*/
public static String upperFirstCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
/**
* 首字母小写
* @param str
* @return
*/
public static String lowerFirstCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'A' && ch[0] <= 'Z') {
ch[0] = (char) (ch[0] + 32);
}
return new String(ch);
}
public static String getStaticFile(String fileName){
if(fileName == null){
return null;
}
for(String jsonSuffix : JSONDIR_SUFFIX){
if(fileName.toLowerCase().endsWith(jsonSuffix)){
return STATICDIR+File.separator+"JSON"+File.separator+fileName;
}
}
for(String xmlSuffix : XML_SUFFIX){
if(fileName.toLowerCase().endsWith(xmlSuffix)){
return STATICDIR+File.separator+"XML"+File.separator+fileName;
}
}
return STATICDIR+File.separator+fileName;
}
/**
* 把对象转成对象数组
* @param obj
* @return
*/
public static Object[] transObj2ObjArray(Object obj){
if(obj == null){
return null;
}
if(obj instanceof Object[]){
return (Object[])obj;
}
if(obj instanceof List){
List<?> list = (List<?>)obj;
return list.toArray();
}
return new Object[]{obj};
}
/**
* 获取对象数组的类型
* @param obj
* @return
*/
public static Class<?>[] getObjClazz(Object[] objs){
if(objs == null){
return null;
}
Class<?>[] clazzArray = new Class<?>[objs.length];
for(int i=0; i<clazzArray.length; i++){
clazzArray[i] = objs[i].getClass();
}
return clazzArray;
}
}
| [
"865208597@qq.com"
] | 865208597@qq.com |
8340c76029d70edb1f418106b3cc9ab6770486f5 | f05d29ab5093f463a139c8e1db0da0cf754cfa86 | /Android Projects/ThePeoplesKitchen/src/com/example/thepeopleskitchen/ParseFood.java | ff17554146b6dcfdd4ca5bcd3d11ca09af71eaf0 | [] | no_license | skarpath/DevelopmentExamples | 2e2cf8f88a9c7e54320fc4d35a389d7f6c4962f0 | bf2bc615efcc1a7a7238150d84b52a2c4019e68a | refs/heads/master | 2021-01-10T03:22:25.688571 | 2018-10-30T19:58:14 | 2018-10-30T19:58:14 | 42,538,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,109 | java | package com.example.thepeopleskitchen;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseFood {
public ArrayList<Recipe> ParseJson(String toParse) {
ArrayList<Recipe> recipes_list = new ArrayList<Recipe>();
try {
JSONObject root = new JSONObject(toParse);
JSONArray rarray = root.getJSONArray("recipes");
JSONObject obj;
for (int i = 0; i < rarray.length(); i++) {
{
obj = rarray.getJSONObject(i);
Recipe r = new Recipe();
r.setTitle(obj.getString("title"));
r.setImage_url(obj.getString("image_url"));
r.setRecipe_id(obj.getString("recipe_id"));
r.setPublisher_url(obj.getString("publisher_url"));
r.setPublisher(obj.getString("publisher"));
r.setRecipe_url(obj.getString("f2f_url"));
r.setSource_url(obj.getString("source_url"));
r.setRank(obj.getString("social_rank"));
recipes_list.add(r);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.d("Parser",recipes_list.toString());
return recipes_list;
}
}
| [
"="
] | = |
1202454e3a54da5d956b9a73c463aa1d648fb588 | b3a79c99e20db39e7e0405c20bedad5a762b903e | /TaskFirebaseDatabase/app/src/main/java/com/example/appinventiv/taskfirebasedatabase/fragment/ChatFragment.java | 2e0f23de6ad07eaa2223ee4bec35e1578fb4462c | [] | no_license | salonibisht/ChatApp | d108459be83beaf26f42a7335d50ac3d8f0215a5 | c78e73c47a345c297e1ba40995304d49f21885f4 | refs/heads/master | 2020-03-07T22:42:50.958932 | 2018-04-02T14:25:41 | 2018-04-02T14:25:41 | 127,761,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,147 | java | package com.example.appinventiv.taskfirebasedatabase.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.appinventiv.taskfirebasedatabase.R;
import com.example.appinventiv.taskfirebasedatabase.activity.ChatActivity;
import com.example.appinventiv.taskfirebasedatabase.activity.LogInActivity;
import com.example.appinventiv.taskfirebasedatabase.interfaces.UserInfoInterface;
import com.example.appinventiv.taskfirebasedatabase.model.UserInfo;
import com.example.appinventiv.taskfirebasedatabase.utility.AppConstants;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* A simple {@link Fragment} subclass.
*/
public class ChatFragment extends Fragment implements UserInfoInterface {
@BindView(R.id.iv_back)
ImageView ivBack;
@BindView(R.id.toolbar_title)
TextView toolbarTitle;
Unbinder unbinder;
@BindView(R.id.toolbar_profile)
ImageView toolbarProfile;
@BindView(R.id.rv_chat_contacts)
RecyclerView rvChatContacts;
private DatabaseReference mDatabasereference;
private FirebaseUser firebaseUser;
private Query query;
private TextView tvName;
private String name;
private FirebaseRecyclerAdapter<UserInfo,UserViewHolder> firebaseRecyclerAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
unbinder = ButterKnife.bind(this, view);
toolbarTitle.setText(R.string.messages);
toolbarProfile.setVisibility(View.VISIBLE);
firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
query = FirebaseDatabase.getInstance()
.getReference()
.child(AppConstants.KEY_USER);
rvChatContacts.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onStart() {
super.onStart();
setChatAdapter();
}
/**
* set Adapter to show User name on inbox....
*/
private void setChatAdapter() {
FirebaseRecyclerOptions<UserInfo> options =
new FirebaseRecyclerOptions.Builder<UserInfo>()
.setQuery(query, UserInfo.class)
.build();
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<UserInfo, UserViewHolder>(options) {
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_status, parent, false);
return new UserViewHolder(view); }
@Override
protected void onBindViewHolder(@NonNull UserViewHolder holder, int position, @NonNull UserInfo model) {
holder.setName(model.getmFirstName(),model.getmSurname());
}
};
firebaseRecyclerAdapter.startListening();
rvChatContacts.setAdapter(firebaseRecyclerAdapter);
}
@OnClick(R.id.iv_back)
public void onViewClicked() {
}
@Override
public void setOnItemClickListener(View view, int position) {
Intent intent=new Intent(getActivity(),ChatActivity.class);
intent.putExtra("selectedUserId",firebaseRecyclerAdapter.getRef(position).getKey());
intent.putExtra("name",name);
intent.putExtra("type","inboxUser");
startActivity(intent);
}
public class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
tvName=itemView.findViewById(R.id.tv_user_name);
mView=itemView;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setOnItemClickListener(view,getAdapterPosition());
}
});
}
/**
* Set name present in the database to the text view in the inox..
* @param s
* @param s1
*/
public void setName(String s, String s1) {
name=s+" "+s1;
tvName.setText(s+" "+s1);
}
}
}
| [
"you@example.com"
] | you@example.com |
823c53980c4b6d78e9cb4698a76fbe29a85e1b3e | 74f220bb490b8b9e3872a72f4fe0dce747c19b2b | /aws-java-sdk-comprehend/src/main/java/com/amazonaws/services/comprehend/model/StartSentimentDetectionJobRequest.java | a702f5179ad49aa0006320e7541ac0643e12b4aa | [
"Apache-2.0"
] | permissive | eginez/aws-sdk-java | 13f463d2f801b72bf4b65a54f73dc69b69157cce | fc5034d88b02731361ee12cbc34b600c97793557 | refs/heads/master | 2020-05-22T19:44:49.199107 | 2019-05-13T20:29:27 | 2019-05-13T20:29:27 | 186,497,171 | 1 | 0 | Apache-2.0 | 2019-05-13T21:19:19 | 2019-05-13T21:19:19 | null | UTF-8 | Java | false | false | 22,423 | java | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.comprehend.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/comprehend-2017-11-27/StartSentimentDetectionJob"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartSentimentDetectionJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*/
private InputDataConfig inputDataConfig;
/**
* <p>
* Specifies where to send the output files.
* </p>
*/
private OutputDataConfig outputDataConfig;
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*/
private String dataAccessRoleArn;
/**
* <p>
* The identifier of the job.
* </p>
*/
private String jobName;
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*/
private String languageCode;
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*/
private String clientRequestToken;
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*/
private String volumeKmsKeyId;
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @param inputDataConfig
* Specifies the format and location of the input data for the job.
*/
public void setInputDataConfig(InputDataConfig inputDataConfig) {
this.inputDataConfig = inputDataConfig;
}
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @return Specifies the format and location of the input data for the job.
*/
public InputDataConfig getInputDataConfig() {
return this.inputDataConfig;
}
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @param inputDataConfig
* Specifies the format and location of the input data for the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withInputDataConfig(InputDataConfig inputDataConfig) {
setInputDataConfig(inputDataConfig);
return this;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @param outputDataConfig
* Specifies where to send the output files.
*/
public void setOutputDataConfig(OutputDataConfig outputDataConfig) {
this.outputDataConfig = outputDataConfig;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @return Specifies where to send the output files.
*/
public OutputDataConfig getOutputDataConfig() {
return this.outputDataConfig;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @param outputDataConfig
* Specifies where to send the output files.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withOutputDataConfig(OutputDataConfig outputDataConfig) {
setOutputDataConfig(outputDataConfig);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @param dataAccessRoleArn
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
*/
public void setDataAccessRoleArn(String dataAccessRoleArn) {
this.dataAccessRoleArn = dataAccessRoleArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @return The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
*/
public String getDataAccessRoleArn() {
return this.dataAccessRoleArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @param dataAccessRoleArn
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withDataAccessRoleArn(String dataAccessRoleArn) {
setDataAccessRoleArn(dataAccessRoleArn);
return this;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @param jobName
* The identifier of the job.
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @return The identifier of the job.
*/
public String getJobName() {
return this.jobName;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @param jobName
* The identifier of the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withJobName(String jobName) {
setJobName(jobName);
return this;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @see LanguageCode
*/
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @return The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @see LanguageCode
*/
public String getLanguageCode() {
return this.languageCode;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LanguageCode
*/
public StartSentimentDetectionJobRequest withLanguageCode(String languageCode) {
setLanguageCode(languageCode);
return this;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LanguageCode
*/
public StartSentimentDetectionJobRequest withLanguageCode(LanguageCode languageCode) {
this.languageCode = languageCode.toString();
return this;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @param clientRequestToken
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
*/
public void setClientRequestToken(String clientRequestToken) {
this.clientRequestToken = clientRequestToken;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @return A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
*/
public String getClientRequestToken() {
return this.clientRequestToken;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @param clientRequestToken
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withClientRequestToken(String clientRequestToken) {
setClientRequestToken(clientRequestToken);
return this;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @param volumeKmsKeyId
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage
* volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be
* either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
*/
public void setVolumeKmsKeyId(String volumeKmsKeyId) {
this.volumeKmsKeyId = volumeKmsKeyId;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @return ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the
* storage volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId
* can be either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
*/
public String getVolumeKmsKeyId() {
return this.volumeKmsKeyId;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @param volumeKmsKeyId
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage
* volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be
* either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withVolumeKmsKeyId(String volumeKmsKeyId) {
setVolumeKmsKeyId(volumeKmsKeyId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getInputDataConfig() != null)
sb.append("InputDataConfig: ").append(getInputDataConfig()).append(",");
if (getOutputDataConfig() != null)
sb.append("OutputDataConfig: ").append(getOutputDataConfig()).append(",");
if (getDataAccessRoleArn() != null)
sb.append("DataAccessRoleArn: ").append(getDataAccessRoleArn()).append(",");
if (getJobName() != null)
sb.append("JobName: ").append(getJobName()).append(",");
if (getLanguageCode() != null)
sb.append("LanguageCode: ").append(getLanguageCode()).append(",");
if (getClientRequestToken() != null)
sb.append("ClientRequestToken: ").append(getClientRequestToken()).append(",");
if (getVolumeKmsKeyId() != null)
sb.append("VolumeKmsKeyId: ").append(getVolumeKmsKeyId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartSentimentDetectionJobRequest == false)
return false;
StartSentimentDetectionJobRequest other = (StartSentimentDetectionJobRequest) obj;
if (other.getInputDataConfig() == null ^ this.getInputDataConfig() == null)
return false;
if (other.getInputDataConfig() != null && other.getInputDataConfig().equals(this.getInputDataConfig()) == false)
return false;
if (other.getOutputDataConfig() == null ^ this.getOutputDataConfig() == null)
return false;
if (other.getOutputDataConfig() != null && other.getOutputDataConfig().equals(this.getOutputDataConfig()) == false)
return false;
if (other.getDataAccessRoleArn() == null ^ this.getDataAccessRoleArn() == null)
return false;
if (other.getDataAccessRoleArn() != null && other.getDataAccessRoleArn().equals(this.getDataAccessRoleArn()) == false)
return false;
if (other.getJobName() == null ^ this.getJobName() == null)
return false;
if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
return false;
if (other.getLanguageCode() == null ^ this.getLanguageCode() == null)
return false;
if (other.getLanguageCode() != null && other.getLanguageCode().equals(this.getLanguageCode()) == false)
return false;
if (other.getClientRequestToken() == null ^ this.getClientRequestToken() == null)
return false;
if (other.getClientRequestToken() != null && other.getClientRequestToken().equals(this.getClientRequestToken()) == false)
return false;
if (other.getVolumeKmsKeyId() == null ^ this.getVolumeKmsKeyId() == null)
return false;
if (other.getVolumeKmsKeyId() != null && other.getVolumeKmsKeyId().equals(this.getVolumeKmsKeyId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInputDataConfig() == null) ? 0 : getInputDataConfig().hashCode());
hashCode = prime * hashCode + ((getOutputDataConfig() == null) ? 0 : getOutputDataConfig().hashCode());
hashCode = prime * hashCode + ((getDataAccessRoleArn() == null) ? 0 : getDataAccessRoleArn().hashCode());
hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
hashCode = prime * hashCode + ((getLanguageCode() == null) ? 0 : getLanguageCode().hashCode());
hashCode = prime * hashCode + ((getClientRequestToken() == null) ? 0 : getClientRequestToken().hashCode());
hashCode = prime * hashCode + ((getVolumeKmsKeyId() == null) ? 0 : getVolumeKmsKeyId().hashCode());
return hashCode;
}
@Override
public StartSentimentDetectionJobRequest clone() {
return (StartSentimentDetectionJobRequest) super.clone();
}
}
| [
""
] | |
00a2feade55fa7cbd468091a6518a6bcfeb1799c | a674a24708c7808d028f4eeffbdb08d64802dfbb | /src/test/java/Training/TrainigDemo/MobileTest.java | 1cbd4915da58984af4c59af93cd839f452543cc9 | [] | no_license | SelvendranAutomation/TraininDemo | 7a3696d187795028df98ea6575ffe817d96ca40a | 8d9f2c1d51e4f1b15f30866f59f4959f9714b11b | refs/heads/master | 2020-04-13T05:10:27.701946 | 2018-12-24T12:00:16 | 2018-12-24T12:00:16 | 162,983,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 812 | java | package Training.TrainigDemo;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class MobileTest {
@Test
public void open(){
System.out.println("Mobile Emulator browser..");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\BackupDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.close();
}
}
| [
"selvendranmecse@gmail.com"
] | selvendranmecse@gmail.com |
681cdfb941636186e016a6e0fbc0bfc806e1db16 | dcf729ee06ef88e658be5cdc0568dd617a711856 | /one_to_fifty/Four.java | eb778c2e6145d3ced973324bcb6f4e9623f016ef | [] | no_license | Dendiom/Algorithm | 0ab21298a686d1f2f08dfb77b987833ef1b6e2fe | ca22fe9d2a6226917e28642f8556528c61e0be35 | refs/heads/master | 2021-07-07T11:07:28.992315 | 2019-04-13T08:12:25 | 2019-04-13T08:12:25 | 86,013,289 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,200 | java | package LeetCode.one_to_fifty;
public class Four {
//o(m + n)
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int target1 = 0, target2 = 0;
if ((m + n) % 2 == 0) {
target1 = (m + n) / 2 - 1;
target2 = target1 + 1;
} else {
target1 = (m + n) / 2;
}
int index1 = 0, index2 = 0, count = -1;
while (index1 < m && index2 < n) {
if (nums1[index1] <= nums2[index2]) {
count++;
if (count == target1) {
target1 = nums1[index1];
if (target2 == 0) {
return target1;
} else {
if (index1 + 1 < m) {
target2 = Math.min(nums1[index1 + 1], nums2[index2]);
} else {
target2 = nums2[index2];
}
return (target1 + target2) / 2.0;
}
}
index1++;
} else {
count++;
if (count == target1) {
target1 = nums2[index2];
if (target2 == 0) {
return target1;
} else {
if (index2 + 1 < n) {
target2 = Math.min(nums1[index1], nums2[index2 + 1]);
} else {
target2 = nums1[index1];
}
return (target1 + target2) / 2.0;
}
}
index2++;
}
}
count++;
if (index1 == m) {
while (count < target1) {
count++;
index2++;
}
return target2 == 0? nums2[index2] : (nums2[index2] + nums2[index2 + 1]) / 2.0;
} else {
while (count < target1) {
count++;
index1++;
}
return target2 == 0? nums1[index1] : (nums1[index1] + nums1[index1 + 1]) / 2.0;
}
}
public static double brief(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int len = m + n;
int index1 = 0, index2 = 0;
int first = 0, second = 0;
for (int i = 0; i <= len / 2; i++) {
first = second;
if (index1 < m && (index2 >= n || nums1[index1] <= nums2[index2])) {
second = nums1[index1++];
} else {
second = nums2[index2++];
}
}
if (len % 2 == 0) {
return (first + second) / 2.0;
}
return second;
}
public static void main(String[] args) {
System.out.println(findMedianSortedArrays(new int[]{1,3,5}, new int[]{}));
System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,6}));
System.out.println(brief(new int[]{}, new int[]{1,6}));
System.out.println(brief(new int[]{1, 6, 7 }, new int[]{1,6}));
}
}
| [
"lucky@DendideMacBook-Pro.local"
] | lucky@DendideMacBook-Pro.local |
4600088bbaa1c23a84c32dc5c29c0d7e410ad145 | c234bcc35162f427921b014c4c47d1bda4ba66cc | /Lab/StringCompare.java | 25551cbfa951ed875a9f703b547a84e76e2abb5a | [] | no_license | sharvil1996/DataStructure | f19b27e81235a4bf2279234389b7b8ebb267582a | 612a450a823c8c6e0f6175283dc98a18d310f297 | refs/heads/master | 2021-08-23T21:30:54.055373 | 2017-12-06T16:43:00 | 2017-12-06T16:43:00 | 113,341,586 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 607 | java | import java.util.Scanner;
public class StringCompare {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String str = sc.next();
int cnt = sc.nextInt();
String strTemp[] = new String[50];
String min = "";
String max = "";
int temp = 0;
while (temp != str.length()+1) {
strTemp[temp] = str.substring(temp, temp + cnt);
if (strTemp[temp].compareTo(min) > 0)
min = strTemp[temp];
if (strTemp[temp].compareTo(max) < 0)
max = strTemp[temp];
temp++;
}
System.out.println(min);
System.out.println(max);
}
}
| [
"sharvilshah1996@gmail.com"
] | sharvilshah1996@gmail.com |
8dc2faf830ecb08ab14708be7852fe5542129121 | 519c85c1fc630335d2ffca3fbb3ab141d1d8c784 | /spring_study/study6/src/main/java/inu/appcenter/study6/controller/MemberController.java | 1ac28e699cbd8937547cf8fea5737033f806837e | [] | no_license | wornjs135/Spring_Study | e25829dac43bb68b30a9c42cd7318cd8f07cb0cd | e9ae75a6a23292b7259b74a12ab4b448ac43079d | refs/heads/master | 2023-06-09T12:02:47.739994 | 2021-07-03T13:42:03 | 2021-07-03T13:42:03 | 382,614,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 900 | java | package inu.appcenter.study6.controller;
import inu.appcenter.study6.domain.Member;
import inu.appcenter.study6.model.MemberCreateRequest;
import inu.appcenter.study6.model.MemberResponse;
import inu.appcenter.study6.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class MemberController {
private final MemberService memberService;
@PostMapping("/members")
public ResponseEntity<MemberResponse> saveMember(@RequestBody MemberCreateRequest request){
Member savedMember = memberService.saveMember(request);
return ResponseEntity.ok(MemberResponse.from(savedMember));
}
}
| [
"rjeowornjs@naver.com"
] | rjeowornjs@naver.com |
ecbdb759f7fa146a122ddcacb7ee5fe5df68b476 | 9fa6c0450f3a190a20223b37097660a6694f35c2 | /Agnus/app/build/generated/source/r/debug/android/support/v4/R.java | ec2f0d58e1f2fb0a336023ac099c4b00e1b10fb0 | [] | no_license | juargore/Agnus | 6ac1f51f15ea3290ba337a9a53699e977a5a4546 | e9b9fc992648cbd6938857f6db0e2d5d431ca566 | refs/heads/master | 2020-08-06T16:09:12.503692 | 2019-10-05T20:35:39 | 2019-10-05T20:35:39 | 213,066,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,685 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v4;
public final class R {
public static final class attr {
public static final int coordinatorLayoutStyle = 0x7f04007e;
public static final int font = 0x7f0400a7;
public static final int fontProviderAuthority = 0x7f0400a9;
public static final int fontProviderCerts = 0x7f0400aa;
public static final int fontProviderFetchStrategy = 0x7f0400ab;
public static final int fontProviderFetchTimeout = 0x7f0400ac;
public static final int fontProviderPackage = 0x7f0400ad;
public static final int fontProviderQuery = 0x7f0400ae;
public static final int fontStyle = 0x7f0400af;
public static final int fontWeight = 0x7f0400b0;
public static final int keylines = 0x7f0400cc;
public static final int layout_anchor = 0x7f0400cf;
public static final int layout_anchorGravity = 0x7f0400d0;
public static final int layout_behavior = 0x7f0400d1;
public static final int layout_dodgeInsetEdges = 0x7f0400fd;
public static final int layout_insetEdge = 0x7f040106;
public static final int layout_keyline = 0x7f040107;
public static final int statusBarBackground = 0x7f040155;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f050000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f060059;
public static final int notification_icon_bg_color = 0x7f06005a;
public static final int notification_material_background_media_default_color = 0x7f06005b;
public static final int primary_text_default_material_dark = 0x7f060060;
public static final int ripple_material_light = 0x7f060065;
public static final int secondary_text_default_material_dark = 0x7f060066;
public static final int secondary_text_default_material_light = 0x7f060067;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f07004e;
public static final int compat_button_inset_vertical_material = 0x7f07004f;
public static final int compat_button_padding_horizontal_material = 0x7f070050;
public static final int compat_button_padding_vertical_material = 0x7f070051;
public static final int compat_control_corner_material = 0x7f070052;
public static final int notification_action_icon_size = 0x7f070089;
public static final int notification_action_text_size = 0x7f07008a;
public static final int notification_big_circle_margin = 0x7f07008b;
public static final int notification_content_margin_start = 0x7f07008c;
public static final int notification_large_icon_height = 0x7f07008d;
public static final int notification_large_icon_width = 0x7f07008e;
public static final int notification_main_column_padding_top = 0x7f07008f;
public static final int notification_media_narrow_margin = 0x7f070090;
public static final int notification_right_icon_size = 0x7f070091;
public static final int notification_right_side_padding_top = 0x7f070092;
public static final int notification_small_icon_background_padding = 0x7f070093;
public static final int notification_small_icon_size_as_large = 0x7f070094;
public static final int notification_subtext_size = 0x7f070095;
public static final int notification_top_pad = 0x7f070096;
public static final int notification_top_pad_large_text = 0x7f070097;
}
public static final class drawable {
public static final int notification_action_background = 0x7f080091;
public static final int notification_bg = 0x7f080092;
public static final int notification_bg_low = 0x7f080093;
public static final int notification_bg_low_normal = 0x7f080094;
public static final int notification_bg_low_pressed = 0x7f080095;
public static final int notification_bg_normal = 0x7f080096;
public static final int notification_bg_normal_pressed = 0x7f080097;
public static final int notification_icon_background = 0x7f080098;
public static final int notification_template_icon_bg = 0x7f080099;
public static final int notification_template_icon_low_bg = 0x7f08009a;
public static final int notification_tile_bg = 0x7f08009b;
public static final int notify_panel_notification_icon_bg = 0x7f08009c;
}
public static final class id {
public static final int action0 = 0x7f090007;
public static final int action_container = 0x7f09000f;
public static final int action_divider = 0x7f090011;
public static final int action_image = 0x7f090012;
public static final int action_text = 0x7f090018;
public static final int actions = 0x7f090019;
public static final int async = 0x7f090022;
public static final int blocking = 0x7f090029;
public static final int bottom = 0x7f09002a;
public static final int cancel_action = 0x7f090033;
public static final int chronometer = 0x7f09003b;
public static final int end = 0x7f090052;
public static final int end_padder = 0x7f090053;
public static final int forever = 0x7f09006c;
public static final int icon = 0x7f090074;
public static final int icon_group = 0x7f090075;
public static final int info = 0x7f09008b;
public static final int italic = 0x7f09008d;
public static final int left = 0x7f0900b6;
public static final int line1 = 0x7f0900b8;
public static final int line3 = 0x7f0900b9;
public static final int media_actions = 0x7f0900e1;
public static final int none = 0x7f0900ea;
public static final int normal = 0x7f0900eb;
public static final int notification_background = 0x7f0900ec;
public static final int notification_main_column = 0x7f0900ed;
public static final int notification_main_column_container = 0x7f0900ee;
public static final int right = 0x7f09010a;
public static final int right_icon = 0x7f09010b;
public static final int right_side = 0x7f09010c;
public static final int start = 0x7f090144;
public static final int status_bar_latest_event_content = 0x7f090145;
public static final int tag_transition_group = 0x7f090151;
public static final int text = 0x7f090152;
public static final int text2 = 0x7f090153;
public static final int time = 0x7f090169;
public static final int title = 0x7f09016a;
public static final int top = 0x7f09016e;
}
public static final class integer {
public static final int cancel_button_image_alpha = 0x7f0a0004;
public static final int status_bar_notification_info_maxnum = 0x7f0a000a;
}
public static final class layout {
public static final int notification_action = 0x7f0b0055;
public static final int notification_action_tombstone = 0x7f0b0056;
public static final int notification_media_action = 0x7f0b0057;
public static final int notification_media_cancel_action = 0x7f0b0058;
public static final int notification_template_big_media = 0x7f0b0059;
public static final int notification_template_big_media_custom = 0x7f0b005a;
public static final int notification_template_big_media_narrow = 0x7f0b005b;
public static final int notification_template_big_media_narrow_custom = 0x7f0b005c;
public static final int notification_template_custom_big = 0x7f0b005d;
public static final int notification_template_icon_group = 0x7f0b005e;
public static final int notification_template_lines_media = 0x7f0b005f;
public static final int notification_template_media = 0x7f0b0060;
public static final int notification_template_media_custom = 0x7f0b0061;
public static final int notification_template_part_chronometer = 0x7f0b0062;
public static final int notification_template_part_time = 0x7f0b0063;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0f0047;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f1000f6;
public static final int TextAppearance_Compat_Notification_Info = 0x7f1000f7;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f1000f8;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f1000f9;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f1000fa;
public static final int TextAppearance_Compat_Notification_Media = 0x7f1000fb;
public static final int TextAppearance_Compat_Notification_Time = 0x7f1000fc;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f1000fd;
public static final int TextAppearance_Compat_Notification_Title = 0x7f1000fe;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f1000ff;
public static final int Widget_Compat_NotificationActionContainer = 0x7f100174;
public static final int Widget_Compat_NotificationActionText = 0x7f100175;
public static final int Widget_Support_CoordinatorLayout = 0x7f100181;
}
public static final class styleable {
public static final int[] CoordinatorLayout = { 0x7f0400cc, 0x7f040155 };
public static final int CoordinatorLayout_keylines = 0;
public static final int CoordinatorLayout_statusBarBackground = 1;
public static final int[] CoordinatorLayout_Layout = { 0x010100b3, 0x7f0400cf, 0x7f0400d0, 0x7f0400d1, 0x7f0400fd, 0x7f040106, 0x7f040107 };
public static final int CoordinatorLayout_Layout_android_layout_gravity = 0;
public static final int CoordinatorLayout_Layout_layout_anchor = 1;
public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2;
public static final int CoordinatorLayout_Layout_layout_behavior = 3;
public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4;
public static final int CoordinatorLayout_Layout_layout_insetEdge = 5;
public static final int CoordinatorLayout_Layout_layout_keyline = 6;
public static final int[] FontFamily = { 0x7f0400a9, 0x7f0400aa, 0x7f0400ab, 0x7f0400ac, 0x7f0400ad, 0x7f0400ae };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f0400a7, 0x7f0400af, 0x7f0400b0 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
| [
"arturo.g.resendiz@gmail.com"
] | arturo.g.resendiz@gmail.com |
8d93fa37dc361e8594a19db5c703974df0885f22 | 2443d42b6874610071cbddbb28429b2db5b70a4f | /day7/src/main/java/stream/Main.java | 47dd7a56187b430ac1d9c6eb5f81ce0b43d14509 | [] | no_license | callmeislaan/SmartOsc_Study | fd044d98c96d8325bcb942a71fdf088558419f3d | c6b8cdfd7c000d947ca82df75679cf0d955ed9bd | refs/heads/master | 2022-12-23T09:53:43.745871 | 2020-09-25T21:42:05 | 2020-09-25T21:42:05 | 298,684,376 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,603 | java | package stream;
interface itf<T> {
// void bbc(T s1, T s2);
// T get();
T[] a(int size);
}
class MyString {
public MyString() {
System.out.println("day la A");
}
@Override
public String toString() {
return "Day la toString A";
}
// public MyString(String s1, String s2) {
//// return -s1.compareTo(s2);
// System.out.println("a");
// }
public int compareTo(String s1, String s2) {
return -s1.compareTo(s2);
}
}
public class Main {
public static void main(String[] args) {
// MyString myString = new MyString();
// Logger logger = LoggerFactory.getLogger(Main.class);
// logger.error("a", 1);
// logger.info("a", 2);
// logger.info("a", 3);
// logger.info("a", 4);
String[] list = {"Java", "Python", "C#"};
// Stream.of(list).filter(s -> s.startsWith("J")).forEach(s -> System.out.println(s));
// Stream.of(list).filter(s -> s.startsWith("J")).forEach(s -> System.out.println(s));
// streamSupplier.get().forEach(s -> System.out.println(s));
// streamSupplier.get().forEach(s -> System.out.println(s));
// IntStream.of(1, 2, 3).forEach(value -> System.out.println(value));
// DoubleStream.of(1, 2, 3, 4).forEach(value -> System.out.println(value));
// Stream.of(1, 2, 3, 4).forEach(integer -> System.out.println(integer));
// Stream<Integer> stream = Stream.of(new Integer[] {1, 2, 3});
// stream.forEach(integer -> System.out.println(integer));
// Stream stream1 = new ArrayList<Integer>().stream();
// Stream s = Stream.generate(() -> new Date()).limit(10);
//// s.forEach(o -> System.out.println(o));
// Stream.Builder builder = Stream.builder();
// builder.add(1);
// List<String> data = Arrays.asList("Java", "C#", "C++", "PHP", "Javascript");
String[] data = {"Java", "C#", "C++", "PHP", "Javascript", "Java"};
// Integer[] i = {2, 1, 3, 5, 4};
// Stream.of(i).peek(integers -> System.out.println(integers)).count();
// itf compareTo = MyString::compareTo;
// Consumer<String> a = MyString::new;
itf<MyString[]> my = MyString[][]::new;
MyString[][] a = my.a(3);
System.out.println(a.length);
// itf a = MyString::new;
// a.bbc("a", "a");
// Stream.of(data)
//// .peek(System.out::println)
// .sorted()
// .distinct()
//// .toArray();
// .forEach(System.out::println);
}
} | [
"truongphuoc7398@gmail.com"
] | truongphuoc7398@gmail.com |
14feb8349214ba9a3303d8b1af376a8ec5d7c124 | 1eb33cf6cff62ba84359b7b4b39ec121cbe0f72b | /src/main/java/construction/NoArgConstructor.java | 434a2bc4d9e40ea7b501e82fafe17d7fb9d8c621 | [] | no_license | jiuli/java_practice | 6068cedb4b5da41d5346be3d7f9ded5122d058e6 | b3baa327c1ca21415f8666aa76d1ab1bbce87c5f | refs/heads/master | 2021-06-05T17:39:09.249150 | 2021-06-03T08:27:23 | 2021-06-03T08:27:23 | 76,339,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 127 | java | package construction;
public class NoArgConstructor {
public NoArgConstructor() {
// Constructor body here
}
} | [
"554856005@qq.com"
] | 554856005@qq.com |
e11e7b46c6853f760b782f80f689651822708c13 | fae77554a7eda03bf5b6c005c3c42ff15c829d3b | /app/src/main/java/fragment/SendFragment.java | 36b59fba7e0e0952ce5f67de029f6ec6a4d5ffb2 | [] | no_license | food91/Weather | ab9df13046891a683a27abf7e5bfa84a7b8eed56 | 81b08d6b4542045f6f743ff4dc26c2487710003f | refs/heads/master | 2023-03-03T21:08:41.032056 | 2021-02-14T22:28:34 | 2021-02-14T22:28:34 | 338,920,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.xiekun.myapplication.R;
public class SendFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_send, container, false);
final TextView textView = root.findViewById(R.id.text_send);
return root;
}
} | [
"saberxk@163.com"
] | saberxk@163.com |
d69c492cd879bd60ddb410edba1f58ae65bf005c | 6492d445e8413e4e820ba16fa1d3cf61e9b8d5ad | /app/src/main/java/com/example/rajayambigms/allnotifications/SimpleNotification.java | 9774e537c1c47f55ce9b7b9d2472ce4b43baf50f | [] | no_license | RajendranEshwaran/ALL_NOTIFICATION_android | 7d87f88c8a9c51d7d1bfc97f94407e580416e27c | c5af104b202201e7d866727ef8b03369feb61784 | refs/heads/master | 2020-05-04T12:47:44.632687 | 2019-04-02T20:03:31 | 2019-04-02T20:03:31 | 179,135,424 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package com.example.rajayambigms.allnotifications;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SimpleNotification extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_notification);
}
}
| [
"rajendranmca2010@gmail.com"
] | rajendranmca2010@gmail.com |
d5b595eb6895924711564f2ad90857fe369516bb | ba7fcd0a28ab1cc9349ccd34a3f00241788026ff | /app/src/main/java/com/lecslt/travelmantics/TravelDeal.java | cadc452ae4c41f802d04d88c58569e58d79cf9cc | [] | no_license | EricMbouwe/Travelmantics | 9be300368918c2ce81b8addc3f14b0115d44fea0 | 597cad28a537ccc110ff93b8cd42491e5a0f6e0b | refs/heads/master | 2020-07-01T11:53:22.376823 | 2020-03-12T11:11:08 | 2020-03-12T11:11:08 | 201,167,377 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,506 | java | package com.lecslt.travelmantics;
import java.io.Serializable;
public class TravelDeal implements Serializable{
private String id;
private String title;
private String description;
private String price;
private String imageUrl;
private String imageName;
public TravelDeal() {
}
public TravelDeal(String title, String description, String price, String imageUrl, String imageName) {
this.setId(id);
this.setTitle(title);
this.setDescription(description);
this.setPrice(price);
this.setImageUrl(imageUrl);
this.setImageUrl(imageName);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
| [
"ericmbouwe@yahoo.fr"
] | ericmbouwe@yahoo.fr |
fba263791dd4bbc0741afcdc0d9e3f3b6aed9eda | b9942691bc3388795183564e7a32a123aeb5c074 | /src/main/java/ua/iv_fr/lukach/marian/in100gram/security/JWTAuthenticationEntryPoint.java | 45844a82a8db912ba70b0155694ea6e5644bcac7 | [] | no_license | wertyxa/In100gram | e53757085d10c43dd2e0265b1b171b6ab0812ca4 | 6d3ef5573dce5cf7e8a784b808dab48e40a08660 | refs/heads/master | 2023-08-13T17:22:44.062954 | 2021-10-17T21:33:06 | 2021-10-17T21:33:06 | 410,641,942 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,132 | java | package ua.iv_fr.lukach.marian.in100gram.security;
import com.google.gson.Gson;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import ua.iv_fr.lukach.marian.in100gram.payload.response.InvalidLoginResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
InvalidLoginResponse loginResponse = new InvalidLoginResponse();
String jsonLoginResponse = new Gson().toJson(loginResponse);
httpServletResponse.setContentType(SecurityConstants.CONTENT_TYPE);
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().println(jsonLoginResponse);
}
}
| [
"wertyxa.amin@gmail.com"
] | wertyxa.amin@gmail.com |
c812495b11d91abe5129dc3adcc899cb69592d1c | 5b82e2f7c720c49dff236970aacd610e7c41a077 | /QueryReformulation-master 2/data/ExampleSourceCodeFiles/CSSPropertyTitleFormsHandler.java | aa781857a41365a7c8cfc57641b0fe99929e3dfe | [] | no_license | shy942/EGITrepoOnlineVersion | 4b157da0f76dc5bbf179437242d2224d782dd267 | f88fb20497dcc30ff1add5fe359cbca772142b09 | refs/heads/master | 2021-01-20T16:04:23.509863 | 2016-07-21T20:43:22 | 2016-07-21T20:43:22 | 63,737,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,345 | java | /Users/user/eclipse.platform.ui/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/internal/forms/css/properties/css2/CSSPropertyTitleFormsHandler.java
org eclipse internal forms css properties css org eclipse css core engine engine org eclipse css swt properties abstract property handler org eclipse swt graphics color org eclipse swt widgets control org eclipse forms widgets section org dom css value property title forms handler abstract property handler string background color gradient titlebar string background color titlebar string border color titlebar override apply property control control string property value string pseudo engine engine exception equals ignore case property control section css value type value color color color engine convert color control display section control set title bar gradient background color css value type value equals ignore case property control section css value type value color color color engine convert color control display section control set title bar background color css value type value equals ignore case property control section css value type value color color color engine convert color control display section control set title bar border color color css value type value override string retrieve property control control string property string pseudo engine engine exception null | [
"muktacseku@gmail.com"
] | muktacseku@gmail.com |
3ef09c6fd45bcbaf4ce739f97eb3a7157e77216f | 648179f5f66f1ea3db57d3dad53ab313bcf6ddc7 | /Vehicleautomat/src/main/resources/defaultTypes/java/lang/Boolean.java | c51a733035e1b8e15df9cd0c84783d6ab8bdef5e | [] | no_license | dina-25/industrie4.0 | ef670f7b38868277472ad44d0df384dee49e2ebc | 74c7516a7a27cdf5abe42298be1e0ff19a665cca | refs/heads/master | 2020-03-28T10:59:24.002569 | 2018-09-10T14:13:41 | 2018-09-10T14:13:41 | 148,166,255 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 58 | java | package java.lang;
public class Boolean extends Object {
} | [
"40601380+dina-25@users.noreply.github.com"
] | 40601380+dina-25@users.noreply.github.com |
4f505d0a25b25c441345ef989a7ade580ebd17d6 | 124cef9be26df75c62ad766bfaebd281f75c8152 | /src/main/java/com/hansoleee/corespringsecurity/domain/dto/AccountDto.java | 261ed70e58a36e10b2fc8752e865133b2bd81781 | [] | no_license | hansoleee/core-spring-security | ad72ec2e15e97e076fe6b0f02a0f9fa77c325955 | 803b1e778ae47e0603d09a84191376ac1734340e | refs/heads/main | 2023-07-15T09:36:48.418674 | 2021-08-16T13:41:11 | 2021-08-16T13:41:11 | 395,935,597 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | package com.hansoleee.corespringsecurity.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class AccountDto {
private String id;
private String username;
private String email;
private int age;
private String password;
private List<String> roles;
@Builder
public AccountDto(String id, String username, String email, int age, String password, List<String> roles) {
this.id = id;
this.username = username;
this.email = email;
this.age = age;
this.password = password;
this.roles = roles;
}
}
| [
"leehansol.kr@gmail.com"
] | leehansol.kr@gmail.com |
4a886dda28205906b5e685a763368749c3f71514 | 6578045c16d9560d4ed6d35c3bb99c76717bb3ef | /Invasion/src/com/codeday/invasion/AbstractScreen.java | 89678c8320449955af7b6bf5c04d50f3cf993273 | [] | no_license | TomWerner/Invasion-game | 0b64a5e81dbf64c4f8d7abc50689ce744e829def | 63311e4c76f15c7b6a46e70b76123bbed7ff8e45 | refs/heads/master | 2021-01-22T09:50:37.782130 | 2015-03-10T03:30:11 | 2015-03-10T03:30:11 | 16,967,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,792 | java | package com.codeday.invasion;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
/**
* The base class for all game screens.
*/
public abstract class AbstractScreen implements Screen
{
// the fixed viewport dimensions (ratio: 1.6)
public static final int GAME_VIEWPORT_WIDTH = 800,
GAME_VIEWPORT_HEIGHT = 600;
public static final int MENU_VIEWPORT_WIDTH = 800,
MENU_VIEWPORT_HEIGHT = 600;
protected final Invasion game;
protected Stage stage;
private BitmapFont font;
private SpriteBatch batch;
private Skin skin;
private TextureAtlas atlas;
private Table table;
public AbstractScreen(Invasion game)
{
this.game = game;
int width = (isGameScreen() ? GAME_VIEWPORT_WIDTH : MENU_VIEWPORT_WIDTH);
int height = (isGameScreen() ? GAME_VIEWPORT_HEIGHT
: MENU_VIEWPORT_HEIGHT);
this.stage = new Stage(width, height, true);
}
protected String getName()
{
return getClass().getSimpleName();
}
protected boolean isGameScreen()
{
return false;
}
// Lazily loaded collaborators
public BitmapFont getFont()
{
if (font == null)
{
font = new BitmapFont();
}
return font;
}
public SpriteBatch getBatch()
{
if (batch == null)
{
batch = new SpriteBatch();
}
return batch;
}
// public TextureAtlas getAtlas()
// {
// if (atlas == null)
// {
// atlas = new TextureAtlas(
// Gdx.files.internal("image-atlases/pages.atlas"));
// }
// return atlas;
// }
protected Skin getSkin()
{
if (skin == null)
{
FileHandle skinFile = Gdx.files.internal("skin/uiskin.json");
skin = new Skin(skinFile);
}
return skin;
}
protected Table getTable()
{
if (table == null)
{
table = new Table(getSkin());
table.setFillParent(true);
if (Invasion.DEV_MODE)
{
table.debug();
}
stage.addActor(table);
}
return table;
}
// Screen implementation
@Override
public void show()
{
Gdx.app.log(Invasion.LOG, "Showing screen: " + getName());
// set the stage as the input processor
Gdx.input.setInputProcessor(stage);
}
@Override
public void resize(int width, int height)
{
Gdx.app.log(Invasion.LOG, "Resizing screen: " + getName() + " to: " + width
+ " x " + height);
}
@Override
public void render(float delta)
{
// (1) process the game logic
// update the actors
stage.act(delta);
// (2) draw the result
// clear the screen with the given RGB color (black)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// draw the actors
stage.draw();
// draw the table debug lines
Table.drawDebug(stage);
}
@Override
public void hide()
{
Gdx.app.log(Invasion.LOG, "Hiding screen: " + getName());
// dispose the screen when leaving the screen;
// note that the dipose() method is not called automatically by the
// framework, so we must figure out when it's appropriate to call it
dispose();
}
@Override
public void pause()
{
Gdx.app.log(Invasion.LOG, "Pausing screen: " + getName());
}
@Override
public void resume()
{
Gdx.app.log(Invasion.LOG, "Resuming screen: " + getName());
}
@Override
public void dispose()
{
Gdx.app.log(Invasion.LOG, "Disposing screen: " + getName());
// as the collaborators are lazily loaded, they may be null
if (font != null)
font.dispose();
if (batch != null)
batch.dispose();
if (skin != null)
skin.dispose();
if (atlas != null)
atlas.dispose();
}
} | [
"tomwer3@gmail.com"
] | tomwer3@gmail.com |
9427c2174083dd77cea51a65944ec3e1c43f4d92 | dfa85f8e4cda79ba9ad75cc15534253336685818 | /src/main/java/com/example/blogsystem/entity/BlogTagRelation.java | e37aff79918d7c0250c431fc0dde6b87f774930f | [] | no_license | Changri-Liuhen/BlogSystem | 35dd29a4d77b88d0352e926402f5de79b5a7b630 | 7e4c576b329c621e9d1b499e5be31892853afc49 | refs/heads/master | 2023-05-20T22:16:29.842460 | 2021-06-13T16:21:00 | 2021-06-13T16:21:00 | 376,553,653 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,286 | java | package com.example.blogsystem.entity;
import java.util.Date;
public class BlogTagRelation {
private Long relationId;
private Long blogId;
private Integer tagId;
private Date createTime;
public Long getRelationId() {
return relationId;
}
public void setRelationId(Long relationId) {
this.relationId = relationId;
}
public Long getBlogId() {
return blogId;
}
public void setBlogId(Long blogId) {
this.blogId = blogId;
}
public Integer getTagId() {
return tagId;
}
public void setTagId(Integer tagId) {
this.tagId = tagId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", relationId=").append(relationId);
sb.append(", blogId=").append(blogId);
sb.append(", tagId=").append(tagId);
sb.append(", createTime=").append(createTime);
sb.append("]");
return sb.toString();
}
} | [
"duhy001512@163.com"
] | duhy001512@163.com |
4f8900782aedf172837d5e3f12bb360ce4913037 | 97b46ff38b675d934948ff3731cf1607a1cc0fc9 | /DataPack/dist/game/data/scripts/transformations/AurabirdFalcon.java | 7dc199c05842adc37ee4d53b28755270c287bd6f | [] | no_license | l2brutal/pk-elfo_H5 | a6703d734111e687ad2f1b2ebae769e071a911a4 | 766fa2a92cb3dcde5da6e68a7f3d41603b9c037e | refs/heads/master | 2020-12-28T13:33:46.142303 | 2016-01-20T09:53:10 | 2016-01-20T09:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,067 | java | package transformations;
import pk.elfo.gameserver.instancemanager.TransformationManager;
import pk.elfo.gameserver.model.L2Transformation;
import pk.elfo.gameserver.model.skills.L2Skill;
public class AurabirdFalcon extends L2Transformation
{
private static final int[] SKILLS = new int[]
{
884,
885,
886,
888,
890,
891,
894,
911,
932,
619
};
public AurabirdFalcon()
{
// id, colRadius, colHeight
super(8, 38, 14.25);
}
@Override
public void onTransform()
{
if ((getPlayer().getTransformationId() != 8) || getPlayer().isCursedWeaponEquipped())
{
return;
}
getPlayer().setIsFlyingMounted(true);
transformedSkills();
}
@Override
public void onUntransform()
{
getPlayer().setIsFlyingMounted(false);
removeSkills();
}
public void removeSkills()
{
// Air Blink
getPlayer().removeSkill(L2Skill.valueOf(885, 1), false);
// Exhilarate
getPlayer().removeSkill(L2Skill.valueOf(894, 1), false);
int lvl = getPlayer().getLevel() - 74;
if (lvl > 0)
{
// Air Assault (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(884, lvl), false);
// Air Shock Bomb (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(886, lvl), false);
// Energy Storm (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(888, lvl), false);
// Prodigious Flare (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(890, lvl), false);
// Energy Shot (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(891, lvl), false);
// Energy Burst (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(911, lvl), false);
}
// Transform Dispel
getPlayer().removeSkill(L2Skill.valueOf(619, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
public void transformedSkills()
{
// Air Blink
if (getPlayer().getLevel() >= 75)
{
getPlayer().addSkill(L2Skill.valueOf(885, 1), false);
}
// Exhilarate
if (getPlayer().getLevel() >= 83)
{
getPlayer().addSkill(L2Skill.valueOf(894, 1), false);
}
int lvl = getPlayer().getLevel() - 74;
if (lvl > 0)
{
// Air Assault (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(884, lvl), false);
// Air Shock Bomb (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(886, lvl), false);
// Energy Storm (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(888, lvl), false);
// Prodigious Flare (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(890, lvl), false);
// Energy Shot (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(891, lvl), false);
// Energy Burst (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(911, lvl), false);
}
// Transform Dispel
getPlayer().addSkill(L2Skill.valueOf(619, 1), false);
getPlayer().setTransformAllowedSkills(SKILLS);
}
public static void main(String[] args)
{
TransformationManager.getInstance().registerTransformation(new AurabirdFalcon());
}
} | [
"PkElfo@13720c4f-9a1f-4619-977f-b36a0ac534ba"
] | PkElfo@13720c4f-9a1f-4619-977f-b36a0ac534ba |
30fc87fb697228ea328f91df709c57ab66c9888d | 6f33127cadc2226c200045bb98a2ecaebab7cef6 | /WebXslt/src/test/java/com/github/rabid_fish/web/ServletActionTest.java | 5a10a3cd3fce5d4a6a69e4fd8cb5b066aae35b43 | [
"Apache-2.0"
] | permissive | rabid-fish/JavaXslt | b4b949ebcfc8b1de05c9e495a3b62fc0dc1276c8 | 64ad55c3a3332714e7996279f2e7c6e2050242e0 | refs/heads/master | 2020-05-30T18:24:50.711081 | 2014-08-18T04:28:31 | 2014-08-18T04:28:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 961 | java | package com.github.rabid_fish.web;
import static org.junit.Assert.*;
import org.junit.Test;
public class ServletActionTest {
@Test
public void testTranslateFromString() {
ServletAction servletAction = ServletAction.translateFromString(ServletAction.LIST.toString());
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringWithLowercaseActionString() {
ServletAction servletAction = ServletAction.translateFromString(ServletAction.LIST.toString().toLowerCase());
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringCheckForNull() {
ServletAction servletAction = ServletAction.translateFromString(null);
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringCheckForGibberish() {
ServletAction servletAction = ServletAction.translateFromString("gibberish");
assertEquals(servletAction, null);
}
}
| [
"spam@danandlaurajuliano.com"
] | spam@danandlaurajuliano.com |
92ed94eb4808fb6026c427b76be5ff8896659243 | 9ccd9d652366b633663350466c6b770fed354d42 | /src/main/java/leetcode/GasStation.java | 4cfccd6b5a24fedacf0257b507638aa197dacda7 | [] | no_license | xigui2013/leetcode | e16686661c0b7e8ef52a06ce01c7c6a92f9eb399 | 99c19e25835dde7d90bc51d2618b252fb60bd919 | refs/heads/master | 2021-01-23T08:04:26.023277 | 2018-06-24T03:30:24 | 2018-06-24T03:30:24 | 86,475,009 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,481 | java | package leetcode;
/**
* leetcode
* Created by wjw on 16/05/2017.
*/
public class GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
int length = gas.length;
int[] remain = new int[length];
for (int index = 0; index < length; index++) {
remain[index] = gas[index] - cost[index];
}
for (int flag = 0; flag < length; flag++) {
if (remain[flag] < 0) {
continue;
}
int index = flag + 1;
int remainGas = remain[flag];
boolean noway = false;
while (index != flag) {
if (index == length) {
index = 0;
continue;
}
remainGas += remain[index];
if (remainGas < 0) {
noway = true;
break;
}
index++;
}
if (!noway) {
return flag;
}
}
return -1;
}
public int canCompleteCircuit2(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int j = 0;
for (int i = 0; i < gas.length; ++i) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
j = i + 1;
sum = 0;
}
}
if (total < 0) {
return -1;
}
return j;
}
}
| [
"jianwenwei1@creditease.cn"
] | jianwenwei1@creditease.cn |
687684be9a30a812931fb31576b994ff68934dfe | 47436699ac32b3b138c53f2c7931b4636ea79eb9 | /server/dictionary-api/src/main/java/com/tsoft/dictionary/util/library/WordCounter.java | 24d1a04904c05bd7da516d617d66e096b9b1bf8e | [] | no_license | knivit/dictionary | 8108f67a9a2c066afa9d02cddec59d5f0d7668e0 | d4285dec0352f124130a43e7a1acff6e053e196d | refs/heads/master | 2021-01-13T02:11:44.807469 | 2015-03-15T13:15:31 | 2015-03-15T13:15:31 | 32,261,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 193 | java | package com.tsoft.library;
public class WordCounter {
private int count;
public int getCount() {
return count;
}
public void inc(int n) {
count += n;
}
}
| [
"knivit@gmail.com"
] | knivit@gmail.com |
d8073d240fb9c004f0d76a70ef8188dcecbbfa42 | db184b57945a665d617edde42ef0185085c5e322 | /FoodApp/app/src/main/java/com/khmkau/codeu/foodapp/ManualInputActivity.java | 614a19fec535edd262b7644614e37e53f503d163 | [
"MIT"
] | permissive | anthonyuitz/FoodApp | 1236de9cb35ead5d9d7895b07152781a299af197 | a86f8bcf618014257257d332f04232ed39bd26e3 | refs/heads/master | 2021-01-15T16:15:00.857684 | 2015-08-19T01:47:23 | 2015-08-19T01:47:23 | 39,339,698 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 22,344 | java | package com.khmkau.codeu.foodapp;
import android.app.DatePickerDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.Toast;
import com.khmkau.codeu.foodapp.data.FoodContract;
import com.khmkau.codeu.foodapp.data.FoodDbHelper;
import java.util.Calendar;
import java.util.Date;
public class ManualInputActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_input);
}
@Override
protected void onResume() {
super.onResume();
Spinner tableSpinner = (Spinner) findViewById(R.id.tableSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.table_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
tableSpinner.setAdapter(adapter);
tableSpinner.setOnItemSelectedListener(this);
Spinner quantitySpinner = (Spinner) findViewById(R.id.quantitySpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = ArrayAdapter.createFromResource(this,
R.array.quantity_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
quantitySpinner.setAdapter(adapter);
quantitySpinner.setAdapter(adapter);
quantitySpinner.setOnItemSelectedListener(this);
Spinner editFoodGroup = (Spinner) findViewById(R.id.editFoodGroup);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = ArrayAdapter.createFromResource(this,
R.array.food_groups, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
editFoodGroup.setAdapter(adapter);
EditText purchaseByEditText = (EditText)findViewById(R.id.editPurchasedBy);
purchaseByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog(ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText) findViewById(R.id.editPurchasedBy);
c.setText("" + (selectedmonth + 1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText expiredByEditText = (EditText)findViewById(R.id.editExpiresBy);
expiredByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editExpiresBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText consumedByEditText = (EditText)findViewById(R.id.editConsumedBy);
consumedByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editConsumedBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText thrownByEditText = (EditText)findViewById(R.id.editThrownBy);
thrownByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editThrownBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
switch(parent.getId()) {
case R.id.tableSpinner:
TableRow rowConsumed = (TableRow) findViewById(R.id.rowConsumed);
TableRow rowThrown = (TableRow) findViewById(R.id.rowThrown);
switch (pos) {
case 0:
rowConsumed.setVisibility(View.GONE);
rowThrown.setVisibility(View.GONE);
break;
case 1:
rowConsumed.setVisibility(View.VISIBLE);
rowThrown.setVisibility(View.GONE);
break;
case 2:
rowConsumed.setVisibility(View.GONE);
rowThrown.setVisibility(View.VISIBLE);
break;
}
break;
case R.id.quantitySpinner:
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void inputFood(View view) {
//Toast.makeText(getApplicationContext(), "This feature is not yet implemented. Sorry!",
// Toast.LENGTH_SHORT).show();
ContentValues infoValues = new ContentValues();
ContentValues foodValues = new ContentValues();
EditText nameTextView = (EditText)findViewById(R.id.editName);
EditText quantityTextView = (EditText)findViewById(R.id.editQuantity);
EditText purchasedByTextView = (EditText)findViewById(R.id.editPurchasedBy);
EditText expiredByTextView = (EditText)findViewById(R.id.editExpiresBy);
Spinner foodgroupTextView = (Spinner)findViewById(R.id.editFoodGroup);
EditText totalCostTextView = (EditText)findViewById(R.id.editTotalCost);
EditText caloriesTextView = (EditText)findViewById(R.id.editCalories);
EditText totalFatTextView = (EditText)findViewById(R.id.editTotalFat);
EditText satFatTextView = (EditText)findViewById(R.id.editSatFat);
EditText transFatTextView = (EditText)findViewById(R.id.editTransFat);
EditText cholesterolTextView = (EditText)findViewById(R.id.editCholesterol);
EditText sodiumTextView = (EditText)findViewById(R.id.editSodium);
EditText totalCarbsTextView = (EditText)findViewById(R.id.editTotalCarbs);
EditText sugarTextView = (EditText)findViewById(R.id.editSugar);
EditText proteinTextView = (EditText)findViewById(R.id.editProtein);
Spinner servingTextView = (Spinner)findViewById(R.id.quantitySpinner);
String nameText = nameTextView.getText().toString();
String quantityText = quantityTextView.getText().toString();
String purchasedByText = purchasedByTextView.getText().toString();
String expiredByText = expiredByTextView.getText().toString();
String foodgroupText = foodgroupTextView.getSelectedItem().toString();
String totalCostText = totalCostTextView.getText().toString();
String caloriesText = caloriesTextView.getText().toString();
String totalFatText = totalFatTextView.getText().toString();
String satFatText = satFatTextView.getText().toString();
String transFatText = transFatTextView.getText().toString();
String cholesterolText = cholesterolTextView.getText().toString();
String sodiumText = sodiumTextView.getText().toString();
String totalCarbsText = totalCarbsTextView.getText().toString();
String sugarText = sugarTextView.getText().toString();
String proteinText = proteinTextView.getText().toString();
String servingText = servingTextView.getSelectedItem().toString();
Spinner tableTextView = (Spinner)findViewById(R.id.tableSpinner);
String tableText = tableTextView.getSelectedItem().toString();
String consumedByText = "";
String thrownByText = "";
boolean isValid = true;
if(!Utility.isNumeric(quantityText) || quantityText.equals("")) {
isValid = false;
quantityTextView.setHint(R.string.quantity_error);
quantityTextView.setHintTextColor(Color.RED);
}
int[] purchasedByArray = Utility.validateDate(purchasedByText);
if(purchasedByArray[0] == -1) {
isValid = false;
purchasedByTextView.setHint(R.string.purchased_by_error);
purchasedByTextView.setHintTextColor(Color.RED);
}
int[] expiredByArray = Utility.validateDate(expiredByText);
if(expiredByArray[0] == -1) {
isValid = false;
expiredByTextView.setHint(R.string.expires_by_error);
expiredByTextView.setHintTextColor(Color.RED);
}
if(!totalCarbsText.equals("")) {
if (totalCostText.charAt(0) == '$') {
totalCostText = totalCostText.substring(1);
}
}
if(!Utility.isDouble(totalCostText) || totalCostText.equals("")) {
isValid = false;
totalCostTextView.setHint(R.string.total_cost_error);
totalCostTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(caloriesText) || caloriesText.equals("")) {
isValid = false;
caloriesTextView.setHint(R.string.calories_error);
caloriesTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(totalFatText)) {
isValid = false;
totalFatTextView.setHint(R.string.total_fat_error);
totalFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(satFatText)) {
isValid = false;
satFatTextView.setHint(R.string.saturated_fat_error);
satFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(transFatText)) {
isValid = false;
transFatTextView.setHint(R.string.trans_fat_error);
transFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(cholesterolText)) {
isValid = false;
cholesterolTextView.setHint(R.string.cholesterol_error);
cholesterolTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(sodiumText)) {
isValid = false;
sodiumTextView.setHint(R.string.sodium_error);
sodiumTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(totalCarbsText)) {
isValid = false;
totalCarbsTextView.setHint(R.string.total_carbs_error);
totalCarbsTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(sugarText)) {
isValid = false;
sugarTextView.setHint(R.string.sugar_error);
sugarTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(proteinText)) {
isValid = false;
proteinTextView.setHint(R.string.protein_error);
proteinTextView.setHintTextColor(Color.RED);
}
if(isValid) {
infoValues.put(FoodContract.InfoEntry.COLUMN_FOOD_NAME, nameText);
infoValues.put(FoodContract.InfoEntry.COLUMN_FOOD_GROUP, foodgroupText);
infoValues.put(FoodContract.InfoEntry.COLUMN_SERVING_UNIT, servingText);
infoValues.put(FoodContract.InfoEntry.COLUMN_CALORIES, Integer.parseInt(caloriesText));
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SATURATED_FAT, Integer.parseInt(satFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TRANS_FAT, Integer.parseInt(transFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TOTAL_FAT, Integer.parseInt(totalFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_CHOLESTEROL, Integer.parseInt(cholesterolText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SODIUM, Integer.parseInt(sodiumText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TOTAL_CARBOHYDRATE, Integer.parseInt(totalCarbsText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SUGAR, Integer.parseInt(sugarText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_PROTEIN, Integer.parseInt(proteinText));
}
long food_id = ContentUris.parseId(getContentResolver().insert(FoodContract.InfoEntry.CONTENT_URI, infoValues));
//check which table is being inserted to and get relevant fields
if (tableText.equals("Consumed")) {
EditText consumedByTextView = (EditText) findViewById(R.id.editConsumedBy);
consumedByText = consumedByTextView.getText().toString();
int[] consumedDates = Utility.validateDate(consumedByText);
if (consumedDates[0] == -1) {
consumedByTextView.setHintTextColor(Color.RED);
consumedByTextView.setHint(R.string.consumed_by_error);
consumedByTextView.setText("");
isValid = false;
} else {
Date consumedDateTemp = new Date(consumedDates[2], consumedDates[0], consumedDates[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_DATE_CONSUMED, FoodContract.normalizeDate(consumedDateTemp.getTime()));
}
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.ConsumedEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.ConsumedEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.ConsumedEntry.CONTENT_URI, foodValues);
}
} else if (tableText.equals("Thrown")) {
EditText thrownByTextView = (EditText) findViewById(R.id.editThrownBy);
thrownByText = thrownByTextView.getText().toString();
int[] thrownDates = Utility.validateDate(thrownByText);
if (thrownDates[0] == -1) {
thrownByTextView.setHintTextColor(Color.RED);
thrownByTextView.setHint(R.string.thrown_by_error);
thrownByTextView.setText("");
isValid = false;
} else {
Date thrownDateTemp = new Date(thrownDates[2], thrownDates[0], thrownDates[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_DATE_THROWN, FoodContract.normalizeDate(thrownDateTemp.getTime()));
}
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.ThrownEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.ThrownEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.ThrownEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.ThrownEntry.CONTENT_URI, foodValues);
}
} else {
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.CurrentEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.CurrentEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.CurrentEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.CurrentEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.CurrentEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.CurrentEntry.CONTENT_URI, foodValues);
}
}
}
if(isValid) {
Toast.makeText(getApplicationContext(), "Food added to " + tableText + ".",
Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(getApplicationContext(), "Failed to add food item.",
Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manual_input, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"aru5mf@virginia.edu"
] | aru5mf@virginia.edu |
be4429d61359750fcb538b9ade69eff72f49a064 | 41d767a6d315a908a416c9edaa7dfb7edc8ec752 | /2.JavaCore/src/com/javarush/task/task15/task1515/Solution.java | 03e8daf7725c8d87ec5d7fe59707078510f14e3b | [] | no_license | NSergeyI/JavaRushTasks | a272fa0e8d6c25217c3fdf05c4079dd83724a6e9 | 6e48200d46cd843220e401b3897fb35b624abc32 | refs/heads/master | 2020-03-13T14:47:09.930568 | 2019-03-10T19:59:37 | 2019-03-10T19:59:37 | 100,500,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package com.javarush.task.task15.task1515;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
Статики-2
*/
public class Solution {
public static int A;
public static int B;
static
{
try {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String sa = read.readLine();
String sb = read.readLine();
read.close();
A = Integer.parseInt(sa);
B = Integer.parseInt(sb);
} catch(Exception ex){
ex.printStackTrace();
}
}
public static final int MIN = min(A, B);
public static void main(String[] args) {
System.out.println(MIN);
}
public static int min(int a, int b) {
return a < b ? a : b;
}
}
| [
"yardox@gmail.com"
] | yardox@gmail.com |
6fd511ccfddfc59f2b28f7241743ba4bfd381e93 | fdd9a347189cfee0c13401e7e12585d48ee20577 | /src/main/java/com/github/sunnybat/commoncode/utilities/IPAddress.java | a2340a1adaa8fc2791736514a3c2cf1773b58698 | [] | no_license | SunnyBat/CommonCode | 1a2a4e3f052de54b64ca6a30997e461edb666cca | 30a253d884cb78e5e1c8af7342db3d86478cd39b | refs/heads/development | 2021-01-17T10:06:17.765935 | 2019-05-29T15:13:52 | 2019-05-29T15:14:09 | 30,432,986 | 1 | 4 | null | 2016-05-08T17:24:46 | 2015-02-06T21:05:21 | Java | UTF-8 | Java | false | false | 1,104 | java | package com.github.sunnybat.commoncode.utilities;
import java.io.IOException;
/**
*
* @author SunnyBat
*/
public class IPAddress {
private static final String CHECK_IP_SITE = "http://checkip.amazonaws.com";
/**
* Gets the internal IP address of the given machine.
*
* @return The visible IP address, or [Not Found] if unable to find it
*/
public static String getInternalIP() {
try {
return java.net.Inet4Address.getLocalHost().getHostAddress();
} catch (IOException e) {
return "[Not Found]";
}
}
/**
* Gets the external IP address of the given machine.
*
* @return The visible IP address, or [Not Found] if unable to find it
*/
public static String getExternalIP() {
// Credit to StackOverflow user bakkal
try {
java.net.URL whatismyip = new java.net.URL(CHECK_IP_SITE);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(whatismyip.openStream()));
return in.readLine(); // Only line returned is the IP
} catch (IOException e) {
return "[Not Found]";
}
}
}
| [
"Sunnybat@yahoo.com"
] | Sunnybat@yahoo.com |
74bdd4948d927934038f714acb41c6f7c45c5aca | 76875917925793ea446a1b1536606633a3272653 | /evo-async-all/src/main/java/com/tazine/evo/async/spring/finish/FinishService.java | 73462a2681e54fec91aca81e63fd59c7ea258854 | [
"MIT"
] | permissive | BookFrank/EVO-World | 01555355c434fac65406e158ffa5f7aebf3ff7dc | 3d27ae414f0281668024838a4c64db4bdd4a6377 | refs/heads/master | 2022-06-22T05:56:43.648597 | 2020-05-05T15:44:32 | 2020-05-05T15:44:32 | 147,456,884 | 1 | 1 | MIT | 2022-06-21T02:58:35 | 2018-09-05T03:54:10 | Java | UTF-8 | Java | false | false | 1,375 | java | package com.tazine.evo.async.spring.finish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* FinishService
*
* @author frank
* @date 2019/3/5
*/
@Slf4j
@Service
public class FinishService {
@Async
public ListenableFuture<Integer> asyncProcess() {
log.info("执行中");
int sec = new Random().nextInt(3);
System.out.println(sec + " s");
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<>(sec);
}
@Async
public ListenableFuture<Integer> latchProcess(CountDownLatch latch) {
log.info("执行中");
int sec = new Random().nextInt(5);
System.out.println(sec + " s");
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
log.info("进行countDown,剩余 {} 个", latch.getCount());
return new AsyncResult<>(sec);
}
}
| [
"bookfrank@foxmail.com"
] | bookfrank@foxmail.com |
ca00199fcc4b49e17263c5d18b98f711917f1980 | 26d412a165b9d4d3f66908ec8ff65617b93799c0 | /striverSheet/binarySearchTree/predecessorSuccessor/PredecessorSuccessor.java | 4b45e0c57dd3c54e0b72a9f674443e7d819a40d2 | [] | no_license | shanu822486/DSAPreparation | 312c35a326c6d1367c7eb9439cb63769654370a0 | 578cc6bcb0cdaf19f6e1971279de92721c58308d | refs/heads/master | 2023-07-13T12:33:49.943942 | 2021-08-26T17:12:16 | 2021-08-26T17:12:16 | 376,103,371 | 0 | 0 | null | 2021-08-21T18:26:59 | 2021-06-11T17:54:00 | Java | UTF-8 | Java | false | false | 1,098 | java |
// link to Question - https://practice.geeksforgeeks.org/problems/predecessor-and-successor/1#
class GfG
{
public static void findPreSuc(Node root, Res p, Res s, int key)
{
// add your code here
Node pre = null;
Node suc = null;
if(root == null){
return;
}
while(root != null){
if(root.data == key){
if(root.left != null){
pre = root.left;
while(pre.right != null)
pre = pre.right;
}
if(root.right != null){
suc = root.right;
while(suc.left != null)
suc = suc.left;
}
p.pre = pre;
s.succ = suc;
return;
}
if(root.data > key){
suc = root;
root = root.left;
}
else {
pre = root;
root = root.right;
}
}
p.pre = pre;
s.succ = suc;
}
}
| [
"shanutyagi2028@gmail.com"
] | shanutyagi2028@gmail.com |
9163fb379cf73358ab3dbe47348a29d02db5bbb4 | 6f1f272bcf6bed8ec5c3352223b694f21b0e37e4 | /transponder/src/test/java/it/acalabro/transponder/KieLauncher.java | 7c6d8dcb2d191378f3770b6b37f586373d65d6cb | [] | no_license | acalabro/RSW_TH | e543c8ac2a893179b3fb4da749f088efae07c00d | 1290f8d6ed17067ae8d342d4284c11deed0eace2 | refs/heads/master | 2023-07-17T22:45:22.646417 | 2021-09-02T11:11:43 | 2021-09-02T11:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,122 | java | package it.acalabro.transponder;
import it.acalabro.transponder.cep.CepType;
import it.acalabro.transponder.event.ConcernProbeEvent;
public class KieLauncher {
public KieLauncher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws InterruptedException {
DroolsKieTest asd = new DroolsKieTest();
asd.start();
DroolsKieTest.loadRule();
Thread.sleep(1000);
System.out.println("ora mando");
ConcernProbeEvent<String> evt = new ConcernProbeEvent<String>(
System.currentTimeMillis(),
"senderA", "destinationA", "sessionA",
"checksum",
"SLA Alert", "coccole", CepType.DROOLS,"open");
DroolsKieTest.insertEvent(evt);
Thread.sleep(1000);
System.out.println("ora mando altro");
ConcernProbeEvent<String> evt2 = new ConcernProbeEvent<String>(
System.currentTimeMillis(),
"senderA", "destinationA", "sessionA",
"checksum",
"load_one", "coccole", CepType.DROOLS,"open");
DroolsKieTest.insertEvent(evt2);
Thread.sleep(2000);
}
public static void printer(String toprint) {
System.out.println(toprint);
}
}
| [
"antonello.calabro@isti.cnr.it"
] | antonello.calabro@isti.cnr.it |
c1573eeff4cb1c5edc92ffa2a268004747337063 | 3e1ae46eaf303db5c7d103a597a3d54dd833f6b3 | /app/src/main/java/com/herokuapp/tastyapp/tasty/DispatchActivity.java | 99ec3de076ce795b29c013fd405fe4f39ac00839 | [] | no_license | kristjin/Tasty-Android | 6d728df7928e1ecba16b1b42eb3019eb42c17ccf | 01ebf726b578c3dc140f5d009f2b718e47b06673 | refs/heads/master | 2021-01-10T08:35:08.691737 | 2015-06-08T15:00:52 | 2015-06-08T15:00:52 | 36,157,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 206 | java | package com.herokuapp.tastyapp.tasty;
public class DispatchActivity extends ParseLoginDispatchActivity {
@Override
protected Class<?> getTargetClass() {
return MainActivity.class;
}
}
| [
"matthew.conquergood@gmail.com"
] | matthew.conquergood@gmail.com |
513c5b5129f8fa667063c4cbd34846cbf32cfb44 | a52c82754183ca5cc7550036ec995427001130b2 | /dhruv.java | 472ea786db4e6182e2dacd68a8df11f7477809cf | [] | no_license | mondalraj/financeForKids | ff74ea0521357bae996053775b06874fedb44a09 | bbb9461167fd66a842857e17319e85add42102cf | refs/heads/main | 2023-06-29T21:59:57.200517 | 2021-08-02T14:01:33 | 2021-08-02T14:01:33 | 391,561,455 | 0 | 2 | null | 2021-08-02T14:01:34 | 2021-08-01T07:44:06 | Java | UTF-8 | Java | false | false | 239 | java | public class dhruv{
public static void main(String[] args){
byte age = 30;
byte x = 90;
System.out.println(x+"\n");
System.out.println(age);
System.out.println("thats it!!");
}
} | [
"86662038+Hitansh1G@users.noreply.github.com"
] | 86662038+Hitansh1G@users.noreply.github.com |
353cf36981edc8e5fa201e752f46bbc08686a537 | 161078e887ecec2d09c1081cdb22f5178c699026 | /Theappfolder/app/src/main/java/com/example/love/solarswitch/CheckNSell.java | 61c192fda9b7aaedc98ce2749c7691bfaa623671 | [
"MIT"
] | permissive | lovepreetsi/hatch-template-project | f79c16c189ee61cdd88bb8867a5ca74ef42cd444 | df3f7d415992305c13014d9a1d12575a0a8d3cfc | refs/heads/master | 2020-04-08T02:23:07.871768 | 2018-11-25T13:20:03 | 2018-11-25T13:20:03 | 158,933,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 188 | java | package com.example.love.solarswitch;
public class CheckNSell {
//Add functionality here for the buyer side
//Add a function that checks for the nearest available seller
}
| [
"zcablsi@ucl.ac.uk"
] | zcablsi@ucl.ac.uk |
7c3bceafc6c60a3e94122d6262ce3c2fe8d6494f | 91bac731a3ca26af7011e67602f73a3427195104 | /L8.2.2/src/main/java/ru/otus/l822/NioMain.java | a8cabee246b8a5e9459605599d09c7f97f3ff173 | [
"MIT"
] | permissive | kundzi/otus_java_2017_04 | 80ae01c6449e60fe31b1147b775794d0886747e7 | 417929594f9c6ffd401d088c74b1acded67e2ade | refs/heads/master | 2020-12-03T00:32:54.085415 | 2017-08-16T20:32:36 | 2017-08-16T20:32:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 877 | java | package ru.otus.l822;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioMain {
public static void main(String[] args) throws Exception {
try (RandomAccessFile aFile = new RandomAccessFile("data/data.txt", "rw")) {
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(64);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
System.out.print("\n");
buf.clear();
bytesRead = inChannel.read(buf);
}
}
}
}
| [
"vitaly.chibrikov@gmail.com"
] | vitaly.chibrikov@gmail.com |
e4c61bcab90ba633745020126e1915d150d8a168 | 88ed30ae68858ad6365357d4b0a95ad07594c430 | /platform/arcus-lib/src/main/java/com/iris/core/dao/cassandra/PersonDAOImpl.java | f242f35d8aeaff5d966c5ca2a2a9f146c16235f6 | [
"Apache-2.0"
] | permissive | Diffblue-benchmarks/arcusplatform | 686f58654d2cdf3ca3c25bc475bf8f04db0c4eb3 | b95cb4886b99548a6c67702e8ba770317df63fe2 | refs/heads/master | 2020-05-23T15:41:39.298441 | 2019-05-01T03:56:47 | 2019-05-01T03:56:47 | 186,830,996 | 0 | 0 | Apache-2.0 | 2019-05-30T11:13:52 | 2019-05-15T13:22:26 | Java | UTF-8 | Java | false | false | 40,400 | java | /*
* Copyright 2019 Arcus Project
*
* 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.iris.core.dao.cassandra;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.FAILURE;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.SUCCESS;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.TOKEN_FAILURE;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.UUID;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.iris.Utils;
import com.iris.bootstrap.ServiceLocator;
import com.iris.capability.util.PhoneNumber;
import com.iris.capability.util.PhoneNumbers;
import com.iris.capability.util.PhoneNumbers.PhoneNumberFormat;
import com.iris.core.dao.PersonDAO;
import com.iris.core.dao.PersonPlaceAssocDAO;
import com.iris.core.dao.exception.EmailInUseException;
import com.iris.core.dao.exception.EmailMismatchException;
import com.iris.core.dao.exception.PinNotUniqueAtPlaceException;
import com.iris.core.dao.metrics.ColumnRepairMetrics;
import com.iris.core.dao.metrics.DaoMetrics;
import com.iris.messages.address.Address;
import com.iris.messages.address.PlatformServiceAddress;
import com.iris.messages.errors.ErrorEventException;
import com.iris.messages.errors.Errors;
import com.iris.messages.errors.NotFoundException;
import com.iris.messages.model.Person;
import com.iris.messages.services.PlatformConstants;
import com.iris.platform.PagedResults;
import com.iris.security.Login;
import com.iris.security.ParsedEmail;
import com.iris.security.credentials.CredentialsHashingStrategy;
import com.iris.security.crypto.AES;
import com.iris.util.TokenUtil;
@Singleton
public class PersonDAOImpl extends BaseCassandraCRUDDao<UUID, Person> implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private static final Timer findByEmailTimer = DaoMetrics.readTimer(PersonDAO.class, "findByEmail");
private static final Timer updatePasswordTimer = DaoMetrics.updateTimer(PersonDAO.class, "updatePassword");
private static final Timer findLoginTimer = DaoMetrics.readTimer(PersonDAO.class, "findLogin");
private static final Timer generatePasswordResetTokenTimer = DaoMetrics.updateTimer(PersonDAO.class, "generatePasswordResetToken");
private static final Timer resetPasswordTimer = DaoMetrics.updateTimer(PersonDAO.class, "resetPassword");
private static final Timer updatePersonAndEmailTimer = DaoMetrics.upsertTimer(PersonDAO.class, "updatePersonAndEmail");
private static final Timer updatePinAtPlaceTimer = DaoMetrics.updateTimer(PersonDAO.class, "updatePinAtPlace");
private static final Timer setUpdateFlagTimer = DaoMetrics.updateTimer(PersonDAO.class, "setUpdateFlag");
private static final Timer getUpdateFlagTimer = DaoMetrics.readTimer(PersonDAO.class, "getUpdateFlag");
private static final Timer listPersonsTimer = DaoMetrics.readTimer(PersonDAO.class, "listPersons");
private static final Timer listByPlaceIdTimer = DaoMetrics.readTimer(PersonDAO.class, "listByPlaceId");
private static final Timer streamAllTimer = DaoMetrics.readTimer(PersonDAO.class, "streamAll");
static final String TABLE = "person";
private static final String UPDATEFLAG = "updateflag";
private static class LoginColumns {
final static String DOMAIN = "domain";
final static String USER_0_3 = "user_0_3";
final static String USER = "user";
final static String PASSWORD = "password";
final static String PASSWORD_SALT = "password_salt";
final static String USERID = "personid";
final static String RESET_TOKEN = "reset_token";
final static String LAST_PASS_CHANGE = "lastPassChange";
}
static class PersonEntityColumns {
final static String ACCOUNT_ID = "accountId";
final static String FIRST_NAME = "firstName";
final static String LAST_NAME = "lastName";
final static String TERMS_AGREED = "termsAgreed";
final static String PRIVACY_POLICY_AGREED = "privacyPolicyAgreed";
final static String EMAIL = "email";
final static String EMAIL_VERIFIED = "emailVerified";
final static String MOBILE_NUMBER = "mobileNumber";
final static String MOBILE_VERIFIED = "mobileVerified";
final static String MOBILE_NOTIFICATION_ENDPOINTS = "mobileNotificationEndpoints";
final static String CURRENT_PLACE = "currPlace";
final static String CURRENT_PLACE_METHOD = "currPlaceMethod";
final static String CURRENT_LOCATION = "currLocation";
final static String CURRENT_LOCATION_TIME = "currLocationTime";
final static String CURRENT_LOCATION_METHOD = "currLocationMethod";
final static String CONSENT_OFFERSPROMOTIONS = "consentOffersPromotions";
final static String CONSENT_STATEMENT = "consentStatement";
@Deprecated
final static String PIN = "pin";
@Deprecated
final static String PIN2 = "pin2";
final static String PINPERPLACE = "pinPerPlace";
final static String SECURITY_ANSWERS = "securityAnswers";
final static String HAS_LOGIN = "hasLogin";
final static String EMAIL_VERIFICATION_TOKEN = "emailVerificationToken";
};
private static final String[] COLUMN_ORDER = {
PersonEntityColumns.ACCOUNT_ID,
PersonEntityColumns.FIRST_NAME,
PersonEntityColumns.LAST_NAME,
PersonEntityColumns.TERMS_AGREED,
PersonEntityColumns.PRIVACY_POLICY_AGREED,
PersonEntityColumns.EMAIL,
PersonEntityColumns.EMAIL_VERIFIED,
PersonEntityColumns.MOBILE_NUMBER,
PersonEntityColumns.MOBILE_VERIFIED,
PersonEntityColumns.MOBILE_NOTIFICATION_ENDPOINTS,
PersonEntityColumns.CURRENT_PLACE,
PersonEntityColumns.CURRENT_PLACE_METHOD,
PersonEntityColumns.CURRENT_LOCATION,
PersonEntityColumns.CURRENT_LOCATION_TIME,
PersonEntityColumns.CURRENT_LOCATION_METHOD,
PersonEntityColumns.CONSENT_OFFERSPROMOTIONS,
PersonEntityColumns.CONSENT_STATEMENT,
PersonEntityColumns.SECURITY_ANSWERS,
PersonEntityColumns.HAS_LOGIN,
PersonEntityColumns.EMAIL_VERIFICATION_TOKEN
};
private static final String[] READ_ONLY_COLUMN_ORDER = {
PersonEntityColumns.PIN2,
PersonEntityColumns.PINPERPLACE
};
private static final String OPTIMISTIC_UPDATE =
CassandraQueryBuilder
.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(BaseEntityColumns.TAGS)
.addColumn(BaseEntityColumns.IMAGES)
.addColumns(COLUMN_ORDER)
.addWhereColumnEquals(BaseEntityColumns.ID)
.toQuery()
// TODO lightweight transaction support to cassandra query builder
.append(" IF ")
.append(PersonEntityColumns.EMAIL)
.append(" = ?")
.toString();
private PreparedStatement insertLogin;
private PreparedStatement findLoginByEmail;
private PreparedStatement deleteIndex;
private PreparedStatement updatePersonOptimistic;
private PreparedStatement updatePassword;
private PreparedStatement updatePinAtPlace;
private PreparedStatement updatePinAtPlaceAndPin2;
private PreparedStatement initMobileDeviceSequence;
private PreparedStatement deleteMobileDevices;
private PreparedStatement setUpdateFlag;
private PreparedStatement getUpdateFlag;
private PreparedStatement findAllPeople;
private PreparedStatement findAllPeopleLimit;
private final PreparedStatement listPaged;
private final AES aes;
private final PersonPlaceAssocDAO personPlaceAssocDAO;
@Inject(optional = true)
@Named("login.reset.token_ttl_mins")
private int tokenTTLMinutes = 15;
@Inject(optional = true)
@Named("dao.person.asynctimeoutms")
private long asyncTimeoutMs = 30000;
@Inject
@Named("questions.aes.secret")
private String questionsAesSecret;
@Inject
public PersonDAOImpl(Session session, AES aes, PersonPlaceAssocDAO personPlaceAssocDAO) {
super(session, TABLE, COLUMN_ORDER, READ_ONLY_COLUMN_ORDER);
insertLogin = prepareInsertLogin();
findLoginByEmail = prepareFindLoginByEmail();
deleteIndex = prepareDeleteIndex();
updatePersonOptimistic = prepareOptimisticUpdate();
updatePassword = prepareUpdatePassword();
updatePinAtPlace = prepareUpdatePinAtPlace();
updatePinAtPlaceAndPin2 = prepareUpdatePinAtPlaceAndPin2();
initMobileDeviceSequence = prepareInitMobileDeviceSequence();
deleteMobileDevices = prepareDeleteMobileDevices();
setUpdateFlag = prepareSetUpdateFlag();
getUpdateFlag = prepareGetUpdateFlag();
findAllPeople = prepareFindAllPeople();
findAllPeopleLimit = prepareFindAllPeopleLimit();
this.aes = aes;
this.personPlaceAssocDAO = personPlaceAssocDAO;
listPaged = prepareListPaged();
}
@Override
public Person findByAddress(Address addr) {
if(addr == null) {
return null;
}
if(!(addr instanceof PlatformServiceAddress)) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " is not a person");
}
PlatformServiceAddress platAddr = (PlatformServiceAddress) addr;
if(!PlatformConstants.SERVICE_PEOPLE.equals(platAddr.getGroup())) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " is not a person");
}
Object id = addr.getId();
if(id == null || !(id instanceof UUID)) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " does not contain a valid perosn id");
}
return findById((UUID) id);
}
@Override
protected CassandraQueryBuilder selectNonEntityColumns(CassandraQueryBuilder queryBuilder) {
queryBuilder.addColumns(PersonEntityColumns.PIN);
return super.selectNonEntityColumns(queryBuilder);
}
@Override
protected List<Object> getValues(Person entity) {
List<Object> values = new LinkedList<Object>();
values.add(entity.getAccountId());
values.add(entity.getFirstName());
values.add(entity.getLastName());
values.add(entity.getTermsAgreed());
values.add(entity.getPrivacyPolicyAgreed());
values.add(entity.getEmail());
values.add(entity.getEmailVerified());
values.add(entity.getMobileNumber());
values.add(entity.getMobileVerified());
values.add(entity.getMobileNotificationEndpoints());
values.add(entity.getCurrPlace());
values.add(entity.getCurrPlaceMethod());
values.add(entity.getCurrLocation());
values.add(entity.getCurrLocationTime());
values.add(entity.getCurrLocationMethod());
values.add(entity.getConsentOffersPromotions());
values.add(entity.getConsentStatement());
if(entity.getSecurityAnswers() != null) {
Map<String,String> securityAnswers = new HashMap<>(entity.getSecurityAnswers());
securityAnswers.replaceAll((k,v) -> { return Utils.aesEncrypt(questionsAesSecret, v); });
values.add(securityAnswers);
} else {
values.add(null);
}
values.add(entity.getHasLogin());
values.add(entity.getEmailVerificationToken());
return values;
}
@Override
protected Person createEntity() {
return new Person();
}
@Override
protected void populateEntity(Row row, Person entity) {
entity.setAccountId(row.getUUID(PersonEntityColumns.ACCOUNT_ID));
entity.setCurrLocation(row.getString(PersonEntityColumns.CURRENT_LOCATION));
entity.setCurrLocationMethod(row.getString(PersonEntityColumns.CURRENT_LOCATION_METHOD));
entity.setCurrLocationTime(row.getDate(PersonEntityColumns.CURRENT_LOCATION_TIME));
entity.setCurrPlace(row.getUUID(PersonEntityColumns.CURRENT_PLACE));
entity.setCurrPlaceMethod(row.getString(PersonEntityColumns.CURRENT_PLACE_METHOD));
entity.setEmailVerified(row.getDate(PersonEntityColumns.EMAIL_VERIFIED));
entity.setMobileNotificationEndpoints(row.getList(PersonEntityColumns.MOBILE_NOTIFICATION_ENDPOINTS, String.class));
String mobileNumberStr = row.getString(PersonEntityColumns.MOBILE_NUMBER);
try {
PhoneNumber phone = PhoneNumbers.fromString(mobileNumberStr);
if(phone != null) {
entity.setMobileNumber(PhoneNumbers.format(phone, PhoneNumberFormat.PARENS));
}
}catch(IllegalArgumentException e) {
logger.warn("Error retrieving person's mobile number from DB.", e);
//TODO - what do we with existing invalid phone numbers since we have not validated them until now?
entity.setMobileNumber(mobileNumberStr);
}
entity.setMobileVerified(row.getDate(PersonEntityColumns.MOBILE_VERIFIED));
entity.setFirstName(row.getString(PersonEntityColumns.FIRST_NAME));
entity.setLastName(row.getString(PersonEntityColumns.LAST_NAME));
Map<String,String> pinPerPlace = row.getMap(PersonEntityColumns.PINPERPLACE, String.class, String.class);
if(pinPerPlace != null && !pinPerPlace.isEmpty()) {
Map<String,String> decrypted = new HashMap<>(pinPerPlace);
decrypted.replaceAll((k,v) -> { return aes.decrypt(entity.getId().toString(), v); });
entity.setPinPerPlace(decrypted);
} else {
String pin = row.getString(PersonEntityColumns.PIN2);
if(pin == null) {
pin = row.getString(PersonEntityColumns.PIN);
if(pin != null) {
ColumnRepairMetrics.incPinCounter();
}
}
if(pin != null) {
if(entity.getCurrPlace() == null) {
logger.warn("Unable to determine current place -- can't set pin");
}
else {
entity.setPinAtPlace(entity.getCurrPlace(), aes.decrypt(entity.getId().toString(), pin));
}
}
else {
logger.debug("User [{}] does not have a pin", entity.getId());
}
}
entity.setTermsAgreed(row.getDate(PersonEntityColumns.TERMS_AGREED));
entity.setPrivacyPolicyAgreed(row.getDate(PersonEntityColumns.PRIVACY_POLICY_AGREED));
entity.setConsentOffersPromotions(row.getDate(PersonEntityColumns.CONSENT_OFFERSPROMOTIONS));
entity.setConsentStatement(row.getDate(PersonEntityColumns.CONSENT_STATEMENT));
Map<String,String> securityAnswers = row.getMap(PersonEntityColumns.SECURITY_ANSWERS, String.class, String.class);
if(securityAnswers != null && !securityAnswers.isEmpty()) {
securityAnswers = new HashMap<>(securityAnswers);
securityAnswers.replaceAll((k,v) -> { return Utils.aesDecrypt(questionsAesSecret, v); });
entity.setSecurityAnswers(securityAnswers);
}
entity.setHasLogin(row.getBool(PersonEntityColumns.HAS_LOGIN));
entity.setEmail(row.getString(PersonEntityColumns.EMAIL));
entity.setEmailVerificationToken(row.getString(PersonEntityColumns.EMAIL_VERIFICATION_TOKEN));
}
@Override
protected Person doInsert(UUID id, Person entity) {
Person copy = entity.copy();
copy.setId(id);
copy = super.doInsert(id, copy);
session.execute(new BoundStatement(initMobileDeviceSequence).bind(id));
return copy;
}
protected Person doInsert(UUID id, Person person, String password) {
Person copy = person.copy();
boolean success = false;
insertLoginIndex(person.getEmail(), id, password);
try {
copy.setId(id);
copy.setHasLogin(true);
copy = super.doInsert(id, copy);
success = true;
}
finally {
if(!success) {
deleteLoginIndex(copy.getEmail());
}
}
session.execute(new BoundStatement(initMobileDeviceSequence).bind(id));
return copy;
}
/* (non-Javadoc)
* @see com.iris.core.dao.cassandra.BaseCassandraCRUDDao#doUpdate(com.iris.messages.model.BaseEntity)
*/
@Override
protected Person doUpdate(Person entity) {
if(!entity.getHasLogin()) {
return super.doUpdate(entity);
}
// else need to manage the email index
Person copy = entity.copy();
copy.setModified(new Date());
BoundStatement bs = bindUpdate(copy, copy.getEmail());
ResultSet rs = session.execute(bs);
if(!rs.wasApplied()) {
throw new EmailMismatchException(entity.getEmail());
}
return copy;
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#create(com.iris.messages.model.Person, java.lang.String)
*/
@Override
public Person create(Person person, String password) throws EmailInUseException {
Preconditions.checkArgument(person.getId() == null, "can't create a person with an existing id");
Preconditions.checkNotNull(password, "password may not be null for a credentialed user");
validateAndFormatMobileNumber(person);
UUID id = nextId(person);
return doInsert(id, person, password);
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#createPersonWithNoLogin(com.iris.messages.model.Person)
*/
@Override
public Person createPersonWithNoLogin(Person person) {
Preconditions.checkArgument(person.getId() == null, "can't create a person with an existing id");
Preconditions.checkArgument(person.getCreated() == null, "can't create a person with a created date");
validateAndFormatMobileNumber(person);
Person copy = person.copy();
copy.setHasLogin(false);
return super.save(copy);
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#update(com.iris.messages.model.Person)
*/
@Override
public Person update(Person person) {
validateAndFormatMobileNumber(person);
Preconditions.checkNotNull(person.getId(), "can't update a person with no id");
Preconditions.checkNotNull(person.getCreated(), "can't update a non-persisted person");
return super.save(person);
}
@Override
public Person findByEmail(String email) {
if(StringUtils.isBlank(email)) {
return null;
}
try(Context ctxt = findByEmailTimer.time()) {
UUID personId = findIdByEmail(email);
return personId == null ? null : findById(personId);
}
}
@Override
public void delete(Person entity) {
if(entity.getHasLogin()) {
deleteLoginIndex(entity.getEmail());
}
session.execute(new BoundStatement(deleteMobileDevices).bind(entity.getId()));
super.delete(entity);
}
@Override
public boolean updatePassword(String email, String oldPassword, String newPassword) {
Preconditions.checkArgument(!StringUtils.isBlank(email), "email must not be blank");
Preconditions.checkArgument(!StringUtils.isBlank(newPassword), "newPassword must not be blank");
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
ParsedEmail parsed = ParsedEmail.parse(email);
oldPassword = StringUtils.trimToNull(oldPassword);
Login curLogin = findLogin(email);
if(curLogin != null && hashingStrategy.isSalted()) {
oldPassword = hashingStrategy.hashCredentials(oldPassword, hashingStrategy.saltAsBytes(curLogin.getPasswordSalt()));
}
if(!StringUtils.equals(oldPassword, curLogin.getPassword() == null ? null : curLogin.getPassword())) {
return false;
}
try(Context ctxt = updatePasswordTimer.time()) {
return updatePassword(parsed, newPassword);
}
}
@Override
public Login findLogin(String username) {
Row row;
try(Context ctxt = findLoginTimer.time()) {
row = findLoginRowByUsername(username);
}
if(row == null) {
return null;
}
Login login = new Login();
login.setPassword(row.getString(LoginColumns.PASSWORD));
login.setPasswordSalt(row.getString(LoginColumns.PASSWORD_SALT));
login.setUserId(row.getUUID(LoginColumns.USERID));
login.setUsername(username);
login.setLastPasswordChange(row.getDate(LoginColumns.LAST_PASS_CHANGE));
return login;
}
private static final int TOKEN_LENGTH = 6;
@Override
public String generatePasswordResetToken(String email) {
Preconditions.checkNotNull(email, "Email must be provided");
try(Context ctxt = generatePasswordResetTokenTimer.time()) {
String token = TokenUtil.randomTokenString(TOKEN_LENGTH);
ParsedEmail parsed = ParsedEmail.parse(email);
Statement stmt = QueryBuilder.update("login")
.using(QueryBuilder.ttl(tokenTTLMinutes * 60))
.with(QueryBuilder.set(LoginColumns.RESET_TOKEN, token))
.where(QueryBuilder.eq(LoginColumns.DOMAIN, parsed.getDomain()))
.and(QueryBuilder.eq(LoginColumns.USER_0_3, parsed.getUser_0_3()))
.and(QueryBuilder.eq(LoginColumns.USER, parsed.getUser()));
session.execute(stmt);
return token.toString();
}
}
@Override
public ResetPasswordResult resetPassword(String email, String token, String password) {
if(StringUtils.isBlank(email)) {
return FAILURE;
}
if(StringUtils.isBlank(token)) {
return FAILURE;
}
if(StringUtils.isBlank(password)) {
return FAILURE;
}
ParsedEmail parsed = ParsedEmail.parse(email);
try(Context ctxt = resetPasswordTimer.time()) {
BoundStatement boundStatement = new BoundStatement(findLoginByEmail);
Row row = session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser())).one();
if(row == null) {
return FAILURE;
}
if(!Objects.equal(token, row.getString(LoginColumns.RESET_TOKEN))) {
return TOKEN_FAILURE;
}
boolean succeeded = updatePassword(parsed, password);
if(succeeded) {
Statement stmt = QueryBuilder.update("login")
.with(QueryBuilder.set(LoginColumns.RESET_TOKEN, null))
.where(QueryBuilder.eq(LoginColumns.DOMAIN, parsed.getDomain()))
.and(QueryBuilder.eq(LoginColumns.USER_0_3, parsed.getUser_0_3()))
.and(QueryBuilder.eq(LoginColumns.USER, parsed.getUser()));
session.execute(stmt);
}
return succeeded ? SUCCESS : FAILURE;
}
}
@Override
public Person updatePinAtPlace(Person person, UUID placeId, String newPin) throws PinNotUniqueAtPlaceException
{
Preconditions.checkArgument(person != null, "person cannot be null");
Preconditions.checkArgument(placeId != null, "placeId cannot be null");
Preconditions.checkArgument(StringUtils.isNotBlank(newPin), "newPin cannot be blank");
try (Context timerContext = updatePinAtPlaceTimer.time())
{
List<Person> personsAtPlace = listByPlaceId(placeId);
verifyNewPinUniqueness(personsAtPlace, placeId, newPin);
Date modified = new Date();
String encryptedNewPin = aes.encrypt(person.getId().toString(), newPin);
boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);
Statement updateStatement = isCurrentPlace ?
new BoundStatement(updatePinAtPlaceAndPin2)
.bind(modified, placeId.toString(), encryptedNewPin, encryptedNewPin, person.getId()) :
new BoundStatement(updatePinAtPlace)
.bind(modified, placeId.toString(), encryptedNewPin, person.getId());
session.execute(updateStatement);
Person copy = person.copy();
copy.setModified(modified);
copy.setPinAtPlace(placeId, newPin);
return copy;
}
}
private List<Person> listByPlaceId(UUID placeId)
{
try (Context timerContext = listByPlaceIdTimer.time())
{
Set<UUID> personIds = personPlaceAssocDAO.findPersonIdsByPlace(placeId);
Function<ResultSet, Person> entityTransform =
resultSet -> buildEntity(resultSet.one());
return listByIdsAsync(personIds, entityTransform, asyncTimeoutMs);
}
}
private void verifyNewPinUniqueness(List<Person> personsAtPlace, UUID placeId, String newPin)
throws PinNotUniqueAtPlaceException
{
for (Person personAtPlace : personsAtPlace)
{
if (personAtPlace.hasPinAtPlace(placeId))
{
String pinAtPlace = personAtPlace.getPinAtPlace(placeId);
if (StringUtils.equals(pinAtPlace, newPin))
{
throw new PinNotUniqueAtPlaceException();
}
}
}
}
@Override
public Person deletePinAtPlace(Person person, UUID placeId)
{
Preconditions.checkArgument(person != null, "person cannot be null");
Preconditions.checkArgument(placeId != null, "placeId cannot be null");
try (Context timerContext = updatePinAtPlaceTimer.time())
{
Date modified = new Date();
boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);
Statement deleteStatement = isCurrentPlace ?
new BoundStatement(updatePinAtPlaceAndPin2).bind(modified, placeId.toString(), null, null, person.getId()) :
new BoundStatement(updatePinAtPlace).bind(modified, placeId.toString(), null, person.getId());
session.execute(deleteStatement);
Person copy = person.copy();
copy.setModified(modified);
copy.clearPin(placeId);
return copy;
}
}
@Override
public Person updatePersonAndEmail(Person person, String currentLoginEmail) {
if(!person.getHasLogin()) {
return update(person);
}
String newLoginEmail = person.getEmail();
ParsedEmail oldParsedEmail = ParsedEmail.parse(person.getEmail());
if (!oldParsedEmail.isValid()) {
throw new IllegalArgumentException("Old email address is not valid: " + currentLoginEmail);
}
ParsedEmail newParsedEmail = ParsedEmail.parse(newLoginEmail);
if (!newParsedEmail.isValid()) {
throw new IllegalArgumentException("New email address is not valid: " + newLoginEmail);
}
Row row = findLoginRowByUsername(currentLoginEmail);
if (row == null) {
throw new NotFoundException(Address.fromString(person.getAddress()));
}
String password = row.getString(LoginColumns.PASSWORD);
String password_salt = row.getString(LoginColumns.PASSWORD_SALT);
UUID userId = row.getUUID(LoginColumns.USERID);
Date lastPassChange = row.getDate(LoginColumns.LAST_PASS_CHANGE);
BoundStatement insert = new BoundStatement(insertLogin)
.setString(LoginColumns.DOMAIN, newParsedEmail.getDomain())
.setString(LoginColumns.USER_0_3, newParsedEmail.getUser_0_3())
.setString(LoginColumns.USER, newParsedEmail.getUser())
.setString(LoginColumns.PASSWORD, password)
.setString(LoginColumns.PASSWORD_SALT, password_salt)
.setUUID(LoginColumns.USERID, userId)
// changing the email invalidates the reset token
.setString(LoginColumns.RESET_TOKEN, null)
.setDate(LoginColumns.LAST_PASS_CHANGE, lastPassChange);
Person copy = person.copy();
copy.setModified(new Date());
copy.setEmailVerificationToken(null);
copy.setEmailVerified(null); //clear emailverified date and token
BoundStatement update = bindUpdate(copy, currentLoginEmail);
try(Context ctxt = updatePersonAndEmailTimer.time()) {
ResultSet rs = session.execute(insert);
if(!rs.wasApplied()) {
throw new EmailInUseException(newLoginEmail);
}
boolean success = false;
try {
ResultSet updateRs = session.execute(update);
if(!updateRs.wasApplied()) {
throw new EmailMismatchException(currentLoginEmail);
}
success = true;
}
finally {
if(!success) {
deleteLoginIndex(newLoginEmail);
}
}
deleteLoginIndex(currentLoginEmail);
}
return copy;
}
@Override
public void setUpdateFlag(UUID personId, boolean updateFlag) {
Preconditions.checkArgument(personId != null, "The person id cannot be null");
BoundStatement statement = new BoundStatement(setUpdateFlag);
try(Context ctxt = setUpdateFlagTimer.time()) {
session.execute(statement.bind(updateFlag, personId));
}
}
@Override
public boolean getUpdateFlag(UUID personId) {
Preconditions.checkArgument(personId != null, "The person id cannot be null");
BoundStatement statement = new BoundStatement(getUpdateFlag);
ResultSet resultSet;
try(Context ctxt = getUpdateFlagTimer.time()) {
resultSet = session.execute(statement.bind(personId));
}
Row row = resultSet.one();
return row.getBool(UPDATEFLAG);
}
private BoundStatement bindUpdate(Person person, String currentEmail) {
List<Object> values = new ArrayList<Object>(COLUMN_ORDER.length + 5);
values.add(person.getModified());
values.add(person.getTags());
values.add(person.getImages());
values.addAll(getValues(person));
values.add(person.getId());
values.add(currentEmail);
// use an optimistic update to prevent inadvertently changing the
// email address and corrupting the index
BoundStatement bs = new BoundStatement(updatePersonOptimistic);
return bs.bind(values.toArray());
}
private BoundStatement bindDeleteLogin(ParsedEmail parsed) {
return
new BoundStatement(deleteIndex)
.setString(LoginColumns.DOMAIN, parsed.getDomain())
.setString(LoginColumns.USER_0_3, parsed.getUser_0_3())
.setString(LoginColumns.USER, parsed.getUser()); }
private boolean updatePassword(ParsedEmail parsed, String password) {
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
List<String> hashAndSalt = generateHashAndSalt(password);
BoundStatement update = new BoundStatement(updatePassword);
ResultSet rs = session.execute(update.bind(hashAndSalt.get(0), hashAndSalt.get(1), new Date(), parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser()));
return rs.wasApplied();
}
private List<String> generateHashAndSalt(String password) {
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
String hashedPassword = password;
String salt = null;
if(hashingStrategy.isSalted()) {
ByteSource saltBytes = hashingStrategy.generateSalt();
salt = saltBytes.toBase64();
hashedPassword = hashingStrategy.hashCredentials(password, saltBytes);
}
return ImmutableList.of(hashedPassword, salt);
}
@Override
protected UUID getIdFromRow(Row row) {
return row.getUUID(BaseEntityColumns.ID);
}
@Override
protected UUID nextId(Person person) {
return UUID.randomUUID();
}
private Row findLoginRowByUsername(String username) {
ParsedEmail parsed = ParsedEmail.parse(username);
BoundStatement boundStatement = new BoundStatement(findLoginByEmail);
return session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser())).one();
}
private void insertLoginIndex(String email, UUID id, String password) {
ParsedEmail parsed = ParsedEmail.parse(email);
List<String> hashAndSalt = generateHashAndSalt(password);
BoundStatement boundStatement = new BoundStatement(insertLogin);
ResultSet rs = session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser(), hashAndSalt.get(0), hashAndSalt.get(1), id, null, new Date()));
if(!rs.wasApplied()) {
throw new EmailInUseException(email);
}
}
private void deleteLoginIndex(String email) {
ParsedEmail parsed = ParsedEmail.parse(email);
BoundStatement boundStatement = bindDeleteLogin(parsed);
session.execute(boundStatement);
}
private UUID findIdByEmail(String email) {
Login login = findLogin(email);
return login == null ? null : login.getUserId();
}
@Override
public PagedResults<Person> listPersons(PersonQuery query) {
BoundStatement bs = null;
if (query.getToken() != null) {
bs = listPaged.bind(UUID.fromString(query.getToken()), query.getLimit() + 1);
} else {
bs = findAllPeopleLimit.bind(query.getLimit() + 1);
}
try(Context ctxt = listPersonsTimer.time()) {
return doList(bs, query.getLimit());
}
}
@Override
public Stream<Person> streamAll() {
try(Context ctxt = streamAllTimer.time()) {
Iterator<Row> rows = session.execute(new BoundStatement(findAllPeople)).iterator();
Iterator<Person> result = Iterators.transform(rows, (row) -> buildEntity(row));
Spliterator<Person> stream = Spliterators.spliteratorUnknownSize(result, Spliterator.IMMUTABLE | Spliterator.NONNULL);
return StreamSupport.stream(stream, false);
}
}
private PreparedStatement prepareOptimisticUpdate() {
PreparedStatement stmt = session.prepare(OPTIMISTIC_UPDATE);
stmt.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
return stmt;
}
private PreparedStatement prepareInsertLogin() {
return CassandraQueryBuilder.insert(Tables.LOGIN)
.addColumn(LoginColumns.DOMAIN)
.addColumn(LoginColumns.USER_0_3)
.addColumn(LoginColumns.USER)
.addColumn(LoginColumns.PASSWORD)
.addColumn(LoginColumns.PASSWORD_SALT)
.addColumn(LoginColumns.USERID)
.addColumn(LoginColumns.RESET_TOKEN)
.addColumn(LoginColumns.LAST_PASS_CHANGE)
.ifNotExists()
.prepare(session);
}
private PreparedStatement prepareFindLoginByEmail() {
return CassandraQueryBuilder.select(Tables.LOGIN)
.addColumns(LoginColumns.DOMAIN, LoginColumns.USER_0_3, LoginColumns.USER, LoginColumns.PASSWORD, LoginColumns.PASSWORD_SALT, LoginColumns.USERID, LoginColumns.RESET_TOKEN, LoginColumns.LAST_PASS_CHANGE)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareDeleteIndex() {
return CassandraQueryBuilder.delete(Tables.LOGIN)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareUpdatePassword() {
return CassandraQueryBuilder.update(Tables.LOGIN)
.addColumn(LoginColumns.PASSWORD)
.addColumn(LoginColumns.PASSWORD_SALT)
.addColumn(LoginColumns.LAST_PASS_CHANGE)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareUpdatePinAtPlace() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(PersonEntityColumns.PINPERPLACE + "[?]")
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareUpdatePinAtPlaceAndPin2() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(PersonEntityColumns.PINPERPLACE + "[?]")
.addColumn(PersonEntityColumns.PIN2)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareDeleteMobileDevices() {
return CassandraQueryBuilder.delete(Tables.MOBILE_DEVICES)
.addWhereColumnEquals(Tables.MobileDevicesCols.PERSON_ID)
.prepare(session);
}
private PreparedStatement prepareInitMobileDeviceSequence() {
return CassandraQueryBuilder.update(TABLE)
.set("mobileDeviceSequence=0")
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareSetUpdateFlag() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(UPDATEFLAG)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareGetUpdateFlag() {
return CassandraQueryBuilder.select(TABLE)
.addColumn(UPDATEFLAG)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareFindAllPeople() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE);
return addAllColumns(queryBuilder).prepare(session);
}
private PreparedStatement prepareFindAllPeopleLimit() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE)
.boundLimit();
return addAllColumns(queryBuilder).prepare(session);
}
private PreparedStatement prepareListPaged() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE)
.where("token(" + BaseEntityColumns.ID + ") >= token(?) LIMIT ?");
return addAllColumns(queryBuilder).prepare(session);
}
private CassandraQueryBuilder addAllColumns(CassandraQueryBuilder queryBuilder) {
queryBuilder.addColumns(BASE_COLUMN_ORDER).addColumns(COLUMN_ORDER).addColumns(READ_ONLY_COLUMN_ORDER);
return selectNonEntityColumns(queryBuilder);
}
private void validateAndFormatMobileNumber(Person person) {
//Validate and format phone number
PhoneNumber phone1 = PhoneNumbers.fromString(person.getMobileNumber());
if(phone1 != null) {
person.setMobileNumber(PhoneNumbers.format(phone1, PhoneNumberFormat.PARENS));
}
}
}
| [
"b@yoyo.com"
] | b@yoyo.com |
5bb40ff5193c7eb86d7e5c7f2de34fd914e4378d | 58d037736fe260001cbb82783d75156f7fd3ad0d | /app/src/main/java/com/postterminal/postterminal/OtpSignUpActivity.java | abda1e014fc861068631d83d611943439a8d72df | [] | no_license | AmirNotch/AlphaHumoTerminal_JAVA | cc87c8f1ea4b7b1fac5789ce091da224eeefba86 | 5028c896f2f96e515646d56abb61b09d44e12005 | refs/heads/master | 2023-03-15T20:34:18.442714 | 2021-03-10T10:16:42 | 2021-03-10T10:16:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,852 | java | package com.postterminal.postterminal;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.postterminal.postterminal.JsonObjects.OtpCode;
import com.postterminal.postterminal.JsonObjects.SendSmS;
import com.postterminal.postterminal.PostRequest.APIInterface;
import java.io.IOException;
import java.util.Objects;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.postterminal.postterminal.PhoneActivity.main_auth;
import static com.postterminal.postterminal.PhoneActivity.number1;
public class OtpSignUpActivity extends AppCompatActivity {
TextView otpText,timer;
Button btnOtp,btnSendsms;
private int counter;
APIInterface apiInterface;
/*@SuppressLint("HardwareIds")
public String uniqueId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);*/
public static String access_tok_signUp;
//public static String main_auth1 = main_auth;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp_sign_up_activity);
Objects.requireNonNull(getSupportActionBar()).hide();
String ID = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request newRequest = originalRequest.newBuilder()
//.headers()
//.header("Authorization", main_auth)
//.header("uuid_device", ID)*/
.addHeader("Authorization", "Bearer " + main_auth)
.addHeader("uuid", ID)
.build();
return chain.proceed(newRequest);
}
})
.addInterceptor(loggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.43.26:8080")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
apiInterface = retrofit.create(APIInterface.class);
//apiInterface = APIClient.getClient().create(APIInterface.class);
otpText = findViewById(R.id.textOtp);
timer = findViewById(R.id.timer);
btnOtp = findViewById(R.id.btnOtp);
btnSendsms = findViewById(R.id.btnSendSMS);
new CountDownTimer(120000, 1000){
@SuppressLint("SetTextI18n")
public void onTick(long millisUntilFinished){
btnSendsms.setEnabled(false);
timer.setText(String.valueOf(120-counter) + " сек.");
counter++;
}
public void onFinish(){
timer.setText("Вы можете получить смс ещё раз");
btnSendsms.setEnabled(true);
}
}.start();
btnOtp.setOnClickListener(new View.OnClickListener() {
//String number = PhoneActivity.number;
@Override
public void onClick(View v) {
Integer sms = Integer.parseInt(otpText.getText().toString());
OtpCode otp = new OtpCode(number1,"signup",sms);
Log.d("error",main_auth + " \n " + number1 +" \n "+ otpText + " ");
Call< OtpCode > call = apiInterface.doCallOtp(/*main_auth,ID,*/otp);
call.enqueue(new Callback< OtpCode >() {
@Override
public void onResponse(Call< OtpCode > call, Response< OtpCode > response) {
OtpCode resource = response.body();
//String result_desc = resource.result_desc;
//String result_code = resource.result_code;
// Log.d("errorCode", result_code + " \n ");
/*if (resource != null) {*/
String access_token = resource.access_token;
String refresh_token = resource.refresh_token;
String result_type = resource.result_code;
access_tok_signUp = access_token;
if (access_token == null || refresh_token == null || result_type == null) {
Toast.makeText(getApplicationContext(), "Повторите процедуру ещё раз", Toast.LENGTH_LONG).show();
}
Log.d("error", access_token + " \n " + refresh_token + " \n "/*+ result_type*/);
if (access_token == null && refresh_token == null && result_type == null) {
Toast.makeText(getApplicationContext(), "Вы ввели не правильно СМС либо перешлите СМС", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_type.equals("1") && !access_token.isEmpty() && !refresh_token.isEmpty()) {
startActivity(new Intent(OtpSignUpActivity.this, SignUpActivity.class));
Toast.makeText(getApplicationContext(), "Придумайте Pin-Code пожалуйста", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_type.equals("0") && access_token.isEmpty() && refresh_token.isEmpty()) {
Toast.makeText(getApplicationContext(), "Попробуйте снова", Toast.LENGTH_LONG).show();
}
/*}
else {
Toast.makeText(getApplicationContext(), "Повторите процедуру ещё раз", Toast.LENGTH_LONG).show();
}*/
}
@Override
public void onFailure(Call< OtpCode > call, Throwable t) {
Toast.makeText(getApplicationContext(),"Извините но произошла ошибка попробуйте снова", Toast.LENGTH_LONG).show();
Log.d("error", call.request().url() + " \n ");
}
});
}
});
btnSendsms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.setText(0);
new CountDownTimer(120000, 1000){
@SuppressLint("SetTextI18n")
public void onTick(long millisUntilFinished){
btnSendsms.setEnabled(false);
timer.setText(String.valueOf(120 + 120-counter) + " сек.");
counter++;
}
public void onFinish(){
timer.setText("Вы можете получить смс ещё раз");
btnSendsms.setEnabled(true);
}
}.start();
SendSmS SmS = new SendSmS(number1,"signup");
Log.d("error",main_auth + " \n " + number1 +" \n ");
Call< SendSmS> call = apiInterface.doSendSmS(SmS);
call.enqueue(new Callback< SendSmS >() {
@Override
public void onResponse(Call< SendSmS > call, Response< SendSmS > response) {
SendSmS resource = response.body();
String result_code = resource.result_code;
String sign_type = resource.sign_type;
String auth_token = resource.auth_token;
main_auth = auth_token;
if (response.isSuccessful() && result_code.equals("signup") && sign_type.equals("1") && !auth_token.isEmpty()){
Toast.makeText(getApplicationContext(),"Сообщение отправлено подождите.", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_code.equals("signup") && sign_type.equals("0") && !auth_token.isEmpty()){
Toast.makeText(getApplicationContext(),"Повторите ещё раз.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call< SendSmS > call, Throwable t) {
Toast.makeText(getApplicationContext(),"Проверьте интернет соединение", Toast.LENGTH_LONG).show();
}
});
}
});
}
}
| [
"ibragimov-amir@list.ru"
] | ibragimov-amir@list.ru |
b4ca4275ec07d0cc507d9669d32918239ea69eae | cef95dbe9ac9dd71b179d715f7d4d2ff8c659921 | /SupportSpeed/src/main/java/com/titannet/service/IServicioService.java | 0a1dec0a38a78f29311429dc73ff0d5269565221 | [] | no_license | victoralbertosg/sysSupportSpeed | 216a09960a571b22aa0974ca75c9f306c9d03c7e | d7966db5f9aa5ebf3c8304134343ad6b7181e0e1 | refs/heads/master | 2022-06-30T07:35:19.662379 | 2019-09-05T05:28:35 | 2019-09-05T05:28:35 | 196,319,041 | 0 | 0 | null | 2022-06-21T01:26:12 | 2019-07-11T04:20:45 | Java | UTF-8 | Java | false | false | 862 | java | package com.titannet.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.titannet.entity.ControlServicio;
import com.titannet.entity.EstadoServicio;
import com.titannet.entity.Persona;
import com.titannet.entity.Servicio;
public interface IServicioService {
public List<Servicio> findAll();
public Page<Servicio> findAll(Pageable pageable);
public void save(Servicio servicio);
public Servicio findById(Long id);
public void delete(Servicio servicio);
public List<Servicio> servicioEstado1(EstadoServicio es);
public List<Servicio> servicioTrabajador (Persona persona);
public List<Servicio> servicioTrabajadorEstado (Persona persona,EstadoServicio es);
public List<Servicio> servicioClienteEstado (Persona persona,EstadoServicio es);
}
| [
"undacvasg@gmail.com"
] | undacvasg@gmail.com |
c116e9637b3e01349a6ee79bffada9c39c701c70 | ceca9162a8b8a2653620a1eb2b5362e06c8f0b63 | /srcM/javaconcurrent/Semaphore/SemaphoreExample.java | 1bdd6c11f86dbf919710487013c1959e4c37716f | [] | no_license | jal285/study_1 | 762c933b443e481b4d618ebb69dfd29d6214bc5e | 60b4d4aa08813bbb841e310b4d163c003eed375a | refs/heads/master | 2023-08-17T03:31:55.435983 | 2021-09-15T14:25:58 | 2021-09-15T14:25:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package javaconcurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
PrinteQueue printerQueue = new PrinteQueue();
Thread thread[]=new Thread[10];
for (int i=0; i<10;i++){
thread[i] = new Thread(new PrintingJob(printerQueue),"Thread"+i);
}
for (int i=0;i<10;i++){
thread[i].start();
}
}
}
| [
"2233451206@qq.com"
] | 2233451206@qq.com |
d6ebc129144645ba03bf08ca8296a26b37ab07d1 | f0b7aba39aed384415ce6b375db6157635922847 | /erp_dao/src/main/java/cn/feituo/erp/dao/impl/InventoryDao.java | 1b4322843d78768cafcedea6759202e33a1349e1 | [] | no_license | qiuxr/ERP | 104ac9a83b09bdf4209b9ef354f2571f763d33b9 | 567ab36de4f52ed47219973ddec6f4ed57b5be4d | refs/heads/master | 2018-12-25T02:08:55.960561 | 2018-10-25T01:52:50 | 2018-10-25T01:52:50 | 103,376,934 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,256 | java | package cn.feituo.erp.dao.impl;
import java.util.Calendar;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import cn.feituo.erp.dao.IInventoryDao;
import cn.feituo.erp.entity.Inventory;
/**
* 盘盈盘亏数据访问类
* @author Administrator
*
*/
public class InventoryDao extends BaseDao<Inventory> implements IInventoryDao {
/**
* 构建查询条件
* @param dep1
* @param dep2
* @param param
* @return
*/
public DetachedCriteria getDetachedCriteria(Inventory inventory1,Inventory inventory2,Object param){
DetachedCriteria dc=DetachedCriteria.forClass(Inventory.class);
if(inventory1!=null){
if(null != inventory1.getType() && inventory1.getType().trim().length()>0){
dc.add(Restrictions.like("type", inventory1.getType(), MatchMode.ANYWHERE));
}
if(null != inventory1.getState() && inventory1.getState().trim().length()>0){
dc.add(Restrictions.like("state", inventory1.getState(), MatchMode.ANYWHERE));
}
if(null != inventory1.getRemark() && inventory1.getRemark().trim().length()>0){
dc.add(Restrictions.like("remark", inventory1.getRemark(), MatchMode.ANYWHERE));
}
//提交日期
if(null != inventory1.getCreatetime()){
dc.add(Restrictions.ge("opertime",inventory1.getCreatetime()));
}
if(null != inventory1.getChecktime()){
dc.add(Restrictions.ge("opertime",inventory1.getChecktime()));
}
}
if(null != inventory2){
//结束日期
if(null != inventory2.getCreatetime()){
Calendar car = Calendar.getInstance();
car.setTime(inventory2.getCreatetime());
car.set(Calendar.HOUR, 23);//23点
car.set(Calendar.MINUTE, 59);//59分
car.set(Calendar.SECOND, 59);//秒
car.set(Calendar.MILLISECOND, 999);//毫秒
dc.add(Restrictions.le("createtime", car.getTime()));
}
if(null != inventory2.getChecktime()){
Calendar car = Calendar.getInstance();
car.setTime(inventory2.getChecktime());
car.set(Calendar.HOUR, 23);//23点
car.set(Calendar.MINUTE, 59);//59分
car.set(Calendar.SECOND, 59);//秒
car.set(Calendar.MILLISECOND, 999);//毫秒
dc.add(Restrictions.le("checktime", car.getTime()));
}
}
return dc;
}
}
| [
"qiuxr@qq.com"
] | qiuxr@qq.com |
70b1e8b8e4d336a65e7eb1ec63c1ca92f72b17f7 | dc5f91cbf5a4dfd0dc45687f9ac25873e3556b6d | /app/src/main/java/com/fm/modules/models/PlatilloSeleccionado.java | 70df28158cb49a229eb509d8dd2a3c61794b9996 | [] | no_license | Bateyss/AppDeliveryFuimonos | 796fdd77ea9bb973aaaf0679f0739d980c6d53c3 | bd04ca8683ad0983804de8609e2ae057288f4aeb | refs/heads/main | 2023-01-20T09:49:48.789362 | 2020-11-27T16:42:02 | 2020-11-27T16:42:02 | 316,553,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,291 | java | package com.fm.modules.models;
public class PlatilloSeleccionado {
private Long platilloSeleccionadoId;
private Platillo platillo;
private Pedido pedido;
private String nombre;
private double precio;
private int cantidad;
public PlatilloSeleccionado() {
}
public PlatilloSeleccionado(Long platilloSeleccionadoId, Platillo platillo, Pedido pedido, String nombre,
double precio, int cantidad) {
this.platilloSeleccionadoId = platilloSeleccionadoId;
this.platillo = platillo;
this.pedido = pedido;
this.nombre = nombre;
this.precio = precio;
this.cantidad = cantidad;
}
public Long getPlatilloSeleccionadoId() {
return platilloSeleccionadoId;
}
public void setPlatilloSeleccionadoId(Long platilloSeleccionadoId) {
this.platilloSeleccionadoId = platilloSeleccionadoId;
}
public Platillo getPlatillo() {
return platillo;
}
public void setPlatillo(Platillo platillo) {
this.platillo = platillo;
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{platilloSeleccionadoId:'");
builder.append(platilloSeleccionadoId);
builder.append("',platillos:'");
builder.append(platillo);
builder.append("',pedidos:'");
builder.append(pedido);
builder.append("',nombre:'");
builder.append(nombre);
builder.append("',precio:'");
builder.append(precio);
builder.append("',cantidad:'");
builder.append(cantidad);
builder.append("'}");
return builder.toString();
}
}
| [
"58366298+Bateyss@users.noreply.github.com"
] | 58366298+Bateyss@users.noreply.github.com |
cc3b95bcfba3685d3f5d2e67e0d467408b2103c7 | 889bd5447489a92723db41b40bc368ee3b809500 | /src/com/chariotsolutions/nfc/plugin/NfcPlugin.java | e04f783cc41a5db4392cc4484b52c8612f796dc2 | [] | no_license | fradinni/izitag-mobile | 6e2eae32718d06d1abf0a2c184b807fa5466b963 | 81df05e2073ec48a0a59ca1d3b46948442bb0f5e | refs/heads/master | 2020-04-23T12:17:59.252282 | 2013-05-12T11:36:23 | 2013-05-12T11:36:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,131 | java | package com.chariotsolutions.nfc.plugin;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;
import android.util.Log;
public class NfcPlugin extends CordovaPlugin {
private static final String REGISTER_MIME_TYPE = "registerMimeType";
private static final String REGISTER_NDEF = "registerNdef";
private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable";
private static final String REGISTER_DEFAULT_TAG = "registerTag";
private static final String WRITE_TAG = "writeTag";
private static final String ERASE_TAG = "eraseTag";
private static final String SHARE_TAG = "shareTag";
private static final String UNSHARE_TAG = "unshareTag";
private static final String INIT = "init";
private static final String NDEF = "ndef";
private static final String NDEF_MIME = "ndef-mime";
private static final String NDEF_FORMATABLE = "ndef-formatable";
private static final String TAG_DEFAULT = "tag";
private static final String STATUS_NFC_OK = "NFC_OK";
private static final String STATUS_NO_NFC = "NO_NFC";
private static final String STATUS_NFC_DISABLED = "NFC_DISABLED";
private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED";
private static final String TAG = "NfcPlugin";
private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
private final ArrayList<String[]> techLists = new ArrayList<String[]>();
private NdefMessage p2pMessage = null;
private PendingIntent pendingIntent = null;
private Intent savedIntent = null;
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "execute " + action);
if (!getNfcStatus().equals(STATUS_NFC_OK)) {
callbackContext.error(getNfcStatus());
return true; // short circuit
}
createPendingIntent();
if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) {
registerMimeType(data, callbackContext);
} else if (action.equalsIgnoreCase(REGISTER_NDEF)) {
registerNdef(callbackContext);
} else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) {
registerNdefFormattable(callbackContext);
} else if (action.equals(REGISTER_DEFAULT_TAG)) {
registerDefaultTag(callbackContext);
} else if (action.equalsIgnoreCase(WRITE_TAG)) {
writeTag(data, callbackContext);
} else if (action.equalsIgnoreCase(ERASE_TAG)) {
eraseTag(callbackContext);
} else if (action.equalsIgnoreCase(SHARE_TAG)) {
shareTag(data, callbackContext);
} else if (action.equalsIgnoreCase(UNSHARE_TAG)) {
unshareTag(callbackContext);
} else if (action.equalsIgnoreCase(INIT)) {
init(callbackContext);
} else {
// invalid action
return false;
}
return true;
}
private String getNfcStatus() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter == null) {
return STATUS_NO_NFC;
} else if (!nfcAdapter.isEnabled()) {
return STATUS_NFC_DISABLED;
} else {
return STATUS_NFC_OK;
}
}
private void registerDefaultTag(CallbackContext callbackContext) {
addTagFilter();
callbackContext.success();
}
private void registerNdefFormattable(CallbackContext callbackContext) {
addTechList(new String[]{NdefFormatable.class.getName()});
callbackContext.success();
}
private void registerNdef(CallbackContext callbackContext) {
addTechList(new String[]{Ndef.class.getName()});
callbackContext.success();
}
private void unshareTag(CallbackContext callbackContext) {
p2pMessage = null;
stopNdefPush();
callbackContext.success();
}
private void init(CallbackContext callbackContext) {
Log.d(TAG, "Enabling plugin " + getIntent());
startNfc();
if (!recycledIntent()) {
parseMessage();
}
callbackContext.success();
}
private void registerMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException {
String mimeType = "";
try {
mimeType = data.getString(0);
intentFilters.add(createIntentFilter(mimeType));
callbackContext.success();
} catch (MalformedMimeTypeException e) {
callbackContext.error("Invalid MIME Type " + mimeType);
}
}
// Cheating and writing an empty record. We may actually be able to erase some tag types.
private void eraseTag(CallbackContext callbackContext) throws JSONException {
Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefRecord[] records = {
new NdefRecord(NdefRecord.TNF_EMPTY, new byte[0], new byte[0], new byte[0])
};
writeNdefMessage(new NdefMessage(records), tag, callbackContext);
}
private void writeTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
if (getIntent() == null) { // TODO remove this and handle LostTag
callbackContext.error("Failed to write tag, received null intent");
}
Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
writeNdefMessage(new NdefMessage(records), tag, callbackContext);
}
private void writeNdefMessage(final NdefMessage message, final Tag tag, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (ndef.isWritable()) {
int size = message.toByteArray().length;
if (ndef.getMaxSize() < size) {
callbackContext.error("Tag capacity is " + ndef.getMaxSize() +
" bytes, message is " + size + " bytes.");
} else {
ndef.writeNdefMessage(message);
callbackContext.success();
}
} else {
callbackContext.error("Tag is read only");
}
ndef.close();
} else {
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable != null) {
formatable.connect();
formatable.format(message);
callbackContext.success();
formatable.close();
} else {
callbackContext.error("Tag doesn't support NDEF");
}
}
} catch (FormatException e) {
callbackContext.error(e.getMessage());
} catch (TagLostException e) {
callbackContext.error(e.getMessage());
} catch (IOException e) {
callbackContext.error(e.getMessage());
}
}
});
}
private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
this.p2pMessage = new NdefMessage(records);
startNdefPush(callbackContext);
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void addTechList(String[] list) {
this.addTechFilter();
this.addToTechList(list);
}
private void addTechFilter() {
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
}
private void addTagFilter() {
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && getActivity().isFinishing() == false) {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(getActivity());
}
}
});
}
private void startNdefPush(final CallbackContext callbackContext) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter == null) {
callbackContext.error(STATUS_NO_NFC);
// isNdefPushEnabled would be nice, but requires android-17
//} else if (!nfcAdapter.isNdefPushEnabled()) {
// callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
} else {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
callbackContext.success();
}
}
});
}
private void stopNdefPush() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
nfcAdapter.setNdefPushMessage(null, getActivity());
}
}
});
}
private void addToTechList(String[] techs) {
techLists.add(techs);
}
private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException {
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
intentFilter.addDataType(mimeType);
return intentFilter;
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
void parseMessage() {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Log.d(TAG, "parseMessage " + getIntent());
Intent intent = getIntent();
String action = intent.getAction();
Log.d(TAG, "action " + action);
if (action == null) {
return;
}
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Ndef ndef = Ndef.get(tag);
fireNdefEvent(NDEF_MIME, ndef, messages);
} else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
for (String tagTech : tag.getTechList()) {
Log.d(TAG, tagTech);
if (tagTech.equals(NdefFormatable.class.getName())) {
fireNdefFormatableEvent(tag);
} else if (tagTech.equals(Ndef.class.getName())) { //
Ndef ndef = Ndef.get(tag);
fireNdefEvent(NDEF, ndef, messages);
}
}
}
if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
fireTagEvent(tag);
}
setIntent(new Intent());
}
});
}
private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) {
JSONObject jsonObject = buildNdefJSON(ndef, messages);
String tag = jsonObject.toString();
String command = MessageFormat.format(javaScriptEventTemplate, type, tag);
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
private void fireNdefFormatableEvent (Tag tag) {
String command = MessageFormat.format(javaScriptEventTemplate, NDEF_FORMATABLE, Util.tagToJSON(tag));
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
private void fireTagEvent (Tag tag) {
String command = MessageFormat.format(javaScriptEventTemplate, TAG_DEFAULT, Util.tagToJSON(tag));
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
JSONObject json = Util.ndefToJSON(ndef);
// ndef is null for peer-to-peer
// ndef and messages are null for ndef format-able
if (ndef == null && messages != null) {
try {
if (messages.length > 0) {
NdefMessage message = (NdefMessage) messages[0];
json.put("ndefMessage", Util.messageToJSON(message));
// guessing type, would prefer a more definitive way to determine type
json.put("type", "NDEF Push Protocol");
}
if (messages.length > 1) {
Log.wtf(TAG, "Expected one ndefMessage but found " + messages.length);
}
} catch (JSONException e) {
// shouldn't happen
Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
}
}
return json;
}
private boolean recycledIntent() { // TODO this is a kludge, find real solution
int flags = getIntent().getFlags();
if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) {
Log.i(TAG, "Launched from history, killing recycled intent");
setIntent(new Intent());
return true;
}
return false;
}
@Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getIntent());
super.onPause(multitasking);
stopNfc();
}
@Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getIntent());
super.onResume(multitasking);
startNfc();
}
@Override
public void onNewIntent(Intent intent) {
Log.d(TAG, "onNewIntent " + intent);
super.onNewIntent(intent);
setIntent(intent);
savedIntent = intent;
parseMessage();
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private Intent getIntent() {
return getActivity().getIntent();
}
private void setIntent(Intent intent) {
getActivity().setIntent(intent);
}
String javaScriptEventTemplate =
"var e = document.createEvent(''Events'');\n" +
"e.initEvent(''{0}'');\n" +
"e.tag = {1};\n" +
"document.dispatchEvent(e);";
}
| [
"fradinni@gmail.com"
] | fradinni@gmail.com |
dbedf0705e36b25e070d7b93b010b6b23a82de9e | d2c586de0f0b5b28f11a102afb80b42a0cbc655b | /src/HaksaStudent.java | 30ebb2f2f4bd80685d6633d3770cd91d8eecbfff | [] | no_license | meloning/HaksaManagerProgramGUI | 2630e34adc228dd5f4ee577f01f2cb90546e5f6f | 0247edd70797a082a5a52a87910ecf66895b6a95 | refs/heads/master | 2020-05-22T03:36:06.862194 | 2019-05-23T16:00:33 | 2019-05-23T16:00:33 | 186,215,369 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 8,079 | java | import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import DAO.StudentDAO;
import DTO.StudentDTO;
public class HaksaStudent extends JPanel{
//컴포넌트 그룹.
JTextField nameInput;
JTextField hakgwaInput;
JTextField addressInput;
JTextField hakbunInput;
JButton insertBtn;
JButton selectBtn;
JButton updateBtn;
JButton deleteBtn;
JButton searchBtn;
DefaultTableModel model;
JTable table;
//DAO 데이터접근 객체
StudentDAO stdDAO = new StudentDAO();
public HaksaStudent() {
this.setLayout(new FlowLayout());
hakbunInput = new JTextField(14);
nameInput = new JTextField(20);
hakgwaInput = new JTextField("컴퓨터공학과",20);
addressInput = new JTextField("서울시...",20);
insertBtn = new JButton("등록");
selectBtn = new JButton("목록");
updateBtn = new JButton("수정");
deleteBtn = new JButton("삭제");
searchBtn = new JButton("검색");
//입력 폼 추가.
this.add(new JLabel("학번 "));this.add(hakbunInput);this.add(searchBtn);//검색추가(Layout매니저적용되었기에..)
this.add(new JLabel("이름 "));this.add(nameInput);
this.add(new JLabel("학과 "));this.add(hakgwaInput);
this.add(new JLabel("주소 "));this.add(addressInput);
//출력 폼 추가(Table형태)
String colName[]={"학번","이름","학과","주소"};//Table 필드명
model=new DefaultTableModel(colName,0);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(270,120));
this.add(table);
this.add(new JScrollPane(table));
//버튼 추가.
this.add(insertBtn);this.add(selectBtn);this.add(updateBtn);this.add(deleteBtn);
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StudentDTO stdTemp = null;
stdTemp=stdDAO.SelectById(hakbunInput.getText());
hakbunInput.setText(stdTemp.getId());
nameInput.setText(stdTemp.getName());
hakgwaInput.setText(stdTemp.getDepartmentId());
addressInput.setText(stdTemp.getAddress());
}
});
insertBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//필수입력체크
if(nameInput.getText().length()==0||hakbunInput.getText().length()==0||
hakgwaInput.getText().length()==0||addressInput.getText().length()==0) {
JOptionPane.showMessageDialog(null, "빈칸이 있습니다. 전부입력해주세요.","Message"
,JOptionPane.ERROR_MESSAGE);
}else {
StudentDTO stdTemp = new StudentDTO();
stdTemp.setId(hakbunInput.getText());
stdTemp.setName(nameInput.getText());
stdTemp.setDepartmentId(hakgwaInput.getText());
stdTemp.setAddress(addressInput.getText());
int result = stdDAO.Insert(stdTemp);
if(result>0) {
JOptionPane.showMessageDialog(null, "입력성공.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "입력실패.","Fail",JOptionPane.ERROR_MESSAGE);
}
//출력 메소드 호출
ShowList();
}
}
});
selectBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//출력 메소드 호출
ShowList();
}
});
updateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String id="";
StudentDTO stdTemp = null;
//수정할 목록을 출력하는 부분.
/*if(IsUpdate==false) {
id=JOptionPane.showInputDialog("변경할 id 입력(7글자):");
//취소한경우,
if(id==null) return;
stdTemp=dbm.SelectById(id);
if(stdTemp==null) {
JOptionPane.showMessageDialog(null, "존재하지 않는 id입니다."+id,"Message",JOptionPane.ERROR_MESSAGE);
}
hakbunInput.setText(stdTemp.getId());
nameInput.setText(stdTemp.getName());
hakgwaInput.setText(stdTemp.getDept());
addressInput.setText(stdTemp.getAddress());
updateBtn.setText("완료");
IsUpdate=true;
}else {*/
//실질적인 수정을 적용하는 부분.
stdTemp=new StudentDTO();
stdTemp.setId(hakbunInput.getText());
stdTemp.setName(nameInput.getText());
stdTemp.setDepartmentId(hakgwaInput.getText());
stdTemp.setAddress(addressInput.getText());
int result = stdDAO.Update(stdTemp);
if(result>0) {
JOptionPane.showMessageDialog(null, "수정되었습니다.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "수정하지 못했습니다.:"+id,"Fail",JOptionPane.ERROR_MESSAGE);
}
ShowList();
//updateBtn.setText("수정");
//IsUpdate=false;
//}
}
});
deleteBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null, "삭제할것입니까?","Confirm",JOptionPane.YES_NO_OPTION);
//YES이면,
if(result==JOptionPane.YES_OPTION) {
//String id=JOptionPane.showInputDialog("삭제할 id 입력(7글자):");
//취소한경우,
//if(id==null) return;
if(hakbunInput.getText()==null) {
JOptionPane.showMessageDialog(null, "삭제할 학번을 입력해주세요.","Success",JOptionPane.INFORMATION_MESSAGE);
}
int result2 = stdDAO.Delete(hakbunInput.getText());
if(result2>0) {
JOptionPane.showMessageDialog(null, "삭제되었습니다.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "삭제하지 못했습니다.:","Fail",JOptionPane.ERROR_MESSAGE);
}
//출력 메소드 호출
ShowList();
}
//NO라면 없음.
}
});
table.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
table=(JTable)e.getComponent();//클릭한 테이블 구하기
model=(DefaultTableModel)table.getModel();
String id = (String) model.getValueAt(table.getSelectedRow(), 0);
hakbunInput.setText(id);
String name = (String) model.getValueAt(table.getSelectedRow(), 1);
nameInput.setText(name);
String dept = (String) model.getValueAt(table.getSelectedRow(), 2);
hakgwaInput.setText(dept);
String address = (String) model.getValueAt(table.getSelectedRow(), 3);
addressInput.setText(address);
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
//this.setResizable(false);
this.setSize(290, 350);
this.setVisible(true);
}
//출력(Table) 메소드
public void ShowList() {
//입력폼 초기화
hakbunInput.setText("");
nameInput.setText("");
hakgwaInput.setText("");
addressInput.setText("");
//Table 초기화
model.setNumRows(0);
ArrayList<StudentDTO> arrStd = null;
arrStd=stdDAO.SelectAll();
if(arrStd==null) {
JOptionPane.showMessageDialog(null, "출력실패.","Fail",JOptionPane.ERROR_MESSAGE);
}
//컬럼의 갯수=> 4
String[] row=new String[4];
for(StudentDTO stdTemp:arrStd) {
//jta.append(stdTemp+"\n");
row[0]=stdTemp.getId();
row[1]=stdTemp.getName();
row[2]=stdTemp.getDepartmentId();
row[3]=stdTemp.getAddress();
model.addRow(row);
}
}
/*public static void main(String[] args) {
new NewHaksa();
}*/
}
| [
"31540738+JANGJUNSU@users.noreply.github.com"
] | 31540738+JANGJUNSU@users.noreply.github.com |
639d42526134c96f6400414ad9a2c7b046513af6 | 7454db1033695b233820e2c0d8071028451e5b42 | /FTPServer.java | 85cc41633f906c3e8f3673058026ecbb95168377 | [] | no_license | shahzain/Java-Projects | a5c8e781d49d09d1e7e974f7b92d15a177d29c4c | 9d3009aa402da33cc5040fd28b48d303bc5babfa | refs/heads/master | 2021-01-24T18:37:37.848326 | 2017-03-09T15:31:02 | 2017-03-09T15:31:02 | 84,456,125 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,824 | java | package ftpserver;
import java.net.*;
import java.io.*;
import java.util.*;
public class FTPServer {
public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("server.txt"), "utf-8"))) {
writer.write("from server");
}
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}}
}
class transferfile extends Thread
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{
}
}
void SendFile() throws Exception
{
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception
{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ...");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\tSEND Command Receiced ...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
catch(Exception ex)
{
}
}
}
}
| [
"shahzain009@gmail.com"
] | shahzain009@gmail.com |
f64812b7e02dbd92f8764223e215c148d1be4490 | d57473533fe009c46f835ca372b82c7ecfd1ceea | /src/DatabaseManager.java | 223a90b43cc13dfbf2099977bfe2cf936d32427e | [] | no_license | Tuna0128/Database | aa7987d1adfe67d2825a63c9c9092ea470386b11 | 85c7833931db185a4c8c1ccd7693e9e599e03649 | refs/heads/master | 2021-04-12T09:56:46.634648 | 2017-06-16T15:21:09 | 2017-06-16T15:21:09 | 94,524,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,700 | java | import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseManager {
Connection db;
Statement state;
PreparedStatement pState;
DatabaseManager() {
init();
}
private void init() {
try {
db = DriverManager.getConnection("jdbc:mariadb://140.127.74.210/410477013", "410477013", "e853w");
state = db.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addMovie(String title, String genres, int year, int price, String company, String url)
throws SQLException {
int mv_id = 0;
pState = db.prepareStatement(
"INSERT INTO `movie` " + "(`mv_id`, `title`, `genres`, `released_year`, `price`, `company`, `url`) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)");
pState.setInt(1, mv_id);
pState.setString(2, title);
pState.setString(3, genres);
pState.setInt(4, year);
pState.setInt(5, price);
pState.setString(6, company);
pState.setString(7, url);
pState.execute();
}
public void updateMovie(int mv_id, String title, String genres, int year, int price, String company, String url)
throws SQLException {
ResultSet result = state.executeQuery("SELECT * FROM `movie` WHERE `mv_id` = 0 ");
result.next();
if (mv_id == -1)
mv_id = result.getInt("mv_id");
if (title == null)
title = result.getString("title");
if (genres == null)
genres = result.getString("genres");
if (year == -1)
year = result.getInt("released_year");
if (price == -1)
price = result.getInt("price");
if (company == null)
company = result.getString("company");
if (url == null)
url = result.getString("url");
pState = db.prepareStatement("UPDATE `movie` "
+ "SET `title` = ?, `genres` = ?, `released_year` = ?, `price` = ?, `company` = ?, `url` = ? "
+ "WHERE `movie`.`mv_id` = ? ");
pState.setString(1, title);
pState.setString(2, genres);
pState.setInt(3, year);
pState.setInt(4, price);
pState.setString(5, company);
pState.setString(6, url);
pState.setInt(7, mv_id);
pState.execute();
}
public void removeMovie(int mv_id) throws SQLException {
pState = db.prepareStatement("DELETE FROM `movie` " + "WHERE mv_id = ?");
pState.setInt(1, mv_id);
pState.execute();
}
public int getDownloads(int mv_id) throws SQLException {
pState = db
.prepareStatement("SELECT COUNT(`b_id`) " + "FROM `bill` natural join `movie` " + "WHERE `mv_id` = ? ");
pState.setInt(1, mv_id);
ResultSet result = pState.executeQuery();
result.next();
int i = result.getInt(1);
return i;
}
}
| [
"tn0128wayne@gmail.com"
] | tn0128wayne@gmail.com |
0aa4012f159f2dd7a7325e0a0bbb0dbd440ea9e2 | 4c7ab60f25fb91f5b3222750316b9e09ce46c954 | /book/src/main/java/com/pc/composite/IBranch.java | e5ea07f75994943a63b4240b55e884a7f7d60b66 | [] | no_license | chad0204/design-pattern | 9f8c7a98f05fb873ad90156437fe80cd23f81689 | 29009e7b39f948bdd50679763a51c7b1ba7d6875 | refs/heads/master | 2023-03-08T09:38:17.931451 | 2023-03-01T14:37:15 | 2023-03-01T14:37:15 | 205,509,612 | 0 | 0 | null | 2022-08-11T09:44:18 | 2019-08-31T07:08:40 | Java | UTF-8 | Java | false | false | 230 | java | package com.pc.composite;
import java.util.List;
/**
* 领导职位
*
* @author pengchao
* @since 2023/1/31 14:01
*/
public interface IBranch extends ICrop {
void addCrop(ICrop iCrop);
List<ICrop> getChildes();
}
| [
"2389367080@qq.com"
] | 2389367080@qq.com |
7d6c10e01da2a437586a07e7024d188ba0b4ee88 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/27/27_f3a1e317e1e2e56da5febe80fcec91a24a90888e/NetController/27_f3a1e317e1e2e56da5febe80fcec91a24a90888e_NetController_s.java | 28adfabcfc8e1f291a5b22d7545621b7cfc0851e | [] | 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 | 32,044 | java | package com.game.rania.net;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.game.rania.Config;
import com.game.rania.controller.CommandController;
import com.game.rania.controller.Controllers;
import com.game.rania.controller.command.AddLocationCommand;
import com.game.rania.controller.command.AddPlanetCommand;
import com.game.rania.controller.command.AddUserCommand;
import com.game.rania.controller.command.AttackCommand;
import com.game.rania.controller.command.ChatNewMessageCommand;
import com.game.rania.controller.command.RemoveUserCommand;
import com.game.rania.controller.command.RepairCommand;
import com.game.rania.controller.command.SetTargetCommand;
import com.game.rania.controller.command.SwitchScreenCommand;
import com.game.rania.model.Domain;
import com.game.rania.model.Nebula;
import com.game.rania.model.Player;
import com.game.rania.model.Target;
import com.game.rania.model.User;
import com.game.rania.model.Location;
import com.game.rania.model.Planet;
import com.game.rania.model.items.Consumable;
import com.game.rania.model.items.Device;
import com.game.rania.model.items.RepairKit;
import com.game.rania.model.items.Engine;
import com.game.rania.model.items.Equip;
import com.game.rania.model.items.Fuelbag;
import com.game.rania.model.items.Hyper;
import com.game.rania.model.items.Item;
import com.game.rania.model.items.ItemCollection;
import com.game.rania.model.items.Radar;
import com.game.rania.model.items.Shield;
import com.game.rania.model.items.Body;
import com.game.rania.model.items.Weapon;
import com.game.rania.screen.MainMenu;
import com.game.rania.userdata.Command;
import com.game.rania.userdata.Client;
import com.game.rania.userdata.IOStream;
import com.game.rania.utils.Condition;
public class NetController
{
private Receiver receiver = null;
private CommandController cController = null;
private Client mClient = null;
private int ProtocolVersion = 10;
public NetController(CommandController commandController)
{
cController = commandController;
}
public void dispose()
{
if (receiver != null)
receiver.stopThread();
}
public void sendTouchPoint(int x, int y, int currentX, int currentY, boolean stop)
{
byte[] data = new byte[8];
byte[] userxArr = intToByteArray(x);
byte[] useryArr = intToByteArray(y);
System.arraycopy(userxArr, 0, data, 0, 4);
System.arraycopy(useryArr, 0, data, 4, 4);
try
{
mClient.stream.sendCommand(Command.touchPlayer, data);
} catch (Exception ex)
{
}
}
public void sendTarget(Target target)
{
byte[] data = new byte[8];
byte[] targetTypeArr = intToByteArray(target.type);
byte[] targetArr = intToByteArray(target.id);
System.arraycopy(targetTypeArr, 0, data, 0, 4);
System.arraycopy(targetArr, 0, data, 4, 4);
try
{
mClient.stream.sendCommand(Command.setTarget, data);
} catch (Exception ex)
{
}
}
public void sendUseEquip(int equip_id)
{
byte[] data = new byte[4];
byte[] useEquipArr = intToByteArray(equip_id);
System.arraycopy(useEquipArr, 0, data, 0, 4);
try
{
mClient.stream.sendCommand(Command.useEquips, data);
} catch (Exception ex)
{
}
}
public int getServerTime()
{
return mClient.serverTime;
}
public boolean login(String Login, String Password)
{
mClient = new Client();
mClient.login = Login;
mClient.socket = null;
mClient.isLogin = false;
try
{
mClient.socket = new Socket(InetAddress.getByName(Config.serverAddress), Config.serverPort);
if (mClient.socket.isConnected())
{
mClient.stream = new IOStream(mClient.socket.getInputStream(), mClient.socket.getOutputStream());
byte[] LoginArr = Login.getBytes("UTF-16LE");
byte[] LoginLenArr = intToByteArray(LoginArr.length);
byte[] ProtocolVersionArr = intToByteArray(ProtocolVersion);
byte[] data = new byte[LoginArr.length + LoginLenArr.length + ProtocolVersionArr.length];
System.arraycopy(ProtocolVersionArr, 0, data, 0, 4);
System.arraycopy(LoginLenArr, 0, data, 4, 4);
System.arraycopy(LoginArr, 0, data, 8, LoginArr.length);
mClient.stream.sendCommand(Command.login, data);
byte[] PasswordArr = Password.getBytes("UTF-16LE");
byte[] PasswordLenArr = intToByteArray(PasswordArr.length);
data = new byte[PasswordArr.length + PasswordLenArr.length];
System.arraycopy(PasswordLenArr, 0, data, 0, 4);
System.arraycopy(PasswordArr, 0, data, 4, PasswordArr.length);
mClient.stream.sendCommand(Command.password, data);
// Command command = waitCommand();
Command command = mClient.stream.readCommand();
if (command.idCommand == Command.login)
{
CommandReader cr = new CommandReader(command);
mClient.isLogin = true;
mClient.serverTime = cr.getInt();
receiver = new Receiver(mClient, this);
receiver.start();
checkCRC(command, cr);
return true;
}
if (command.idCommand == Command.faillogin)
{
// CommandReader ArrPtr = new CommandReader(command.data);
mClient.isLogin = false;
}
if (command.idCommand == Command.failversion)
{
// CommandReader ArrPtr = new CommandReader(command.data);
mClient.isLogin = false;
}
}
} catch (Exception ex)
{
return false;
}
return false;
}
public boolean checkCRC(Command command, CommandReader cr)
{
if (command.controlCRC != cr.crc)
{
Gdx.app.log("CRC error", "Login");
return false;
}
return true;
}
public void disconnect()
{
try
{
if (mClient != null && mClient.socket.isConnected() && mClient.isLogin)
{
mClient.stream.sendCommand(Command.disconnect);
receiver.stopThread();
mClient.socket.shutdownInput();
mClient.socket.shutdownOutput();
mClient.socket.close();
}
} catch (Exception ex)
{
}
}
public void sendChatMessage(String Message, int channel)
{
String toPilot = "";
if (Message.isEmpty())
return;
try
{
byte[] ChannelArr = intToByteArray(channel);
byte[] MessageArr = Message.getBytes("UTF-16LE");
byte[] MessageLenArr = intToByteArray(MessageArr.length);
byte[] toPilotArr = toPilot.getBytes("UTF-16LE");
byte[] toPilotLenArr = intToByteArray(toPilotArr.length);
byte[] data = new byte[ChannelArr.length + MessageArr.length + MessageLenArr.length + toPilotArr.length + toPilotLenArr.length];
System.arraycopy(ChannelArr, 0, data, 0, 4);
System.arraycopy(MessageLenArr, 0, data, 4, 4);
System.arraycopy(MessageArr, 0, data, 8, MessageArr.length);
System.arraycopy(toPilotLenArr, 0, data, 8 + MessageArr.length, 4);
System.arraycopy(toPilotArr, 0, data, 8 + MessageArr.length + 4, toPilotArr.length);
mClient.stream.sendCommand(Command.message, data);
} catch (Exception ex)
{
}
}
public void clientRelogin()
{
// mClient.relogin
}
public void loadComplite()
{
try
{
mClient.stream.sendCommand(Command.loadComplite);
} catch (Exception ex)
{
}
}
public ItemCollection getItems()
{
ItemCollection iCollect = new ItemCollection();
try
{
mClient.stream.sendCommand(Command.items);
Command command = waitCommand(Command.items);
CommandReader cr = new CommandReader(command);
int listItemsCount = cr.getInt();
for (int i = 0; i < listItemsCount; i++)
{
int itemsCount = cr.getInt();
for (int j = 0; j < itemsCount; j++)
{
int item_id = cr.getInt();
int item_itemType = cr.getInt();
String item_description = cr.getString();
int item_volume = cr.getInt();
int item_region_id = cr.getInt();
int item_use_only = cr.getInt();
int item_price = cr.getInt();
if (item_itemType == 1)
{
String device_vendorStr = cr.getString();
int device_deviceType = cr.getInt();
int device_durability = cr.getInt();
switch (device_deviceType)
{
case Device.Type.body:
{
int body_slot_weapons = cr.getInt();
int body_slot_droids = cr.getInt();
int body_slot_shield = cr.getInt();
int body_slot_hyper = cr.getInt();
Body body = new Body();
body.id = item_id;
body.itemType = item_itemType;
body.description = item_description;
body.volume = item_volume;
body.region_id = item_region_id;
body.vendorStr = device_vendorStr;
body.deviceType = device_deviceType;
body.durability = device_durability;
body.use_only = item_use_only;
body.price = item_price;
body.slot_weapons = body_slot_weapons;
body.slot_droids = body_slot_droids;
body.slot_shield = body_slot_shield;
body.slot_hyper = body_slot_hyper;
iCollect.bodies.put(body.id, body);
break;
}
case Device.Type.engine:
{
int engine_power = cr.getInt();
int engine_economic = cr.getInt();
Engine engine = new Engine();
engine.id = item_id;
engine.itemType = item_itemType;
engine.description = item_description;
engine.volume = item_volume;
engine.region_id = item_region_id;
engine.vendorStr = device_vendorStr;
engine.deviceType = device_deviceType;
engine.durability = device_durability;
engine.use_only = item_use_only;
engine.price = item_price;
engine.power = engine_power;
engine.economic = engine_economic;
iCollect.engines.put(engine.id, engine);
break;
}
case Device.Type.fuelbag:
{
int fuelbag_compress = cr.getInt();
Fuelbag fuelbag = new Fuelbag();
fuelbag.id = item_id;
fuelbag.itemType = item_itemType;
fuelbag.description = item_description;
fuelbag.volume = item_volume;
fuelbag.region_id = item_region_id;
fuelbag.vendorStr = device_vendorStr;
fuelbag.deviceType = device_deviceType;
fuelbag.durability = device_durability;
fuelbag.use_only = item_use_only;
fuelbag.price = item_price;
fuelbag.compress = fuelbag_compress;
iCollect.fuelbags.put(fuelbag.id, fuelbag);
break;
}
case Device.Type.droid:
{
int droid_power = cr.getInt();
int droid_time_reload = cr.getInt();
int radius = cr.getInt();
RepairKit droid = new RepairKit();
droid.id = item_id;
droid.itemType = item_itemType;
droid.description = item_description;
droid.volume = item_volume;
droid.region_id = item_region_id;
droid.vendorStr = device_vendorStr;
droid.deviceType = device_deviceType;
droid.durability = device_durability;
droid.use_only = item_use_only;
droid.price = item_price;
droid.power = droid_power;
droid.time_reload = radius;
droid.radius = droid_time_reload;
iCollect.droids.put(droid.id, droid);
break;
}
case Device.Type.shield:
{
int shield_power = cr.getInt();
Shield shield = new Shield();
shield.id = item_id;
shield.itemType = item_itemType;
shield.description = item_description;
shield.volume = item_volume;
shield.region_id = item_region_id;
shield.vendorStr = device_vendorStr;
shield.deviceType = device_deviceType;
shield.durability = device_durability;
shield.use_only = item_use_only;
shield.price = item_price;
shield.power = shield_power;
iCollect.shields.put(shield.id, shield);
break;
}
case Device.Type.hyper:
{
int hyper_radius = cr.getInt();
int hyper_time_start = cr.getInt();
int hyper_time_reload = cr.getInt();
Hyper hyper = new Hyper();
hyper.id = item_id;
hyper.itemType = item_itemType;
hyper.description = item_description;
hyper.volume = item_volume;
hyper.region_id = item_region_id;
hyper.vendorStr = device_vendorStr;
hyper.deviceType = device_deviceType;
hyper.durability = device_durability;
hyper.use_only = item_use_only;
hyper.price = item_price;
hyper.radius = hyper_radius;
hyper.time_start = hyper_time_start;
hyper.time_reload = hyper_time_reload;
iCollect.hypers.put(hyper.id, hyper);
break;
}
case Device.Type.radar:
{
int radar_radius = cr.getInt();
int radar_defense = cr.getInt();
int big_radius = cr.getInt();
Radar radar = new Radar();
radar.id = item_id;
radar.itemType = item_itemType;
radar.description = item_description;
radar.volume = item_volume;
radar.region_id = item_region_id;
radar.vendorStr = device_vendorStr;
radar.deviceType = device_deviceType;
radar.durability = device_durability;
radar.use_only = item_use_only;
radar.price = item_price;
radar.radius = radar_radius;
radar.defense = radar_defense;
radar.big_radius = big_radius;
iCollect.radars.put(radar.id, radar);
break;
}
case Device.Type.weapon:
{
int weapon_weaponType = cr.getInt();
int weapon_radius = cr.getInt();
int weapon_power = cr.getInt();
int weapon_time_start = cr.getInt();
int weapon_time_reload = cr.getInt();
Weapon weapon = new Weapon();
weapon.id = item_id;
weapon.itemType = item_itemType;
weapon.description = item_description;
weapon.volume = item_volume;
weapon.region_id = item_region_id;
weapon.vendorStr = device_vendorStr;
weapon.deviceType = device_deviceType;
weapon.durability = device_durability;
weapon.use_only = item_use_only;
weapon.price = item_price;
weapon.weaponType = weapon_weaponType;
weapon.radius = weapon_radius;
weapon.power = weapon_power;
weapon.time_start = weapon_time_start;
weapon.time_reload = weapon_time_reload;
iCollect.weapons.put(weapon.id, weapon);
break;
}
}
}
if (item_itemType == 2)
{
Consumable item = new Consumable();
item.id = item_id;
item.itemType = item_itemType;
item.description = item_description;
item.volume = item_volume;
item.region_id = item_region_id;
iCollect.consumables.put(item.id, item);
}
}
}
checkCRC(command, cr);
} catch (Exception ex)
{
}
return iCollect;
}
public HashMap<Integer, Planet> getPlanets(int idLocation, boolean wait)
{
HashMap<Integer, Planet> planets = new HashMap<Integer, Planet>();
try
{
mClient.stream.sendCommand(Command.planets, intToByteArray(idLocation));
if (!wait)
return null;
Command command = waitCommand(Command.planets);
CommandReader cr = new CommandReader(command);
cr.delta(4);
int PlanetsCount = cr.getInt();
for (int i = 0; i < PlanetsCount; i++)
{
int PlanetId = cr.getInt();
String PlanetName = cr.getString();
int PlanetType = cr.getInt();
int PlanetSpeed = cr.getInt();
int PlanetOrbit = cr.getInt();
int PlanetRadius = cr.getInt();
Color color = cr.getColor();
Color atmColor = cr.getColor();
int PlanetDomain = cr.getInt();
int PlanetAtmosphere_speedX = cr.getInt();
int PlanetAtmosphere_speedY = cr.getInt();
int PlanetPrice_coef = cr.getInt();
Planet planet = new Planet(PlanetId, PlanetName, PlanetType, PlanetRadius, PlanetSpeed, PlanetOrbit, idLocation, PlanetDomain, PlanetAtmosphere_speedX, PlanetAtmosphere_speedY);
planet.color = color;
planet.price_coef = PlanetPrice_coef;
planet.atmophereColor = atmColor;
planets.put(PlanetId, planet);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return planets;
}
public HashMap<Integer, Nebula> getAllNebulas()
{
HashMap<Integer, Nebula> nebulas = new HashMap<Integer, Nebula>();
try
{
mClient.stream.sendCommand(Command.nebulas);
Command command = waitCommand(Command.nebulas);
CommandReader cr = new CommandReader(command);
int NebulasCount = cr.getInt();
for (int i = 0; i < NebulasCount; i++)
{
int NebId = cr.getInt();
int NebType = cr.getInt();
int NebX = cr.getInt();
int NebY = cr.getInt();
int NebScale = cr.getInt();
int NebAngle = cr.getInt();
Nebula Neb = new Nebula(NebId, NebType, NebX, NebY, NebAngle, NebScale);
nebulas.put(Neb.id, Neb);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return nebulas;
}
public HashMap<Integer, Domain> getAllDomains()
{
HashMap<Integer, Domain> domains = new HashMap<Integer, Domain>();
try
{
mClient.stream.sendCommand(Command.domains);
Command command = waitCommand(Command.domains);
CommandReader cr = new CommandReader(command);
int DomainsCount = cr.getInt();
for (int i = 0; i < DomainsCount; i++)
{
Domain domain = new Domain();
domain.id = cr.getInt();
domain.color = cr.getColor();
domain.domainName = cr.getString();
domain.x = cr.getInt();
domain.y = cr.getInt();
int enemyCount = cr.getInt();
domain.enemy = new int[enemyCount];
for (int j = 0; j < enemyCount; j++)
{
domain.enemy[j] = cr.getInt();
}
domains.put(domain.id, domain);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return domains;
}
public Player getUserData()
{
try
{
mClient.stream.sendCommand(Command.player);
Command command = waitCommand(Command.player);
CommandReader cr = new CommandReader(command);
int UserId = cr.getInt();
int UserX = cr.getInt();
int UserY = cr.getInt();
int UserDomain = cr.getInt();
int UserInPlanet = cr.getInt();
String PName = cr.getString();
String SName = cr.getString();
Player player = new Player(UserId, UserX, UserY, PName, SName, UserDomain, UserInPlanet);
player.setEquips(getEquips(cr));
checkCRC(command, cr);
return player;
} catch (Exception ex)
{
clientRelogin();
}
return null;
}
public static int byteArrayToInt(byte[] b)
{
return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24;
}
public static double byteArrayToDouble(byte[] b)
{
long longBits = ((b[7] & 0xFFL) << 56) |
((b[6] & 0xFFL) << 48) |
((b[5] & 0xFFL) << 40) |
((b[4] & 0xFFL) << 32) |
((b[3] & 0xFFL) << 24) |
((b[2] & 0xFFL) << 16) |
((b[1] & 0xFFL) << 8) |
((b[0] & 0xFFL) << 0);
return Double.longBitsToDouble(longBits);
}
public static byte[] intToByteArray(int a)
{
return new byte[] { (byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
}
// commands
private Condition cWaitCommand = new Condition(), cCopyCommand = new Condition();
private volatile int idWaitCommand = Command.none;
private volatile Command currentCommand = null;
public Command waitCommand(int idCommand) throws InterruptedException
{
idWaitCommand = idCommand;
cWaitCommand.signalWait();
Command command = currentCommand;
cCopyCommand.signal();
return command;
}
public void processingCommand(Command command) throws InterruptedException, UnsupportedEncodingException
{
if (idWaitCommand != Command.none && idWaitCommand == command.idCommand)
{
idWaitCommand = Command.none;
currentCommand = command;
cWaitCommand.signal();
cCopyCommand.signalWait();
return;
}
CommandReader cr = new CommandReader(command);
switch (command.idCommand)
{
case Command.addUser:
{
int UserId = cr.getInt();
String ShipName = cr.getString();
int UserX = cr.getInt();
int UserY = cr.getInt();
int TargetX = cr.getInt();
int TargetY = cr.getInt();
int UserDomain = cr.getInt();
User user = new User(UserId, UserX, UserY, ShipName, "", UserDomain);
//user.setPositionTarget(TargetX, TargetY);
user.setEquips(getEquips(cr));
cController.addCommand(new AddUserCommand(user));
break;
}
case Command.touchUser:
{
int UserId = cr.getInt();
int UserTouchX = cr.getInt();
int UserTouchY = cr.getInt();
int flyTime = cr.getInt();
int fuel = cr.getInt();
cController.addCommand(new SetTargetCommand(UserId, UserTouchX, UserTouchY, flyTime * 0.001f, fuel));
break;
}
case Command.removeUser:
{
int UserId = cr.getInt();
cController.addCommand(new RemoveUserCommand(UserId));
break;
}
case Command.disconnect:
{
try
{
receiver.stopThread();
mClient.socket.shutdownInput();
mClient.socket.shutdownOutput();
mClient.socket.close();
cController.addCommand(new SwitchScreenCommand(new MainMenu()));
} catch (Exception ex)
{
}
}
case Command.message:
{
int channel = cr.getInt();
String message = cr.getString();
String userName = cr.getString();
String toPilot = cr.getString();
cController.addCommand(new ChatNewMessageCommand(userName, channel, message, toPilot));
break;
}
case Command.userAction:
{
int equipID = cr.getInt();
int userID = cr.getInt();
int targetID = cr.getInt();
int action = cr.getInt();
switch (action)
{
case User.Action.attack:
{
int dmg = cr.getInt();
cController.addCommand(new AttackCommand(userID, targetID, equipID, dmg));
break;
}
case User.Action.repair:
{
int rapair = cr.getInt();
cController.addCommand(new RepairCommand(userID, targetID, equipID, rapair));
break;
}
}
break;
}
case Command.planets:
{
int locID = cr.getInt();
int PlanetsCount = cr.getInt();
for (int i = 0; i < PlanetsCount; i++)
{
int PlanetId = cr.getInt();
String PlanetName = cr.getString();
int PlanetType = cr.getInt();
int PlanetSpeed = cr.getInt();
int PlanetOrbit = cr.getInt();
int PlanetRadius = cr.getInt();
Color PlanetColor = cr.getColor();
Color AtmColor = cr.getColor();
int PlanetDomain = cr.getInt();
int PlanetAtmosphere_speedX = cr.getInt();
int PlanetAtmosphere_speedY = cr.getInt();
int PlanetPrice_coef = cr.getInt();
Planet planet = new Planet(PlanetId, PlanetName, PlanetType, PlanetRadius, PlanetSpeed, PlanetOrbit, locID, PlanetDomain, PlanetAtmosphere_speedX, PlanetAtmosphere_speedY);
planet.color = PlanetColor;
planet.atmophereColor = AtmColor;
planet.price_coef = PlanetPrice_coef;
cController.addCommand(new AddPlanetCommand(planet));
}
break;
}
case Command.location:
{
int LocationsCount = cr.getInt();
for (int i = 0; i < LocationsCount; i++)
{
Location location = new Location();
location.id = cr.getInt();
location.starName = cr.getString();
location.starType = cr.getInt();
location.x = cr.getInt();
location.y = cr.getInt();
location.starRadius = cr.getInt();
location.domain = cr.getInt();
cController.addCommand(new AddLocationCommand(location));
}
break;
}
default:
break;
}
checkCRC(command, cr);
}
private List<Equip<Item>> getEquips(CommandReader cr)
{
ItemCollection items = Controllers.locController.getItems();
if (items == null)
return null;
List<Equip<Item>> equip = new ArrayList<Equip<Item>>();
int eqCount = cr.getInt();
for (int j = 0; j < eqCount; j++)
{
int equip_id = cr.getInt();
int item_id = cr.getInt();
int iType = cr.getInt();
int dType = cr.getInt();
int in_use = cr.getInt();
int wear = cr.getInt();
int in_planet = cr.getInt();
int num = cr.getInt();
Equip<Item> eq = new Equip<Item>();
eq.id = equip_id;
eq.in_use = in_use == 1 ? true : false;
eq.wear = wear;
eq.in_planet = in_planet;
eq.num = num;
eq.item = null;
if (iType == Item.Type.device)
{
switch (dType)
{
case Device.Type.droid:
{
eq.item = items.droids.get(item_id);
break;
}
case Device.Type.engine:
{
eq.item = items.engines.get(item_id);
break;
}
case Device.Type.fuelbag:
{
eq.item = items.fuelbags.get(item_id);
break;
}
case Device.Type.hyper:
{
eq.item = items.hypers.get(item_id);
break;
}
case Device.Type.radar:
{
eq.item = items.radars.get(item_id);
break;
}
case Device.Type.shield:
{
eq.item = items.shields.get(item_id);
break;
}
case Device.Type.body:
{
eq.item = items.bodies.get(item_id);
break;
}
case Device.Type.weapon:
{
eq.item = items.weapons.get(item_id);
break;
}
}
}
else if (iType == Item.Type.consumable)
{
eq.item = items.consumables.get(item_id);
}
equip.add(eq);
}
return equip;
}
class CommandReader
{
public int address;
public byte[] data;
public int crc;
public boolean endOfData;
public CommandReader()
{
this.data = null;
this.address = 0;
this.crc = 0;
this.endOfData = false;
}
public CommandReader(Command cmd)
{
this.data = cmd.data;
this.address = 0;
this.crc = 0;
this.endOfData = false;
}
public void delta(int delta)
{
for (int i = 0; i < delta; i++)
{
char b = (char) (this.data[this.address + i] & 0xFF);
this.crc = this.crc + b * (this.address + i);
}
this.address += delta;
if (this.address == data.length)
{
this.endOfData = true;
}
}
public int getInt()
{
int Res = 0;
if (!this.endOfData)
{
byte[] Arr = new byte[4];
System.arraycopy(this.data, this.address, Arr, 0, 4);
delta(4);
Res = byteArrayToInt(Arr);
}
else
{
Gdx.app.log("Read Data error", "getIntValue");
}
return Res;
}
public double getDbl()
{
double Res = 0.0f;
if (!this.endOfData)
{
byte[] Arr = new byte[8];
System.arraycopy(this.data, this.address, Arr, 0, 8);
delta(8);
Res = byteArrayToDouble(Arr);
}
else
{
Gdx.app.log("Read Data error", "getDoubleValue");
}
return Res;
}
public String getString()
{
String Res = "";
if (!this.endOfData)
{
int SL = this.getInt();
byte[] Arr = new byte[SL];
System.arraycopy(this.data, this.address, Arr, 0, SL);
delta(SL);
try
{
Res = new String(Arr, "UTF-16LE");
} catch (UnsupportedEncodingException e)
{
Gdx.app.log(" ", ": " + e.getMessage());
}
}
else
{
Gdx.app.log("Read Data error", "getStringValue");
}
return Res;
}
private Color getColor()
{
Color Res = null;
if (!this.endOfData)
{
byte[] Arr = new byte[4];
System.arraycopy(this.data, this.address, Arr, 0, 4);
delta(4);
char R = (char) (Arr[0] & 0xFF);
char G = (char) (Arr[1] & 0xFF);
char B = (char) (Arr[2] & 0xFF);
char A = (char) (Arr[3] & 0xFF);
Res = new Color(R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f);
}
else
{
Gdx.app.log("Read Data error", "getColorValue");
}
return Res;
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
f22db35474ef20fa9afddfbdf29f5d3ed41bd30e | b2321d70021f9662d20c77728db888cb278d54e4 | /src/flowMap/model/OS.java | 303ec021175f15f6b6246beb86bb54ac9f5cabf3 | [] | no_license | 51mon/flowMap | 64a86d833a4811d503ccb4131963b3e875f56676 | 6005c5e984c0f44230da208143ca009208a6eb0b | refs/heads/master | 2020-04-05T23:31:52.877474 | 2013-11-20T00:00:52 | 2013-11-20T00:00:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,487 | java | package flowMap.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "oses")
public class OS extends NamedIntId {
public static final String STAGE_ID_COL = "stage_id";
@DatabaseField(columnName = STAGE_ID_COL, foreign = true)
Stage stage;
public static final String VERSION_COL = "version";
@DatabaseField(columnName = VERSION_COL)
private String version;
public static final String ARCHITECTURE_COL = "architecture";
@DatabaseField(columnName = ARCHITECTURE_COL)
private String architecture;
public static final String HOST_NAME_COL = "host_name";
@DatabaseField(columnName = HOST_NAME_COL)
private String hostName;
public OS() {}
public OS(String hostName) {
this.hostName = hostName;
}
public OS(String arch, String name, String version) {
super(name);
this.architecture = arch;
this.version = version;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
}
| [
"simon@majou.org"
] | simon@majou.org |
52f66eac5009ce2de1abc88e2c6980a731ae9a69 | 2d5aa15ce0f39e6f02e24c013c9405b8a3261617 | /src/main/java/com/kaytech/bugtracker/domain/User.java | 72819b9eaab5e3437995aae00048870a761e052e | [] | no_license | driscol/BugTrackerJHipster | 82c6defbbe38d862f954b80a01ab052241ab8997 | f532aa8c85a356fae3e019248a54c67441c05fc8 | refs/heads/main | 2023-03-10T21:05:38.051449 | 2021-02-22T23:51:51 | 2021-02-22T23:51:51 | 341,370,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,536 | java | package com.kaytech.bugtracker.domain;
import com.kaytech.bugtracker.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
| [
"/"
] | / |
ce980b7e035214b590d61b51f0deaa05e30d9e9a | d04da34e2bd704c45136c06605a7d6598b17030f | /weekly-core/src/main/java/com/weekly/framework/datasource/DynamicDataSource.java | 1322673b54f6991157c92fc62692ef4e49ffa0ff | [] | no_license | peiweipan/weeklySchedule | 427e7cab8d2c4a854b14b72e7ecf5108be9ca84b | a28f41436bedd5db1ba1fed9078f1338340c1fd1 | refs/heads/master | 2023-04-14T21:16:40.174340 | 2020-09-02T02:12:32 | 2020-09-02T02:12:32 | 361,801,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 705 | java | package com.weekly.framework.datasource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*
* @author weekly
*/
public class DynamicDataSource extends AbstractRoutingDataSource
{
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
{
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey()
{
return DynamicDataSourceContextHolder.getDataSourceType();
}
} | [
"38575998+a1215305395@users.noreply.github.com"
] | 38575998+a1215305395@users.noreply.github.com |
b20817b90fd8fd43aeebcda5c442f22c72498592 | f6a693800d563581c576d94dd6b02dc030774d85 | /app/src/main/java/id/sch/smktelkom_mlg/learn/recyclerview3/model/Hotel.java | 04b1e97dcda15b8d8007c02d26780bc6fc888b33 | [] | no_license | fadhilikhsann/RecyclerView3 | 0c71abc89af127c1d1b4af8974e3bf1c543f87cf | 548e6828cd8844ceed6a0c01106140185a69d97a | refs/heads/master | 2021-06-07T03:28:51.520207 | 2016-11-05T08:25:09 | 2016-11-05T08:25:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 567 | java | package id.sch.smktelkom_mlg.learn.recyclerview3.model;
import java.io.Serializable;
/**
* Created by Fadhil Ikhsan on 03/11/2016.
*/
public class Hotel implements Serializable {
public String judul;
public String deskripsi;
public String detail;
public String lokasi;
public String foto;
public Hotel(String judul, String deskripsi, String detail, String lokasi, String foto) {
this.judul = judul;
this.deskripsi = deskripsi;
this.detail = detail;
this.lokasi = lokasi;
this.foto = foto;
}
}
| [
"f.ikhsanta@gmail.com"
] | f.ikhsanta@gmail.com |
e86ff35356cca4543678777b88d03fd2e2f1acab | 588208f2b8c6a4b45108a712812c07267d49f796 | /keg-MrDAP/mrdapPlatform/src/edu/thu/keg/link/client2/TaskLib.java | 34d3563839a3bc95956e5a720371a6043fabf4e7 | [] | no_license | Ariesnix/KEG | ce50fdbd87f1ad1b848a280ad232656019e1ecc5 | 643e0a58118e3b90a006c0dc621b8cd6afc9462a | refs/heads/master | 2021-01-01T20:05:33.893308 | 2014-12-07T11:34:25 | 2014-12-07T11:34:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 687 | java | package edu.thu.keg.link.client2;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import edu.thu.keg.link.client.env.Default;
import edu.thu.keg.link.common.request.Request;
public class TaskLib
{
public static void main(String[] args) throws JSONException
{
System.out.println(list());
}
public static JSONArray list() throws JSONException
{
List<String[]> list = new ArrayList<String[]>();
String app_submit_url = Default.getValue("APPLICATION_SUBMIT_URL");
String info= Request.post(app_submit_url + "TaskJarCollection2", list);
return new JSONArray(info);
}
}
| [
"ariesnix93@gmail.com"
] | ariesnix93@gmail.com |
ce242588be81174c01fd68b0a26fa9b49b41a117 | 6d620667c6df8acf05e79bbaa86643655e0ef339 | /src/main/java/expression/Expression.java | 7675da4edd7469fc4cab2d1df3dd8b9573992f9b | [] | no_license | saimonsaret/ExpressionGenerator | 5170d6bdff4dacfbaf4c7e5a38ce8522baf45244 | d98eaed189b7100ee37bd08c644c01ec2bdeab46 | refs/heads/master | 2021-01-20T09:14:20.263070 | 2017-08-27T23:19:05 | 2017-08-27T23:19:05 | 101,586,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package expression;
import expression.token.Token;
import java.util.List;
public class Expression {
private final List<Token> tokens;
public Expression(List<Token> tokens) {
this.tokens = tokens;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Token token : tokens) {
builder.append(token.getValue());
}
return builder.toString();
}
public List<Token> getTokens() {
return tokens;
}
}
| [
"saimon_saret@mail.ru"
] | saimon_saret@mail.ru |
ba6a89d2f4491ebba22b2bba79aac0dc1f7272d3 | 05eef6968dbbc5d8d08c48f44d50827a63a790a6 | /bank/src/com/neusoft/po/CreditCardBill.java | 9fc5c2a1950deb5b5fa8ea9a73d11552948ff390 | [] | no_license | NEU-ORG/bank | 087169a3ce5b41a3d6adf31c02ad163204081041 | 352dd5d63f17e3bf2f9967718b591459c7957d7d | refs/heads/master | 2020-04-06T08:53:32.339197 | 2016-09-05T10:48:22 | 2016-09-05T10:48:22 | 64,071,261 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,695 | java | package com.neusoft.po;
import java.util.Date;
/**
* CreditCardBill entity. @author MyEclipse Persistence Tools
*/
public class CreditCardBill implements java.io.Serializable {
// Fields
private Integer id;
private CreditCard creditCard;
private Date statementDate;
private double dueDate;
private String currency;
private long statementBalance;
private long minPayment;
private long lastStatementBalance;
private long amountPayment;
private long amountReceived;
// Constructors
/** default constructor */
public CreditCardBill() {
}
/** full constructor */
public CreditCardBill(CreditCard creditCard, Date statementDate,
double dueDate, String currency, long statementBalance,
long minPayment, long lastStatementBalance, long amountPayment,
long amountReceived) {
this.creditCard = creditCard;
this.statementDate = statementDate;
this.dueDate = dueDate;
this.currency = currency;
this.statementBalance = statementBalance;
this.minPayment = minPayment;
this.lastStatementBalance = lastStatementBalance;
this.amountPayment = amountPayment;
this.amountReceived = amountReceived;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public CreditCard getCreditCard() {
return this.creditCard;
}
public void setCreditCard(CreditCard creditCard) {
this.creditCard = creditCard;
}
public Date getStatementDate() {
return this.statementDate;
}
public void setStatementDate(Date statementDate) {
this.statementDate = statementDate;
}
public double getDueDate() {
return this.dueDate;
}
public void setDueDate(double dueDate) {
this.dueDate = dueDate;
}
public String getCurrency() {
return this.currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public long getStatementBalance() {
return this.statementBalance;
}
public void setStatementBalance(long statementBalance) {
this.statementBalance = statementBalance;
}
public long getMinPayment() {
return this.minPayment;
}
public void setMinPayment(long minPayment) {
this.minPayment = minPayment;
}
public long getLastStatementBalance() {
return this.lastStatementBalance;
}
public void setLastStatementBalance(long lastStatementBalance) {
this.lastStatementBalance = lastStatementBalance;
}
public long getAmountPayment() {
return this.amountPayment;
}
public void setAmountPayment(long amountPayment) {
this.amountPayment = amountPayment;
}
public long getAmountReceived() {
return this.amountReceived;
}
public void setAmountReceived(long amountReceived) {
this.amountReceived = amountReceived;
}
} | [
"1085677575@qq.com"
] | 1085677575@qq.com |
8f319b84e4101a2739146ae7408e715832b93a9c | b733c258761e7d91a7ef0e15ca0e01427618dc33 | /cards/src/main/java/org/rnd/jmagic/cards/LoneMissionary.java | d075bd955858c5f0967e684e9019c90ae88c78f1 | [] | no_license | jmagicdev/jmagic | d43aa3d2288f46a5fa950152486235614c6783e6 | 40e573f8e6d1cf42603fd05928f42e7080ce0f0d | refs/heads/master | 2021-01-20T06:57:51.007411 | 2014-10-22T03:03:34 | 2014-10-22T03:03:34 | 9,589,102 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 878 | java | package org.rnd.jmagic.cards;
import static org.rnd.jmagic.Convenience.*;
import org.rnd.jmagic.engine.*;
import org.rnd.jmagic.engine.generators.*;
@Name("Lone Missionary")
@Types({Type.CREATURE})
@SubTypes({SubType.KOR, SubType.MONK})
@ManaCost("1W")
@ColorIdentity({Color.WHITE})
public final class LoneMissionary extends Card
{
public static final class ETBGainLife extends EventTriggeredAbility
{
public ETBGainLife(GameState state)
{
super(state, "When Lone Missionary enters the battlefield, you gain 4 life.");
this.addPattern(whenThisEntersTheBattlefield());
this.addEffect(gainLife(You.instance(), 4, "You gain 4 life."));
}
}
public LoneMissionary(GameState state)
{
super(state);
this.setPower(2);
this.setToughness(1);
// When Lone Missionary enters the battlefield, you gain 4 life.
this.addAbility(new ETBGainLife(state));
}
}
| [
"robyter@gmail"
] | robyter@gmail |
c27c3bc70edcff5a7a8796f3d74ab075822e066f | 9d50774b302b61c58639ce25586dd7f26f8dac9f | /GamerLobby3/app/src/main/java/com/example/jewishbear/gamerlobby/SignupActivity.java | baf0aac208506d93708c156c8040e213721e37f0 | [] | no_license | mindvortex/proje | 53e8bfc7e0512eb23029ff236314dd7d29ce4e9f | 4dcd3c05afac92ba56502d730578b956cfa8f31a | refs/heads/master | 2020-01-23T21:29:15.515276 | 2016-11-24T20:08:34 | 2016-11-24T20:08:34 | 74,702,094 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 926 | java | package com.example.jewishbear.gamerlobby;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* Created by jewishbear on 11/20/2016.
*/
public class SignupActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_activity);
Button signupbtn = (Button) findViewById(R.id.signup_button);
signupbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignupActivity.this,HomeActivity.class);
startActivity(intent);
}
});
}
}
| [
"onurg34@gmail.com"
] | onurg34@gmail.com |
ff433620367e358da1fd67d816c20315caf51f6a | 7f9e87256e62771a6ec72d1c9546a3d1e4f41281 | /src/day53/Ex4.java | c851a1e2cc2de051aebb85009029272eb93b929d | [] | no_license | jeonseojin/Java | df7c670cfc28706ab0207a5035d3bcf347d35bb2 | a5fd3b5ed7b219d9f24dd8619fbf9ab327c0c5d1 | refs/heads/master | 2022-11-22T15:13:53.090180 | 2020-07-09T00:48:05 | 2020-07-09T00:48:10 | 257,480,244 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 228 | java | package day53;
public class Ex4 {
public static void main(String[] args) {
// while문 9단
int num=9;
int n=1;
while(n<=9) {
System.out.printf("%d X %d = %d\n",num,n,num*n);
n++;
}
}
}
| [
"lijvlij@naver.com"
] | lijvlij@naver.com |
a23d14295837320637ae65b4a457cbc802de98f7 | 7378e110798a847629bf16d18104ba7e18b53917 | /app/src/main/java/com/rhaghis/quranproject/MainActivity.java | 2719c05569215e444ffe75acd065604e35fc4ca9 | [] | no_license | RHAghis/AlquranAppsUAS | e1b13ebcaf22f44c566f55095dfc7c0dee5f3fa1 | 162d95328cda896c591f2920329d084daedc09f9 | refs/heads/master | 2021-09-06T03:58:49.487758 | 2018-02-02T07:03:24 | 2018-02-02T07:03:24 | 119,938,280 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,709 | java | package com.rhaghis.quranproject;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.rhaghis.quranproject.adapter.QuranAdapter;
import com.rhaghis.quranproject.generator.ServiceGenerator;
import com.rhaghis.quranproject.models.Quran;
import com.rhaghis.quranproject.models.Surah;
import com.rhaghis.quranproject.services.QuranService;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
QuranService service;
RecyclerView rvSursh;
QuranAdapter quranAdapter;
List<Surah> surahList = new ArrayList<>();
RecyclerView.LayoutManager layoutManager;
ProgressDialog pr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
service = ServiceGenerator.createService(QuranService.class);
reloadData();
quranAdapter = new QuranAdapter(getApplicationContext(), surahList);
layoutManager = new LinearLayoutManager(this);
rvSursh = findViewById(R.id.rvSurah);
rvSursh.setLayoutManager(layoutManager);
rvSursh.setAdapter(quranAdapter);
}
private void reloadData() {
pr = ProgressDialog.show(this, "List Surah", "Silahkan Tunggu Sebentar....", true, false);
Call<Quran> call = service.getQuran();
call.enqueue(new Callback<Quran>() {
@Override
public void onResponse(Call<Quran> call, Response<Quran> response) {
if(response.isSuccessful()){
pr.dismiss();
Log.d("Suk", "Sukses !!! ");
surahList.clear();
surahList.addAll(response.body().getData().getSurahs());
quranAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Data Telah Tampil", Toast.LENGTH_SHORT).show();
}else {
pr.dismiss();
Toast.makeText(MainActivity.this, "Gagal Memuat Data", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Quran> call, Throwable t) {
Log.d(String.valueOf(t), "Error : "+t);
Toast.makeText(MainActivity.this, "Harap Periksa Koneksi anda", Toast.LENGTH_SHORT).show();
}
});
}
}
| [
"raden.hadzi@gmail.com"
] | raden.hadzi@gmail.com |
4e904b8a2b42d86eec3ed34b987833e9f15eeb9d | bb2114897acd90dbeeab38b886a308a5826d7bf3 | /atmosphere-springboot-server/src/test/java/com/harshild/SampleAtmosphereServerTests.java | 9657a461545fc2aaeaddb0b41f0b25b1e8f3fa78 | [
"MIT"
] | permissive | harshild/atmosphere-all-clients | ced03c10452be395c974c7c5f056529710d524e2 | d1e6319b610ca831b9856227ee3d9e9bf657c827 | refs/heads/master | 2021-05-03T04:51:16.447817 | 2018-02-22T14:41:02 | 2018-02-22T14:41:02 | 120,627,704 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,772 | java | /*
* Copyright 2008-2018-2008-2018 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 com.harshild;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AtmosphereServer.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class SampleAtmosphereServerTests {
private static Log logger = LogFactory.getLog(SampleAtmosphereServerTests.class);
@Value("${local.server.port}")
private int port = 1234;
@Test
public void chatEndpoint() throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class)
.properties(
"websocket.uri:ws://localhost:" + this.port + "/chat/websocket")
.run("--spring.main.web_environment=false");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
AtomicReference<String> messagePayloadReference = context
.getBean(ClientConfiguration.class).messagePayload;
context.close();
assertThat(count, equalTo(0L));
assertThat(messagePayloadReference.get(),
containsString("{\"message\":\"test\",\"author\":\"test\",\"time\":"));
}
@Configuration
static class ClientConfiguration implements CommandLineRunner {
@Value("${websocket.uri}")
private String webSocketUri;
private final CountDownLatch latch = new CountDownLatch(1);
private final AtomicReference<String> messagePayload = new AtomicReference<String>();
@Override
public void run(String... args) throws Exception {
logger.info("Waiting for response: latch=" + this.latch.getCount());
if (this.latch.await(10, TimeUnit.SECONDS)) {
logger.info("Got response: " + this.messagePayload.get());
}
else {
logger.info("Response not received: latch=" + this.latch.getCount());
}
}
@Bean
public WebSocketConnectionManager wsConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(),
handler(), this.webSocketUri);
manager.setAutoStartup(true);
return manager;
}
@Bean
public StandardWebSocketClient client() {
return new StandardWebSocketClient();
}
@Bean
public TextWebSocketHandler handler() {
return new TextWebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
session.sendMessage(new TextMessage(
"{\"author\":\"test\",\"message\":\"test\"}"));
}
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
logger.info("Received: " + message + " ("
+ ClientConfiguration.this.latch.getCount() + ")");
session.close();
ClientConfiguration.this.messagePayload.set(message.getPayload());
ClientConfiguration.this.latch.countDown();
}
};
}
}
}
| [
"harshil.dhariwal@gmail.com"
] | harshil.dhariwal@gmail.com |
00ebf7edd551dec1ee82b3203a0f548747e280c3 | 29482a8cd1a75b33f043a28e5ade29f96bc79605 | /doji-practice/src/main/java/com/dayton/doji/practice/concurrentPrograming/chap01/demo01/ConcurrencyTest.java | f6d2c34aad9aa9dc46fda393cc26deefd6beb8d0 | [
"Apache-2.0"
] | permissive | dym3093/doji | ced52b7a05391f12c53b60d8312b73982d0d79a2 | 057047bd323540bc818d48687d256208e2494d81 | refs/heads/master | 2023-01-30T07:56:42.712146 | 2020-12-15T14:25:41 | 2020-12-15T14:25:41 | 285,522,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,264 | java | package com.dayton.doji.practice.concurrentPrograming.chap01.demo01;
/**
* @author Martin Deng
* @since 2020-11-16 20:58
*/
public class ConcurrencyTest {
private static final long COUNT = 10000*10000L;
public static void main(String[] args) throws InterruptedException {
concurrency();
serial();
}
/**
* 并发执行
* @return void
* @author Martin Deng
* @since 2020/11/16 21:05
*/
private static void concurrency() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread(() -> {
int a = 0;
for (int i = 0; i < COUNT; i++) {
a += 5;
}
});
thread.start();
int b = 0;
for (int i = 0; i < COUNT; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
thread.join();
System.out.println("concurrency : " + time + " ms, b=" + b );
}
/**
* 串行执行
* @return void
* @author Martin Deng
* @since 2020/11/16 21:05
*/
private static void serial(){
long start = System.currentTimeMillis();
int a = 0;
for (int i = 0; i < COUNT; i++) {
a += 5;
}
int b = 0;
for (int i = 0; i < COUNT; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("serial : " + time + " ms, b=" + b + ", a=" + a);
}
}
| [
"dengyouming@nokia.com"
] | dengyouming@nokia.com |
715d468d3e7a071b71aabdd9b86ee6f3cddce84d | 8936384665bdfdeb87be220bce6ccda7a0a75484 | /app/src/main/java/com/fif/iclass/me/model/MeModel.java | 08784b6d8d565bf2edd80cd302d0fae9ed2b22d1 | [] | no_license | qqchen2593598460/MVPFramework | e6f8cdb694f65fcd61456c5eda946980f827831a | ea86ddbba096be2bbc1e2d0b85fb0dee21f24cea | refs/heads/master | 2020-03-13T10:40:04.559788 | 2018-04-26T09:10:59 | 2018-04-26T09:10:59 | 131,087,931 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 587 | java | package com.fif.iclass.me.model;
import android.util.ArrayMap;
import android.widget.Toast;
import com.fif.baselib.widget.toasty.Toasty;
import com.fif.iclass.common.bean.UpdateBean;
import com.fif.iclass.common.http.NetWorkRequest;
import com.fif.iclass.common.http.NetWorkSubscriber;
import com.fif.iclass.me.contract.MeContract;
/**
* Created by
*/
public class MeModel implements MeContract.MeInterface.MeIModel {
private MeContract.MeInterface.MeIListener listener;
public MeModel(MeContract.MeInterface.MeIListener listener) {
this.listener = listener;
}
}
| [
"2593598460@qq.com"
] | 2593598460@qq.com |
bc266b6bd1ca95864bbd89138b14b1505c10fba0 | 2fa0fcd8afb9b9905f94ff46b9fe989e39e66000 | /accesibilitymodifiers in java/src/pak2/Three.java | 02c9009d9d9a621c9749bdbe194ef0dabf27f9d3 | [] | no_license | nerdseeker365/Core-java | dea9bb5b30500a4cc5827d2777fea57b4ce65b22 | 7823877cef124749da1c6d7c1d90bbbabfd67768 | refs/heads/master | 2022-04-08T14:21:11.553451 | 2020-03-17T04:20:22 | 2020-03-17T04:20:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 507 | java | package pak2;
import access.One;
public class Three extends One {
public static void main(String args[]) {
One o=new One();
Three t=new Three();
//System.out.println(o.a);// error because of private variable not allowed to access another class
//System.out.println(o.b);//package level or default variable not allowed to access another package
System.out.println(Three.c);
//System.out.println(One.c);
//System.out.println(t.c);
System.out.println(o.d);
}
}
| [
"karrasankar158@gmail.com"
] | karrasankar158@gmail.com |
768203c52c56512ab2cd7570bb2cdd14bb986ac3 | c157633108584c813e4c27bca00a766900561abf | /h2o-algos/src/main/java/hex/deeplearning/Dropout.java | 0cb4c1c2d45c1bd966854ea2a43ec67bf75aacdc | [
"Apache-2.0"
] | permissive | voltek62/h2o-3 | 18ef87f6e1cfa5ce4eabcfec59c651c58ed7546f | d581245120bf0cb6fab2bc7e8273b4f41f461448 | refs/heads/master | 2021-01-14T14:02:10.771288 | 2016-05-02T01:28:14 | 2016-05-02T01:28:14 | 57,887,717 | 0 | 0 | Apache-2.0 | 2019-10-13T20:52:43 | 2016-05-02T12:10:05 | Java | UTF-8 | Java | false | false | 2,415 | java | package hex.deeplearning;
import water.util.RandomUtils;
import java.util.Arrays;
import java.util.Random;
/**
* Helper class for dropout training of Neural Nets
*/
public class Dropout {
private transient Random _rand;
private transient byte[] _bits;
private transient double _rate;
public byte[] bits() { return _bits; }
// public Dropout() {
// _rate = 0.5;
// }
@Override
public String toString() {
String s = "Dropout: " + super.toString();
s += "\nRandom: " + _rand.toString();
s += "\nDropout rate: " + _rate;
s += "\nbits: ";
for (int i=0; i< _bits.length*8; ++i) s += unit_active(i) ? "1":"0";
s += "\n";
return s;
}
Dropout(int units) {
_bits = new byte[(units+7)/8];
_rand = RandomUtils.getRNG(0);
_rate = 0.5;
}
Dropout(int units, double rate) {
this(units);
_rate = rate;
}
public void randomlySparsifyActivation(Storage.Vector a, long seed) {
if (a instanceof Storage.DenseVector)
randomlySparsifyActivation((Storage.DenseVector) a, seed);
else if (a instanceof Storage.SparseVector)
randomlySparsifyActivation((Storage.SparseVector)a, seed);
else throw new UnsupportedOperationException("randomlySparsifyActivation not implemented for this type: " + a.getClass().getSimpleName());
}
// for input layer
private void randomlySparsifyActivation(Storage.DenseVector a, long seed) {
if (_rate == 0) return;
setSeed(seed);
for( int i = 0; i < a.size(); i++ )
if (_rand.nextFloat() < _rate) a.set(i, 0);
}
private void randomlySparsifyActivation(Storage.SparseVector a, long seed) {
if (_rate == 0) return;
setSeed(seed);
for (Storage.SparseVector.Iterator it=a.begin(); !it.equals(a.end()); it.next())
if (_rand.nextFloat() < _rate) it.setValue(0f);
}
// for hidden layers
public void fillBytes(long seed) {
setSeed(seed);
if (_rate == 0.5) _rand.nextBytes(_bits);
else {
Arrays.fill(_bits, (byte)0);
for (int i=0;i<_bits.length*8;++i)
if (_rand.nextFloat() > _rate) _bits[i / 8] |= 1 << (i % 8);
}
}
public boolean unit_active(int o) {
return (_bits[o / 8] & (1 << (o % 8))) != 0;
}
private void setSeed(long seed) {
if ((seed >>> 32) < 0x0000ffffL) seed |= 0x5b93000000000000L;
if (((seed << 32) >>> 32) < 0x0000ffffL) seed |= 0xdb910000L;
_rand.setSeed(seed);
}
}
| [
"arno.candel@gmail.com"
] | arno.candel@gmail.com |
0e3454e511d692850f67e642f1ef84ae237a5e5e | 8d33527bcc89572589b48a08b4390629c0de1412 | /Linked List/findLoopHead/FindLoopingListHead.java | 0a85968d9dcdb40ca49ffbbee5f3473bd916910a | [] | no_license | tam0202/CrackingCoding | 45ad40d45a1ab05271144307e34f057543808b4b | 89a1704d5099b07885ff4b0dc0bd678b804d7560 | refs/heads/master | 2021-05-28T07:37:19.372925 | 2015-03-04T04:57:56 | 2015-03-04T04:57:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,465 | java | /*
* Question 2.6: Given a circular linked list, implement an algorithm which returns the
* node at the beginning of the loop
*/
package findLoopHead;
import helper.linkedlist.LinkedListLoop;
import helper.linkedlist.LinkedListNode;
public class FindLoopingListHead {
public static void main (String[] args) {
int[] data = {1, 2, 3, 4, 5, 6, 7, 8};
LinkedListLoop loopedList = new LinkedListLoop(data, 4);
loopedList.printLoopStart();
loopedList.print();
LinkedListNode node = findLoopStart(loopedList.mHead);
node.print();
}
static LinkedListNode findLoopStart (LinkedListNode head) {
LinkedListNode slowRunner = head;
LinkedListNode fastRunner = head;
// Find meeting point. This will be LOOP_SIZE - k steps into the linked list.
while (fastRunner != null && fastRunner.mNext != null) {
slowRunner = slowRunner.mNext;
fastRunner = fastRunner.mNext.mNext;
if (slowRunner == fastRunner) {
break;
}
}
// Error check - no meeting point, and therefore no loop
if (fastRunner == null || fastRunner.mNext == null) {
return null;
}
/* Move slow to Head. Keep fast at Meeting Point. Each are k
* steps from the Loop Start. If they move at the same pace,
* they must meet at Loop Start. */
slowRunner = head;
while (slowRunner != fastRunner) {
slowRunner = slowRunner.mNext;
fastRunner = fastRunner.mNext;
}
// Both now point to the start of the loop
return fastRunner;
}
}
| [
"0002dr@gmail.com"
] | 0002dr@gmail.com |
3ba1944dede6f4f99d48c4e84791fd8e51e9cbbd | befcad493faf7d15614ff1b081e91c17496825c6 | /jax-rs-linker-processor/src/test/resources/query_parameters_misdetection/PeopleResource.java | bd6b49bb95304c474ea84dbe11360e77e14a8277 | [
"MIT"
] | permissive | vidal-community/jax-rs-linker | 1dd465a46e7cae037bc7733299bb26ff18dac00a | 1572ca9a139b6535b4328cc73952097273354bde | refs/heads/master | 2023-04-12T09:56:36.878128 | 2022-07-25T12:39:53 | 2022-07-25T12:46:39 | 27,789,592 | 2 | 0 | MIT | 2023-02-27T11:57:46 | 2014-12-09T22:06:36 | Java | UTF-8 | Java | false | false | 1,130 | java | package query_parameters_misdetection;
import fr.vidal.oss.jax_rs_linker.api.Self;
import fr.vidal.oss.jax_rs_linker.api.SubResource;
import javax.ws.rs.*;
public class PeopleResource {
@GET
@Path("/{id}")
@Self
public Stuff searchById(@PathParam("id") Integer id) {
return null;
}
@GET
@Path("/{id}/friends")
@SubResource(value = PeopleResource.class, qualifier = "friends")
public Stuff findFriendsFilteredByCityOrCountry(@PathParam("id") Integer id,
@BeanParam Localization localization) {
return null;
}
private static class Stuff {}
private static class Localization {
private final String country;
private final String city;
public Localization(@QueryParam("pays") String country,
@QueryParam("ville") String city) {
this.country = country;
this.city = city;
}
public String getCountry() {
return country;
}
public String getCity() {
return city;
}
}
}
| [
"florent.biville@gmail.com"
] | florent.biville@gmail.com |
8895b2bcd1dae57b7e637c4bcd412c27fb2addde | b4cf19d02b4300b11daab82fc9c5445aaf11191b | /src/main/java/com/example/sweater/domain/User.java | e46b50c1dc9ceae43f2c8747fe499a93136284ac | [
"MIT"
] | permissive | IMozgg/sweater | c602ca39b3d49227d18690d3addb9488e684a337 | aeba870dd29b041b355fa43cf5c35b9ae7e04ebe | refs/heads/master | 2020-04-24T12:58:09.968214 | 2019-03-05T20:32:59 | 2019-03-05T20:32:59 | 171,972,108 | 0 | 0 | MIT | 2019-03-05T22:03:36 | 2019-02-22T01:22:28 | Java | UTF-8 | Java | false | false | 1,869 | java | package com.example.sweater.domain;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Set;
@Entity
@Table(name = "usr")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean isActive;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
private Set<Role> roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return isActive;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
| [
"mozgachev.ivan@gmail.com"
] | mozgachev.ivan@gmail.com |
88f853e6abd03be0c0f1f41c3b4affeca39c9ba0 | 45a2b5462cfde59821b73def5a527233a64f51f4 | /app/src/main/java/com/linksu/videofeed/demo/VisibilePercentsUtils.java | faca22c3de5b2782393555d8140d91aed9d432a5 | [
"MIT"
] | permissive | DevAlliances/VideoFeed | 455c869b1eb91167a4f6b9d806f98ed839707950 | 0071e7252dc990a6dd73f8e76599da167eb0ba34 | refs/heads/master | 2021-01-15T22:10:15.459053 | 2017-08-09T11:00:33 | 2017-08-09T11:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,657 | java | package com.linksu.videofeed.demo;
import android.graphics.Rect;
import android.view.View;
/**
* ================================================
* 作 者:linksus
* 版 本:1.0
* 创建日期:7/27 0027
* 描 述:
* 修订历史:
* ================================================
*/
public class VisibilePercentsUtils {
private static VisibilePercentsUtils mVisibilePercentsUtils = null;
private VisibilePercentsUtils() {
}
public static VisibilePercentsUtils getInstance() {
if (mVisibilePercentsUtils == null) {
synchronized (VisibilePercentsUtils.class) {
if (mVisibilePercentsUtils == null) {
mVisibilePercentsUtils = new VisibilePercentsUtils();
}
}
}
return mVisibilePercentsUtils;
}
private final Rect mCurrentViewRect = new Rect();
public int getVisibilityPercents(View view) {
int percents = 100;
view.getLocalVisibleRect(mCurrentViewRect);
int height = view.getHeight();
if (viewIsPartiallyHiddenTop()) {
// view is partially hidden behind the top edge
percents = (height - mCurrentViewRect.top) * 100 / height;
} else if (viewIsPartiallyHiddenBottom(height)) {
percents = mCurrentViewRect.bottom * 100 / height;
}
return percents;
}
private boolean viewIsPartiallyHiddenBottom(int height) {
return mCurrentViewRect.bottom > 0 && mCurrentViewRect.bottom < height;
}
private boolean viewIsPartiallyHiddenTop() {
return mCurrentViewRect.top > 0;
}
}
| [
"1760473022@qq.com"
] | 1760473022@qq.com |
cecd28595edbccd605659d9c187d458c82c65d93 | 015fa633ea034d2be6aaa92aa3e1c663b38877e9 | /src/main/java/array/others/poisk_v_otsortirovanom_masive/ArraySearching.java | 5b739a1d2dee161934c822815bd93cd94d78addb | [] | no_license | programming-practices/java-core | b510a5104f417e670d74b94d62b6beff8d829b44 | 7680e92adc6bb9310ecc401b3768fc66b3ee66c2 | refs/heads/main | 2023-03-15T09:44:59.469839 | 2021-03-01T11:53:50 | 2021-03-01T11:53:50 | 303,077,639 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java | package array.others.poisk_v_otsortirovanom_masive;
import array.others.heneratoru_dannux.RandomGenerator;
import array.others.primenenie_heneratorov_dlya_sozdania_masivov.ConvertTo;
import array.others.primenenie_heneratorov_dlya_sozdania_masivov.Generated;
import others.entities.Generator;
import java.util.Arrays;
public class ArraySearching {
public static void main(String[] args) {
Generator<Integer> gen = new RandomGenerator.Integer(1000);
int[] a = ConvertTo.primitive(Generated.array(new Integer[25], gen));
Arrays.sort(a);
System.out.println("Sorted array: " + Arrays.toString(a));
while (true) {
int r = gen.next();
int location = Arrays.binarySearch(a, r);
if (location >= 0) {
System.out.println("Location of " + r + " is " + location +
", a[" + location + "] = " + a[location]);
break; // Out of while loop
}
}
}
}
| [
"tsyupryk.roman@gmail.com"
] | tsyupryk.roman@gmail.com |
5eaf8ff430617a526e300944a35175c83be7ddbf | 274facced4421d2f54d3630eb223fd4e40620375 | /src/fr/seijuro/PvP/Main.java | 5bd3405ba2b030553f890854b1cde7468284c7a4 | [] | no_license | Gwenzy/1vs1-BlastFight | 8923ceccd059d8a6253949da2a1f5ca31b5aa84f | 059d398a60bf5765ed4b9379246d07d1ded4b112 | refs/heads/master | 2021-01-10T17:44:12.937574 | 2016-01-31T12:09:45 | 2016-01-31T12:09:45 | 50,740,038 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,012 | java | package fr.seijuro.PvP;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
public class Main
extends JavaPlugin
{
private DuelManager duelManager;
private DuelManagerRanked duelManagerRanked;
private List<WaitingPlayer> waitingPlayers;
public void onEnable()
{
this.duelManager = new DuelManager(this);
getServer().getPluginManager().registerEvents(new GameListener(this), this);
this.waitingPlayers = new ArrayList<WaitingPlayer>();
final Main main = this;
//SQLITE INIT
try
{
Connection con;
Statement state;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:plugins/1vs1-Blastfight/data.db");
state = con.createStatement();
state.executeUpdate("CREATE TABLE IF NOT EXISTS Ranked " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" pseudo VARCHAR(16) NOT NULL, " +
" elo INT NOT NULL, " +
" win INT NOT NULL, " +
" lose INT NOT NULL)");
con.close();
}
//Test commentary
catch(Exception e){e.printStackTrace();}
//SQLITE INIT END
Bukkit.getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable(){
@Override
public void run() {
duelManagerRanked = new DuelManagerRanked(main);
// Chaque seconde, on v�rifie les joueurs en file d'attente
//On add une seconde dans leur timer
for(WaitingPlayer wp : waitingPlayers)
{
wp.addSecond();
}
//On check si un joueur dans la plage d'elo 75-125% existe |
for(WaitingPlayer wp : waitingPlayers)
{
//if(wp.)
}
//Si oui, on lance des confirmations aux deux joueurs
//Si les deux acceptent, on les enl�ve de la liste d'attente et on les fait combattre
//On start un duel classique
//Quand un des deux meurt, on effectue le calcul du nouvel elo en fonction de la fonction dans la config
//Si un des deux refuse, on enl�ve celui qui a refus� de la file et on remet l'autre
}
}, 0, 20);
}
public void onDisable() {}
public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args)
{
if (cmdLabel.equalsIgnoreCase("setlobby"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permissions de faire ca.");
return true;
}
if (args.length <= 0)
{
getConfig().set("Lobby.world", p.getLocation().getWorld().getName());
getConfig().set("Lobby.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Lobby.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Lobby.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Lobby.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Lobby.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Lobby du serveur training bien enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setlobby'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setfirst"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("First.world", p.getLocation().getWorld().getName());
getConfig().set("First.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("First.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("First.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("First.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("First.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Premi�re place du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setfirst'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setsecond")) {
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "You don't have permission.");
return true;
}
getConfig().set("Second.world", p.getLocation().getWorld().getName());
getConfig().set("Second.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Second.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Second.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Second.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Second.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Deuxi�me position du combat enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setsecond'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setArena"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Arena.world", p.getLocation().getWorld().getName());
getConfig().set("Arena.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Arena.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Arena.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Arena.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Arena.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Place de combat du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setarena'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setdeath"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Death.world", p.getLocation().getWorld().getName());
getConfig().set("Death.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Death.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Death.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Death.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Death.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Place de mort du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setdeath'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setrankedfirst"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Rankedfirst.world", p.getLocation().getWorld().getName());
getConfig().set("Rankedfirst.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Rankedfirst.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Rankedfirst.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Rankedfirst.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Rankedfirst.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Premi�re place du combat ranked d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setrankedfirst'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setrankedsecond")) {
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "You don't have permission.");
return true;
}
getConfig().set("Rankedsecond.world", p.getLocation().getWorld().getName());
getConfig().set("Rankedsecond.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Rankedsecond.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Rankedsecond.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Rankedsecond.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Rankedsecond.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Deuxi�me position du combat ranked enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setrankedsecond'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
return true;
}
public Location getLobby()
{
Location loc = null;
String world = getConfig().getString("Lobby.world");
double x = getConfig().getDouble("Lobby.x");
double y = getConfig().getDouble("Lobby.y");
double z = getConfig().getDouble("Lobby.z");
float yaw = (float)getConfig().getDouble("Lobby.yaw");
float pitch = (float)getConfig().getDouble("Lobby.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getDeath()
{
Location loc = null;
String world = getConfig().getString("Death.world");
double x = getConfig().getDouble("Death.x");
double y = getConfig().getDouble("Death.y");
double z = getConfig().getDouble("Death.z");
float yaw = (float)getConfig().getDouble("Death.yaw");
float pitch = (float)getConfig().getDouble("Death.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getArena()
{
Location loc = null;
String world = getConfig().getString("Arena.world");
double x = getConfig().getDouble("Arena.x");
double y = getConfig().getDouble("Arena.y");
double z = getConfig().getDouble("Arena.z");
float yaw = (float)getConfig().getDouble("Arena.yaw");
float pitch = (float)getConfig().getDouble("Arena.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getFirst()
{
Location loc = null;
String world = getConfig().getString("First.world");
double x = getConfig().getDouble("First.x");
double y = getConfig().getDouble("First.y");
double z = getConfig().getDouble("First.z");
float yaw = (float)getConfig().getDouble("First.yaw");
float pitch = (float)getConfig().getDouble("First.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getSecond()
{
Location loc = null;
String world = getConfig().getString("Second.world");
double x = getConfig().getDouble("Second.x");
double y = getConfig().getDouble("Second.y");
double z = getConfig().getDouble("Second.z");
float yaw = (float)getConfig().getDouble("Second.yaw");
float pitch = (float)getConfig().getDouble("Second.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public DuelManager getDuelManager()
{
return this.duelManager;
}
public boolean addWaitingPlayer(Player p)
{
if(isPlayerWaiting(p))
return false;
else
{
this.waitingPlayers.add(new WaitingPlayer(p.getUniqueId()));
return true;
}
}
public boolean isPlayerWaiting(Player p)
{
for(WaitingPlayer wp : this.waitingPlayers)
{
if(wp.getUUID().equals(p.getUniqueId()))
return true;
}
return false;
}
public boolean removeWaitingPlayer(Player p)
{
if(isPlayerWaiting(p))
{
for(WaitingPlayer wp : this.waitingPlayers)
{
if(wp.getUUID().equals(p.getUniqueId()))
{
this.waitingPlayers.remove(wp);
return true;
}
}
}
else
return false;
return false;
}
public void clearPlayer(Player p1)
{
p1.getInventory().clear();
p1.getInventory().setArmorContents(null);
for (PotionEffect pe : p1.getActivePotionEffects()) {
p1.removePotionEffect(pe.getType());
}
}
}
| [
"gwendal-lottin@hotmail.fr"
] | gwendal-lottin@hotmail.fr |
080d7cba61e3edc5a96e27d9c6686d2dae40e405 | 4e828f3aec1018c7cdf9ccc9d9f5e6148502e10f | /chapter7-rpc/rpc-transporter/client-api/src/main/java/com/wuhulala/rpc/client/exception/TimeoutException.java | 438dcb35af3f8192004b740065dbc1627a2e02a0 | [] | no_license | Anthony-byte/netty-action | 03b92f3eb3adc3dff868190235f601dd1c88d222 | 787421ca46655d2ee20bd5c206374b14d20d62e3 | refs/heads/master | 2023-03-10T07:44:22.990100 | 2021-02-18T06:24:45 | 2021-02-18T06:24:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,970 | 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 com.wuhulala.rpc.client.exception;
import io.netty.channel.Channel;
import java.net.InetSocketAddress;
/**
* TimeoutException. (API, Prototype, ThreadSafe)
*
* @export
* @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get()
*/
public class TimeoutException extends RemotingException {
public static final int CLIENT_SIDE = 0;
public static final int SERVER_SIDE = 1;
private static final long serialVersionUID = 3122966731958222692L;
private final int phase;
public TimeoutException(boolean serverSide, Channel channel, String message) {
super(channel, message);
this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE;
}
public TimeoutException(boolean serverSide, InetSocketAddress localAddress,
InetSocketAddress remoteAddress, String message) {
super(localAddress, remoteAddress, message);
this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE;
}
public int getPhase() {
return phase;
}
public boolean isServerSide() {
return phase == 1;
}
public boolean isClientSide() {
return phase == 0;
}
} | [
"370031044@qq.com"
] | 370031044@qq.com |
bea178d68d8c71cc6ed7873c1f5ae324a293a169 | 6511f9cd8fbd37499294e5a9f50a4bc73b75ed8e | /lib/lib-beans/src/test/java/com/gainmatrix/lib/paging/pager/impl/ForecastPagerTest.java | a0553142aa4793c3165e537bb0ae275e892e7d1f | [
"Apache-2.0"
] | permissive | mazurkin/gainmatrix | 736cce1e97d83c987ac0a4fab96bd5ac31cba952 | 296766e8516035275287954ffe85dcecbcd9bebe | refs/heads/master | 2021-03-12T23:39:23.105356 | 2015-09-30T15:29:44 | 2015-09-30T15:29:44 | 41,808,921 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,682 | java | package com.gainmatrix.lib.paging.pager.impl;
import com.gainmatrix.lib.paging.Extraction;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ForecastPagerTest {
@Test
public void testAll() {
ForecastPager pager = new ForecastPager();
pager.setPageSize(10);
pager.setForecast(2);
pager.setPageLimit(100);
Extraction extraction;
List<String> list;
//
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(0, pager.getPageCount());
//
extraction = pager.getExtraction();
Assert.assertEquals(0, extraction.getOffset());
Assert.assertEquals(21, extraction.getCount());
//
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(3, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(2, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(2, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(0, list.size());
//
pager.setPage(0);
Assert.assertEquals(1, pager.getPage());
pager.setPage(10000000);
Assert.assertEquals(100, pager.getPage());
//
pager.setPage(12);
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(14, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(13, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(13, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(0, list.size());
//
pager.setPage(99);
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(0, list.size());
}
}
| [
"mazurkin@gmail.com"
] | mazurkin@gmail.com |
724194728fcfdc8886fc98c13f26262a9e5332da | 4a04de6d4bb9972e0e2e30082d58f68a33c5e1c4 | /src/br/com/trainee_tqi/modelo/Cliente.java | 9a1c0d717af6aa76e7d0dab13d306b0ecd9e5870 | [] | no_license | alexandrecvf/Trainee_TQI | e6638c3ca086bb3c0d1d9863af2ffa6d48c3c0f2 | 770402b77ebaf9ab5ad7e87b8ec42524a7ead4ed | refs/heads/master | 2022-12-07T21:17:59.761913 | 2020-09-01T02:35:43 | 2020-09-01T02:35:43 | 290,641,185 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,360 | java | package br.com.trainee_tqi.modelo;
/**
* <h1>Classe Modelo Cliente</h1>
* Modelo de cliente da aplicação. Possui todos os atributos do cliente e ainda seus getters e setters.
*
* @author Alexandre Vilarinho
*/
public class Cliente {
/** Id do cliente*/
Long id;
/** Nome do cliente*/
String nome;
/** CPF do cliente*/
String cpf;
/** RG do cliente*/
String rg;
/** Telefone do cliente*/
String telefone;
/** E-mail do cliente*/
String email;
/** Senha do cliente*/
String senha;
/** Endereço do cliente*/
String endereco;
/** CEP do cliente*/
String cep;
/** Renda mensal do cliente*/
float renda_mensal;
/** Recebe o id
* @return id id do cliente
* */
public Long getId() {
return id;
}
/**Define o id do cliente.
*
* @param id Id do cliente
* */
public void setId(Long id) {
this.id = id;
}
/** Recebe o nome do cliente.
* @return nome Nome do cliente
* */
public String getNome() {
return nome;
}
/**Define o nome do cliente.
*
* @param nome Nome do cliente.
* */
public void setNome(String nome) {
this.nome = nome;
}
/** Recebe o CPF do cliente
* @return cpf CPF do cliente
* */
public String getCpf() {
return cpf;
}
/**Define o CPF do cliente
*
* @param cpf CPF do cliente.
* */
public void setCpf(String cpf) {
this.cpf = cpf;
}
/** Recebe o RG do cliente
* @return rg RG do cliente
* */
public String getRg() {
return rg;
}
/**Define o RG do cliente.
*
* @param rg RG do cliente.
* */
public void setRg(String rg) {
this.rg = rg;
}
/** Recebe o telefone do cliente.
* @return telefone Telefone do cliente.
* */
public String getTelefone() {
return telefone;
}
/**Define o telefone do cliente.
*
* @param telefone Telefone do cliente.
* */
public void setTelefone(String telefone) {
this.telefone = telefone;
}
/** Recebe o e-mail do cliente.
* @return email E-mail do cliente.
* */
public String getEmail() {
return email;
}
/**
* Define o e-mail do cliente.
*
* @param email E-mail do cliente.
* */
public void setEmail(String email) {
this.email = email;
}
/** Recebe o endereço do cliente
* @return endereco Endereço do cliente.
* */
public String getEndereco() {
return endereco;
}
/**Define o endereço do cliente.
*
* @param endereco Endereço do cliente.
* */
public void setEndereco(String endereco) {
this.endereco = endereco;
}
/** Recebe o CEP do cliente.
* @return cep CEP do cliente.
* */
public String getCep() {
return cep;
}
/** Define o CEP do cliente
*
* @param cep CEP do cliente
* */
public void setCep(String cep) {
this.cep = cep;
}
/** Recebe a renda mensal do cliente.
* @return renda_mensal Renda mensal do cliente.
* */
public float getRenda_mensal() {
return renda_mensal;
}
/** Define a renda mensal do cliente
*
* @param renda_mensal Renda mensal do cliente.
* */
public void setRenda_mensal(float renda_mensal) {
this.renda_mensal = renda_mensal;
}
/** Recebe a senha do cliente
* @return senha Senha do cliente.
* */
public String getSenha() {
return senha;
}
/** Define a senha do cliente
*
* @param senha Senha do cliente.
* */
public void setSenha(String senha) {
this.senha = senha;
}
}
| [
"33914918+alexandrecvf@users.noreply.github.com"
] | 33914918+alexandrecvf@users.noreply.github.com |
a74543b23ab29015cb4fe2006f54b684cdc38ba7 | 563eea2b0615e9b534b8db4a61a7e1ab4ec49cf6 | /lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.java | 37b4b9ac2a2a50b9f66b76a74ee6bcaff85d32ff | [] | no_license | prabhakaran302/leetcode | a20207ba6cca87111d23ee905ce8ce6fd63b5c22 | 93c9f14b1bd1f44367eafec0941e660fff5df579 | refs/heads/main | 2023-09-03T13:45:55.432595 | 2021-11-19T06:31:49 | 2021-11-19T06:31:49 | 235,970,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 654 | java | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(root == p || root == q)
return root;
TreeNode l = lowestCommonAncestor(root.left, p , q);
TreeNode r = lowestCommonAncestor(root.right, p , q);
if(l != null && r != null)
return root;
return l == null ? r : l;
}
} | [
"prabhakaran.nivanil@gmail.com"
] | prabhakaran.nivanil@gmail.com |
cd99258e3b843a6acd1c6adff730293fd4e082d9 | d0697b92f898c08ab262c6f7aa5086a89b3215f6 | /Assignments/A3/davinder_Weather/app/src/main/java/com/dv/davinder_weather/models/LocationContainer.java | 7e1de5d2f25aa11e569a5220bf9b57720ec9120e | [] | no_license | shersingh7/MAP524 | dc94ec2d299a502e49d38d45982f1f9620224411 | fb622885dacf3848467620bb75d923a087ff0cd4 | refs/heads/master | 2023-06-30T22:58:19.385609 | 2021-08-10T13:35:17 | 2021-08-10T13:35:17 | 370,216,667 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 322 | java | package com.dv.davinder_weather.models;
import com.google.gson.annotations.SerializedName;
public class LocationContainer {
@SerializedName("location")
private Location location;
public Location getLocation() {return location;}
public void setWeather(Location location) {this.location = location;}
}
| [
"66485246+shersingh7@users.noreply.github.com"
] | 66485246+shersingh7@users.noreply.github.com |
d7b9567266c279551116aaa2095d2a4e4a51c3eb | 0e106521124839fb6831c3d918c75d25647f9bcf | /swing-util/src/main/java/nl/fw/swing/KeyAction.java | 7d032eac5a02a3e645c7da0e4a50c5917e41b884 | [] | no_license | fwi/HVLayout | 73419eecfd5523f1c286b400e441f24c285d6c44 | b623d6102552cc0356dfc25ae607bc8ae7ab2d39 | refs/heads/master | 2020-04-05T04:26:06.033310 | 2018-02-24T15:57:41 | 2018-02-24T15:58:21 | 21,492,747 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,656 | java | /*
* This software is licensed under the GNU Lesser GPL, see
* http://www.gnu.org/licenses/ for details.
* You can use this free software in commercial and non-commercial products,
* as long as you give credit to this software when you use it.
* This softwware is provided "as is" and the use of this software is
* completely at your own risk, there are absolutely no warranties.
*
*/
package nl.fw.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
/**
* An action associated with a key that can be put into an action map so that
* an action-event is fired for the appropriate event listener
* (usually a button). When the cancel-event listener is also
* related to a keyboard action (Escape key for example) via an input map,
* a window can respond properly to a user pressing the Escape key to
* indicate he/she wants to "close the window without storing changes".
* <br> See OkCancelDialog.init() for an implementation example.
* @author Fred
*
*/
public class KeyAction extends AbstractAction {
private static final long serialVersionUID = -206322771023763629L;
public static final String KEY_ACTION = "KeyAction";
private final ActionListener keyListener;
private final ActionEvent keyEvent;
public KeyAction(Object keySource, ActionListener keyActionlistener) {
super();
keyListener = keyActionlistener;
keyEvent = new ActionEvent(keySource, ActionEvent.ACTION_PERFORMED, KEY_ACTION);
}
@Override
public void actionPerformed(ActionEvent e) {
keyListener.actionPerformed(keyEvent);
}
}
| [
"frederik.wiers@gmail.com"
] | frederik.wiers@gmail.com |
ee9e001749bfe96c7c0d5913fd9f5580c5cbac28 | 3c106005060f5e58c2a4aa8ee1f11750da86260a | /src/afi/Day13.java | a65bd17a9465ebedec0575a2ce2b44bf85e484a0 | [] | no_license | gauravmahajan25/corejava | 71d11a80e0ddd2ff2f4d39eba9d17a01fd8fcdcf | da02845a98e86078bb392de97e376d3fb7ed547f | refs/heads/master | 2020-12-31T00:17:17.571167 | 2017-03-29T08:16:21 | 2017-03-29T08:16:21 | 86,555,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package afi;
import java.util.*;
abstract class Book
{
String title;
String author;
Book(String t,String a){
title=t;
author=a;
}
abstract void display();
}
class MyBook extends Book {
int price;
MyBook(String title, String author, int price) {
super(title, author);
this.price = price;
}
void display() {
System.out.println("Title: "+this.title);
System.out.println("Author: "+this.author);
System.out.println("Price: "+this.price);
}
}
public class Day13 {
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
String title=sc.nextLine();
String author=sc.nextLine();
int price=sc.nextInt();
Book new_novel=new MyBook(title,author,price);
new_novel.display();
}
}
| [
"gaurav.mahajan25@gmail.com"
] | gaurav.mahajan25@gmail.com |
0de9af8cf684c4f9de73e3a159da46224992c401 | 92c90af534a0aabfe99015cb101e7693f7c3d902 | /src/main/java/com/wh/test/util/SystemEnv.java | 2151f9420250404a6f73dddd82b3122040f5854f | [] | no_license | leizton/whtest | 5b5b0a7d18a8aa0ac9d5249487a3453d0e3e2c5c | 29557397a722b38b7f65ecf048cdec911e9ab667 | refs/heads/master | 2022-12-03T18:27:16.219870 | 2020-07-16T05:51:28 | 2020-07-16T05:51:28 | 131,404,466 | 0 | 0 | null | 2022-11-16T07:50:39 | 2018-04-28T11:39:59 | Java | UTF-8 | Java | false | false | 166 | java | package com.wh.test.util;
/**
* 2018/4/28
*/
public class SystemEnv {
public static String getUserHomeDir() {
return System.getProperty("user.home");
}
}
| [
"leizton@126.com"
] | leizton@126.com |
fea1ff2486afd3c81375963e9a49dd7f6bc69f46 | a9b2cf65bb01492e74715dda9c18122ad1d6b02a | /Java-Study-Tasks/src/PrimeNumbersArrayList.java | 6c76b09570fef24ecda67bd05102d2202018103a | [] | no_license | StoyanKerkelov/Java-programming-Exercises | 310e8797b251c5ddf13862ea817a0b9cf77b942d | 9c24c0b2335a69ef3646cb8e10065bda4814549d | refs/heads/master | 2021-01-01T18:20:04.651417 | 2017-07-25T13:55:09 | 2017-07-25T13:55:09 | 98,307,985 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 704 | java | import java.util.ArrayList;
public class PrimeNumbersArrayList {
//Write a method that finds all primes in set interval of numbers
public static ArrayList<Integer> getPrimes(int start, int end) {
ArrayList<Integer> primesList = new ArrayList<Integer>();
for (int num = start; num <= end; num++) {
boolean prime = true;
for (int div = 2; div <= Math.sqrt(num); div++) {
if (num % div == 0) {
prime = false;
break;
}
}
if (prime)
primesList.add(num);
}
return primesList;
}
public static void main(String[] args) {
ArrayList<Integer> primes = getPrimes(1460, 2002);
for (int p : primes) {
System.out.printf("%d ", p);
}
System.out.println();
}
}
| [
"stoyan.v.kerkelov@gmail.com"
] | stoyan.v.kerkelov@gmail.com |
994bc9cecd9c932f7f1385a48dabb185d538a6cb | c8621066f7d3c13d5a33c1b2c73f6c22c45c7624 | /src/Client.java | b04da9f4a9955c01d5ee82bafb137d651ea9f31c | [] | no_license | DISCoders81/DIS5 | db8a9311caac970cdb96b81bfb650ca45073fa6f | 45adc6aff3fda1d27c5e3ccfaf9f296f33042c61 | refs/heads/master | 2020-12-24T17:08:10.830631 | 2014-05-26T00:45:25 | 2014-05-26T00:45:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,200 | java | /**
* @author joantomaspape This class represents a database client. The 5
* different clients have access to disjunctive sets of pages, thus
* making the access mutually exclusive.
*/
public class Client extends Thread {
int clientId;
int minPage;
int maxPage;
Transaction currentTa;
public Client(int clientId) {
this.clientId = clientId;
this.minPage = clientId * 10;
this.maxPage = minPage + 9;
}
public void run() {
int actPage = minPage;
while (actPage <= maxPage)
{
try
{
beginTransaction();
Client.sleep(1000);
write("Erster Eintrag Für Transaction " + currentTa.getTaId(),
actPage);
actPage++;
Client.sleep(1500);
write("Zweiter Eintrag Für Transaction " + currentTa.getTaId(),
actPage);
actPage++;
Client.sleep(1200);
commit();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
private void beginTransaction() {
currentTa = PersistanceManager.getInstance().beginTransaction();
}
private void write(String data, int actPage) {
currentTa.write(actPage, data);
}
private void commit() {
PersistanceManager.getInstance().commit(currentTa);
}
}
| [
"joanpape@gmx.de"
] | joanpape@gmx.de |
7bafa068b57e3eb94967924c029ab58739dad51f | cc153bdc1238b6888d309939fc683e6d1589df80 | /commonsys/qrdplus/Extension/apps/SimContacts/src/com/android/contacts/format/FormatUtils.java | cf8a81b4ca2d34707e470e15e9f500973c028ee3 | [
"Apache-2.0"
] | permissive | ml-think-tanks/msm8996-vendor | bb9aa72dabe59a9bd9158cd7a6e350a287fa6a35 | b506122cefbe34508214e0bc6a57941a1bfbbe97 | refs/heads/master | 2022-10-21T17:39:51.458074 | 2020-06-18T08:35:56 | 2020-06-18T08:35:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,930 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.android.contacts.format;
import android.database.CharArrayBuffer;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import java.util.Arrays;
/**
* Assorted utility methods related to text formatting in Contacts.
*/
public class FormatUtils {
/**
* Finds the earliest point in buffer1 at which the first part of buffer2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(CharArrayBuffer buffer1, CharArrayBuffer buffer2) {
if (buffer1 == null || buffer2 == null) {
return -1;
}
return overlapPoint(Arrays.copyOfRange(buffer1.data, 0, buffer1.sizeCopied),
Arrays.copyOfRange(buffer2.data, 0, buffer2.sizeCopied));
}
/**
* Finds the earliest point in string1 at which the first part of string2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(String string1, String string2) {
if (string1 == null || string2 == null) {
return -1;
}
return overlapPoint(string1.toCharArray(), string2.toCharArray());
}
/**
* Finds the earliest point in array1 at which the first part of array2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(char[] array1, char[] array2) {
if (array1 == null || array2 == null) {
return -1;
}
int count1 = array1.length;
int count2 = array2.length;
// Ignore matching tails of the two arrays.
while (count1 > 0 && count2 > 0 && array1[count1 - 1] == array2[count2 - 1]) {
count1--;
count2--;
}
int size = count2;
for (int i = 0; i < count1; i++) {
if (i + size > count1) {
size = count1 - i;
}
int j;
for (j = 0; j < size; j++) {
if (array1[i+j] != array2[j]) {
break;
}
}
if (j == size) {
return i;
}
}
return -1;
}
/**
* Applies the given style to a range of the input CharSequence.
* @param style The style to apply (see the style constants in {@link Typeface}).
* @param input The CharSequence to style.
* @param start Starting index of the range to style (will be clamped to be a minimum of 0).
* @param end Ending index of the range to style (will be clamped to a maximum of the input
* length).
* @param flags Bitmask for configuring behavior of the span. See {@link android.text.Spanned}.
* @return The styled CharSequence.
*/
public static CharSequence applyStyleToSpan(int style, CharSequence input, int start, int end,
int flags) {
// Enforce bounds of the char sequence.
start = Math.max(0, start);
end = Math.min(input.length(), end);
SpannableString text = new SpannableString(input);
text.setSpan(new StyleSpan(style), start, end, flags);
return text;
}
public static void copyToCharArrayBuffer(String text, CharArrayBuffer buffer) {
if (text != null) {
char[] data = buffer.data;
if (data == null || data.length < text.length()) {
buffer.data = text.toCharArray();
} else {
text.getChars(0, text.length(), data, 0);
}
buffer.sizeCopied = text.length();
} else {
buffer.sizeCopied = 0;
}
}
/** Returns a String that represents the content of the given {@link CharArrayBuffer}. */
public static String charArrayBufferToString(CharArrayBuffer buffer) {
return new String(buffer.data, 0, buffer.sizeCopied);
}
/**
* Finds the index of the first word that starts with the given prefix.
* <p>
* If not found, returns -1.
*
* @param text the text in which to search for the prefix
* @param prefix the text to find, in upper case letters
*/
public static int indexOfWordPrefix(CharSequence text, String prefix) {
if (prefix == null || text == null) {
return -1;
}
int textLength = text.length();
int prefixLength = prefix.length();
if (prefixLength == 0 || textLength < prefixLength) {
return -1;
}
int i = 0;
while (i < textLength) {
// Skip non-word characters
while (i < textLength && !Character.isLetterOrDigit(text.charAt(i))) {
i++;
}
if (i + prefixLength > textLength) {
return -1;
}
// Compare the prefixes
int j;
for (j = 0; j < prefixLength; j++) {
if (Character.toUpperCase(text.charAt(i + j)) != prefix.charAt(j)) {
break;
}
}
if (j == prefixLength) {
return i;
}
// Skip this word
while (i < textLength && Character.isLetterOrDigit(text.charAt(i))) {
i++;
}
}
return -1;
}
}
| [
"deepakjeganathan@gmail.com"
] | deepakjeganathan@gmail.com |
0f02fd50857d6db5ff5177d95840bcbe47595d10 | 44316c9065993113d9c3c942b8112a16d089d1e8 | /src/other/UseInterface.java | b6112e36b1931ff72af1adaf69dac78179f87d25 | [] | no_license | gjain3693/Core-Java-Concepts | 31dad3150b2fe4b24b49cf6bf753fa4f7d9ea092 | b48d3baa63a9682f75863751f6fad3ce1d3bd6d6 | refs/heads/master | 2021-07-23T12:14:34.953296 | 2017-11-03T15:18:54 | 2017-11-03T15:18:54 | 106,716,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package other;
public class UseInterface implements Mobile {
@Override
public void dialing() {
System.out.println("Method of Interface");
}
public void extraMethod() {
System.out.println("Method Implementer");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
UseInterface useInterface = new UseInterface();
Mobile mobile = new UseInterface();
mobile.dialing();
useInterface.dialing();
}
}
| [
"gjain3693@gmail.com"
] | gjain3693@gmail.com |
8cf2ac6394f3c35abeb2b67e17bbae594472ba45 | de5b95b8e71772adbe5a456420879e68b0981b14 | /src/main/java/com/example/marketinnovation/exception/UnexpectedException.java | f4f6b5a72e5f211e56705dbf141573ef23668f90 | [] | no_license | paolamfz/inventory-innovation | 284b4a67965f6d62c39a24a2520a267e7d71b105 | 22d2abfd222ba66492fbf2ac449c8c42a6bc7a90 | refs/heads/master | 2023-08-05T09:55:58.756235 | 2021-09-24T03:12:05 | 2021-09-24T03:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 845 | java | /**
* @author: Edson A. Terceros T.
*/
package com.example.marketinnovation.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class UnexpectedException extends RuntimeException {
public UnexpectedException() {
super();
}
public UnexpectedException(String message) {
super(message);
}
public UnexpectedException(String message, Throwable cause) {
super(message, cause);
}
public UnexpectedException(Throwable cause) {
super(cause);
}
protected UnexpectedException(String message, Throwable cause, boolean enableSuppression, boolean
writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| [
"edsonrosas321@gmail.com"
] | edsonrosas321@gmail.com |
7b083e82cd643b82c6f7b1e9da47c83f3039a2ff | 65846e42555dfd9154e34d04a1926ecc53667429 | /app/src/main/java/moodlistener/blusay/model/MoodModel.java | dd01916ece31a43af07c293093c3b50b59808d0a | [
"Apache-2.0"
] | permissive | laimich/Blusay | afd76a499d987c5ea19d0d2ec6a301b2bdb40a87 | 7a0e5fa37a035b65e26a5e8b437a49ab6ed47f0a | refs/heads/master | 2021-01-22T07:48:01.165676 | 2017-12-30T00:18:06 | 2017-12-30T00:18:06 | 92,576,722 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 439 | java | package moodlistener.blusay.model;
import moodlistener.blusay.item.*;
import java.util.ArrayList;
/**
* Created by Michelle on 6/13/2017.
*/
public class MoodModel {
//for current user
private Account currentUser;
private Mood selectedMood;
private String display; //can be "light" or "dark"
//for saved info
//private AccountUnlocked unlockedAccount;
//private ArrayList<AccountLocked> lockedAccounts;
}
| [
"laimich3@gmail.com"
] | laimich3@gmail.com |
a6a33dc6f2a4ecd0031d74e9b9bc8afaf9723c6d | 8c7ddcdbed59ee4547121db4381519edfebc2031 | /ep-pthread-ep3/Monitor.java | a498d1f1bbf9dcc6d18149fa504f7e853a46dca7 | [] | no_license | evandrofg/EP | be0552e7a1b8611ec9156dbe1d9a74a3e4dae4e2 | a6450698fa5a098230fbf07c5cb716ce4bb41a05 | refs/heads/master | 2020-09-25T11:12:28.310762 | 2016-08-24T19:18:46 | 2016-08-24T19:18:46 | 66,492,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,247 | java | public class Monitor {
private int contents;
private int Capacidade;
private int Repeticoes;
private int Contador;
private boolean ControleProdutor;
private boolean ControleConsumidor;
private boolean full = false;
private boolean empty = true;
public Monitor(int C, int R){
this.Capacidade = C;
this.Repeticoes = R;
this.Contador = 0;
this.ControleProdutor = true;
this.ControleConsumidor = true;
}
void signal() { super.notify(); }
void signal_all() { super.notifyAll(); }
public synchronized boolean get(int who, int cont) {
if (ControleConsumidor == false) return false;
while (empty == true) {
try {
wait();
} catch (InterruptedException e) { }
}
// se nao temos mais porcoes, para
if (ControleConsumidor == false) return false;
contents--;
System.out.println("Selvagem " + who + " pegou sua porção n° " + cont + ", restam " + contents +" no prato.");
if (contents == 0){
System.out.println("Selvagem " + who + " notou o pote vazio.");
empty = true;
if (ControleProdutor == false) // ninguem vai produzir mais; sair
ControleConsumidor = false;
}
full = false;
signal_all();
return ControleConsumidor;
}
public synchronized boolean enche_prato(int who, int cont) {
if (ControleProdutor == false) return false;
while (empty == false) {
try {
wait();
} catch (InterruptedException e) { }
}
// se algum produtor ja produziu o ultimo, esse termina
if (ControleProdutor == false)
return false;
contents = Capacidade;
Contador++;
full = true;
empty = false;
System.out.println("Cozinheiro " + who + " encheu o prato pela " + cont + "ª vez.");
signal_all();
if (Contador == Repeticoes){
ControleProdutor = false;
//System.out.println("Parando após " + Contador + " repetições." );
}
return ControleProdutor;
}
}
| [
"efgiovanini@gmail.com"
] | efgiovanini@gmail.com |
6ba3c24c3a0d6e484f388459687197511805ccc2 | 09d0ddd512472a10bab82c912b66cbb13113fcbf | /TestApplications/WhereYouGo-0.9.3-beta/DecompiledCode/Fernflower/src/main/java/menion/android/whereyougo/gui/extension/DataInfo.java | 84e689d15ec9fe4c097c0129d49ff3ea0525918f | [] | no_license | sgros/activity_flow_plugin | bde2de3745d95e8097c053795c9e990c829a88f4 | 9e59f8b3adacf078946990db9c58f4965a5ccb48 | refs/heads/master | 2020-06-19T02:39:13.865609 | 2019-07-08T20:17:28 | 2019-07-08T20:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,235 | java | package menion.android.whereyougo.gui.extension;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import menion.android.whereyougo.geo.location.Location;
public class DataInfo implements Comparable {
private static final String TAG = "DataInfo";
public Object addData01;
public Object addData02;
private double azimuth;
private String description;
private double distance;
public boolean enabled;
private int id;
private int image;
private Bitmap imageB;
private Drawable imageD;
private Bitmap imageRight;
private String name;
public double value01;
public double value02;
public DataInfo(int var1, String var2) {
this(var1, var2, "", -1);
}
public DataInfo(int var1, String var2, Bitmap var3) {
this(var1, var2, "", var3);
}
public DataInfo(int var1, String var2, String var3) {
this(var1, var2, var3, -1);
}
public DataInfo(int var1, String var2, String var3, int var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.image = var4;
}
public DataInfo(int var1, String var2, String var3, Bitmap var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.imageB = var4;
}
public DataInfo(int var1, String var2, String var3, Drawable var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.imageD = var4;
}
public DataInfo(String var1) {
this(-1, var1, "", -1);
}
public DataInfo(String var1, String var2) {
this(-1, var1, var2, -1);
}
public DataInfo(String var1, String var2, int var3) {
this(-1, var1, var2, var3);
}
public DataInfo(String var1, String var2, Bitmap var3) {
this(-1, var1, var2, (Bitmap)var3);
}
public DataInfo(String var1, String var2, Drawable var3) {
this(-1, var1, var2, (Drawable)var3);
}
public DataInfo(String var1, String var2, Object var3) {
this(-1, var1, var2, -1);
this.addData01 = var3;
}
public DataInfo(DataInfo var1) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.id = var1.id;
this.name = var1.name;
this.description = var1.description;
this.image = var1.image;
this.imageD = var1.imageD;
this.imageB = var1.imageB;
this.imageRight = var1.imageRight;
this.value01 = var1.value01;
this.value02 = var1.value02;
this.distance = var1.distance;
this.addData01 = var1.addData01;
}
private void setBasics(int var1, String var2, String var3) {
this.id = var1;
this.name = var2;
this.description = var3;
this.image = -1;
this.imageD = null;
this.imageB = null;
this.imageRight = null;
}
public void addDescription(String var1) {
if (this.description != null && this.description.length() != 0) {
this.description = this.description + ", " + var1;
} else {
this.description = var1;
}
}
public void clearDistAzi() {
this.distance = -1.0D;
}
public int compareTo(DataInfo var1) {
return this.name.compareTo(var1.getName());
}
public String getDescription() {
return this.description;
}
public int getId() {
return this.id;
}
public int getImage() {
return this.image;
}
public Bitmap getImageB() {
return this.imageB;
}
public Drawable getImageD() {
return this.imageD;
}
public Bitmap getImageRight() {
return this.imageRight;
}
public Location getLocation() {
Location var1 = new Location("DataInfo");
var1.setLatitude(this.value01);
var1.setLongitude(this.value02);
return var1;
}
public String getName() {
return this.name;
}
public boolean isDistAziSet() {
boolean var1;
if (this.distance != -1.0D) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
public DataInfo setAddData01(Object var1) {
this.addData01 = var1;
return this;
}
public void setCoordinates(double var1, double var3) {
this.value01 = var1;
this.value02 = var3;
}
public void setDescription(String var1) {
this.description = var1;
}
public void setDistAzi(float var1, float var2) {
this.distance = (double)var1;
this.azimuth = (double)var2;
}
public void setDistAzi(Location var1) {
Location var2 = this.getLocation();
this.distance = (double)var1.distanceTo(var2);
this.azimuth = (double)var1.bearingTo(var2);
}
public void setId(int var1) {
this.id = var1;
}
public void setImage(int var1) {
this.image = var1;
}
public void setImage(Bitmap var1) {
this.imageB = var1;
}
public DataInfo setImageRight(Bitmap var1) {
this.imageRight = var1;
return this;
}
public void setName(String var1) {
this.name = var1;
}
public String toString() {
return this.getName();
}
}
| [
"crash@home.home.hr"
] | crash@home.home.hr |
e83ddc0a61628871cbacab88c4ddd36504562fa2 | 94adf73463b12ced810d6c5ce56ea0c273df8aa1 | /user-service/src/main/java/com/cgs/dao/ResourceDAO.java | cc2e52542204a632c8899874a939336b8ef179da | [] | no_license | duanmuhan/user | 2d15459106072756f592ca3e0da0d8217ef26316 | c976dfc111e509115c5f907fa88f712d8fb34499 | refs/heads/master | 2023-03-02T09:21:24.715511 | 2021-02-08T16:40:19 | 2021-02-08T16:40:19 | 300,297,302 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | package com.cgs.dao;
import com.cgs.po.ResourcePO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author caoguangshu
* @date 2020/12/13
* @time 下午3:00
*/
@Repository
public interface ResourceDAO {
String TABLE_NAME = "resource_info";
String COLUMNS = "resource_id, resource_name, valid, description";
@Results( id = "resultMap",value = {
@Result(property = "resourceId",column = "resource_id"),
@Result(property = "name",column = "name"),
@Result(property = "description",column = "description"),
@Result(property = "valid",column = "valid")
})
@Insert("insert into " + TABLE_NAME + "(" + COLUMNS + ")"
+ " values (#{resource.resourceId}, #{resource.name}, #{resource.description}, #{resource.valid} )")
void addResource(@Param("resource") ResourcePO resourcePO);
@Select("select * from " + TABLE_NAME + " where valid = 1 ")
@ResultMap(value = "resultMap")
List<ResourcePO> queryAllResources();
}
| [
"caoguangshu@corp.netease.com"
] | caoguangshu@corp.netease.com |
94d449ef0515096de35517414292f4a9b8d11c54 | baba7ae4f32f0e680f084effcd658890183e7710 | /MutationFramework/muJava/src/mujava/cmd/MutantsGenerator.java | bfa7dbd5c6822abbe76736f4b01e80d769b28183 | [
"Apache-2.0"
] | permissive | TUBS-ISF/MutationAnalysisForDBC-FormaliSE21 | 75972c823c3c358494d2a2e9ec12e0a00e26d771 | de825bc9e743db851f5ec1c5133dca3f04d20bad | refs/heads/main | 2023-04-22T21:29:28.165271 | 2021-05-17T07:43:22 | 2021-05-17T07:43:22 | 368,096,901 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,101 | java | /**
* Copyright (C) 2015 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 src.mujava.cmd;
import java.io.*;
import src.mujava.*;
import src.mujava.util.Debug;
/**
* <p>
* Description:
* </p>
*
* @author Jeff Offutt and Yu-Seung Ma
* @version 1.0
*
*/
public class MutantsGenerator {
static public void generateMutants(String[] file_names){
generateMutants(file_names,MutationSystem.cm_operators, MutationSystem.tm_operators);
}
static public void generateClassMutants(String[] file_names){
generateMutants(file_names,MutationSystem.cm_operators, null);
}
static public void generateClassMutants(String[] file_names, String[] class_ops){
generateMutants(file_names,class_ops, null);
}
static public void generateTraditionalMutants(String[] file_names){
generateMutants(file_names, null, MutationSystem.tm_operators);
}
static public void generateTraditionalMutants(String[] file_names,String[] traditional_ops){
generateMutants(file_names, null,traditional_ops );
}
static public void generateMutants(String[] file_names, String[] class_ops, String[] traditional_ops){
// file_names = Relative path from MutationSystem.SRC_PATH
String file_name;
for(int i=0;i<file_names.length;i++){
file_name = file_names[i];
System.out.println(file_name);
try{
System.out.println(i+" : " +file_name);
String temp = file_name.substring(0,file_name.length()-".java".length());
String class_name="";
for(int ii=0;ii<temp.length();ii++){
if( (temp.charAt(ii)=='\\') || (temp.charAt(ii)=='/') ){
class_name = class_name + ".";
}else{
class_name = class_name + temp.charAt(ii);
}
}
// Class c = Class.forName(class_name);
int class_type = MutationSystem.getClassType(class_name);
if(class_type==MutationSystem.NORMAL){
}else if(class_type==MutationSystem.MAIN){
System.out.println(" -- " + file_name+ " class contains 'static void main()' method.");
System.out.println(" Pleas note that mutants are not generated for the 'static void main()' method");
}else{
switch(class_type){
case MutationSystem.MAIN :
System.out.println(" -- Can't apply because " + file_name+ " contains only 'static void main()' method.");
break;
case MutationSystem.INTERFACE :
System.out.println(" -- Can't apply because " + file_name+ " is 'interface' ");
break;
case MutationSystem.ABSTRACT :
System.out.println(" -- Can't apply because " + file_name+ " is 'abstract' class ");
break;
case MutationSystem.APPLET :
System.out.println(" -- Can't apply because " + file_name+ " is 'applet' class ");
break;
case MutationSystem.GUI :
System.out.println(" -- Can't apply because " + file_name+ " is 'GUI' class ");
break;
}
deleteDirectory();
continue;
}
// [2] Apply mutation testing
setMutationSystemPathFor(file_name);
//File[] original_files = new File[1];
//original_files[0] = new File(MutationSystem.SRC_PATH,file_name);
File original_file = new File(MutationSystem.SRC_PATH,file_name);
AllMutantsGenerator genEngine;
Debug.setDebugLevel(3);
genEngine = new AllMutantsGenerator(original_file,class_ops,traditional_ops);
genEngine.makeMutants();
genEngine.compileMutants();
}catch(OpenJavaException oje){
System.out.println("[OJException] " + file_name + " " + oje.toString());
//System.out.println("Can't generate mutants for " +file_name + " because OpenJava " + oje.getMessage());
deleteDirectory();
}catch(Exception exp){
System.out.println("[Exception] " + file_name + " " + exp.toString());
exp.printStackTrace();
//System.out.println("Can't generate mutants for " +file_name + " due to exception" + exp.getClass().getName());
//exp.printStackTrace();
deleteDirectory();
}catch(Error er){
System.out.println("[Error] " + file_names + " " + er.toString());
//System.out.println("Can't generate mutants for " +file_name + " due to error" + er.getClass().getName());
deleteDirectory();
}
}
}
static void setMutationSystemPathFor(String file_name){
try{
String temp;
temp = file_name.substring(0,file_name.length()-".java".length());
temp = temp.replace('/','.');
temp = temp.replace('\\','.');
int separator_index = temp.lastIndexOf(".");
if(separator_index>=0){
MutationSystem.CLASS_NAME=temp.substring(separator_index+1,temp.length());
}else{
MutationSystem.CLASS_NAME = temp;
}
String mutant_dir_path = MutationSystem.MUTANT_HOME+"/"+temp;
File mutant_path = new File(mutant_dir_path);
mutant_path.mkdir();
String class_mutant_dir_path = mutant_dir_path + "/" + MutationSystem.CM_DIR_NAME;
File class_mutant_path = new File(class_mutant_dir_path);
class_mutant_path.mkdir();
String traditional_mutant_dir_path = mutant_dir_path + "/" + MutationSystem.TM_DIR_NAME;
File traditional_mutant_path = new File(traditional_mutant_dir_path);
traditional_mutant_path.mkdir();
String original_dir_path = mutant_dir_path + "/" + MutationSystem.ORIGINAL_DIR_NAME;
File original_path = new File(original_dir_path);
original_path.mkdir();
MutationSystem.CLASS_MUTANT_PATH = class_mutant_dir_path;
MutationSystem.TRADITIONAL_MUTANT_PATH = traditional_mutant_dir_path;
MutationSystem.ORIGINAL_PATH = original_dir_path;
MutationSystem.DIR_NAME = temp;
}catch(Exception e){
System.err.println(e);
}
}
static void deleteDirectory(){
File originalDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.ORIGINAL_DIR_NAME);
while(originalDir.delete()){
}
File cmDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.CM_DIR_NAME);
while(cmDir.delete()){}
File tmDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.TM_DIR_NAME);
while(tmDir.delete()){}
File myHomeDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME);
while(myHomeDir.delete()){}
}
} | [
"a.knueppel@tu-bs.de"
] | a.knueppel@tu-bs.de |
c19ef3b5638d993d279899a9b69397ab296c46ff | bfa283d187023b37398a512a8d7c863e9b013d22 | /src/Platypus.java | 9c8ac05e7fc647aab9d5a79f8b159462d761e5a7 | [] | no_license | League-Level1-Student/old-level1-module2-NikitaD111 | 3d1572ef04deb24ef9234ae1d366f1c987a16eed | 42d4752eeac9eab2127721818c1043b470422ed7 | refs/heads/master | 2020-03-31T01:41:52.049263 | 2018-11-17T02:31:01 | 2018-11-17T02:31:01 | 151,791,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 207 | java |
public class Platypus {
private String name;
public Platypus(String name) {
this.name = name;
}
void sayHi(){
System.out.println("The platypus " + name + " is smarter than your average platypus.");
}
}
| [
"league@iMac-8.attlocal.net"
] | league@iMac-8.attlocal.net |
ee684fff2bf6bb4e532fea6247f1c2682dff7785 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/18/18_20f21462f7dcd8c0151fe6ba3488b2d0142c09f8/HRMController/18_20f21462f7dcd8c0151fe6ba3488b2d0142c09f8_HRMController_s.java | 97786af407ea15267ac59a7e476d80c9fe8cb82c | [] | 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 | 164,054 | java | /*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Observer;
import de.tuilmenau.ics.fog.FoGEntity;
import de.tuilmenau.ics.fog.IEvent;
import de.tuilmenau.ics.fog.application.Application;
import de.tuilmenau.ics.fog.application.util.ServerCallback;
import de.tuilmenau.ics.fog.application.util.Service;
import de.tuilmenau.ics.fog.eclipse.GraphViewer;
import de.tuilmenau.ics.fog.facade.Binding;
import de.tuilmenau.ics.fog.facade.Connection;
import de.tuilmenau.ics.fog.facade.Description;
import de.tuilmenau.ics.fog.facade.Identity;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.Namespace;
import de.tuilmenau.ics.fog.facade.NetworkException;
import de.tuilmenau.ics.fog.facade.RequirementsException;
import de.tuilmenau.ics.fog.facade.RoutingException;
import de.tuilmenau.ics.fog.facade.Signature;
import de.tuilmenau.ics.fog.facade.events.ConnectedEvent;
import de.tuilmenau.ics.fog.facade.events.ErrorEvent;
import de.tuilmenau.ics.fog.facade.events.Event;
import de.tuilmenau.ics.fog.facade.properties.CommunicationTypeProperty;
import de.tuilmenau.ics.fog.packets.hierarchical.clustering.RequestClusterMembership;
import de.tuilmenau.ics.fog.routing.Route;
import de.tuilmenau.ics.fog.routing.RouteSegmentPath;
import de.tuilmenau.ics.fog.routing.RoutingServiceLink;
import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority;
import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector;
import de.tuilmenau.ics.fog.routing.hierarchical.management.*;
import de.tuilmenau.ics.fog.routing.hierarchical.properties.*;
import de.tuilmenau.ics.fog.routing.naming.HierarchicalNameMappingService;
import de.tuilmenau.ics.fog.routing.naming.NameMappingEntry;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMName;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address;
import de.tuilmenau.ics.fog.topology.AutonomousSystem;
import de.tuilmenau.ics.fog.topology.NetworkInterface;
import de.tuilmenau.ics.fog.topology.Node;
import de.tuilmenau.ics.fog.transfer.TransferPlaneObserver.NamingLevel;
import de.tuilmenau.ics.fog.transfer.gates.GateID;
import de.tuilmenau.ics.fog.ui.Decoration;
import de.tuilmenau.ics.fog.ui.Logging;
import de.tuilmenau.ics.fog.ui.eclipse.NodeDecorator;
import de.tuilmenau.ics.fog.util.BlockingEventHandling;
import de.tuilmenau.ics.fog.util.SimpleName;
import edu.uci.ics.jung.graph.util.Pair;
/**
* This is the main HRM controller. It provides functions that are necessary to build up the hierarchical structure - every node contains such an object
*/
public class HRMController extends Application implements ServerCallback, IEvent
{
/**
* Stores the node specific graph decorator for HRM coordinators and HRMIDs
*/
private NodeDecorator mDecoratorForCoordinatorsAndHRMIDs = null;
/**
* Stores the node specific graph decorator for HRM coordinators and clusters
*/
private NodeDecorator mDecoratorForCoordinatorsAndClusters = null;
/**
* Stores the node specific graph decorator for the active HRM infrastructure
*/
private NodeDecorator mDecoratorActiveHRMInfrastructure = null;
/**
* Stores the node specific graph decorator for HRM node base priority
*/
private NodeDecorator mDecoratorForNodePriorities = null;
/**
* Stores the GUI observable, which is used to notify possible GUIs about changes within this HRMController instance.
*/
private HRMControllerObservable mGUIInformer = new HRMControllerObservable(this);
/**
* Stores the HRG-GUI observable, which is used to notify possible HRG-GUI about changes within the HRG of the HRMController instance.
*/
private HRMControllerObservable mHRGGUIInformer = new HRMControllerObservable(this);
/**
* The name under which the HRMController application is registered on the local node.
*/
private SimpleName mApplicationName = null;
/**
* Reference to physical node.
*/
private Node mNode;
/**
* Stores a reference to the local autonomous system instance.
*/
private AutonomousSystem mAS = null;
/**
* Stores the registered HRMIDs.
* This is used within the GUI and during "share phase".
*/
private LinkedList<HRMID> mRegisteredOwnHRMIDs = new LinkedList<HRMID>();
/**
* Stores a database about all registered coordinators.
* For example, this list is used for the GUI.
*/
private LinkedList<Coordinator> mLocalCoordinators = new LinkedList<Coordinator>();
/**
* Stores all former known Coordinator IDs
*/
private LinkedList<Long> mFormerLocalCoordinatorIDs = new LinkedList<Long>();
/**
* Stores a database about all registered coordinator proxies.
*/
private LinkedList<CoordinatorProxy> mLocalCoordinatorProxies = new LinkedList<CoordinatorProxy>();
/**
* Stores a database about all registered clusters.
* For example, this list is used for the GUI.
*/
private LinkedList<Cluster> mLocalClusters = new LinkedList<Cluster>();
/**
* Stores a database about all registered cluster members (including Cluster objects).
*/
private LinkedList<ClusterMember> mLocalClusterMembers = new LinkedList<ClusterMember>();
/**
* Stores a database about all registered L0 cluster members (including Cluster objects).
* This list is used for deriving connectivity data for the distribution of topology data.
*/
private LinkedList<ClusterMember> mLocalL0ClusterMembers = new LinkedList<ClusterMember>();
/**
* Stores a database about all registered CoordinatorAsClusterMemeber instances.
*/
private LinkedList<CoordinatorAsClusterMember> mLocalCoordinatorAsClusterMemebers = new LinkedList<CoordinatorAsClusterMember>();
/**
* Stores a database about all registered comm. sessions.
*/
private LinkedList<ComSession> mCommunicationSessions = new LinkedList<ComSession>();
/**
* Stores a reference to the local instance of the hierarchical routing service.
*/
private HRMRoutingService mHierarchicalRoutingService = null;
/**
* Stores if the application was already started.
*/
private boolean mApplicationStarted = false;
/**
* Stores a database including all HRMControllers of this physical simulation machine
*/
private static LinkedList<HRMController> mRegisteredHRMControllers = new LinkedList<HRMController>();
/**
* Stores an abstract routing graph (ARG), which provides an abstract overview about logical links between clusters/coordinator.
*/
private AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> mAbstractRoutingGraph = new AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink>();
/**
* Stores the hierarchical routing graph (HRG), which provides a hierarchical overview about the network topology.
*/
private AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> mHierarchicalRoutingGraph = new AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink>(true);
/**
* Count the outgoing connections
*/
private int mCounterOutgoingConnections = 0;
/**
* Stores if the entire FoGSiEm simulation was already created.
* This is only used for debugging purposes. This is NOT a way for avoiding race conditions in signaling.
*/
private static boolean mFoGSiEmSimulationCreationFinished = false;
/**
* Stores the node priority per hierarchy level.
* Level 0 isn't used here. (see "mNodeConnectivityPriority")
*/
private long mNodeHierarchyPriority[] = new long[HRMConfig.Hierarchy.HEIGHT + 2];
/**
* Stores the connectivity node priority
*/
private long mNodeConnectivityPriority = HRMConfig.Election.DEFAULT_BULLY_PRIORITY;
/**
* Stores the central node for the ARG
*/
private CentralNodeARG mCentralARGNode = null;
/**
* Stores a description about all connectivity priority updates
*/
private String mDesriptionConnectivityPriorityUpdates = new String();
/**
* Stores a description about all HRMID updates
*/
private String mDescriptionHRMIDUpdates = new String();
/**
* Stores a description about all HRG updates
*/
private String mDescriptionHRGUpdates = new String();
/**
* Stores a description about all hierarchy priority updates
*/
private String mDesriptionHierarchyPriorityUpdates = new String();
/**
* Stores the thread for clustering tasks and packet processing
*/
private HRMControllerProcessor mProcessorThread = null;
/**
* Stores a database about all known superior coordinators
*/
private LinkedList<ClusterName> mSuperiorCoordinators = new LinkedList<ClusterName>();
/**
* Stores a database about all known network interfaces of this node
*/
private LinkedList<NetworkInterface> mLocalNetworkInterfaces = new LinkedList<NetworkInterface>();
/**
* Stores the node-global election state
*/
private Object mNodeElectionState = null;
/**
* Stores the node-global election state change description
*/
private String mDescriptionNodeElectionState = new String();
/**
* Stores if the GUI user has selected to deactivate topology reports.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_REPORT_TOPOLOGY = HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY;
/**
* Stores if the GUI user has selected to deactivate topology reports.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_SHARE_ROUTES = HRMConfig.Routing.SHARE_ROUTES_AUTOMATICALLY;
/**
* Stores if the GUI user has selected to deactivate announcements.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = true;
/**
* Stores the simulation time of the last AnnounceCoordinator, which had impact on the current hierarchy structure
* This value is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
private static double mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = 0;
/**
* @param pAS the autonomous system at which this HRMController is instantiated
* @param pNode the node on which this controller was started
* @param pHRS is the hierarchical routing service that should be used
*/
public HRMController(AutonomousSystem pAS, Node pNode, HRMRoutingService pHierarchicalRoutingService)
{
// initialize the application context
super(pNode, null, pNode.getIdentity());
// define the local name "routing://"
mApplicationName = new SimpleName(ROUTING_NAMESPACE, null);
// reference to the physical node
mNode = pNode;
// reference to the AutonomousSystem object
mAS = pAS;
// set the node-global election state
mNodeElectionState = Elector.createNodeElectionState();
/**
* Create the node specific decorator for HRM coordinators and HRMIDs
*/
mDecoratorForCoordinatorsAndHRMIDs = new NodeDecorator();
/**
* Create the node specific decorator for HRM coordinators and clusters
*/
mDecoratorForCoordinatorsAndClusters = new NodeDecorator();
/**
* Create the node specific decorator for HRM node priorities
*/
mDecoratorForNodePriorities = new NodeDecorator();
/**
* Create the node specific decorator for the active HRM infrastructure
*/
mDecoratorActiveHRMInfrastructure = new NodeDecorator();
/**
* Initialize the node hierarchy priority
*/
for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
mNodeHierarchyPriority[i] = HRMConfig.Election.DEFAULT_BULLY_PRIORITY;
}
/**
* Set the node decorations
*/
Decoration tDecoration = null;
// create own decoration for HRM coordinators & HRMIDs
tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_HRMIDS);
tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndHRMIDs);
// create own decoration for HRM coordinators and clusters
tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_CLUSTERS);
tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndClusters);
// create own decoration for HRM node priorities
tDecoration = Decoration.getInstance(DECORATION_NAME_NODE_PRIORITIES);
tDecoration.setDecorator(mNode, mDecoratorForNodePriorities);
// create own decoration for HRM node priorities
tDecoration = Decoration.getInstance(DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE);
tDecoration.setDecorator(mNode, mDecoratorActiveHRMInfrastructure);
// overwrite default decoration
tDecoration = Decoration.getInstance(GraphViewer.DEFAULT_DECORATION);
tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndHRMIDs);
/**
* Create clusterer thread
*/
mProcessorThread = new HRMControllerProcessor(this);
/**
* Start the clusterer thread
*/
mProcessorThread.start();
/**
* Create communication service
*/
// bind the HRMController application to a local socket
Binding tServerSocket=null;
// enable simple datagram based communication
Description tServiceReq = getDescription();
tServiceReq.set(CommunicationTypeProperty.DATAGRAM);
tServerSocket = getLayer().bind(null, mApplicationName, tServiceReq, getIdentity());
if (tServerSocket != null){
// create and start the socket service
Service tService = new Service(false, this);
tService.start(tServerSocket);
}else{
Logging.err(this, "Unable to start the HRMController service");
}
// store the reference to the local instance of hierarchical routing service
mHierarchicalRoutingService = pHierarchicalRoutingService;
// create central node in the local ARG
mCentralARGNode = new CentralNodeARG(this);
// create local loopback session
ComSession.createLoopback(this);
// fire the first "report/share phase" trigger
reportAndShare();
Logging.log(this, "CREATED");
// start the application
start();
}
/**
* Returns the local instance of the hierarchical routing service
*
* @return hierarchical routing service of this entity
*/
public HRMRoutingService getHRS()
{
return mHierarchicalRoutingService;
}
/**
* Returns the local physical node object.
*
* @return the physical node running this coordinator
*/
public Node getNode()
{
return mNode;
}
/**
* Return the actual GUI name description of the physical node;
* However, this function should only be used for debug outputs, e.g., GUI outputs.
*
* @return the GUI name
*/
@SuppressWarnings("deprecation")
public String getNodeGUIName()
{
return mNode.getName();
}
/**
* Notifies the GUI about essential updates within the HRM system
*/
private void notifyGUI(Object pArgument)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Got notification with argument " + pArgument);
}
mGUIInformer.notifyObservers(pArgument);
}
/**
* Notifies the HRGViewer about essential updates within the HRG graph
*/
private void notifyHRGGUI(Object pArgument)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Got HRG notification with argument " + pArgument);
}
mHRGGUIInformer.notifyObservers(pArgument);
}
/**
* Registers a GUI for being notified about HRMController internal changes.
*/
public void registerGUI(Observer pGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Registering GUI " + pGUI);
}
mGUIInformer.addObserver(pGUI);
}
/**
* Registers a HRG-GUI for being notified about HRG internal changes.
*/
public void registerHRGGUI(Observer pHRGGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Registering HRG-GUI " + pHRGGUI);
}
mHRGGUIInformer.addObserver(pHRGGUI);
}
/**
* Unregisters a GUI for being notified about HRMController internal changes.
*/
public void unregisterGUI(Observer pGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Unregistering GUI " + pGUI);
}
mGUIInformer.deleteObserver(pGUI);
}
/**
* Unregisters a HRG-GUI for being notified about HRG internal changes.
*/
public void unregisterHRGGUI(Observer pHRGGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Unregistering HRG-GUI " + pHRGGUI);
}
mHRGGUIInformer.deleteObserver(pHRGGUI);
}
/**
* Registers a coordinator proxy at the local database.
*
* @param pCoordinatorProxy the coordinator proxy for a defined coordinator
*/
public synchronized void registerCoordinatorProxy(CoordinatorProxy pCoordinatorProxy)
{
Logging.log(this, "Registering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue());
synchronized (mLocalCoordinatorProxies) {
// register as known coordinator proxy
mLocalCoordinatorProxies.add(pCoordinatorProxy);
}
// increase hierarchy node priority
increaseHierarchyNodePriority_KnownCoordinator(pCoordinatorProxy);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator prxy in the local ARG
registerNodeARG(pCoordinatorProxy);
// it's time to update the GUI
notifyGUI(pCoordinatorProxy);
}
/**
* Unregisters a coordinator proxy from the local database.
*
* @param pCoordinatorProxy the coordinator proxy for a defined coordinator
*/
public synchronized void unregisterCoordinatorProxy(CoordinatorProxy pCoordinatorProxy)
{
Logging.log(this, "Unregistering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue());
synchronized (mLocalCoordinatorProxies) {
// unregister as known coordinator proxy
mLocalCoordinatorProxies.remove(pCoordinatorProxy);
}
// increase hierarchy node priority
decreaseHierarchyNodePriority_KnownCoordinator(pCoordinatorProxy);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator prxy in the local ARG
unregisterNodeARG(pCoordinatorProxy);
// it's time to update the GUI
notifyGUI(pCoordinatorProxy);
}
/**
* Registers a coordinator at the local database.
*
* @param pCoordinator the coordinator for a defined cluster
*/
public synchronized void registerCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "Registering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue());
Coordinator tFoundAnInferiorCoordinator = getCoordinator(pCoordinator.getHierarchyLevel().getValue() - 1);
/**
* Check if the hierarchy is continuous
*/
if((!pCoordinator.getHierarchyLevel().isBaseLevel()) && (tFoundAnInferiorCoordinator == null)){
Logging.err(this, "Hierarchy is temporary non continuous, detected an error in the Matrix!?");
}
synchronized (mLocalCoordinators) {
// register as known coordinator
mLocalCoordinators.add(pCoordinator);
}
// increase hierarchy node priority
increaseHierarchyNodePriority_KnownCoordinator(pCoordinator);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator in the local ARG
registerNodeARG(pCoordinator);
registerLinkARG(pCoordinator, pCoordinator.getCluster(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
// it's time to update the GUI
notifyGUI(pCoordinator);
}
/**
* Unregisters a coordinator from the internal database.
*
* @param pCoordinator the coordinator which should be unregistered
*/
public synchronized void unregisterCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "Unregistering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue());
synchronized (mLocalCoordinators) {
// unregister from list of known coordinators
mLocalCoordinators.remove(pCoordinator);
synchronized (mFormerLocalCoordinatorIDs) {
mFormerLocalCoordinatorIDs.add(pCoordinator.getGUICoordinatorID());
}
}
// increase hierarchy node priority
decreaseHierarchyNodePriority_KnownCoordinator(pCoordinator);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// unregister from the ARG
unregisterNodeARG(pCoordinator);
// it's time to update the GUI
notifyGUI(pCoordinator);
}
/**
* Registers an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pCause the cause for the registration
*/
private void registerHRMID(ControlEntity pEntity, String pCause)
{
/**
* Get the new HRMID
*/
HRMID tHRMID = pEntity.getHRMID();
if((tHRMID != null) && (!tHRMID.isZero())){
registerHRMID(pEntity, tHRMID, pCause);
}
}
/**
* Registers an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pHRMID the new HRMID
* @param pCause the cause for the registration
*/
@SuppressWarnings("unchecked")
public void registerHRMID(ControlEntity pEntity, HRMID pHRMID, String pCause)
{
/**
* Some validations
*/
if(pHRMID != null){
// ignore "0.0.0"
if(!pHRMID.isZero()){
/**
* Register the HRMID
*/
synchronized(mRegisteredOwnHRMIDs){
if (!mRegisteredOwnHRMIDs.contains(pHRMID)){
/**
* Update the local address DB with the given HRMID
*/
if(!pHRMID.isClusterAddress()){
/**
* Register a local loopback route for the new address
*/
// register a route to the cluster member as addressable target
addHRMRoute(RoutingEntry.createLocalhostEntry(pHRMID, pCause + ", " + this + "::registerHRMID()"));
/**
* Update the DNS
*/
// register the HRMID in the hierarchical DNS for the local router
HierarchicalNameMappingService<HRMID> tNMS = null;
try {
tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation());
} catch (RuntimeException tExc) {
HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation());
}
// get the local router's human readable name (= DNS name)
Name tLocalRouterName = getNodeName();
// register HRMID for the given DNS name
tNMS.registerName(tLocalRouterName, pHRMID, NamingLevel.NAMES);
// give some debug output about the current DNS state
String tString = new String();
for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) {
if (!tString.isEmpty()){
tString += ", ";
}
tString += tEntry;
}
Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString);
}
}else{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Found a HRMID duplicate for " + pHRMID.toString() + ", additional registration is triggered by " + pEntity);
}
}
/**
* Add the HRMID
*/
if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){
Logging.log(this, "Adding the HRMID to: " + pHRMID.toString() + " for: " + pEntity);
}
// register the new HRMID as local one -> allow duplicates here because two local entities might register the same HRMID and afterwards one of them unregisters its HRMID -> in case one HRMID registration remains!
mRegisteredOwnHRMIDs.add(pHRMID);
mDescriptionHRMIDUpdates += "\n + " + pHRMID.toString() + " <== " + pEntity + ", cause=" + pCause;
/**
* Update the GUI
*/
// updates the GUI decoration for this node
updateGUINodeDecoration();
// it's time to update the GUI
notifyGUI(pEntity);
}
}else{
throw new RuntimeException(this + "registerHRMID() got a zero HRMID " + pHRMID.toString() + " for: " + pEntity);
}
}else{
Logging.err(this, "registerHRMID() got an invalid HRMID for: " + pEntity);
}
}
/**
* Unregisters an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pOldHRMID the old HRMID which should be unregistered
* @param pCause the cause for this call
*/
public void unregisterHRMID(ControlEntity pEntity, HRMID pOldHRMID, String pCause)
{
/**
* Some validations
*/
if(pOldHRMID != null){
// ignore "0.0.0"
if(!pOldHRMID.isZero()){
/**
* Unregister the HRMID
*/
synchronized(mRegisteredOwnHRMIDs){
/**
* Remove the HRMID
*/
if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){
Logging.log(this, "Revoking the HRMID: " + pOldHRMID.toString() + " of: " + pEntity);
}
// unregister the HRMID as local one
mRegisteredOwnHRMIDs.remove(pOldHRMID);
mDescriptionHRMIDUpdates += "\n - " + pOldHRMID.toString() + " <== " + pEntity + ", cause=" + pCause;
if (!mRegisteredOwnHRMIDs.contains(pOldHRMID)){
/**
* Update the local address DB with the given HRMID
*/
if(!pOldHRMID.isClusterAddress()){
/**
* Unregister the local loopback route for the address
*/
// unregister a route to the cluster member as addressable target
delHRMRoute(RoutingEntry.createLocalhostEntry(pOldHRMID, pCause + ", " + this + "::unregisterHRMID()"));
/**
* Update the DNS
*/
//TODO // register the HRMID in the hierarchical DNS for the local router
// HierarchicalNameMappingService<HRMID> tNMS = null;
// try {
// tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation());
// } catch (RuntimeException tExc) {
// HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation());
// }
// // get the local router's human readable name (= DNS name)
// Name tLocalRouterName = getNodeName();
// // register HRMID for the given DNS name
// tNMS.registerName(tLocalRouterName, pOldHRMID, NamingLevel.NAMES);
// // give some debug output about the current DNS state
// String tString = new String();
// for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) {
// if (!tString.isEmpty()){
// tString += ", ";
// }
// tString += tEntry;
// }
// Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString);
}
}else{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Found duplicated HRMID " + pOldHRMID.toString() + ", an unregistration is triggered by " + pEntity);
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
updateGUINodeDecoration();
// it's time to update the GUI
notifyGUI(pEntity);
}
}else{
throw new RuntimeException(this + "unregisterHRMID() got a zero HRMID " + pOldHRMID.toString() + " for: " + pEntity);
}
}else{
Logging.err(this, "unregisterHRMID() got an invalid HRMID for: " + pEntity);
}
}
/**
* Updates the registered HRMID for a defined coordinator.
*
* @param pCluster the cluster whose HRMID is updated
* @param pOldHRMID the old HRMID which should be unregistered
*/
private int mCallsUpdateCoordinatorAddress = 0;
public void updateCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID)
{
mCallsUpdateCoordinatorAddress++;
HRMID tHRMID = pCoordinator.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pCoordinator, pOldHRMID, "updateCoordinatorAddress()(" + mCallsUpdateCoordinatorAddress + ") for " + pCoordinator + ", old HRMID=" + pOldHRMID);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Coordinator " + pCoordinator + ", old HRMID=" + pOldHRMID);
registerHRMID(pCoordinator, "updateCoordinatorAddress()(" + mCallsUpdateCoordinatorAddress + ") for " + pCoordinator);
}
}
/**
* Returns if a coordinator ID is a formerly known one
*
* @param pCoordinatorID the coordinator ID
*
* @return true or false
*/
public boolean isGUIFormerCoordiantorID(long pCoordinatorID)
{
boolean tResult = false;
synchronized (mFormerLocalCoordinatorIDs) {
tResult = mFormerLocalCoordinatorIDs.contains(pCoordinatorID);
}
return tResult;
}
/**
* Revokes a coordinator address
*
* @param pCoordinator the coordinator for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for coordinator " + pCoordinator);
unregisterHRMID(pCoordinator, pOldHRMID, "revokeCoordinatorAddress()");
}
}
/**
* Updates the decoration of the node (image and label text)
*/
private void updateGUINodeDecoration()
{
/**
* Set the decoration texts
*/
String tActiveHRMInfrastructureText = "";
for (int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
LinkedList<Cluster> tClusters = getAllClusters(i);
for(Cluster tCluster : tClusters){
if(tCluster.hasLocalCoordinator()){
if (tActiveHRMInfrastructureText != ""){
tActiveHRMInfrastructureText += ", ";
}
tActiveHRMInfrastructureText += "<" + Long.toString(tCluster.getGUIClusterID()) + ">";
for(int j = 0; j < tCluster.getHierarchyLevel().getValue(); j++){
tActiveHRMInfrastructureText += "^";
}
}
}
}
LinkedList<ClusterName> tSuperiorCoordiantors = getAllSuperiorCoordinators();
for(ClusterName tSuperiorCoordinator : tSuperiorCoordiantors){
if (tActiveHRMInfrastructureText != ""){
tActiveHRMInfrastructureText += ", ";
}
tActiveHRMInfrastructureText += Long.toString(tSuperiorCoordinator.getGUIClusterID());
for(int i = 0; i < tSuperiorCoordinator.getHierarchyLevel().getValue(); i++){
tActiveHRMInfrastructureText += "^";
}
}
mDecoratorActiveHRMInfrastructure.setText(" [Active clusters: " + tActiveHRMInfrastructureText + "]");
String tHierPrio = "";
for(int i = 1; i < HRMConfig.Hierarchy.HEIGHT; i++){
if (tHierPrio != ""){
tHierPrio += ", ";
}
tHierPrio += Long.toString(mNodeHierarchyPriority[i]) +"@" + i;
}
mDecoratorForNodePriorities.setText(" [Hier.: " + tHierPrio + "/ Conn.: " + Long.toString(getConnectivityNodePriority()) + "]");
String tNodeText = "";
synchronized (mRegisteredOwnHRMIDs) {
for (HRMID tHRMID: mRegisteredOwnHRMIDs){
if (((!tHRMID.isRelativeAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_RELATIVE_ADDRESSES)) && ((!tHRMID.isClusterAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_CLUSTER_ADDRESSES))){
if (tNodeText != ""){
tNodeText += ", ";
}
tNodeText += tHRMID.toString();
}
}
}
mDecoratorForCoordinatorsAndHRMIDs.setText(tNodeText);
String tClustersText = "";
tClustersText = "";
LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers();
for (ClusterMember tClusterMember : tAllClusterMembers){
if (tClustersText != ""){
tClustersText += ", ";
}
// is this node the cluster head?
if (tClusterMember instanceof Cluster){
Cluster tCluster = (Cluster)tClusterMember;
if(tCluster.hasLocalCoordinator()){
tClustersText += "<" + Long.toString(tClusterMember.getGUIClusterID()) + ">";
}else{
tClustersText += "(" + Long.toString(tClusterMember.getGUIClusterID()) + ")";
}
}else{
tClustersText += Long.toString(tClusterMember.getGUIClusterID());
}
for(int i = 0; i < tClusterMember.getHierarchyLevel().getValue(); i++){
tClustersText += "^";
}
}
mDecoratorForCoordinatorsAndClusters.setText("- clusters: " + tClustersText);
/**
* Set the decoration images
*/
LinkedList<Coordinator> tAllCoordinators = getAllCoordinators();
int tHighestCoordinatorLevel = -1;
for (Coordinator tCoordinator : tAllCoordinators){
int tCoordLevel = tCoordinator.getHierarchyLevel().getValue();
if (tCoordLevel > tHighestCoordinatorLevel){
tHighestCoordinatorLevel = tCoordLevel;
}
}
mDecoratorForNodePriorities.setImage(tHighestCoordinatorLevel);
mDecoratorForCoordinatorsAndHRMIDs.setImage(tHighestCoordinatorLevel);
mDecoratorForCoordinatorsAndClusters.setImage(tHighestCoordinatorLevel);
mDecoratorActiveHRMInfrastructure.setImage(tHighestCoordinatorLevel);
}
/**
* Returns a list of all known network interfaces
*
* @return the list of known network interfaces
*/
@SuppressWarnings("unchecked")
public LinkedList<NetworkInterface> getAllNetworkInterfaces()
{
LinkedList<NetworkInterface> tResult = null;
synchronized (mLocalNetworkInterfaces) {
tResult = (LinkedList<NetworkInterface>) mLocalNetworkInterfaces.clone();
}
return tResult;
}
/**
* Returns a list of all known local coordinators.
*
* @return the list of known local coordinators
*/
@SuppressWarnings("unchecked")
public LinkedList<Coordinator> getAllCoordinators()
{
LinkedList<Coordinator> tResult;
synchronized (mLocalCoordinators) {
tResult = (LinkedList<Coordinator>) mLocalCoordinators.clone();
}
return tResult;
}
/**
* Returns all known coordinators for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level for which all coordinators have to be determined
*
* @return the list of coordinators on the defined hierarchy level
*/
public LinkedList<Coordinator> getAllCoordinators(int pHierarchyLevel)
{
LinkedList<Coordinator> tResult = new LinkedList<Coordinator>();
// get a list of all known coordinators
LinkedList<Coordinator> tAllCoordinators = getAllCoordinators();
// iterate over all known coordinators
for (Coordinator tCoordinator : tAllCoordinators){
// have we found a matching coordinator?
if (tCoordinator.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCoordinator);
}
}
return tResult;
}
/**
* Returns a list of all known local coordinator proxies.
*
* @return the list of known local coordinator proxies
*/
@SuppressWarnings("unchecked")
public LinkedList<CoordinatorProxy> getAllCoordinatorProxies()
{
LinkedList<CoordinatorProxy> tResult;
synchronized (mLocalCoordinatorProxies) {
tResult = (LinkedList<CoordinatorProxy>) mLocalCoordinatorProxies.clone();
}
return tResult;
}
/**
* Returns all known coordinator proxies for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level for which all coordinator proxies have to be determined
*
* @return the list of coordinator proies at the defined hierarchy level
*/
public LinkedList<CoordinatorProxy> getAllCoordinatorProxies(int pHierarchyLevel)
{
//Logging.log(this, "Searching for coordinator proxies at hierarchy level: " + pHierarchyLevel);
LinkedList<CoordinatorProxy> tResult = new LinkedList<CoordinatorProxy>();
// get a list of all known coordinator proxies
LinkedList<CoordinatorProxy> tAllCoordinatorProxies = getAllCoordinatorProxies();
// iterate over all known coordinator proxies
for (CoordinatorProxy tCoordinatorProxy : tAllCoordinatorProxies){
// have we found a matching coordinator proxy?
if (tCoordinatorProxy.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator proxy to the result
tResult.add(tCoordinatorProxy);
}
}
//Logging.log(this, " ..found: " + tResult);
return tResult;
}
/**
* Registers a coordinator-as-cluster-member at the local database.
*
* @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be registered
*/
public synchronized void registerCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember)
{
int tLevel = pCoordinatorAsClusterMember.getHierarchyLevel().getValue();
Logging.log(this, "Registering coordinator-as-cluster-member " + pCoordinatorAsClusterMember + " at level " + tLevel);
boolean tNewEntry = false;
synchronized (mLocalCoordinatorAsClusterMemebers) {
// make sure the Bully priority is the right one, avoid race conditions here
pCoordinatorAsClusterMember.setPriority(BullyPriority.create(this, getHierarchyNodePriority(pCoordinatorAsClusterMember.getHierarchyLevel())));
if(!mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){
// register as known coordinator-as-cluster-member
mLocalCoordinatorAsClusterMemebers.add(pCoordinatorAsClusterMember);
tNewEntry = true;
}
}
if(tNewEntry){
if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the node in the local ARG
registerNodeARG(pCoordinatorAsClusterMember);
// register the link in the local ARG
registerLinkARG(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getCoordinator(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pCoordinatorAsClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pCoordinatorAsClusterMember);
}
}
}
/**
* Unregister a coordinator-as-cluster-member from the local database
*
* @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be unregistered
*/
public synchronized void unregisterCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember)
{
Logging.log(this, "Unregistering coordinator-as-cluster-member " + pCoordinatorAsClusterMember);
boolean tFoundEntry = false;
synchronized (mLocalCoordinatorAsClusterMemebers) {
if(mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){
// unregister the old HRMID
revokeClusterMemberAddress(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getHRMID());
// unregister from list of known cluster members
mLocalCoordinatorAsClusterMemebers.remove(pCoordinatorAsClusterMember);
Logging.log(this, " ..unregistered: " + pCoordinatorAsClusterMember);
}else{
Logging.log(this, " ..not found: " + pCoordinatorAsClusterMember);
}
}
if(tFoundEntry){
if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pCoordinatorAsClusterMember);
// it's time to update the GUI
notifyGUI(pCoordinatorAsClusterMember);
}
}
}
/**
* Registers a cluster member at the local database.
*
* @param pClusterMember the cluster member which should be registered
*/
public synchronized void registerClusterMember(ClusterMember pClusterMember)
{
int tLevel = pClusterMember.getHierarchyLevel().getValue();
Logging.log(this, "Registering cluster member " + pClusterMember + " at level " + tLevel);
boolean tNewEntry = false;
synchronized (mLocalClusterMembers) {
// make sure the Bully priority is the right one, avoid race conditions here
pClusterMember.setPriority(BullyPriority.create(this, getConnectivityNodePriority()));
if(!mLocalClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalClusterMembers.add(pClusterMember);
tNewEntry = true;
}
}
/**
* Register as L0 ClusterMember
*/
if(pClusterMember.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(!mLocalL0ClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalL0ClusterMembers.add(pClusterMember);
}
}
}
if(tNewEntry){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the cluster in the local ARG
registerNodeARG(pClusterMember);
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pClusterMember);
}
}
/**
* Unregister a cluster member from the local database
*
* @param pClusterMember the cluster member which should be unregistered
*/
public synchronized void unregisterClusterMember(ClusterMember pClusterMember)
{
Logging.log(this, "Unregistering cluster member " + pClusterMember);
boolean tFoundEntry = false;
synchronized (mLocalClusterMembers) {
if(mLocalClusterMembers.contains(pClusterMember)){
// unregister the old HRMID
revokeClusterMemberAddress(pClusterMember, pClusterMember.getHRMID());
// unregister from list of known cluster members
mLocalClusterMembers.remove(pClusterMember);
tFoundEntry = true;
}
}
/**
* Unregister as L0 ClusterMember
*/
if(pClusterMember.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(mLocalL0ClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalL0ClusterMembers.remove(pClusterMember);
}
}
}
if(tFoundEntry){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pClusterMember);
// it's time to update the GUI
notifyGUI(pClusterMember);
}
}
/**
* Registers a cluster at the local database.
*
* @param pCluster the cluster which should be registered
*/
public synchronized void registerCluster(Cluster pCluster)
{
int tLevel = pCluster.getHierarchyLevel().getValue();
Logging.log(this, "Registering cluster " + pCluster + " at level " + tLevel);
synchronized (mLocalClusters) {
// register as known cluster
mLocalClusters.add(pCluster);
}
synchronized (mLocalClusterMembers) {
// register as known cluster member
mLocalClusterMembers.add(pCluster);
}
/**
* Register as L0 ClusterMember
*/
if(pCluster.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(!mLocalL0ClusterMembers.contains(pCluster)){
// register as known cluster member
mLocalL0ClusterMembers.add(pCluster);
}
}
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the cluster in the local ARG
registerNodeARG(pCluster);
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pCluster);
}
/**
* Unregisters a cluster from the local database.
*
* @param pCluster the cluster which should be unregistered.
*/
public synchronized void unregisterCluster(Cluster pCluster)
{
Logging.log(this, "Unregistering cluster " + pCluster);
synchronized (mLocalClusters) {
// unregister the old HRMID
revokeClusterAddress(pCluster, pCluster.getHRMID());
// unregister from list of known clusters
mLocalClusters.remove(pCluster);
}
synchronized (mLocalClusterMembers) {
// unregister from list of known cluster members
mLocalClusterMembers.remove(pCluster);
}
/**
* Unregister as L0 ClusterMember
*/
if(pCluster.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(mLocalL0ClusterMembers.contains(pCluster)){
// register as known cluster member
mLocalL0ClusterMembers.remove(pCluster);
}
}
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pCluster);
// it's time to update the GUI
notifyGUI(pCluster);
}
/**
* Updates the registered HRMID for a defined Cluster.
*
* @param pCluster the Cluster whose HRMID is updated
* @param pOldHRMID the old HRMID
*/
public void updateClusterAddress(Cluster pCluster, HRMID pOldHRMID)
{
HRMID tHRMID = pCluster.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pCluster, pOldHRMID, "updateClusterAddress() for " + pCluster);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Cluster " + pCluster);
registerHRMID(pCluster, "updateClusterAddress() for " + pCluster);
}
}
/**
* Updates the registered HRMID for a defined ClusterMember.
*
* @param pClusterMember the ClusterMember whose HRMID is updated
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void updateClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID)
{
HRMID tHRMID = pClusterMember.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pClusterMember, pOldHRMID, "updateClusterMemberAddress() for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + pOldHRMID.toString() + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for ClusterMember " + pClusterMember + ", old HRMID=" + pOldHRMID);
// process this only if we are at base hierarchy level, otherwise we will receive the same update from
// the corresponding coordinator instance
if (pClusterMember.getHierarchyLevel().isBaseLevel()){
registerHRMID(pClusterMember, "updateClusterMemberAddress() for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}else{
// we are at a higher hierarchy level and don't need the HRMID update because we got the same from the corresponding coordinator instance
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID registration " + (tHRMID != null ? tHRMID.toString() : "null") + " for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}
}
}
}
/**
* Revokes a cluster address
*
* @param pClusterMember the ClusterMember for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for ClusterMember " + pClusterMember);
if (pClusterMember.getHierarchyLevel().isBaseLevel()){
unregisterHRMID(pClusterMember, pOldHRMID, "revokeClusterMemberAddress()");
}else{
// we are at a higher hierarchy level and don't need the HRMID revocation
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pClusterMember);
}
}
}
}
/**
* Revokes a cluster address
*
* @param pCluster the Cluster for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeClusterAddress(Cluster pCluster, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for Cluster " + pCluster);
if (pCluster.getHierarchyLevel().isBaseLevel()){
unregisterHRMID(pCluster, pOldHRMID, "revokeClusterAddress()");
}else{
// we are at a higher hierarchy level and don't need the HRMID revocation
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pCluster);
}
}
}
}
/**
* Registers a superior coordinator at the local database
*
* @param pSuperiorCoordinatorClusterName a description of the announced superior coordinator
*/
public void registerSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName)
{
boolean tUpdateGui = false;
synchronized (mSuperiorCoordinators) {
if(!mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){
Logging.log(this, "Registering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators);
mSuperiorCoordinators.add(pSuperiorCoordinatorClusterName);
tUpdateGui = true;
}else{
// already registered
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
if(tUpdateGui){
updateGUINodeDecoration();
}
}
/**
* Unregisters a formerly registered superior coordinator from the local database
*
* @param pSuperiorCoordinatorClusterName a description of the invalid superior coordinator
*/
public void unregisterSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName)
{
boolean tUpdateGui = false;
synchronized (mSuperiorCoordinators) {
if(mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){
Logging.log(this, "Unregistering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators);
mSuperiorCoordinators.remove(pSuperiorCoordinatorClusterName);
tUpdateGui = true;
}else{
// already removed or never registered
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
if(tUpdateGui){
updateGUINodeDecoration();
}
}
/**
* Returns all superior coordinators
*
* @return the superior coordinators
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterName> getAllSuperiorCoordinators()
{
LinkedList<ClusterName> tResult = null;
synchronized (mSuperiorCoordinators) {
tResult = (LinkedList<ClusterName>) mSuperiorCoordinators.clone();
}
return tResult;
}
/**
* Returns a list of known coordinator as cluster members.
*
* @return the list of known coordinator as cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers()
{
LinkedList<CoordinatorAsClusterMember> tResult = null;
synchronized (mLocalCoordinatorAsClusterMemebers) {
tResult = (LinkedList<CoordinatorAsClusterMember>) mLocalCoordinatorAsClusterMemebers.clone();
}
return tResult;
}
/**
* Returns a list of known cluster members.
*
* @return the list of known cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterMember> getAllClusterMembers()
{
LinkedList<ClusterMember> tResult = null;
synchronized (mLocalClusterMembers) {
tResult = (LinkedList<ClusterMember>) mLocalClusterMembers.clone();
}
return tResult;
}
/**
* Returns a list of known L0 cluster members.
*
* @return the list of known L0 cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterMember> getAllL0ClusterMembers()
{
LinkedList<ClusterMember> tResult = null;
synchronized (mLocalL0ClusterMembers) {
tResult = (LinkedList<ClusterMember>) mLocalL0ClusterMembers.clone();
}
return tResult;
}
/**
* Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of cluster members
*/
public LinkedList<ClusterMember> getAllClusterMembers(HierarchyLevel pHierarchyLevel)
{
return getAllClusterMembers(pHierarchyLevel.getValue());
}
/**
* Returns a list of known CoordinatorAsClusterMember for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of CoordinatorAsClusterMember
*/
public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers(int pHierarchyLevel)
{
LinkedList<CoordinatorAsClusterMember> tResult = new LinkedList<CoordinatorAsClusterMember>();
// get a list of all known coordinators
LinkedList<CoordinatorAsClusterMember> tAllCoordinatorAsClusterMembers = getAllCoordinatorAsClusterMembers();
// iterate over all known coordinators
for (CoordinatorAsClusterMember tCoordinatorAsClusterMember : tAllCoordinatorAsClusterMembers){
// have we found a matching coordinator?
if (tCoordinatorAsClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCoordinatorAsClusterMember);
}
}
return tResult;
}
/**
* Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of cluster members
*/
public LinkedList<ClusterMember> getAllClusterMembers(int pHierarchyLevel)
{
LinkedList<ClusterMember> tResult = new LinkedList<ClusterMember>();
// get a list of all known coordinators
LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers();
// iterate over all known coordinators
for (ClusterMember tClusterMember : tAllClusterMembers){
// have we found a matching coordinator?
if (tClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tClusterMember);
}
}
return tResult;
}
/**
* Returns a list of known clusters.
*
* @return the list of known clusters
*/
@SuppressWarnings("unchecked")
public LinkedList<Cluster> getAllClusters()
{
LinkedList<Cluster> tResult = null;
synchronized (mLocalClusters) {
tResult = (LinkedList<Cluster>) mLocalClusters.clone();
}
return tResult;
}
/**
* Returns a list of known clusters for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of clusters
*/
public LinkedList<Cluster> getAllClusters(HierarchyLevel pHierarchyLevel)
{
return getAllClusters(pHierarchyLevel.getValue());
}
/**
* Returns a list of known clusters for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of clusters
*/
public LinkedList<Cluster> getAllClusters(int pHierarchyLevel)
{
LinkedList<Cluster> tResult = new LinkedList<Cluster>();
// get a list of all known coordinators
LinkedList<Cluster> tAllClusters = getAllClusters();
// iterate over all known coordinators
for (Cluster tCluster : tAllClusters){
// have we found a matching coordinator?
if (tCluster.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCluster);
}
}
return tResult;
}
/**
* Returns the locally known Cluster object for a given hierarchy level
*
* @param pHierarchyLevel the hierarchy level for which the Cluster object is searched
*
* @return the found Cluster object
*/
public Cluster getCluster(int pHierarchyLevel)
{
Cluster tResult = null;
for(Cluster tKnownCluster : getAllClusters()) {
if(tKnownCluster.getHierarchyLevel().getValue() == pHierarchyLevel) {
tResult = tKnownCluster;
break;
}
}
return tResult;
}
/**
* Returns the locally known Coordinator object for a given hierarchy level
*
* @param pHierarchyLevelValue the hierarchy level for which the Coordinator object is searched
*
* @return the found Coordinator object
*/
private Coordinator getCoordinator(int pHierarchyLevelValue)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if(tKnownCoordinator.getHierarchyLevel().getValue() == pHierarchyLevelValue) {
tResult = tKnownCoordinator;
break;
}
}
return tResult;
}
/**
* Returns a locally known Coordinator object for a given hierarchy level.
* HINT: For base hierarchy level, there could exist more than one local coordinator!
*
* @param pHierarchyLevel the hierarchy level for which the Coordinator object is searched
*
* @return the found Coordinator object
*/
public Coordinator getCoordinator(HierarchyLevel pHierarchyLevel)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if(tKnownCoordinator.getHierarchyLevel().equals(pHierarchyLevel)) {
tResult = tKnownCoordinator;
break;
}
}
return tResult;
}
/**
* Returns the locally known CoordinatorProxy object, which was identified by its ClusterName
*
* @param pClusterName the cluster name of the searched coordinator proxy
*
* @return the desired CoordinatorProxy, null if the coordinator isn't known
*/
public CoordinatorProxy getCoordinatorProxyByName(ClusterName pClusterName)
{
CoordinatorProxy tResult = null;
synchronized (mLocalCoordinatorProxies) {
for (CoordinatorProxy tCoordinatorProxy : mLocalCoordinatorProxies){
if(tCoordinatorProxy.equals(pClusterName)){
tResult = tCoordinatorProxy;
break;
}
}
}
return tResult;
}
/**
* Returns a known coordinator, which is identified by its ID.
*
* @param pCoordinatorID the coordinator ID
*
* @return the searched coordinator object
*/
public Coordinator getCoordinatorByID(long pCoordinatorID)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if (tKnownCoordinator.getCoordinatorID() == pCoordinatorID) {
tResult = tKnownCoordinator;
}
}
return tResult;
}
/**
* Clusters the given hierarchy level
* HINT: It is synchronized to only one call at the same time.
*
* @param pHierarchyLevel the hierarchy level where a clustering should be done
*/
public void cluster(ControlEntity pCause, final HierarchyLevel pHierarchyLevel)
{
if(pHierarchyLevel.getValue() <= HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY_HIERARCHY_LIMIT){
Logging.log(this, "CLUSTERING REQUEST for hierarchy level: " + pHierarchyLevel.getValue() + ", cause=" + pCause);
mProcessorThread.eventUpdateCluster(pCause, pHierarchyLevel);
}
}
/**
* Notifies packet processor about a new packet
*
* @param pComChannel the comm. channel which has a new received packet
*/
public void notifyPacketProcessor(ComChannel pComChannel)
{
mProcessorThread.eventReceivedPacket(pComChannel);
}
/**
* Registers an outgoing communication session
*
* @param pComSession the new session
*/
public void registerSession(ComSession pComSession)
{
Logging.log(this, "Registering communication session: " + pComSession);
synchronized (mCommunicationSessions) {
mCommunicationSessions.add(pComSession);
}
}
/**
* Determines the outgoing communication session for a desired target cluster
* HINT: This function has to be called in a separate thread!
*
* @param pDestinationL2Address the L2 address of the destination
*
* @return the found comm. session or null
*/
public ComSession getCreateComSession(L2Address pDestinationL2Address)
{
ComSession tResult = null;
boolean DEBUG = false;
// is the destination valid?
if (pDestinationL2Address != null){
//Logging.log(this, "Searching for outgoing comm. session to: " + pDestinationL2Address);
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
//Logging.log(this, " ..ComSession: " + tComSession);
// get the L2 address of the comm. session peer
L2Address tPeerL2Address = tComSession.getPeerL2Address();
if(pDestinationL2Address.equals(tPeerL2Address)){
//Logging.log(this, " ..found match");
tResult = tComSession;
break;
}else{
//Logging.log(this, " ..uninteresting");
}
}
}
// have we found an already existing connection?
if(tResult == null){
if(DEBUG){
Logging.log(this, "getCreateComSession() could find a comm. session for destination: " + pDestinationL2Address + ", knowing these sessions and their channels:");
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
Logging.log(this, " ..ComSession: " + tComSession);
for(ComChannel tComChannel : tComSession.getAllComChannels()){
Logging.log(this, " ..ComChannel: " + tComChannel);
Logging.log(this, " ..RemoteCluster: " + tComChannel.getRemoteClusterName().toString());
}
}
}
}
/**
* Create the new connection
*/
if(DEBUG){
Logging.log(this, " ..creating new connection and session to: " + pDestinationL2Address);
}
tResult = createComSession(pDestinationL2Address);
}
}else{
//Logging.err(this, "getCreateComSession() detected invalid destination L2 address");
}
return tResult;
}
/**
* Creates a new comm. session (incl. connection) to a given destination L2 address and uses the given connection requirements
* HINT: This function has to be called in a separate thread!
*
* @param pDestinationL2Address the L2 address of the destination
*
* @return the new comm. session or null
*/
private ComSession createComSession(L2Address pDestinationL2Address)
{
ComSession tResult = null;
/**
* Create default connection requirements
*/
Description tConnectionRequirements = createHRMControllerDestinationDescription();
Logging.log(this, "Creating connection/comm. session to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
/**
* Create communication session
*/
Logging.log(this, " ..creating new communication session");
ComSession tComSession = new ComSession(this);
/**
* Wait until the FoGSiEm simulation is created
*/
if(HRMConfig.DebugOutput.BLOCK_HIERARCHY_UNTIL_END_OF_SIMULATION_CREATION)
{
while(!simulationCreationFinished()){
try {
Logging.log(this, "WAITING FOR END OF SIMULATION CREATION");
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
/**
* Connect to the neighbor node
*/
Connection tConnection = null;
Logging.log(this, " ..CONNECTING to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
try {
tConnection = connectBlock(pDestinationL2Address, tConnectionRequirements, getNode().getIdentity());
} catch (NetworkException tExc) {
Logging.err(this, "Cannot connect to: " + pDestinationL2Address, tExc);
}
Logging.log(this, " ..connectBlock() FINISHED");
if(tConnection != null) {
mCounterOutgoingConnections++;
Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections);
tComSession.startConnection(pDestinationL2Address, tConnection);
// return the created comm. session
tResult = tComSession;
}else{
Logging.err(this, " ..connection failed to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
}
return tResult;
}
/**
* Unregisters an outgoing communication session
*
* @param pComSession the session
*/
public void unregisterSession(ComSession pComSession)
{
Logging.log(this, "Unregistering outgoing communication session: " + pComSession);
synchronized (mCommunicationSessions) {
mCommunicationSessions.remove(pComSession);
}
}
/**
* Returns the list of registered own HRMIDs which can be used to address the physical node on which this instance is running.
*
* @return the list of HRMIDs
*/
@SuppressWarnings("unchecked")
public LinkedList<HRMID> getHRMIDs()
{
LinkedList<HRMID> tResult = null;
synchronized(mRegisteredOwnHRMIDs){
tResult = (LinkedList<HRMID>) mRegisteredOwnHRMIDs.clone();
}
return tResult;
}
/**
* Returns true if the given HRMID is a local one.
*
* @param pHRMID the HRMID
*
* @return true if the given HRMID is a local one
*/
private boolean isLocal(HRMID pHRMID)
{
boolean tResult = false;
synchronized(mRegisteredOwnHRMIDs){
for(HRMID tKnownHRMID : mRegisteredOwnHRMIDs){
if(tKnownHRMID.equals(pHRMID)){
tResult = true;
break;
}
}
}
return tResult;
}
/**
* Returns true if the given HRMID is a local one.
*
* @param pHRMID the HRMID of the Cluster
*
* @return true if the local node belongs to the given Cluster
*/
private boolean isLocalCluster(HRMID pHRMID)
{
boolean tResult = false;
if(pHRMID.isClusterAddress()){
synchronized(mRegisteredOwnHRMIDs){
for(HRMID tKnownHRMID : mRegisteredOwnHRMIDs){
//Logging.err(this, "Checking isCluster for " + tKnownHRMID + " and if it is " + pHRMID);
if(tKnownHRMID.isCluster(pHRMID)){
//Logging.err(this, " ..true");
tResult = true;
break;
}
}
}
}else{
Logging.err(this, "isLocalCluster() cannot operate on a given L0 node HRMID");
}
return tResult;
}
/**
* Determines the local sender address for a route with a given next hop
*
* @param pSource the given source
* @param pNextHop the given next hop
*
* @return the local sender address
*/
private HRMID getLocalSenderAddress(HRMID pSource, HRMID pNextHop)
{
HRMID tResult = pSource;
// figure out the L0 cluster
HRMID tNextHopL0Cluster = pNextHop;
tNextHopL0Cluster.setLevelAddress(0, 0);
synchronized(mRegisteredOwnHRMIDs){
// iterate over all local HRMIDs
for(HRMID tLocalHRMID : mRegisteredOwnHRMIDs){
if(!tLocalHRMID.isClusterAddress()){
if(tLocalHRMID.isCluster(tNextHopL0Cluster)){
tResult = tLocalHRMID.clone();
break;
}
}
}
}
return tResult;
}
/**
*
* @param pForeignHRMID
* @return
*/
private HRMID aggregateForeignHRMID(HRMID pForeignHRMID)
{
HRMID tResult = null;
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, "Aggrgating foreign HRMID: " + pForeignHRMID);
}
synchronized(mRegisteredOwnHRMIDs){
int tHierLevel = HRMConfig.Hierarchy.HEIGHT_LIMIT;
// iterate over all local HRMIDs
for(HRMID tLocalHRMID : mRegisteredOwnHRMIDs){
// ignore cluster addresses
if(!tLocalHRMID.isClusterAddress()){
/**
* Is the potentially foreign HRMID a local one?
*/
if(tLocalHRMID.equals(pForeignHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..found matching local HRMID: " + tLocalHRMID);
}
tResult = pForeignHRMID;
break;
}
/**
* Determine the foreign cluster in relation to current local HRMID
*/
HRMID tForeignCluster = tLocalHRMID.getForeignCluster(pForeignHRMID);
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..foreign cluster of " + pForeignHRMID + " for " + tLocalHRMID + " is " + tForeignCluster);
}
/**
* Update the result value
*/
if((tResult == null) || (tHierLevel < tForeignCluster.getHierarchyLevel())){
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..found better result: " + tResult + ", best lvl: " + tHierLevel + ", cur. lvl: " + tForeignCluster.getHierarchyLevel());
}
tHierLevel = tForeignCluster.getHierarchyLevel();
tResult = tForeignCluster;
}
}
}
}
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..result: " + tResult);
}
return tResult;
}
/**
* Adds an entry to the routing table of the local HRS instance.
* In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI.
* If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping.
*
* @param pRoutingEntry the new routing entry
*
* @return true if the entry had new routing data
*/
private int mCallsAddHRMRoute = 0;
private boolean addHRMRoute(RoutingEntry pRoutingEntry)
{
boolean tResult = false;
mCallsAddHRMRoute++;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Adding (" + mCallsAddHRMRoute + ") HRM routing table entry: " + pRoutingEntry);
}
// filter invalid destinations
if(pRoutingEntry.getDest() == null){
throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination in routing entry: " + pRoutingEntry);
}
// filter invalid next hop
if(pRoutingEntry.getNextHop() == null){
throw new RuntimeException(this + "::addHRMRoute() detected an invalid next hop in routing entry: " + pRoutingEntry);
}
// plausibility check
if((!pRoutingEntry.getDest().isClusterAddress()) && (!pRoutingEntry.getDest().equals(pRoutingEntry.getNextHop()))){
throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination (should be equal to the next hop) in routing entry: " + pRoutingEntry);
}
/**
* Inform the HRS about the new route
*/
tResult = getHRS().addHRMRoute(pRoutingEntry);
/**
* Notify GUI
*/
if(tResult){
//Logging.log(this, "Notifying GUI because of: " + pRoutingEntry + ", cause=" + pRoutingEntry.getCause());
// it's time to update the GUI
notifyGUI(pRoutingEntry);
}
return tResult;
}
/**
* Adds interesting parts of a received shared routing table
*
* @param pReceivedSharedRoutingTable the received shared routing table
* @param pReceiverHierarchyLevel the hierarchy level of the receiver
* @param pSenderHRMID the HRMID of the sender
* @param pCause the cause for this addition of routes
*/
public void addHRMRouteShare(RoutingTable pReceivedSharedRoutingTable, HierarchyLevel pReceiverHierarchyLevel, HRMID pSenderHRMID, String pCause)
{
for(RoutingEntry tNewEntry : pReceivedSharedRoutingTable){
RoutingEntry tSharedEntry = tNewEntry.clone();
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
// Logging.err(this, " ..received shared route: " + tNewEntry + ", aggregated foreign destination: " + aggregateForeignHRMID(tNewEntry.getDest()));
}
/**
* Mark as shared entry
*/
tSharedEntry.setSharedLink(pSenderHRMID);
/**
* Store all routes, which start at this node
*/
if(isLocal(tSharedEntry.getSource())){
/**
* ignore routes to cluster this nodes belong to
* => such routes are already known based on neighborhood detection of the L0 comm. channels (Clusters)
*/
if(!isLocalCluster(tSharedEntry.getDest())){
if(tSharedEntry.getHopCount() > 1){
RoutingEntry tNewLocalRoutingEntry = tSharedEntry.clone();
// patch the source with the correct local sender address
tNewLocalRoutingEntry.setSource(getLocalSenderAddress(tNewLocalRoutingEntry.getSource(), tNewLocalRoutingEntry.getNextHop()));
tNewLocalRoutingEntry.extendCause(pCause);
tNewLocalRoutingEntry.extendCause(this + "::addHRMRouteShare() at lvl: " + pReceiverHierarchyLevel.getValue());
/**
* Set the timeout for the found shared route
* => 2 times the time period between two share phase for the sender's hierarchy level
*/
double tTimeoffset = 2 * getPeriodSharePhase(pReceiverHierarchyLevel.getValue() + 1 /* the sender is one level above */);
tNewLocalRoutingEntry.setTimeout(getSimulationTime() + tTimeoffset);
/**
* Store the found route
*/
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "Adding shared route (timeout=" + tNewLocalRoutingEntry.getTimeout() + ", time-offset=" + tTimeoffset + "): " + tNewLocalRoutingEntry);
}
addHRMRoute(tNewLocalRoutingEntry);
}else{
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE_REDUNDANT_ROUTES){
Logging.warn(this, " ..dropping uninteresting (leads to a direct neighbor node/cluster) route: " + tSharedEntry);
}
}
}else{
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE_REDUNDANT_ROUTES){
Logging.warn(this, " ..dropping uninteresting (has same next hop like an existing entry) route: " + tSharedEntry);
}
}
}
}
}
/**
* Registers automatically new links in the HRG based on a given routing table entry.
* This function uses mainly the source and the next hop address. It switches between the hierarchy levels and derives for each hierarchy level the HRG link.
* For example, if a route from 1.2.3 to next 2.5.1 in order to reach 2.0.0 is given, then the following links will be added:
* 1.2.3 <==> 2.5.1
* 1.2.0 <==> 2.5.0
* 1.0.0 <==> 2.0.0
*
* @param pRoutingEntry the routing table entry
*/
public void registerAutoHRG(RoutingEntry pRoutingEntry)
{
HRMID tDestHRMID = pRoutingEntry.getDest();
if(tDestHRMID != null){
if((!tDestHRMID.isClusterAddress()) || (pRoutingEntry.getNextHop().isCluster(tDestHRMID))){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") node-2-node HRG link from " + pRoutingEntry.getSource() + " to " + pRoutingEntry.getNextHop() + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
tRoutingEntry.extendCause(this + "::registerAutoHRG() as " + tRoutingEntry);
tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
double tBefore = HRMController.getRealTime();
registerLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), tRoutingEntry);
double tSpentTime = HRMController.getRealTime() - tBefore;
if(tSpentTime > 30){
Logging.log(this, " ..registerAutoHRG()::registerLinkHRG() took " + tSpentTime + " ms for processing " + pRoutingEntry);
}
}
HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource());
// get the hierarchy level at which this link connects two clusters
int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel();
// initialize the source cluster HRMID
HRMID tSourceClusterHRMID = pRoutingEntry.getSource();
// initialize the destination cluster HRMID
HRMID tDestClusterHRMID = pRoutingEntry.getNextHop();
for(int i = 0; i <= tLinkHierLvl; i++){
// reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID
tSourceClusterHRMID.setLevelAddress(i, 0);
tDestClusterHRMID.setLevelAddress(i, 0);
if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
// tRoutingEntry.setDest(tDestClusterHRMID);
// RoutingEntry.create(pRoutingEntry.getSource().clone(), tDestClusterHRMID.clone(), pRoutingEntry.getNextHop().clone(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause());
// tRoutingEntry.setNextHopL2Address(pRoutingEntry.getNextHopL2Address());
tRoutingEntry.extendCause(this + "::registerAutoHRG() with destination " + tRoutingEntry.getDest() + ", org. destination=" +pRoutingEntry.getDest() + " as " + tRoutingEntry);
// tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
registerCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry);
}
}
}
}
/**
* Adds a table to the routing table of the local HRS instance.
* In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI.
* If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping.
*
* @param pRoutingTable the routing table with new entries
*
* @return true if the table had new routing data
*/
public boolean addHRMRoutes(RoutingTable pRoutingTable)
{
boolean tResult = false;
for(RoutingEntry tEntry : pRoutingTable){
tResult |= addHRMRoute(tEntry);
}
return tResult;
}
/**
* Deletes a route from the local HRM routing table.
*
* @param pRoutingTableEntry the routing table entry
*
* @return true if the entry was found and removed, otherwise false
*/
private boolean delHRMRoute(RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Deleting HRM routing table entry: " + pRoutingEntry);
}
/**
* Inform the HRS about the new route
*/
tResult = getHRS().delHRMRoute(pRoutingEntry);
/**
* Notify GUI
*/
if(tResult){
pRoutingEntry.extendCause(this + "::delHRMRoute()");
// it's time to update the GUI
notifyGUI(pRoutingEntry);
}
return tResult;
}
/**
* Unregisters automatically old links from the HRG based on a given routing table entry
*
* @param pRoutingEntry the routing table entry
*/
public void unregisterAutoHRG(RoutingEntry pRoutingEntry)
{
HRMID tDestHRMID = pRoutingEntry.getDest();
if(tDestHRMID != null){
if((!tDestHRMID.isClusterAddress()) || (pRoutingEntry.getNextHop().isCluster(tDestHRMID))){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..unregistering (" + mCallsAddHRMRoute + ") node-2-node HRG link from " + pRoutingEntry.getSource() + " to " + pRoutingEntry.getNextHop() + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
unregisterLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), tRoutingEntry);
}
HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource());
// get the hierarchy level at which this link connects two clusters
int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel();
// initialize the source cluster HRMID
HRMID tSourceClusterHRMID = pRoutingEntry.getSource().clone();
// initialize the destination cluster HRMID
HRMID tDestClusterHRMID = pRoutingEntry.getNextHop().clone();
for(int i = 0; i <= tLinkHierLvl; i++){
// reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID
tSourceClusterHRMID.setLevelAddress(i, 0);
tDestClusterHRMID.setLevelAddress(i, 0);
if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..unregistering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
// tRoutingEntry.setDest(tDestClusterHRMID);
// RoutingEntry.create(pRoutingEntry.getSource().clone(), tDestClusterHRMID.clone(), pRoutingEntry.getNextHop().clone(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause());
// tRoutingEntry.setNextHopL2Address(pRoutingEntry.getNextHopL2Address());
tRoutingEntry.extendCause(this + "::unregisterAutoHRG() with destination " + tRoutingEntry.getDest() + ", org. destination=" +pRoutingEntry.getDest());
// tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
unregisterCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry);
}
}
}
}
/**
* Removes a table from the routing table of the local HRS instance.
*
* @param pRoutingTable the routing table with old entries
*
* @return true if the table had existing routing data
*/
public boolean delHRMRoutes(RoutingTable pRoutingTable)
{
boolean tResult = false;
for(RoutingEntry tEntry : pRoutingTable){
RoutingEntry tDeleteThis = tEntry.clone();
tDeleteThis.extendCause(this + "::delHRMRoutes()");
tResult |= delHRMRoute(tDeleteThis);
}
return tResult;
}
/**
* Adds a route to the local L2 routing table.
*
* @param pToL2Address the L2Address of the destination
* @param pRoute the route to the direct neighbor
*/
public void registerLinkL2(L2Address pToL2Address, Route pRoute)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING LINK (L2):\n DEST.=" + pToL2Address + "\n LINK=" + pRoute);
}
// inform the HRS about the new route
if(getHRS().registerLinkL2(pToL2Address, pRoute)){
// it's time to update the GUI
notifyGUI(pRoute);
}
}
/**
* Connects to a service with the given name. Method blocks until the connection has been set up.
*
* @param pDestination the connection destination
* @param pRequirements the requirements for the connection
* @param pIdentity the identity of the connection requester
*
* @return the created connection
*
* @throws NetworkException
*/
private Connection connectBlock(Name pDestination, Description pRequirements, Identity pIdentity) throws NetworkException
{
Logging.log(this, "\n\n\n========> OUTGOING CONNECTION REQUEST TO: " + pDestination + " with requirements: " + pRequirements);
// connect
Connection tConnection = getLayer().connect(pDestination, pRequirements, pIdentity);
Logging.log(this, " ..=====> got connection: " + tConnection);
// create blocking event handler
BlockingEventHandling tBlockingEventHandling = new BlockingEventHandling(tConnection, 1);
// wait for the first event
Event tEvent = tBlockingEventHandling.waitForEvent();
Logging.log(this, " ..=====> got connection event: " + tEvent);
if(tEvent instanceof ConnectedEvent) {
if(!tConnection.isConnected()) {
throw new NetworkException(this, "Connected event but connection is not connected.");
} else {
return tConnection;
}
}else if(tEvent instanceof ErrorEvent) {
Exception exc = ((ErrorEvent) tEvent).getException();
if(exc instanceof NetworkException) {
throw (NetworkException) exc;
} else {
throw new NetworkException(this, "Can not connect to " + pDestination +".", exc);
}
}else{
throw new NetworkException(this, "Can not connect to " + pDestination +" due to " + tEvent);
}
}
/**
* Marks the FoGSiEm simulation creation as finished.
*/
public static void eventSimulationCreationHasFinished()
{
mFoGSiEmSimulationCreationFinished = true;
/**
* Reset FoGSiEm configuration
*/
GUI_USER_CTRL_REPORT_TOPOLOGY = HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY;
GUI_USER_CTRL_SHARE_ROUTES = HRMConfig.Routing.SHARE_ROUTES_AUTOMATICALLY;
GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = true;
mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = 0;
}
/**
* Checks if the entire simulation was created
*
* @return true or false
*/
private boolean simulationCreationFinished()
{
return mFoGSiEmSimulationCreationFinished;
}
/**
* Determines the Cluster object (on hierarchy level 0) for a given network interface
*
* @param pInterface the network interface
*
* @return the found Cluster object, null if nothing was found
*/
private Cluster getBaseHierarchyLevelCluster(NetworkInterface pInterface)
{
Cluster tResult = null;
LinkedList<Cluster> tBaseClusters = getAllClusters(HierarchyLevel.BASE_LEVEL);
for (Cluster tCluster : tBaseClusters){
NetworkInterface tClusterNetIf = tCluster.getBaseHierarchyLevelNetworkInterface();
if ((pInterface == tClusterNetIf) || (pInterface.equals(tCluster.getBaseHierarchyLevelNetworkInterface()))){
tResult = tCluster;
}
}
return tResult;
}
/**
* Determines the hierarchy node priority for Election processes
*
* @return the hierarchy node priority
*/
public long getHierarchyNodePriority(HierarchyLevel pLevel)
{
if (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pLevel.getValue();
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
return mNodeHierarchyPriority[tHierLevel];
}else{
return getConnectivityNodePriority();
}
}
/**
* Determines the connectivity node priority for Election processes
*
* @return the connectivity node priority
*/
public long getConnectivityNodePriority()
{
return mNodeConnectivityPriority;
}
/**
* Sets new connectivity node priority for Election processes
*
* @param pPriority the new connectivity node priority
*/
private int mConnectivityPriorityUpdates = 0;
private synchronized void setConnectivityPriority(long pPriority)
{
Logging.log(this, "Setting new connectivity node priority: " + pPriority);
mNodeConnectivityPriority = pPriority;
mConnectivityPriorityUpdates++;
/**
* Inform all local ClusterMembers/Clusters at level 0 about the change
* HINT: we have to enforce a permanent lock of mLocalClusterMembers,
* otherwise race conditions might be caused (another ClusterMemeber
* could be created while we are updating the priorities of all the
* formerly known ones)
* HINT: mLocalClusterMembers also contains all local Clusters
*/
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<ClusterMember> tLocalL0ClusterMembers = getAllL0ClusterMembers();
Logging.log(this, " ..informing about the priority (" + pPriority + ") update (" + mConnectivityPriorityUpdates + ")");
int i = 0;
for(ClusterMember tClusterMember : tLocalL0ClusterMembers){
// only base hierarchy level!
if(tClusterMember.getHierarchyLevel().isBaseLevel()){
Logging.log(this, " ..update (" + mConnectivityPriorityUpdates + ") - informing[" + i + "]: " + tClusterMember);
tClusterMember.eventConnectivityNodePriorityUpdate(getConnectivityNodePriority());
i++;
}
}
}
/**
* EVENT: hierarchy data changed
*/
private void eventHierarchyDataChanged()
{
/**
* Refresh the stored simulation time describing when the last AnnounceCoordinator packet had impact on the hierarchy
*/
mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = getSimulationTime();
/**
* If GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS is deactivated and the topology changes, we have deactivated the
* AnnounceCoordinator packets too early or the user has deactivated it too early. -> this leads to faulty results with a high probability
*/
if(!GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
Logging.err(this, "------------------------------------------------------------------------------------------------------------------");
Logging.err(this, "--- Detected a hierarchy data change when GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS was already set to false ");
Logging.err(this, "------------------------------------------------------------------------------------------------------------------");
}
}
/**
* Distributes hierarchy node priority update to all important local entities
*
* @param pHierarchyLevel the hierarchy level
*/
public void distributeHierarchyNodePriorityUpdate(HierarchyLevel pHierarchyLevel)
{
long tNewPrio = getHierarchyNodePriority(pHierarchyLevel);
/**
* Inform all local CoordinatorAsClusterMemeber objects about the change
* HINT: we have to enforce a permanent lock of mLocalCoordinatorAsClusterMemebers,
* otherwise race conditions might be caused (another CoordinatorAsClusterMemeber
* could be created while we are updating the priorities of all the
* formerly known ones)
*/
Logging.log(this, " ..informing about the priority (" + tNewPrio + ") update (" + mHierarchyPriorityUpdates + ")");
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<CoordinatorAsClusterMember> tLocalCoordinatorAsClusterMembers = getAllCoordinatorAsClusterMembers();
int i = 0;
for(CoordinatorAsClusterMember tCoordinatorAsClusterMember : tLocalCoordinatorAsClusterMembers){
if((tCoordinatorAsClusterMember.getHierarchyLevel().equals(pHierarchyLevel)) || (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
Logging.log(this, " ..update (" + mHierarchyPriorityUpdates + ") - informing[" + i + "]: " + tCoordinatorAsClusterMember);
tCoordinatorAsClusterMember.eventHierarchyNodePriorityUpdate(getHierarchyNodePriority(pHierarchyLevel));
i++;
}
}
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<Cluster> tLocalClusters = getAllClusters();
i = 0;
for(Cluster tLocalCluster : tLocalClusters){
if((tLocalCluster.getHierarchyLevel().equals(pHierarchyLevel)) || (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
Logging.log(this, " ..update (" + mHierarchyPriorityUpdates + ") - informing[" + i + "]: " + tLocalCluster);
tLocalCluster.eventHierarchyNodePriorityUpdate(getHierarchyNodePriority(pHierarchyLevel));
i++;
}
}
}
/**
* Sets new hierarchy node priority for Election processes
*
* @param pPriority the new hierarchy node priority
* @param pHierarchyLevel the hierarchy level
*/
private int mHierarchyPriorityUpdates = 0;
private synchronized void setHierarchyPriority(long pPriority, HierarchyLevel pHierarchyLevel)
{
Logging.log(this, "Setting new hierarchy node priority: " + pPriority);
mNodeHierarchyPriority[pHierarchyLevel.getValue()] = pPriority;
mHierarchyPriorityUpdates++;
Logging.log(this, " ..informing about the priority (" + pPriority + ") update (" + mHierarchyPriorityUpdates + ")");
/**
* Asynchronous execution of "distributeHierarchyNodePriorityUpdate()" inside context of HRMControllerProcessor.
* This also reduces convergence time for finding the correct network clustering
*/
mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel);
//HINT: for synchronous execution use here "distributeHierarchyNodePriorityUpdate(pHierarchyLevel)"
// instead of "mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel)"
/**
* Trigger: hierarchy data changed
*/
eventHierarchyDataChanged();
}
/**
* Increases base Bully priority
*
* @param pCausingInterfaceToNeighbor the update causing interface to a neighbor
*/
private synchronized void increaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor)
{
// get the current priority
long tPriority = getConnectivityNodePriority();
Logging.log(this, "Increasing node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Increasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Decreases base Bully priority
*
* @param pCausingInterfaceToNeighbor the update causing interface to a neighbor
*/
private synchronized void decreaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor)
{
// get the current priority
long tPriority = getConnectivityNodePriority();
Logging.log(this, "Decreasing node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Decreasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Increases hierarchy Bully priority
*
* @param pCausingEntity the update causing entity
*/
public void increaseHierarchyNodePriority_KnownCoordinator(ControlEntity pCausingEntity)
{
/**
* Are we at base hierarchy level or should we accept all levels?
*/
if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1;
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
int tDistance = 0;
if(pCausingEntity instanceof CoordinatorProxy){
tDistance = ((CoordinatorProxy)pCausingEntity).getDistance();
}
int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS;
if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){
tMaxDistance = 256; //TODO: use a definition here
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance);
}
Logging.log(this, "Increasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance);
// increase priority
tPriority += (long)(tOffset);
mDesriptionHierarchyPriorityUpdates += "\n + " + tOffset + "-L" + tHierLevel + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity;
// update priority
setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel));
}else{
Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance);
}
}
}
/**
* Decreases hierarchy Bully priority
*
* @param pCausingEntity the update causing entity
*/
public void decreaseHierarchyNodePriority_KnownCoordinator(ControlEntity pCausingEntity)
{
/**
* Are we at base hierarchy level or should we accept all levels?
*/
if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1;
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
int tDistance = 0;
if(pCausingEntity instanceof CoordinatorProxy){
tDistance = ((CoordinatorProxy)pCausingEntity).getDistance();
}
int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS;
if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){
tMaxDistance = 256; //TODO: use a definition here
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance);
}
Logging.log(this, "Decreasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance);
// decrease priority
tPriority -= (long)(tOffset);
mDesriptionHierarchyPriorityUpdates += "\n - " + tOffset + "-L" + tHierLevel + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity;
// update priority
setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel));
}else{
Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance);
}
}
}
/**
* Returns a description about all connectivity priority updates.
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionConnectivityPriorityUpdates()
{
return mDesriptionConnectivityPriorityUpdates;
}
/**
* Returns a description about all HRMID updates.
*
* @return the description
*/
public String getGUIDescriptionHRMIDChanges()
{
return mDescriptionHRMIDUpdates;
}
/**
* Returns a description about all HRG updates.
*
* @return the description
*/
public String getGUIDescriptionHRGChanges()
{
return mDescriptionHRGUpdates;
}
/**
* Returns a description about all hierarchy priority updates
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionHierarchyPriorityUpdates()
{
return mDesriptionHierarchyPriorityUpdates;
}
/**
* Returns a log about "update cluster" events
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionClusterUpdates()
{
return mProcessorThread.getGUIDescriptionClusterUpdates();
}
/**
* Returns a description about all used cluster addresses
*
* @return the description
*/
public String getGUIDEscriptionUsedAddresses()
{
String tResult = "";
LinkedList<Cluster> tAllClusters = getAllClusters();
for (Cluster tCluster : tAllClusters){
tResult += "\n .." + tCluster + " uses these addresses:";
LinkedList<Integer> tUsedAddresses = tCluster.getUsedAddresses();
int i = 0;
for (int tUsedAddress : tUsedAddresses){
tResult += "\n ..[" + i + "]: " + tUsedAddress;
i++;
}
LinkedList<ComChannel> tAllClusterChannels = tCluster.getComChannels();
tResult += "\n .." + tCluster + " channels:";
i = 0;
for(ComChannel tComChannel : tAllClusterChannels){
tResult += "\n ..[" + i + "]: " + tComChannel;
i++;
}
}
return tResult;
}
/**
* Reacts on a lost physical neighbor.
* HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN!
*
* @param pInterfaceToNeighbor the network interface to the neighbor
* @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus.
*/
public synchronized void eventLostPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, L2Address pNeighborL2Address)
{
Logging.log(this, "\n\n\n############## LOST DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor);
synchronized (mCommunicationSessions) {
Logging.log(this, " ..known sessions: " + mCommunicationSessions);
for (ComSession tComSession : mCommunicationSessions){
if(tComSession.isPeer(pNeighborL2Address)){
Logging.log(this, " ..stopping session: " + tComSession);
tComSession.stopConnection();
}else{
Logging.log(this, " ..leaving session: " + tComSession);
}
}
}
synchronized (mLocalNetworkInterfaces) {
if(mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){
Logging.log(this, "\n######### Detected lost network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.remove(pInterfaceToNeighbor); //TODO: multiple nodes!?
}
decreaseNodePriority_Connectivity(pInterfaceToNeighbor);
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
}
/**
* Reacts on a detected new physical neighbor. A new connection to this neighbor is created.
* HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN!
*
* @param pInterfaceToNeighbor the network interface to the neighbor
* @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus.
*/
public synchronized void eventDetectedPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, final L2Address pNeighborL2Address)
{
Logging.log(this, "\n\n\n############## FOUND DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor);
/**
* Helper for having access to the HRMController within the created thread
*/
final HRMController tHRMController = this;
/**
* Create connection thread
*/
Thread tThread = new Thread() {
public String toString()
{
return tHRMController.toString();
}
public void run()
{
Thread.currentThread().setName("NeighborConnector@" + tHRMController.getNodeGUIName() + " for " + pNeighborL2Address);
/**
* Create/get the cluster on base hierarchy level
*/
Cluster tParentCluster = null;
synchronized (mLocalNetworkInterfaces) {
if(!mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){
Logging.log(this, "\n######### Detected new network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.add(pInterfaceToNeighbor);
}
//HINT: we make sure that we use only one Cluster object per Bus
Cluster tExistingCluster = getBaseHierarchyLevelCluster(pInterfaceToNeighbor);
if (tExistingCluster != null){
Logging.log(this, " ..using existing level0 cluster: " + tExistingCluster);
tParentCluster = tExistingCluster;
}else{
Logging.log(this, " ..knowing level0 clusters: " + getAllClusters(0));
Logging.log(this, " ..creating new level0 cluster");
tParentCluster = Cluster.createBaseCluster(tHRMController);
tParentCluster.setBaseHierarchyLevelNetworkInterface(pInterfaceToNeighbor);
increaseNodePriority_Connectivity(pInterfaceToNeighbor);
// updates the GUI decoration for this node
updateGUINodeDecoration();
}
}
/**
* Create communication session
*/
Logging.log(this, " ..get/create communication session");
ComSession tComSession = getCreateComSession(pNeighborL2Address);
if(tComSession != null) {
/**
* Update ARG
*/
//registerLinkARG(this, tParentCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.REMOTE_CONNECTION));
/**
* Create communication channel
*/
Logging.log(this, " ..creating new communication channel");
ComChannel tComChannel = new ComChannel(tHRMController, ComChannel.Direction.OUT, tParentCluster, tComSession);
tComChannel.setRemoteClusterName(tParentCluster.createClusterName());
/**
* Send "RequestClusterMembership" along the comm. session
* HINT: we cannot use the created channel because the remote side doesn't know anything about the new comm. channel yet)
*/
RequestClusterMembership tRequestClusterMembership = new RequestClusterMembership(getNodeName(), pNeighborL2Address, tParentCluster.createClusterName(), tParentCluster.createClusterName());
Logging.log(this, " ..sending membership request: " + tRequestClusterMembership);
if (tComSession.write(tRequestClusterMembership)){
Logging.log(this, " ..requested sucessfully for membership of: " + tParentCluster + " at node " + pNeighborL2Address);
}else{
Logging.log(this, " ..failed to request for membership of: " + tParentCluster + " at node " + pNeighborL2Address);
}
Logging.log(this, "Connection thread for " + pNeighborL2Address + " finished");
}else{
Logging.log(this, "Connection thread for " + pNeighborL2Address + " failed");
}
}
};
/**
* Start the connection thread
*/
tThread.start();
}
/**
* Determines a reference to the current AutonomousSystem instance.
*
* @return the desired reference
*/
public AutonomousSystem getAS()
{
return mAS;
}
/**
* Returns the node-global election state
*
* @return the node-global election state
*/
public Object getNodeElectionState()
{
return mNodeElectionState;
}
/**
* Returns the node-global election state change description
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public Object getGUIDescriptionNodeElectionStateChanges()
{
return mDescriptionNodeElectionState;
}
/**
* Adds a description to the node-global election state change description
*
* @param pAdd the additive string
*/
public void addGUIDescriptionNodeElectionStateChange(String pAdd)
{
mDescriptionNodeElectionState += pAdd;
}
/**
* Determines the current simulation time
*
* @return the simulation time
*/
public double getSimulationTime()
{
return mAS.getTimeBase().now();
}
/**
* Determines the current real time
*
* @return the real time in [ms]
*/
public static double getRealTime()
{
double tResult = 0;
Date tDate = new Date();
tResult = tDate.getTime();
return tResult;
}
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.IEvent#fire()
*/
@Override
public void fire()
{
reportAndShare();
}
/**
* Auto-removes all deprecated coordinator proxies
*/
private void autoRemoveObsoleteCoordinatorProxies()
{
if(HRMController.GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
LinkedList<CoordinatorProxy> tProxies = getAllCoordinatorProxies();
for(CoordinatorProxy tProxy : tProxies){
// does the link have a timeout?
if(tProxy.isObsolete()){
Logging.log(this, "AUTO REMOVING COORDINATOR PROXY: " + tProxy);
/**
* Trigger: remote coordinator role invalid
*/
tProxy.eventRemoteCoordinatorRoleInvalid();
}
}
}
}
/**
* Auto-deactivates AnnounceCoordinator packets.
* This function is only useful for measurement speedup or to ease debugging. It is neither part of the concept nor it is used to derive additional data. It only reduces packet overhead in the network.
*/
private void autoDeactivateAnnounceCoordinator()
{
if(mSimulationTimeOfLastCoordinatorAnnouncementWithImpact != 0){
double tTimeWithFixedHierarchyData = getSimulationTime() - mSimulationTimeOfLastCoordinatorAnnouncementWithImpact;
//Logging.log(this, "Simulation time of last AnnounceCoordinator with impact: " + mSimulationTimeOfLastCoordinatorAnnouncementWithImpact + ", time diff: " + tTimeWithFixedHierarchyData);
if(HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS){
if(GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
/**
* Auto-deactivate the AnnounceCoordinator packets if no further change in hierarchy data is expected anymore
*/
if(tTimeWithFixedHierarchyData > HRMConfig.Hierarchy.COORDINATOR_TIMEOUT * 2){
GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = false;
Logging.warn(this, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.warn(this, "+++ Deactivating AnnounceCoordinator packets due to long-term stability of hierarchy data");
Logging.warn(this, "+++ Current simulation time: " + getSimulationTime() + ", treshold time diff: " + (HRMConfig.Hierarchy.COORDINATOR_TIMEOUT * 2) + ", time with stable hierarchy data: " + tTimeWithFixedHierarchyData);
Logging.warn(this, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
if(HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS_AUTO_START_REPORTING_SHARING){
autoActivateReportingSharing();
}
}
}
}
}
}
/**
* Auto-activates reporting/sharing after AnnounceCoordinator packets were deactivated.
*/
private void autoActivateReportingSharing()
{
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.warn(this, "+++ Activating reporting/sharing of topology data");
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
GUI_USER_CTRL_REPORT_TOPOLOGY = true;
}
/**
* Triggers the "report phase" / "share phase" of all known coordinators
*/
private void reportAndShare()
{
if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){
Logging.log(this, "REPORT AND SHARE TRIGGER received");
}
/**
* auto-deactivate AnnounceCoordinator
*/
autoDeactivateAnnounceCoordinator();
/**
* auto-remove old CoordinatorProxies
*/
autoRemoveObsoleteCoordinatorProxies();
/**
* auto-remove old HRG links
*/
autoRemoveObsoleteHRGLinks();
/**
* generalize all known HRM routes to neighbors
*/
// generalizeMeighborHRMRoutesAuto();
if(GUI_USER_CTRL_REPORT_TOPOLOGY){
/**
* report phase
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.reportPhase();
}
if(GUI_USER_CTRL_SHARE_ROUTES){
/**
* share phase
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.sharePhase();
}
}
}
/**
* auto-remove old HRM routes
*/
autoRemoveObsoleteHRMRoutes();
/**
* register next trigger
*/
mAS.getTimeBase().scheduleIn(HRMConfig.Routing.GRANULARITY_SHARE_PHASE, this);
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodSharePhase(int pHierarchyLevelValue)
{
return (double) 2 * HRMConfig.Routing.GRANULARITY_SHARE_PHASE * pHierarchyLevelValue; //TODO: use an exponential time distribution here
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodReportPhase(HierarchyLevel pHierarchyLevel)
{
return (double) HRMConfig.Routing.GRANULARITY_SHARE_PHASE * (pHierarchyLevel.getValue() - 1); //TODO: use an exponential time distribution here
}
/**
* This method is derived from IServerCallback. It is called by the ServerFN in order to acquire the acknowledgment from the HRMController about the incoming connection
*
* @param pAuths the authentications of the requesting sender
* @param pRequirements the requirements for the incoming connection
* @param pTargetName the registered name of the addressed target service
* @return true of false
*/
@Override
public boolean openAck(LinkedList<Signature> pAuths, Description pRequirements, Name pTargetName)
{
//TODO: check if a neighbor wants to explore its neighbor -> select if we want to join its cluster or not
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Incoming request for acknowledging the connection:");
Logging.log(this, " ..source: " + pAuths);
Logging.log(this, " ..destination: " + pTargetName);
Logging.log(this, " ..requirements: " + pRequirements);
}
return true;
}
/**
* Helper function to get the local machine's host name.
* The output of this function is useful for distributed simulations if coordinators/clusters with the name might coexist on different machines.
*
* @return the host name
*/
public static String getHostName()
{
String tResult = null;
try{
tResult = java.net.InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException tExc) {
Logging.err(null, "Unable to determine the local host name", tExc);
}
return tResult;
}
/**
* Determines the L2Address of the first FN towards a neighbor. This corresponds to the FN, located between the central FN and the bus to the neighbor node.
*
* @param pNeighborName the name of the neighbor
* @return the L2Address of the search FN
*/
public L2Address getL2AddressOfFirstFNTowardsNeighbor(Name pNeighborName)
{
L2Address tResult = null;
if (pNeighborName != null){
Route tRoute = null;
// get the name of the central FN
L2Address tCentralFNL2Address = getHRS().getCentralFNL2Address();
// get a route to the neighbor node (the destination of the desired connection)
try {
tRoute = getHRS().getRoute(pNeighborName, new Description(), getNode().getIdentity());
} catch (RoutingException tExc) {
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName, tExc);
} catch (RequirementsException tExc) {
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName + " with requirements no requirents, Huh!", tExc);
}
// have we found a route to the neighbor?
if((tRoute != null) && (!tRoute.isEmpty())) {
// get the first route part, which corresponds to the link between the central FN and the searched first FN towards the neighbor
RouteSegmentPath tPath = (RouteSegmentPath) tRoute.getFirst();
// check if route has entries
if((tPath != null) && (!tPath.isEmpty())){
// get the gate ID of the link
GateID tGateID = tPath.getFirst();
RoutingServiceLink tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = null;
boolean tWithoutException = false; //TODO: rework some software structures to avoid this ugly implementation
while(!tWithoutException){
try{
// get all outgoing links from the central FN
Collection<RoutingServiceLink> tOutgoingLinksFromCentralFN = getHRS().getOutgoingLinks(tCentralFNL2Address);
// iterate over all outgoing links and search for the link from the central FN to the FN, which comes first when routing towards the neighbor
for(RoutingServiceLink tLink : tOutgoingLinksFromCentralFN) {
// compare the GateIDs
if(tLink.equals(tGateID)) {
// found!
tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = tLink;
}
}
tWithoutException = true;
}catch(ConcurrentModificationException tExc){
// FoG has manipulated the topology data and called the HRS for updating the L2 routing graph
continue;
}
}
// determine the searched FN, which comes first when routing towards the neighbor
HRMName tFirstNodeBeforeBusToNeighbor = getHRS().getL2LinkDestination(tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor);
if (tFirstNodeBeforeBusToNeighbor instanceof L2Address){
// get the L2 address
tResult = (L2Address)tFirstNodeBeforeBusToNeighbor;
}else{
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() found a first FN (" + tFirstNodeBeforeBusToNeighbor + ") towards the neighbor " + pNeighborName + " but it has the wrong class type");
}
}else{
Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an empty route to \"neighbor\": " + pNeighborName);
}
}else{
Logging.warn(this, "Got for neighbor " + pNeighborName + " the route: " + tRoute); //HINT: this could also be a local loop -> throw only a warning
}
}else{
Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an invalid neighbor name");
}
return tResult;
}
/**
* This function gets called if the HRMController appl. was started
*/
@Override
protected void started()
{
mApplicationStarted = true;
// register in the global HRMController database
synchronized (mRegisteredHRMControllers) {
mRegisteredHRMControllers.add(this);
}
}
/**
* This function gets called if the HRMController appl. should exit/terminate right now
*/
@Override
public synchronized void exit()
{
mApplicationStarted = false;
Logging.log(this, "\n\n\n############## Exiting..");
Logging.log(this, " ..destroying clusterer-thread");
mProcessorThread.exit();
mProcessorThread = null;
Logging.log(this, " ..destroying all clusters/coordinators");
for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
LinkedList<Cluster> tClusters = getAllClusters(i);
for(Cluster tCluster : tClusters){
tCluster.eventClusterRoleInvalid();
}
}
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
tComSession.stopConnection();
}
}
// register in the global HRMController database
Logging.log(this, " ..removing from the global HRMController database");
synchronized (mRegisteredHRMControllers) {
mRegisteredHRMControllers.remove(this);
}
}
/**
* Return if the HRMController application is running
*
* @return true if the HRMController application is running, otherwise false
*/
@Override
public boolean isRunning()
{
return mApplicationStarted;
}
/**
* Returns the list of known HRMController instances for this physical simulation machine
*
* @return the list of HRMController references
*/
@SuppressWarnings("unchecked")
public static LinkedList<HRMController> getALLHRMControllers()
{
LinkedList<HRMController> tResult = null;
synchronized (mRegisteredHRMControllers) {
tResult = (LinkedList<HRMController>) mRegisteredHRMControllers.clone();
}
return tResult;
}
/**
* Creates a Description, which directs a connection to another HRMController instance
* @return the new description
*/
private Description createHRMControllerDestinationDescription()
{
Description tResult = new Description();
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Creating a HRMController destination description");
}
tResult.set(new DestinationApplicationProperty(HRMController.ROUTING_NAMESPACE, null, null));
return tResult;
}
/**
* Registers a cluster/coordinator to the locally stored abstract routing graph (ARG)
*
* @param pNode the node (cluster/coordinator) which should be stored in the ARG
*/
private synchronized void registerNodeARG(ControlEntity pNode)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING NODE ADDRESS (ARG): " + pNode );
}
synchronized (mAbstractRoutingGraph) {
if(!mAbstractRoutingGraph.contains(pNode)) {
mAbstractRoutingGraph.add(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..added to ARG");
}
}else{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for ARG already known: " + pNode);
}
}
}
}
/**
* Unregisters a cluster/coordinator from the locally stored abstract routing graph (ARG)
*
* @param pNode the node (cluster/coordinator) which should be removed from the ARG
*/
private void unregisterNodeARG(ControlEntity pNode)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "UNREGISTERING NODE ADDRESS (ARG): " + pNode );
}
synchronized (mAbstractRoutingGraph) {
if(mAbstractRoutingGraph.contains(pNode)) {
mAbstractRoutingGraph.remove(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..removed from ARG");
}
}else{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for ARG wasn't known: " + pNode);
}
}
}
}
/**
* Registers a logical link between clusters/coordinators to the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pLink the link between the two nodes
*/
public void registerLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo, AbstractRoutingGraphLink pLink)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pLink);
}
synchronized (mAbstractRoutingGraph) {
mAbstractRoutingGraph.link(pFrom, pTo, pLink);
}
}
/**
* Unregisters a logical link between clusters/coordinators from the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
*/
public void unregisterLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo)
{
AbstractRoutingGraphLink tLink = getLinkARG(pFrom, pTo);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "UNREGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + tLink);
}
if(tLink != null){
synchronized (mAbstractRoutingGraph) {
mAbstractRoutingGraph.unlink(tLink);
}
}
}
/**
* Determines the link between two clusters/coordinators from the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
*
* @return the link between the two nodes
*/
public AbstractRoutingGraphLink getLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo)
{
AbstractRoutingGraphLink tResult = null;
List<AbstractRoutingGraphLink> tRoute = null;
synchronized (mAbstractRoutingGraph) {
tRoute = mAbstractRoutingGraph.getRoute(pFrom, pTo);
}
if((tRoute != null) && (!tRoute.isEmpty())){
if(tRoute.size() == 1){
tResult = tRoute.get(0);
}else{
/**
* We haven't found a direct link - we found a multi-hop route instead.
*/
//Logging.warn(this, "getLinkARG() expected a route with one entry but got: \nSOURCE=" + pFrom + "\nDESTINATION: " + pTo + "\nROUTE: " + tRoute);
}
}
return tResult;
}
/**
* Returns the ARG for the GraphViewer.
* (only for GUI!)
*
* @return the ARG
*/
public AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> getARGForGraphViewer()
{
AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> tResult = null;
synchronized (mAbstractRoutingGraph) {
tResult = mAbstractRoutingGraph; //TODO: use a new clone() method here
}
return tResult;
}
/**
* Registers an HRMID to the locally stored hierarchical routing graph (HRG)
*
* @param pNode the node (HRMID) which should be stored in the HRG
* @param pCause the cause for this HRG update
*/
private synchronized void registerNodeHRG(HRMID pNode, String pCause)
{
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "REGISTERING NODE ADDRESS (HRG): " + pNode );
}
if(pNode.isZero()){
throw new RuntimeException(this + " detected a zero HRMID for an HRG registration");
}
synchronized (mHierarchicalRoutingGraph) {
if(!mHierarchicalRoutingGraph.contains(pNode)) {
mDescriptionHRGUpdates += "\n + " + pNode + " <== " + pCause;
mHierarchicalRoutingGraph.add(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..added to HRG");
}
}else{
mDescriptionHRGUpdates += "\n +/- " + pNode + " <== " + pCause;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for HRG already known: " + pNode);
}
}
}
}
/**
* Unregisters an HRMID from the locally stored hierarchical routing graph (HRG)
*
* @param pNode the node (HRMID) which should be removed from the HRG
* @param pCause the cause for this HRG update
*/
private void unregisterNodeHRG(HRMID pNode, String pCause)
{
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "UNREGISTERING NODE ADDRESS (HRG): " + pNode );
}
synchronized (mHierarchicalRoutingGraph) {
if(mHierarchicalRoutingGraph.contains(pNode)) {
mDescriptionHRGUpdates += "\n - " + pNode + " <== " + pCause;
mHierarchicalRoutingGraph.remove(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..removed from HRG");
}
}else{
mDescriptionHRGUpdates += "\n -/+ " + pNode + " <== " + pCause;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for HRG wasn't known: " + pNode);
}
}
}
}
/**
* Registers a logical link between HRMIDs to the locally stored hierarchical routing graph (HRG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pRoutingEntry the routing entry for this link
*
* @return true if the link is new to the routing graph
*/
public boolean registerLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "REGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n ROUTE=" + pRoutingEntry);
}
if(!pFrom.equals(pTo)){
/**
* Derive the link
*/
double tBefore4 = HRMController.getRealTime();
pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph);
AbstractRoutingGraphLink tLink = new AbstractRoutingGraphLink(new Route(pRoutingEntry));
tLink.setTimeout(pRoutingEntry.getTimeout());
double tSpentTime4 = HRMController.getRealTime() - tBefore4;
if(tSpentTime4 > 10){
Logging.log(this, " ..registerLinkHRG()::AbstractRoutingGraphLink() took " + tSpentTime4 + " ms for processing " + pRoutingEntry);
}
/**
* Do the actual linking
*/
synchronized (mHierarchicalRoutingGraph) {
boolean tLinkAlreadyKnown = false;
double tBefore = HRMController.getRealTime();
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
double tSpentTime = HRMController.getRealTime() - tBefore;
if(tSpentTime > 10){
Logging.log(this, " ..registerLinkHRG()::getOutEdges() took " + tSpentTime + " ms for processing " + pRoutingEntry);
}
if(tLinks != null){
double tBefore3 = HRMController.getRealTime();
for(AbstractRoutingGraphLink tKnownLink : tLinks){
// check if both links are equal
if(tKnownLink.equals(tLink)){
// check of the end points of the already known link are equal to the pFrom/pTo
double tBefore2 = HRMController.getRealTime();
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink);
double tSpentTime2 = HRMController.getRealTime() - tBefore2;
if(tSpentTime2 > 10){
Logging.log(this, " ..registerLinkHRG()::getEndpoints() took " + tSpentTime2 + " ms for processing " + pRoutingEntry);
}
if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) ||
((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){
tKnownLink.incRefCounter();
tLinkAlreadyKnown = true;
if(pRoutingEntry.getTimeout() > 0){
tKnownLink.setTimeout(pRoutingEntry.getTimeout());
}
// it's time to update the HRG-GUI
notifyHRGGUI(tKnownLink);
}
}
}
double tSpentTime3 = HRMController.getRealTime() - tBefore3;
if(tSpentTime3 > 10){
Logging.log(this, " ..registerLinkHRG()::for() took " + tSpentTime3 + " ms for processing " + pRoutingEntry);
}
}
if(!tLinkAlreadyKnown){
mDescriptionHRGUpdates += "\n + " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
double tBefore1 = HRMController.getRealTime();
mHierarchicalRoutingGraph.link(pFrom.clone(), pTo.clone(), tLink);
// it's time to update the HRG-GUI
notifyHRGGUI(tLink);
double tSpentTime1 = HRMController.getRealTime() - tBefore1;
if(tSpentTime1 > 10){
Logging.log(this, " ..registerLinkHRG()::link() took " + tSpentTime1 + " ms for processing " + pRoutingEntry);
}
}else{
/**
* The link is already known -> this can occur if:
* - both end points are located on this node and both of them try to register the same route
* - a route was reported and received as shared
*/
if(HRMConfig.DebugOutput.MEMORY_CONSUMING_OPERATIONS){
mDescriptionHRGUpdates += "\n +" + (tLinkAlreadyKnown ? "(REF)" : "") + " " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
}
}
tResult = true;
}
}else{
//Logging.warn(this, "registerLinkHRG() skipped because self-loop detected for: " + pRoutingEntry);
}
return tResult;
}
/**
* Determines all possible destinations depending on a given root node and its hierarchy level
*
* @param pRootNode the root node
*
* @return the found possible destinations
*/
public LinkedList<HRMID> getSiblingsHRG(HRMID pRootNode)
{
LinkedList<HRMID> tResult = new LinkedList<HRMID>();
HRMID tSuperCluster = pRootNode.getSuperiorClusterAddress();
int tSearchedLvl = pRootNode.getHierarchyLevel();
synchronized (mHierarchicalRoutingGraph) {
// iterate over all nodes in the HRG
Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices();
for(HRMID tNode : tNodes){
if(!tNode.equals(pRootNode)){
// does the node belong to the same hierarchy level like the root node?
if(tNode.getHierarchyLevel() == tSearchedLvl){
if(tNode.isCluster(tSuperCluster)){
tResult.add(tNode.clone());
}else{
//Logging.log(this, "Dropping " + tNode + " as sibling of " + pRootNode);
}
}
}
}
}
return tResult;
}
/**
* Determines a route in the HRG from a given node/cluster to another one
*
* @param pFrom the starting point
* @param pTo the ending point
* @param pCause the cause for this call
*
* @return the found routing entry
*/
public RoutingEntry getRoutingEntryHRG(HRMID pFrom, HRMID pTo, String pCause)
{
boolean DEBUG = false;
RoutingEntry tResult = null;
if (DEBUG){
Logging.log(this, "getRoutingEntryHRG() searches a route from " + pFrom + " to " + pTo);
}
/**
* Are the source and destination addresses equal?
*/
if(pFrom.equals(pTo)){
// create a loop route
tResult = RoutingEntry.createLocalhostEntry(pFrom, pCause);
// describe the cause for the route
tResult.extendCause(this + "::getRoutingEntry() with same source and destination address " + pFrom);
// immediate return here
return tResult;
}
/**
* Is the source address more abstract than the destination one?
* EXAMPLE 1: we are searching for a route from 1.3.0 to 1.4.2.
*/
if(pFrom.getHierarchyLevel() > pTo.getHierarchyLevel()){
/**
* EXAMPLE 1: derive 1.4.0 from 1.4.2
*/
HRMID tAbstractDestination = pTo.getClusterAddress(pFrom.getHierarchyLevel());
if (DEBUG){
Logging.log(this, "getRoutingEntryHRG() searches a more abstract route from " + pFrom + " to more abstract destination " + tAbstractDestination);
}
/**
* EXAMPLE 1: determine the route from 1.3.0 to 1.4.0
* (assumption: the found route starts at 1.3.2 and ends at 1.4.1)
*/
RoutingEntry tFirstRoutePart = getRoutingEntryHRG(pFrom, tAbstractDestination, pCause);
if (DEBUG){
Logging.log(this, " ..first route part: " + tFirstRoutePart);
}
if(tFirstRoutePart != null){
HRMID tIngressGatewayToDestinationCluster = tFirstRoutePart.getLastNextHop();
/**
* EXAMPLE 1: determine the route from 1.4.1 to 1.4.2
*/
RoutingEntry tIntraClusterRoutePart = getRoutingEntryHRG(tIngressGatewayToDestinationCluster, pTo, pCause);
if (DEBUG){
Logging.log(this, " ..second route part: " + tIntraClusterRoutePart);
}
if(tIntraClusterRoutePart != null){
// clone the first part and use it as first part of the result
tResult = tFirstRoutePart.clone();
/**
* EXAMPLE 1: combine routes (1.3.2 => 1.4.1) AND (1.4.1 => 1.4.2)
*/
tResult.append(tIntraClusterRoutePart, pCause);
if (DEBUG){
Logging.log(this, " ..resulting route (" + pFrom + " ==> " + tAbstractDestination + "): " + tResult);
}
/**
* EXAMPLE 1: the result is a route from gateway 1.3.2 (belonging to 1.3.0) to 1.4.2
*/
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + tIngressGatewayToDestinationCluster + " to " + pTo + " as second part for a route from " + pFrom + " to " + pTo);
}
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + pFrom + " to " + tAbstractDestination + " as first part for a route from " + pFrom + " to " + pTo);
}
return tResult;
}
int tStep = 0;
// get the inter-cluster path to the possible destination
List<AbstractRoutingGraphLink> tPath = getRouteHRG(pFrom, pTo);
if(tPath != null){
// the last cluster gateway
HRMID tLastClusterGateway = null;
HRMID tFirstForeignGateway = null;
if(!tPath.isEmpty()){
if (DEBUG){
if (DEBUG){
Logging.log(this, " ..found inter cluster path:");
}
int i = 0;
for(AbstractRoutingGraphLink tLink : tPath){
if (DEBUG){
Logging.log(this, " ..inter-cluster step[" + i + "]: " + tLink);
}
i++;
}
}
for(AbstractRoutingGraphLink tLink : tPath){
RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tLink.getRoute().getFirst().clone();
if(tResult != null){
if(tLastClusterGateway == null){
throw new RuntimeException(this + "::getRoutingEntryHRG() should never reach this point");
}
/************************************************************************************************
* ROUTE PART: the intra-cluster route from the last gateway to the next one if needed
***********************************************************************************************/
// the next cluster gateway
HRMID tNextClusterGateway = tInterClusterRoutingEntry.getSource();
if(!tLastClusterGateway.equals(tNextClusterGateway)){
// the intra-cluster path
List<AbstractRoutingGraphLink> tIntraClusterPath = getRouteHRG(tLastClusterGateway, tNextClusterGateway);
if(tIntraClusterPath != null){
if(!tIntraClusterPath.isEmpty()){
RoutingEntry tLogicalIntraClusterRoutingEntry = null;
/**
* Determine the intra-cluster route part
*/
// check if we have only one hop in intra-cluster route
if(tIntraClusterPath.size() == 1){
AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0);
// get the routing entry from the last gateway to the next one
tLogicalIntraClusterRoutingEntry = (RoutingEntry) tIntraClusterLogLink.getRoute().getFirst();
}else{
tLogicalIntraClusterRoutingEntry = RoutingEntry.create(tIntraClusterPath);
if(tLogicalIntraClusterRoutingEntry == null){
Logging.warn(this, "getRoutingEntryHRG() for " + pFrom + " found a complex intra-cluster path and wasn't able to derive an aggregated logical link from it..");
Logging.warn(this, " ..path: " + tIntraClusterPath);
Logging.warn(this, " ..from: " + tLastClusterGateway);
Logging.warn(this, " ..to: " + tNextClusterGateway);
Logging.warn(this, " ..for a routing from " + pFrom + " to " + pTo);
// reset
tResult = null;
// abort
break;
}
}
/**
* Add the intra-cluster route part
*/
if(tLogicalIntraClusterRoutingEntry != null){
// chain the routing entries
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (intra-cluster): " + tLogicalIntraClusterRoutingEntry);
}
tResult.append(tLogicalIntraClusterRoutingEntry, pCause + "append1_intra_cluster from " + tLastClusterGateway + " to " + tNextClusterGateway);
tStep++;
/**
* Determine the next hop for the resulting path
*/
if(tFirstForeignGateway == null){
if(tLogicalIntraClusterRoutingEntry.getHopCount() > 0){
tFirstForeignGateway = tLogicalIntraClusterRoutingEntry.getNextHop();
}
}
}
}else{
Logging.warn(this, "getRoutingEntryHRG() found an empty intra-cluster path..");
Logging.warn(this, " ..from: " + tLastClusterGateway);
Logging.warn(this, " ..to: " + tNextClusterGateway);
Logging.warn(this, " ..for a routing from " + pFrom + " to " + pTo);
}
}else{
Logging.warn(this, "getRoutingEntryHRG() couldn't find a route from " + tLastClusterGateway + " to " + tNextClusterGateway + " for a routing from " + pFrom + " to " + pTo);
// reset
tResult = null;
// abort
break;
//HINT: do not throw a RuntimeException here because such a situation could have a temporary cause
}
}else{
// tLastClusterGateway and tNextClusterGateway are equal => empty route for cluster traversal
}
/***********************************************************************************************
* ROUTE PART: the inter-cluster link
***********************************************************************************************/
// chain the routing entries
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry);
}
tResult.append(tInterClusterRoutingEntry, pCause + "append2_inter_cluster for a route from " + pFrom + " to " + pTo);
}else{
/***********************************************************************************************
* ROUTE PART: first step of the resulting path
***********************************************************************************************/
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry);
}
tInterClusterRoutingEntry.extendCause(pCause + "append3_start_inter_cluster for a route from " + pFrom + " to " + pTo);
tResult = tInterClusterRoutingEntry;
}
tStep++;
/**
* Determine the next hop for the resulting path
*/
if(tFirstForeignGateway == null){
if(tInterClusterRoutingEntry.getHopCount() > 0){
tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop();
}
}
//update last cluster gateway
tLastClusterGateway = tInterClusterRoutingEntry.getNextHop();
}
}else{
Logging.err(this, "getRoutingEntryHRG() found an empty path from " + pFrom + " to " + pTo);
}
if(tResult != null){
// set the DESTINATION for the resulting routing entry
tResult.setDest(pFrom.getForeignCluster(pTo) /* aggregate the destination here */);
// set the NEXT HOP for the resulting routing entry
if(tFirstForeignGateway != null){
// tResult.setNextHop(tFirstForeignGateway);
}
// reset L2Address for next hop
tResult.setNextHopL2Address(null);
}
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + pFrom + " to " + pTo);
}
return tResult;
}
/**
* Unregisters automatically old links from the HRG based on each link's timeout value
*/
public void autoRemoveObsoleteHRGLinks()
{
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getEdges();
for(AbstractRoutingGraphLink tLink : tLinks){
// does the link have a timeout?
if(tLink.getTimeout() > 0){
// timeout occurred?
if(tLink.getTimeout() < getSimulationTime()){
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tLink);
// remove the link from the HRG
mHierarchicalRoutingGraph.unlink(tLink);
mDescriptionHRGUpdates += "\n -(AUTO_DEL) " + tEndPoints.getFirst() + " to " + tEndPoints.getSecond() + " ==> " + tLink.getRoute().getFirst() + " <== unregisterAutoHRG()";
}
}
}
/**
* Unregister all isolated nodes
*/
unregisterNodesAutoHRG(this + "::unregisterAutoHRG()");
}
/**
* Unregisters automatically old HRM routes based on each route entrie's timeout value
*/
private void autoRemoveObsoleteHRMRoutes()
{
RoutingTable tRoutingTable = mHierarchicalRoutingService.getRoutingTable();
for(RoutingEntry tEntry : tRoutingTable){
// does the link have a timeout?
if(tEntry.getTimeout() > 0){
// timeout occurred?
if(tEntry.getTimeout() < getSimulationTime()){
RoutingEntry tDeleteThis = tEntry.clone();
tDeleteThis.extendCause(this + "::autoRemoveObsoleteHRMRoutes()");
Logging.log(this, "Timeout (" + tEntry.getTimeout() + "<" + getSimulationTime() + ") for: " + tDeleteThis);
delHRMRoute(tDeleteThis);
}
}
}
}
/**
* Unregisters a logical link between HRMIDs from the locally stored hierarchical routing graph (HRG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pRoutingEntry the routing entry of the addressed link
*
* @return if the link was found in the HRG
*/
public boolean unregisterLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "UNREGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pRoutingEntry);
}
if(!pFrom.equals(pTo)){
pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph);
AbstractRoutingGraphLink tSearchPattern = new AbstractRoutingGraphLink(new Route(pRoutingEntry));
boolean tChangedRefCounter = false;
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
if(tOutLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tOutLinks) {
//Logging.warn(this, " ..has link: " + tKnownLink);
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink);
if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) ||
((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){
if(tKnownLink.equals(tSearchPattern)){
//Logging.warn(this, " ..MATCH");
// if(tKnownLink.getRefCounter() == 1){
// remove the link
mHierarchicalRoutingGraph.unlink(tKnownLink);
// it's time to update the HRG-GUI
notifyHRGGUI(null);
// }else{
// if(tKnownLink.getRefCounter() < 1){
// throw new RuntimeException("Found an HRG link with an invalid ref. counter: " + tKnownLink);
// }
//
// tKnownLink.decRefCounter();
// tChangedRefCounter = true;
//
// // it's time to update the HRG-GUI
// notifyHRGGUI(tKnownLink);
// }
// // we have a positive result
tResult = true;
// work is done
break;
}else{
//Logging.warn(this, " ..NO MATCH");
}
}
}
}
}
if(!tResult){
/**
* The route was already removed -> this can occur if both end points of a link are located on this node and both of them try to unregister the same route
*/
mDescriptionHRGUpdates += "\n -/+ " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
Logging.warn(this, "Haven't found " + pRoutingEntry + " as HRG link between " + pFrom + " and " + pTo);
// if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
synchronized (mHierarchicalRoutingGraph) {
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
if(tLinks != null){
if(tLinks.size() > 0){
Logging.warn(this, " ..knowing FROM node: " + pFrom);
for(AbstractRoutingGraphLink tKnownLink : tLinks){
Logging.warn(this, " ..has link: " + tKnownLink);
if(tKnownLink.equals(tSearchPattern)){
Logging.err(this, " ..MATCH");
}else{
Logging.warn(this, " ..NO MATCH");
}
}
}
}
tLinks = mHierarchicalRoutingGraph.getOutEdges(pTo);
if(tLinks != null){
if(tLinks.size() > 0){
Logging.warn(this, " ..knowing TO node: " + pFrom);
for(AbstractRoutingGraphLink tKnownLink : tLinks){
Logging.warn(this, " ..has link: " + tKnownLink);
if(tKnownLink.equals(tSearchPattern)){
Logging.err(this, " ..MATCH");
}else{
Logging.warn(this, " ..NO MATCH");
}
}
}
}
}
// }
}else{
mDescriptionHRGUpdates += "\n -" + (tChangedRefCounter ? "(REF)" : "") +" " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
/**
* Unregister all isolated nodes
*/
unregisterNodesAutoHRG(pRoutingEntry + ", " + this + "::unregisterLinkHRG()_autoDel");
}
}else{
//Logging.warn(this, "unregisterLinkHRG() skipped because self-loop detected for: " + pRoutingEntry);
}
return tResult;
}
/**
* Unregister automatically all HRG nodes which don't have a link anymore
*/
private void unregisterNodesAutoHRG(String pCause)
{
/**
* Iterate over all nodes and delete all of them which don't have any links anymore
*/
boolean tRemovedSomething = false;
synchronized (mHierarchicalRoutingGraph) {
boolean tRemovedANode;
do{
tRemovedANode = false;
Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices();
for(HRMID tKnownNode : tNodes){
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode);
Collection<AbstractRoutingGraphLink> tInLinks = mHierarchicalRoutingGraph.getInEdges(tKnownNode);
if((tOutLinks != null) && (tInLinks != null)){
if((tInLinks.size() == 0) && (tOutLinks.size() == 0)){
// unregister the HRMID in the HRG
unregisterNodeHRG(tKnownNode, pCause);
tRemovedANode = true;
tRemovedSomething = true;
break;
}
}
}
}while(tRemovedANode);
}
if(tRemovedSomething){
// it's time to update the HRG-GUI
notifyHRGGUI(null);
}
}
/**
* Returns a list of direct neighbors of the given HRMID which are stored in the HRG
*
* @param pHRMID the root HRMID
*
* @return the list of direct neighbors
*/
public LinkedList<HRMID> getNeighborsHRG(HRMID pHRMID)
{
LinkedList<HRMID> tResult = new LinkedList<HRMID>();
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pHRMID);
if(tOutLinks != null){
for(AbstractRoutingGraphLink tOutLink : tOutLinks){
HRMID tNeighbor = mHierarchicalRoutingGraph.getDest(tOutLink);
tResult.add(tNeighbor.clone());
}
}
}
return tResult;
}
/**
* Returns routes to neighbors of a given HRG node
*
* @param pHRMID the HRMID of the HRG root node
*
* @return the routing table
*/
public RoutingTable getRoutesWithNeighborsHRG(HRMID pHRMID)
{
RoutingTable tResult = new RoutingTable();
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pHRMID);
if(tOutLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tOutLinks) {
Route tKnownLinkRoute = tKnownLink.getRoute();
if(tKnownLinkRoute.size() == 1){
if(tKnownLinkRoute.getFirst() instanceof RoutingEntry){
RoutingEntry tRouteToNeighbor = ((RoutingEntry)tKnownLinkRoute.getFirst()).clone();
tRouteToNeighbor.extendCause(this + "::getRoutesWithNeighborsHRG() for " + pHRMID);
tResult.add(tRouteToNeighbor);
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route type: " + tKnownLinkRoute);
}
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route size for: " + tKnownLinkRoute);
}
}
}
Collection<AbstractRoutingGraphLink> tInLinks = mHierarchicalRoutingGraph.getInEdges(pHRMID);
if(tInLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tInLinks) {
Route tKnownLinkRoute = tKnownLink.getRoute();
if(tKnownLinkRoute.size() == 1){
if(tKnownLinkRoute.getFirst() instanceof RoutingEntry){
RoutingEntry tRouteToNeighbor = ((RoutingEntry)tKnownLinkRoute.getFirst()).clone();
tRouteToNeighbor.extendCause(this + "::getRoutesWithNeighborsHRG() for " + pHRMID);
tResult.add(tRouteToNeighbor);
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route type: " + tKnownLinkRoute);
}
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route size for: " + tKnownLinkRoute);
}
}
}
}
return tResult;
}
/**
* Registers a link between two clusters.
*
* @param pFromHRMID the start of the link
* @param pToHRMID the end of the link
* @param pRoutingEntry the routing entry for this link
*
* @return true if the link is new to the routing graph
*/
private boolean registerCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
/**
* Store/update link in the HRG
*/
tResult = registerLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry);
if(tResult){
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "Stored cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " in the HRG as: " + pRoutingEntry);
}
}
return tResult;
}
/**
* Unregisters a link between two clusters.
*
* @param pFromHRMID the start of the link
* @param pToHRMID the end of the link
* @param pRoutingEntry the routing entry for this link
*
* @return if the link was found in the HRG
*/
private boolean unregisterCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
/**
* Store/update link in the HRG
*/
tResult = unregisterLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry);
if(tResult){
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "Removed cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " from the HRG as: " + pRoutingEntry);
}
}
return tResult;
}
/**
* Determines a path in the locally stored hierarchical routing graph (HRG).
*
* @param pSource the source of the desired route
* @param pDestination the destination of the desired route
*
* @return the determined route, null if no route could be found
*/
public List<AbstractRoutingGraphLink> getRouteHRG(HRMID pSource, HRMID pDestination)
{
List<AbstractRoutingGraphLink> tResult = null;
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, "GET ROUTE (HRG) from \"" + pSource + "\" to \"" + pDestination +"\"");
}
synchronized (mHierarchicalRoutingGraph) {
tResult = mHierarchicalRoutingGraph.getRoute(pSource, pDestination);
}
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, " ..result: " + tResult);
}
return tResult;
}
/**
* Returns the routing entry from a HRG link between two HRG nodes (neighbors)
*
* @param pSource the starting point of the searched link
* @param pDestination the ending point of the search link
*
* @return the search routing entry
*/
public RoutingEntry getNeighborRoutingEntryHRG(HRMID pSource, HRMID pDestination)
{
RoutingEntry tResult = null;
List<AbstractRoutingGraphLink> tPath = getRouteHRG(pSource, pDestination);
if(tPath != null){
if(tPath.size() == 1){
AbstractRoutingGraphLink tLink = tPath.get(0);
// get the routing entry from the last gateway to the next one
tResult = ((RoutingEntry) tLink.getRoute().getFirst()).clone();
}else{
Logging.warn(this, "getRoutingEntryHRG() found a complex intra-cluster route: " + tPath + " from " + pSource + " to " + pDestination);
}
}else{
// no route found
}
return tResult;
}
/**
* Returns the HRG for the GraphViewer.
* (only for GUI!)
*
* @return the HRG
*/
public AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> getHRGForGraphViewer()
{
AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> tResult = null;
synchronized (mHierarchicalRoutingGraph) {
tResult = mHierarchicalRoutingGraph; //TODO: use a new clone() method here
}
return tResult;
}
/**
* This method is derived from IServerCallback and is called for incoming connection requests by the HRMController application's ServerFN.
* Such a incoming connection can either be triggered by an HRMController application or by a probe-routing request
*
* @param pConnection the incoming connection
*/
@Override
public void newConnection(Connection pConnection)
{
Logging.log(this, "INCOMING CONNECTION " + pConnection.toString() + " with requirements: " + pConnection.getRequirements());
// get the connection requirements
Description tConnectionRequirements = pConnection.getRequirements();
/**
* check if the new connection is a probe-routing connection
*/
ProbeRoutingProperty tPropProbeRouting = (ProbeRoutingProperty) tConnectionRequirements.get(ProbeRoutingProperty.class);
// do we have a probe-routing connection?
if (tPropProbeRouting == null){
/**
* Create the communication session
*/
Logging.log(this, " ..creating communication session");
ComSession tComSession = new ComSession(this);
/**
* Start the communication session
*/
Logging.log(this, " ..starting communication session for the new connection");
tComSession.startConnection(null, pConnection);
}else{
/**
* We have a probe-routing connection and will print some additional information about the taken route of the connection request
*/
// get the recorded route from the property
LinkedList<HRMID> tRecordedHRMIDs = tPropProbeRouting.getRecordedHops();
Logging.log(this, " ..detected a probe-routing connection(source=" + tPropProbeRouting.getSourceDescription() + " with " + tRecordedHRMIDs.size() + " recorded hops");
// print the recorded route
int i = 0;
for(HRMID tHRMID : tRecordedHRMIDs){
Logging.log(this, " [" + i + "]: " + tHRMID);
i++;
}
}
}
/**
* Callback for ServerCallback: gets triggered if an error is caused by the server socket
*
* @param the error cause
*/
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.application.util.ServerCallback#error(de.tuilmenau.ics.fog.facade.events.ErrorEvent)
*/
@Override
public void error(ErrorEvent pCause)
{
Logging.log(this, "Got an error message because of \"" + pCause + "\"");
}
/**
* Creates a descriptive string about this object
*
* @return the descriptive string
*/
public String toString()
{
return "HRM controller@" + getNode();
}
/**
* Determine the name of the central FN of this node
*
* @return the name of the central FN
*/
@SuppressWarnings("deprecation")
public Name getNodeName()
{
// get the name of the central FN of this node
return getHRS().getCentralFN().getName();
}
/**
* Determine the L2 address of the central FN of this node
*
* @return the L2Address of the central FN
*/
public L2Address getNodeL2Address()
{
L2Address tResult = null;
// get the recursive FoG layer
FoGEntity tFoGLayer = (FoGEntity) getNode().getLayer(FoGEntity.class);
if(tFoGLayer != null){
// get the central FN of this node
L2Address tThisHostL2Address = getHRS().getL2AddressFor(tFoGLayer.getCentralFN());
tResult = tThisHostL2Address;
}
return tResult;
}
/**
* The global name space which is used to identify the HRM instances on nodes.
*/
public final static Namespace ROUTING_NAMESPACE = new Namespace("routing");
/**
* Stores the identification string for HRM specific routing graph decorations (coordinators & HRMIDs)
*/
private final static String DECORATION_NAME_COORDINATORS_AND_HRMIDS = "HRM(1) - coordinators & HRMIDs";
/**
* Stores the identification string for HRM specific routing graph decorations (node priorities)
*/
private final static String DECORATION_NAME_NODE_PRIORITIES = "HRM(3) - node priorities";
/**
* Stores the identification string for the active HRM infrastructure
*/
private final static String DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE = "HRM(4) - active infrastructure";
/**
* Stores the identification string for HRM specific routing graph decorations (coordinators & clusters)
*/
private final static String DECORATION_NAME_COORDINATORS_AND_CLUSTERS = "HRM(2) - coordinators & clusters";
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.