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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2720c91c37dbd069c8be2d9ed3e9fcffc01c08e0 | 0995b3a6419ec1a072eef16f5040cd83c123e55d | /src/main/java/com/example/mspr/MsprApplication.java | 6f5ba6c27ecc3301a90d39e21698cda913fb575a | [] | no_license | TheMOKETBOY/MaintEvolApp | 7152565fcef374d811bdebee9479d67146e975b0 | 3ff983fd9a3ef68e586fbe5e3b538dae5702bf71 | refs/heads/master | 2023-06-16T17:57:22.140106 | 2021-07-15T15:58:17 | 2021-07-15T15:58:17 | 386,297,257 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package com.example.mspr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MsprApplication {
public static void main(String[] args) {
SpringApplication.run(MsprApplication.class, args);
}
}
| [
"tatelvilrus.samuel@gmail.com"
] | tatelvilrus.samuel@gmail.com |
aa1708fdc4c3cf25171123f060542fe3316321ba | e674163c2b925e11d5084d573ecb7cf3f273ae8a | /src/com/rackspacecloud/android/ViewServerActivity.java | 88c09d7a3ea7fd79c78c4c7df4651ba393df5f57 | [
"MIT"
] | permissive | patchorang/android-rackspacecloud | 107558ef1e92a8553923ed40218ed710c7f62715 | 9f58d76d048132480b3c7ffe04d7bb0a4ca15d1f | refs/heads/master | 2021-01-01T19:39:25.788090 | 2011-12-13T19:51:53 | 2011-12-13T19:51:53 | 1,828,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,750 | java | /**
*
*/
package com.rackspacecloud.android;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.rackspace.cloud.servers.api.client.CloudServersException;
import com.rackspace.cloud.servers.api.client.Flavor;
import com.rackspace.cloud.servers.api.client.Server;
import com.rackspace.cloud.servers.api.client.ServerManager;
import com.rackspace.cloud.servers.api.client.parsers.CloudServersFaultXMLParser;
/**
* @author Mike Mayo - mike.mayo@rackspace.com - twitter.com/greenisus
*
*/
public class ViewServerActivity extends Activity {
private Server server;
private boolean ipAddressesLoaded; // to prevent polling from loading tons of duplicates
private Flavor[] flavors;
private String[] flavorNames;
private String selectedFlavorId;
private boolean imageLoaded;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
server = (Server) this.getIntent().getExtras().get("server");
setContentView(R.layout.viewserver);
restoreState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("server", server);
outState.putBoolean("imageLoaded", imageLoaded);
}
private void restoreState(Bundle state) {
if (state != null && state.containsKey("server")) {
server = (Server) state.getSerializable("server");
imageLoaded = state.getBoolean("imageLoaded");
}
loadServerData();
setupButtons();
loadFlavors();
}
private void loadImage() {
// hate to do this, but devices run out of memory after a few rotations
// because the background images are so large
if (!imageLoaded) {
ImageView osLogo = (ImageView) findViewById(R.id.view_server_os_logo);
osLogo.setAlpha(100);
osLogo.setImageResource(server.getImage().logoResourceId());
imageLoaded = true;
}
}
private void loadServerData() {
TextView name = (TextView) findViewById(R.id.view_server_name);
name.setText(server.getName());
TextView os = (TextView) findViewById(R.id.view_server_os);
os.setText(server.getImage().getName());
TextView memory = (TextView) findViewById(R.id.view_server_memory);
memory.setText(server.getFlavor().getRam() + " MB");
TextView disk = (TextView) findViewById(R.id.view_server_disk);
disk.setText(server.getFlavor().getDisk() + " GB");
TextView status = (TextView) findViewById(R.id.view_server_status);
// show status and possibly the progress, with polling
if (!"ACTIVE".equals(server.getStatus())) {
status.setText(server.getStatus() + " - " + server.getProgress() + "%");
new PollServerTask().execute((Void[]) null);
} else {
status.setText(server.getStatus());
}
if (!ipAddressesLoaded) {
// public IPs
int layoutIndex = 12; // public IPs start here
LinearLayout layout = (LinearLayout) this.findViewById(R.id.view_server_layout);
String publicIps[] = server.getPublicIpAddresses();
for (int i = 0; i < publicIps.length; i++) {
TextView tv = new TextView(this.getBaseContext());
tv.setLayoutParams(os.getLayoutParams()); // easy quick styling! :)
tv.setTypeface(tv.getTypeface(), 1); // 1 == bold
tv.setTextSize(os.getTextSize());
tv.setTextColor(Color.WHITE);
tv.setText(publicIps[i]);
layout.addView(tv, layoutIndex++);
}
// private IPs
layoutIndex++; // skip over the Private IPs label
String privateIps[] = server.getPrivateIpAddresses();
for (int i = 0; i < privateIps.length; i++) {
TextView tv = new TextView(this.getBaseContext());
tv.setLayoutParams(os.getLayoutParams()); // easy quick styling! :)
tv.setTypeface(tv.getTypeface(), 1); // 1 == bold
tv.setTextSize(os.getTextSize());
tv.setTextColor(Color.WHITE);
tv.setText(privateIps[i]);
layout.addView(tv, layoutIndex++);
}
loadImage();
ipAddressesLoaded = true;
}
}
private void loadFlavors() {
flavorNames = new String[Flavor.getFlavors().size()];
flavors = new Flavor[Flavor.getFlavors().size()];
Iterator<Flavor> iter = Flavor.getFlavors().values().iterator();
int i = 0;
while (iter.hasNext()) {
Flavor flavor = iter.next();
flavors[i] = flavor;
flavorNames[i] = flavor.getName() + ", " + flavor.getDisk() + " GB disk";
i++;
}
selectedFlavorId = flavors[0].getId();
}
private void setupButton(int resourceId, OnClickListener onClickListener) {
Button button = (Button) findViewById(resourceId);
button.setOnClickListener(onClickListener);
}
private void setupButtons() {
setupButton(R.id.view_server_soft_reboot_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_soft_reboot_button);
}
});
setupButton(R.id.view_server_hard_reboot_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_hard_reboot_button);
}
});
setupButton(R.id.view_server_resize_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_resize_button);
}
});
setupButton(R.id.view_server_delete_button, new OnClickListener() {
public void onClick(View v) {
showDialog(R.id.view_server_delete_button);
}
});
}
private void showAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
alert.show();
}
/**
* @return the server
*/
public Server getServer() {
return server;
}
/**
* @param server the server to set
*/
public void setServer(Server server) {
this.server = server;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case R.id.view_server_soft_reboot_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Soft Reboot")
.setMessage("Are you sure you want to perform a soft reboot?")
.setPositiveButton("Reboot Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new SoftRebootServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_hard_reboot_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Hard Reboot")
.setMessage("Are you sure you want to perform a hard reboot?")
.setPositiveButton("Reboot Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new HardRebootServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_resize_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setItems(flavorNames, new ResizeClickListener())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Resize Server")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
case R.id.view_server_delete_button:
return new AlertDialog.Builder(ViewServerActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Delete Server")
.setMessage("Are you sure you want to delete this server? This operation cannot be undone and all backups will be deleted.")
.setPositiveButton("Delete Server", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
new DeleteServerTask().execute((Void[]) null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked Cancel so do some stuff
}
})
.create();
}
return null;
}
private class ResizeClickListener implements android.content.DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
selectedFlavorId = which + "";
new ResizeServerTask().execute((Void[]) null);
}
}
private CloudServersException parseCloudServersException(HttpResponse response) {
CloudServersException cse = new CloudServersException();
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String body = responseHandler.handleResponse(response);
CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.parse(new InputSource(new StringReader(body)));
cse = parser.getException();
} catch (ClientProtocolException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (IOException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (ParserConfigurationException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (SAXException e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
} catch (FactoryConfigurationError e) {
cse = new CloudServersException();
cse.setMessage(e.getLocalizedMessage());
}
return cse;
}
// HTTP request tasks
private class PollServerTask extends AsyncTask<Void, Void, Server> {
@Override
protected Server doInBackground(Void... arg0) {
try {
server = (new ServerManager()).find(Integer.parseInt(server.getId()));
} catch (NumberFormatException e) {
// we're polling, so need to show exceptions
} catch (CloudServersException e) {
// we're polling, so need to show exceptions
}
return server;
}
@Override
protected void onPostExecute(Server result) {
server = result;
loadServerData();
}
}
private class SoftRebootServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).reboot(server, ServerManager.SOFT_REBOOT);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 202) {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem rebooting your server.");
} else {
showAlert("Error", "There was a problem rebooting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem rebooting your server: " + exception.getMessage());
}
}
}
private class HardRebootServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).reboot(server, ServerManager.HARD_REBOOT);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 202) {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem rebooting your server.");
} else {
showAlert("Error", "There was a problem rebooting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem rebooting your server: " + exception.getMessage());
}
}
}
private class ResizeServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).resize(server, Integer.parseInt(selectedFlavorId));
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 202) {
new PollServerTask().execute((Void[]) null);
} else {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem deleting your server.");
} else {
showAlert("Error", "There was a problem deleting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem resizing your server: " + exception.getMessage());
}
}
}
private class DeleteServerTask extends AsyncTask<Void, Void, HttpResponse> {
private CloudServersException exception;
@Override
protected HttpResponse doInBackground(Void... arg0) {
HttpResponse resp = null;
try {
resp = (new ServerManager()).delete(server);
} catch (CloudServersException e) {
exception = e;
}
return resp;
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 202) {
setResult(Activity.RESULT_OK);
finish();
} else {
CloudServersException cse = parseCloudServersException(response);
if ("".equals(cse.getMessage())) {
showAlert("Error", "There was a problem deleting your server.");
} else {
showAlert("Error", "There was a problem deleting your server: " + cse.getMessage());
}
}
} else if (exception != null) {
showAlert("Error", "There was a problem deleting your server: " + exception.getMessage());
}
}
}
}
| [
"greenisus@gmail.com"
] | greenisus@gmail.com |
680a7440a40e73362230cf5190d93519dc85ed6c | e315c2bb2ea17cd8388a39aa0587e47cb417af0a | /backoffice/tn/com/smartsoft/backoffice/referentiel/saison/presentation/model/SaisonsModel.java | 1fe5f1aff9e9f4ee6a5b9ef33dc998ce66a96a48 | [] | no_license | wissem007/badges | 000536a40e34e20592fe6e4cb2684d93604c44c9 | 2064bd07b52141cf3cff0892e628cc62b4f94fdc | refs/heads/master | 2020-12-26T14:06:11.693609 | 2020-01-31T23:40:07 | 2020-01-31T23:40:07 | 237,530,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 277 | java | package tn.com.smartsoft.backoffice.referentiel.saison.presentation.model;
import tn.com.smartsoft.framework.presentation.model.GenericEntiteModel;
public class SaisonsModel extends GenericEntiteModel {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| [
"alouiwiss@gmail.com"
] | alouiwiss@gmail.com |
f83a1dbe8665eb1fce8e307c867b39657f06b560 | e553d647ce9e96e9bada404598d0bd3c7d717ea4 | /app/src/main/java/com/cy8018/iptv/player/VideoMediaPlayerGlue.java | 56959554e8dd196c9f618b75f76635e8bb063960 | [
"MIT"
] | permissive | LeslieZhang1314/IPTV.AndroidBox | 26679fd04a60132894acaa768ba347b32bb9c502 | 00a5c4134b1f4ad8675fd970da45f7db090eb70d | refs/heads/master | 2022-11-19T17:50:15.487828 | 2020-07-23T16:01:02 | 2020-07-23T16:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,446 | java | /*
* Copyright (C) 2016 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.cy8018.iptv.player;
import android.app.Activity;
import android.net.TrafficStats;
import android.os.Handler;
import androidx.leanback.media.PlaybackTransportControlGlue;
import androidx.leanback.media.PlayerAdapter;
import androidx.leanback.widget.PlaybackRowPresenter;
import androidx.leanback.widget.Presenter;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.cy8018.iptv.R;
import com.cy8018.iptv.model.Station;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PlayerGlue for video playback
* @param <T>
*/
public class VideoMediaPlayerGlue<T extends PlayerAdapter> extends PlaybackTransportControlGlue<T> {
private Station currentStation;
private String currentTime = "";
private String currentChannelId = "";
private String targetChannelId = "";
private long lastTotalRxBytes = 0;
private long lastTimeStamp = 0;
public static final int MSG_UPDATE_INFO = 0;
public static String gNetworkSpeed = "";
private static final String TAG = "VideoMediaPlayerGlue";
Activity mContext;
public void setCurrentTime (String time) { this.currentTime = time; }
public void setCurrentChannelId(String currentChannelId)
{
this.currentChannelId = currentChannelId;
}
public void setTargetChannelId(String channelId)
{
this.targetChannelId = channelId;
}
public Station getCurrentStation() {
return currentStation;
}
public String getTargetChannelId() {
return targetChannelId;
}
public void setCurrentStation(Station currentStation) {
this.currentStation = currentStation;
this.currentChannelId = String.valueOf(currentStation.index + 1);
}
public VideoMediaPlayerGlue(Activity context, T impl) {
super(context, impl);
mContext = context;
}
@Override
protected PlaybackRowPresenter onCreateRowPresenter() {
PlayControlPresenter presenter = new PlayControlPresenter();
presenter.setDescriptionPresenter(new MyDescriptionPresenter());
return presenter;
}
private long getNetSpeed() {
long nowTotalRxBytes = TrafficStats.getUidRxBytes(mContext.getApplicationContext().getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : TrafficStats.getTotalRxBytes();
long nowTimeStamp = System.currentTimeMillis();
long calculationTime = (nowTimeStamp - lastTimeStamp);
if (calculationTime == 0) {
return calculationTime;
}
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / calculationTime);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
return speed;
}
public String getNetSpeedText(long speed) {
String text = "";
if (speed >= 0 && speed < 1024) {
text = speed + " B/s";
} else if (speed >= 1024 && speed < (1024 * 1024)) {
text = speed / 1024 + " KB/s";
} else if (speed >= (1024 * 1024) && speed < (1024 * 1024 * 1024)) {
text = speed / (1024 * 1024) + " MB/s";
}
return text;
}
public String getCurrentTimeString()
{
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String dateNowStr = sdf.format(date);
return dateNowStr;
}
public void getNetSpeedInfo() {
gNetworkSpeed = getNetSpeedText(getNetSpeed());
Log.d(TAG, gNetworkSpeed);
}
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
private class MyDescriptionPresenter extends Presenter {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_tv_info, parent, false);
View infoBarView = view.findViewById(R.id.tv_info_bar);
View channelIdBg = view.findViewById(R.id.channel_id_bg);
//logo.setBackgroundColor(Color.DKGRAY);
infoBarView.getBackground().setAlpha(0);
channelIdBg.getBackground().setAlpha(100);
// TextView channelNameTextView = view.findViewById(R.id.channel_name);
// if (channelNameTextView.getText().length()>4)
// {
// channelNameTextView.setTextSize(60);
// }
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
VideoMediaPlayerGlue glue = (VideoMediaPlayerGlue) item;
String channelNameString = glue.getTitle().toString();
((ViewHolder)viewHolder).channelName.setText(channelNameString);
if ((channelNameString.length() > 4 && isContainChinese(channelNameString))
|| channelNameString.length() > 10
)
{
((ViewHolder)viewHolder).channelName.setTextSize(60);
}
else
{
((ViewHolder)viewHolder).channelName.setTextSize(78);
}
((ViewHolder)viewHolder).sourceInfo.setText(glue.getSubtitle());
((ViewHolder)viewHolder).currentTime.setText(currentTime);
((ViewHolder)viewHolder).channelId.setText(currentChannelId);
((ViewHolder)viewHolder).targetChannelId.setText(targetChannelId);
Glide.with(getContext())
.asBitmap()
.apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
.load(glue.getCurrentStation().logo)
.into(((ViewHolder)viewHolder).logo);
}
@Override
public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {
}
class ViewHolder extends Presenter.ViewHolder {
TextView channelId;
TextView targetChannelId;
TextView currentTime;
TextView channelName;
TextView sourceInfo;
TextView networkSpeed;
ImageView logo;
private ViewHolder (View itemView)
{
super(itemView);
channelId = itemView.findViewById(R.id.channel_id);
targetChannelId = itemView.findViewById(R.id.target_channel_id);
currentTime = itemView.findViewById(R.id.current_time);
channelName = itemView.findViewById(R.id.channel_name);
sourceInfo = itemView.findViewById(R.id.source_info);
networkSpeed = itemView.findViewById(R.id.network_speed);
logo = itemView.findViewById(R.id.channel_logo);
new Thread(updateInfoRunnable).start();
}
public void UpdateDisplayInfo() {
networkSpeed.setText(gNetworkSpeed);
currentTime.setText(getCurrentTimeString());
targetChannelId.setText(getTargetChannelId());
}
public final MsgHandler mHandler = new MsgHandler(this);
public class MsgHandler extends Handler {
WeakReference<ViewHolder> mViewHolder;
MsgHandler(ViewHolder viewHolder) {
mViewHolder = new WeakReference<ViewHolder>(viewHolder);
}
@Override
public void handleMessage(@NotNull Message msg) {
super.handleMessage(msg);
ViewHolder vh = mViewHolder.get();
if (msg.what == MSG_UPDATE_INFO) {
getNetSpeedInfo();
vh.UpdateDisplayInfo();
}
}
}
Runnable updateInfoRunnable = new Runnable() {
@Override
public void run() {
while (true) {
try {
mHandler.sendEmptyMessage(MSG_UPDATE_INFO);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
}
} | [
"cy3118018@163.com"
] | cy3118018@163.com |
72dc30005f57e2b823e03a1bcd8b24943d78f996 | 319bceff7ae8f3f986952c6f44cd912a2f5f3e0f | /library/src/main/java/com/hyetec/hmdp/lifecycle/delegate/ActivityDelegateImpl.java | ba2be224f00e8fd493616230c96950db629ac458 | [] | no_license | JimHan1978/HMDP | 7dfa70b906972a3601a88e39a4c66118654f5625 | 295bac50c3f0d6d315d03afb1813efc3b929cc45 | refs/heads/master | 2020-04-16T21:43:48.758819 | 2019-02-22T09:42:44 | 2019-02-22T09:42:44 | 165,937,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,796 | java | package com.hyetec.hmdp.lifecycle.delegate;
import android.app.Activity;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import org.simple.eventbus.EventBus;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
/**
* @author xiaobailong24
* @date 2017/6/16
* Activity 生命周期代理接口实现类
*/
public class ActivityDelegateImpl implements ActivityDelegate, HasSupportFragmentInjector {
private Activity mActivity;
private IActivity iActivity;
@Inject
DispatchingAndroidInjector<Fragment> mFragmentInjector;
public ActivityDelegateImpl(Activity activity) {
this.mActivity = activity;
this.iActivity = (IActivity) activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
//如果要使用eventbus请将此方法返回true
if (iActivity.useEventBus()) {
//注册到事件主线
EventBus.getDefault().register(mActivity);
}
//Dagger.Android 依赖注入
if (iActivity.injectable()) {
AndroidInjection.inject(mActivity);
}
}
@Override
public void onStart() {
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void onStop() {
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
@Override
public void onDestroy() {
//如果要使用eventbus请将此方法返回true
if (iActivity.useEventBus()) {
EventBus.getDefault().unregister(mActivity);
}
this.iActivity = null;
this.mActivity = null;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
protected ActivityDelegateImpl(Parcel in) {
this.mActivity = in.readParcelable(Activity.class.getClassLoader());
this.iActivity = in.readParcelable(IActivity.class.getClassLoader());
}
public static final Parcelable.Creator<ActivityDelegateImpl> CREATOR = new Parcelable.Creator<ActivityDelegateImpl>() {
@Override
public ActivityDelegateImpl createFromParcel(Parcel source) {
return new ActivityDelegateImpl(source);
}
@Override
public ActivityDelegateImpl[] newArray(int size) {
return new ActivityDelegateImpl[size];
}
};
@Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return this.mFragmentInjector;
}
}
| [
"jimhan2014@126.com"
] | jimhan2014@126.com |
d65f8257e5903c8dd84851778b3e5b88d85625e7 | 707f572a136bb4192b5f7f7a05d8ccd670c2521c | /app/src/main/java/com/shervinf/blackbookstrength/LiftFragment.java | 0e589331dc8533a8893849276af69e11b7e18531 | [] | no_license | shervinf1/BlackBookStrength | f635e6b6df91d2fb78e8020b8886fbeeded64795 | 50f103a3d6c6f840ef49b1c94c4e9a5904014bba | refs/heads/master | 2021-07-12T01:41:12.683607 | 2020-09-30T03:55:25 | 2020-09-30T03:55:25 | 202,823,607 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,160 | java | package com.shervinf.blackbookstrength;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LiftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_lift,container,false);
//Code to setup tabs with their corresponding adapters
ViewPager viewPager = view.findViewById(R.id.pager);
LiftPagerAdapter myPagerAdapter = new LiftPagerAdapter(getFragmentManager());
viewPager.setAdapter(myPagerAdapter);
TabLayout tablayout = view.findViewById(R.id.tablayout);
tablayout.setupWithViewPager(viewPager);
return view;
}
}
| [
"shervinf@outlook.com"
] | shervinf@outlook.com |
ca649e982fb818cb790d5e338b3d193558c76526 | 3eba7f9d133a325313d2a83795248acfb1f5e01f | /src/main/java/xdata/Overlap.java | ab42642dc06e9d21957e02c1c1af06dbd0a95acf | [] | no_license | schaban/AndroidEnvLighting | fe058ec61f604fe4def9771dd4cc7f089b6e87a7 | d9d6750be2c4f6814fbbbd1c421015e1624ce5c6 | refs/heads/master | 2020-03-21T11:11:59.025980 | 2019-03-19T11:54:18 | 2019-03-19T11:54:18 | 138,493,843 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,122 | java | // Author: Sergey Chaban <sergey.chaban@gmail.com>
package xdata;
public final class Overlap {
public static boolean spheres(float[] cA, float rA, float[] cB, float rB) {
float cds = Calc.distSq(cA, cB);
float rs = rA + rB;
return cds <= Calc.sq(rs);
}
public static boolean spheres(float[] a, float[] b) {
float ra = a.length < 4 ? 0.0f : a[3];
float rb = b.length < 4 ? 0.0f : b[3];
return spheres(a, ra, b, rb);
}
public static boolean boxes(float[] minmaxA, float[] minmaxB) {
for (int i = 0; i < 3; ++i) {
/* minA > maxB */
if (minmaxA[i] > minmaxB[3 + i]) return false;
}
for (int i = 0; i < 3; ++i) {
/* maxA < minB */
if (minmaxA[3 + i] < minmaxB[i]) return false;
}
return true;
}
public static boolean boxes(float[] minmaxA, int offsA, float[] minmaxB, int offsB) {
for (int i = 0; i < 3; ++i) {
/* minA > maxB */
if (minmaxA[offsA + i] > minmaxB[offsB + 3 + i]) return false;
}
for (int i = 0; i < 3; ++i) {
/* maxA < minB */
if (minmaxA[offsA + 3 + i] < minmaxB[offsB + i]) return false;
}
return true;
}
public static boolean sphereBox(float[] sphC, float sphR, float[] minmax) {
float[] pos = new float[3];
Calc.vclamp(pos, sphC, minmax);
float ds = Calc.distSq(pos, sphC);
return ds <= Calc.sq(sphR);
}
public static boolean sphereBox(float[] sph, float[] minmax) {
float r = 0.0f;
if (sph.length >= 4) {
r = sph[3];
}
return sphereBox(sph, r, minmax);
}
public static boolean pointSphere(float[] pos, float[] c, float r) {
float ds = Calc.distSq(pos, c);
float rs = Calc.sq(r);
return ds <= rs;
}
public static boolean pointSphere(float[] pos, float[] sph) {
float r = sph.length < 4 ? 0.0f : sph[3];
return pointSphere(pos, sph, r);
}
public static boolean pointBox(float x, float y, float z, float[] minmax, int offs) {
if (x < minmax[offs + 0] || x > minmax[offs + 3 + 0]) return false;
if (y < minmax[offs + 1] || y > minmax[offs + 3 + 1]) return false;
if (z < minmax[offs + 2] || z > minmax[offs + 3 + 2]) return false;
return true;
}
public static boolean segmentBox(
float p0x, float p0y, float p0z,
float p1x, float p1y, float p1z,
float[] minmax, int offs
) {
float dirx = p1x - p0x;
float diry = p1y - p0y;
float dirz = p1z - p0z;
float len = Calc.vecLen(dirx, diry, dirz);
if (len < 1.0e-7f) {
return pointBox(p0x, p0y, p0z, minmax, offs);
}
float tmin = 0.0f;
float tmax = len;
float bbminx = minmax[offs];
float bbmaxx = minmax[offs + 3];
if (dirx != 0) {
float dx = len / dirx;
float x1 = (bbminx - p0x) * dx;
float x2 = (bbmaxx - p0x) * dx;
float xmin = Math.min(x1, x2);
float xmax = Math.max(x1, x2);
tmin = Math.max(tmin, xmin);
tmax = Math.min(tmax, xmax);
if (tmin > tmax) {
return false;
}
} else {
if (p0x < bbminx || p0x > bbmaxx) return false;
}
float bbminy = minmax[offs + 1];
float bbmaxy = minmax[offs + 3 + 1];
if (diry != 0) {
float dy = len / diry;
float y1 = (bbminy - p0y) * dy;
float y2 = (bbmaxy - p0y) * dy;
float ymin = Math.min(y1, y2);
float ymax = Math.max(y1, y2);
tmin = Math.max(tmin, ymin);
tmax = Math.min(tmax, ymax);
if (tmin > tmax) {
return false;
}
} else {
if (p0y < bbminy || p0y > bbmaxy) return false;
}
float bbminz = minmax[offs + 2];
float bbmaxz = minmax[offs + 3 + 2];
if (dirz != 0) {
float dz = len / dirz;
float z1 = (bbminz - p0z) * dz;
float z2 = (bbmaxz - p0z) * dz;
float zmin = Math.min(z1, z2);
float zmax = Math.max(z1, z2);
tmin = Math.max(tmin, zmin);
tmax = Math.min(tmax, zmax);
if (tmin > tmax) {
return false;
}
} else {
if (p0z < bbminz || p0z > bbmaxz) return false;
}
if (tmax > len) return false;
return true;
}
public static boolean segmentBox(Vec p0, Vec p1, float[] minmax, int offs) {
return segmentBox(p0.x(), p0.y(), p0.z(), p1.x(), p1.y(), p1.z(), minmax, offs);
}
}
| [
"sergey.chaban@gmail.com"
] | sergey.chaban@gmail.com |
a1f8c80736975ba75567c6993472b8812822cbb4 | 47a1618c7f1e8e197d35746639e4480c6e37492e | /src/oracle/retail/stores/pos/services/instantcredit/DisplayInquiryInfoSite.java | 9dc12a1eaadb2e4a35c473ec148d0c10c70d22ee | [] | no_license | dharmendrams84/POSBaseCode | 41f39039df6a882110adb26f1225218d5dcd8730 | c588c0aa2a2144aa99fa2bbe1bca867e008f47ee | refs/heads/master | 2020-12-31T07:42:29.748967 | 2017-03-29T08:12:34 | 2017-03-29T08:12:34 | 86,555,051 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,545 | java | /* ===========================================================================
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* ===========================================================================
* $Header: rgbustores/applications/pos/src/oracle/retail/stores/pos/services/instantcredit/DisplayInquiryInfoSite.java /rgbustores_13.4x_generic_branch/10 2011/08/30 11:34:34 cgreene Exp $
* ===========================================================================
* NOTES
* <other useful comments, qualifications, etc.>
*
* MODIFIED (MM/DD/YY)
* cgreene 08/30/11 - check for RequestNotSupported first
* blarsen 06/30/11 - Setting ui's financial network status flag based on
* payment manager response. This will update the
* online/offline indicator on POS UI.
* sgu 06/21/11 - handle the case that response status will be null
* cgreene 06/15/11 - implement gift card for servebase and training mode
* sgu 06/13/11 - set training mode flag
* cgreene 05/27/11 - move auth response objects into domain
* sgu 05/24/11 - remove custom id from authorize instant credit
* request
* sgu 05/20/11 - refactor instant credit inquiry flow
* sgu 05/16/11 - move instant credit approval status to its own class
* sgu 05/12/11 - refactor instant credit formatters
* sgu 05/11/11 - define approval status for instant credit as enum
* type
* sgu 05/10/11 - convert instant credit inquiry by SSN to use new
* payment manager
* cgreene 02/15/11 - move constants into interfaces and refactor
* cgreene 05/26/10 - convert to oracle packaging
* cgreene 04/26/10 - XbranchMerge cgreene_tech43 from
* st_rgbustores_techissueseatel_generic_branch
* cgreene 04/02/10 - remove deprecated LocaleContantsIfc and currencies
* dwfung 02/05/10 - write masked SS# to EJ if search done by SSN
* abondala 01/03/10 - update header date
* vchengeg 02/20/09 - for I18N of HouseAccount Enquiry journal entry
* kulu 01/26/09 - Fix the bug that House Account enroll response data
* don't have padding translation at enroll franking
* slip
* kulu 01/22/09 - Switch to use response text instead of use status
* string based on status.
*
* ===========================================================================
* $Log:
* 13 360Commerce 1.12 5/29/2008 4:52:59 PM Maisa De Camargo CR
* 31672 - Setting fields required for the Instant Credit/House
* Account ISD Msg.
* 12 360Commerce 1.11 5/7/2008 8:55:11 PM Alan N. Sinton CR
* 30295: Code modified to present Function Unavailable dialog for
* House Account and Instant Credit when configured with ISD. Code
* reviewed by Anda Cadar.
* 11 360Commerce 1.10 4/27/2008 4:40:12 PM Alan N. Sinton CR
* 30295: Improvements to gift card handling, instant credit and house
* account in the ISD interface. Code was reviewed by Brett Larsen.
* 10 360Commerce 1.9 3/12/2008 12:34:41 PM Deepti Sharma
* changes to display house account number correctly
* 9 360Commerce 1.8 1/17/2008 5:24:06 PM Alan N. Sinton CR
* 29954: Refactor of EncipheredCardData to implement interface and be
* instantiated using a factory.
* 8 360Commerce 1.7 12/27/2007 10:39:29 AM Alan N. Sinton CR
* 29677: Check in changes per code review. Reviews are Michael
* Barnett and Tony Zgarba.
* 7 360Commerce 1.6 12/18/2007 5:47:48 PM Alan N. Sinton CR
* 29661: Changes per code review.
* 6 360Commerce 1.5 11/29/2007 5:15:58 PM Alan N. Sinton CR
* 29677: Protect user entry fields of PAN data.
* 5 360Commerce 1.4 11/27/2007 12:32:24 PM Alan N. Sinton CR
* 29661: Encrypting, masking and hashing account numbers for House
* Account.
* 4 360Commerce 1.3 1/25/2006 4:10:58 PM Brett J. Larsen merge
* 7.1.1 changes (aka. 7.0.3 fixes) into 360Commerce view
* 3 360Commerce 1.2 3/31/2005 4:27:48 PM Robert Pearse
* 2 360Commerce 1.1 3/10/2005 10:21:03 AM Robert Pearse
* 1 360Commerce 1.0 2/11/2005 12:10:39 PM Robert Pearse
*:
* 4 .v700 1.2.1.0 11/4/2005 11:44:43 Jason L. DeLeau 4202:
* Fix extensibility issues for instant credit service
* 3 360Commerce1.2 3/31/2005 15:27:48 Robert Pearse
* 2 360Commerce1.1 3/10/2005 10:21:03 Robert Pearse
* 1 360Commerce1.0 2/11/2005 12:10:39 Robert Pearse
*
* Revision 1.6 2004/08/02 19:59:54 blj
* @scr 6607 - fixed broken site an simulator code. Updated twiki page with new simulator info.
*
* Revision 1.5 2004/05/20 22:54:58 cdb
* @scr 4204 Removed tabs from code base again.
*
* Revision 1.4 2004/05/03 14:47:54 tmorris
* @scr 3890 -Ensures if the House Account variable is empty to respond with proper Error screen.
*
* Revision 1.3 2004/02/12 16:50:40 mcs
* Forcing head revision
*
* Revision 1.2 2004/02/11 21:51:22 rhafernik
* @scr 0 Log4J conversion and code cleanup
*
* Revision 1.1.1.1 2004/02/11 01:04:16 cschellenger
* updating to pvcs 360store-current
*
*
*
* Rev 1.11 Jan 09 2004 17:03:22 nrao
* Formatting the journal entries.
*
* Rev 1.10 Dec 19 2003 14:31:16 nrao
* Fixed potential null pointer exception.
*
* Rev 1.9 Dec 04 2003 17:31:58 nrao
* Code Review Changes.
*
* Rev 1.8 Dec 03 2003 17:25:50 nrao
* Moved screen display to new site.
*
* Rev 1.7 Dec 02 2003 18:10:26 nrao
* Corrected journal entry.
*
* Rev 1.6 Dec 02 2003 17:34:36 nrao
* Added account number to InstantCreditAuthRequest when it is sent to the authorizer. Added error dialog message.
*
* Rev 1.5 Nov 24 2003 19:16:42 nrao
* Using UIUtilities.
*
* Rev 1.4 Nov 21 2003 11:46:12 nrao
* Added ui display for card number.
*
* Rev 1.3 Nov 21 2003 11:36:02 nrao
* Changed card number size.
*
* Rev 1.2 Nov 20 2003 17:45:50 nrao
* Populated model with first name, last name and account number.
*
* Rev 1.1 Nov 20 2003 16:12:14 nrao
* Added journaling and removed "Authorizing ..." message for Inquiry.
*
* ===========================================================================
*/
package oracle.retail.stores.pos.services.instantcredit;
import java.util.Locale;
import oracle.retail.stores.common.parameter.ParameterConstantsIfc;
import oracle.retail.stores.common.utility.Util;
import oracle.retail.stores.domain.DomainGateway;
import oracle.retail.stores.domain.manager.ifc.PaymentManagerIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeInstantCreditRequestIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeInstantCreditResponseIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeRequestIfc;
import oracle.retail.stores.domain.manager.payment.AuthorizeResponseIfc;
import oracle.retail.stores.domain.manager.payment.PaymentServiceResponseIfc.ResponseCode;
import oracle.retail.stores.domain.utility.InstantCreditApprovalStatus;
import oracle.retail.stores.domain.utility.InstantCreditIfc;
import oracle.retail.stores.domain.utility.LocaleConstantsIfc;
import oracle.retail.stores.foundation.manager.ifc.JournalManagerIfc;
import oracle.retail.stores.foundation.manager.ifc.UIManagerIfc;
import oracle.retail.stores.foundation.tour.application.Letter;
import oracle.retail.stores.foundation.tour.gate.Gateway;
import oracle.retail.stores.foundation.tour.ifc.BusIfc;
import oracle.retail.stores.foundation.utility.LocaleMap;
import oracle.retail.stores.keystoreencryption.EncryptionServiceException;
import oracle.retail.stores.pos.manager.ifc.UtilityManagerIfc;
import oracle.retail.stores.pos.manager.utility.UtilityManager;
import oracle.retail.stores.pos.services.PosSiteActionAdapter;
import oracle.retail.stores.pos.services.common.CommonLetterIfc;
import oracle.retail.stores.pos.ui.DialogScreensIfc;
import oracle.retail.stores.pos.ui.POSUIManagerIfc;
import oracle.retail.stores.pos.ui.UIUtilities;
import oracle.retail.stores.pos.ui.beans.DialogBeanModel;
import oracle.retail.stores.pos.utility.ValidationUtility;
import oracle.retail.stores.utility.I18NConstantsIfc;
import oracle.retail.stores.utility.I18NHelper;
import oracle.retail.stores.utility.JournalConstantsIfc;
/**
* This site sends request to the authorizor for instant credit inquiry
*
* @version $Revision: /rgbustores_13.4x_generic_branch/10 $
*/
public class DisplayInquiryInfoSite extends PosSiteActionAdapter implements ParameterConstantsIfc
{
/**
* Serial Version UID
*/
private static final long serialVersionUID = -9083427640926904704L;
/** revision number supplied by version control **/
public static final String revisionNumber = "$Revision: /rgbustores_13.4x_generic_branch/10 $";
/** Constant for HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE */
public static final String HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE = "HouseAccountInquiryFunctionUnavailable";
public static final String MASKED_SOCIAL_SECURITY_NUMBER = "XXX-XX-XXXX";
/**
* Locale
*/
protected static Locale journalLocale = LocaleMap.getLocale(LocaleConstantsIfc.JOURNAL);
/* (non-Javadoc)
* @see oracle.retail.stores.foundation.tour.application.SiteActionAdapter#arrive(oracle.retail.stores.foundation.tour.ifc.BusIfc)
*/
@Override
public void arrive(BusIfc bus)
{
POSUIManagerIfc ui = (POSUIManagerIfc) bus.getManager(UIManagerIfc.TYPE);
InstantCreditCargo cargo = (InstantCreditCargo) bus.getCargo();
UtilityManager utility = (UtilityManager) bus.getManager(UtilityManagerIfc.TYPE);
PaymentManagerIfc paymentMgr = (PaymentManagerIfc)bus.getManager(PaymentManagerIfc.TYPE);
// Create Request to send to Authorizer
AuthorizeInstantCreditRequestIfc request = buildRequest(cargo);
AuthorizeResponseIfc response = paymentMgr.authorize(request);
UIUtilities.setFinancialNetworkUIStatus(response, (POSUIManagerIfc) bus.getManager(UIManagerIfc.TYPE));
if(ResponseCode.RequestNotSupported.equals(response.getResponseCode()))
{
//show the account not found acknowledgement screen
DialogBeanModel model = new DialogBeanModel();
model.setResourceID(HOUSE_ACCOUNT_INQUIRY_FUNCTION_UNAVAILABLE);
model.setType(DialogScreensIfc.ERROR);
model.setButtonLetter(DialogScreensIfc.BUTTON_OK, CommonLetterIfc.FAILURE);
ui.showScreen(POSUIManagerIfc.DIALOG_TEMPLATE, model);
}
else
{
InstantCreditApprovalStatus status = ((AuthorizeInstantCreditResponseIfc)response).getApprovalStatus();
cargo.setApprovalStatus(status);
if (InstantCreditApprovalStatus.APPROVED.equals(status))
{
// ssn/account number found and card information available
// build Instant Credit Card
InstantCreditIfc card = null;
try
{
card = ValidationUtility.createInstantCredit((AuthorizeInstantCreditResponseIfc)response, null, cargo.getSsn(), null);
}
catch(EncryptionServiceException ese)
{
logger.error("Could not encrypt house account number.", ese);
}
if(card != null)
{
cargo.setInstantCredit(card);
// write journal entry
writeJournal(cargo, utility);
// mail "Success" letter for displaying the account information screen
bus.mail(new Letter(CommonLetterIfc.SUCCESS), BusIfc.CURRENT);
}
else
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "InquiryOffline",
null, CommonLetterIfc.NEXT);
}
}
// ssn not found
else if (InstantCreditApprovalStatus.REFERENCE_NOT_FOUND.equals(status))
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "AccountNotFoundError",
null, CommonLetterIfc.NEXT);
}
// account number not found
else if (InstantCreditApprovalStatus.DECLINED.equals(status))
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "AccountNotFoundError",
null, CommonLetterIfc.NEXT);
}
else
{
UIUtilities.setDialogModel(ui, DialogScreensIfc.ACKNOWLEDGEMENT, "InquiryOffline",
null, CommonLetterIfc.NEXT);
}
}
}
/**
* Builds request to be sent to the authorizer
* @param InstantCreditCargo cargo
* @param int timeout
* @return InstantCreditAuthRequest req
*/
protected AuthorizeInstantCreditRequestIfc buildRequest(InstantCreditCargo cargo)
{
AuthorizeInstantCreditRequestIfc req = DomainGateway.getFactory().getAuthorizeInstantCreditRequestInstance();
// set the request sub type for the inquiry
req.setRequestType(AuthorizeRequestIfc.RequestType.InstantCreditInquiry);
// set ssn
req.setSSN(cargo.getSsn());
req.setZipCode(cargo.getZipCode());
req.setHomePhone(cargo.getHomePhone());
if (cargo.getOperator() != null)
{
req.setEmployeeID(cargo.getOperator().getEmployeeID());
}
// set store ID and register ID
req.setWorkstation(cargo.getRegister().getWorkstation());
return req;
}
/**
* Writes the journal entry
* @param cargo InstantCreditCargo
*/
protected void writeJournal(InstantCreditCargo cargo, UtilityManager utility)
{
JournalManagerIfc journal = (JournalManagerIfc)Gateway.getDispatcher().getManager(JournalManagerIfc.TYPE);
if (journal != null)
{
StringBuffer sb = new StringBuffer();
Object data[];
sb.append(Util.EOL);
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.HOUSE_ACCOUNT_INQUIRY_LABEL, null, journalLocale));
sb.append(Util.EOL);
data = new Object[] { cargo.getOperator().getLoginID() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE, JournalConstantsIfc.CASHIER_ID_LABEL, data,
journalLocale));
sb.append(Util.EOL);
data = new Object[] { cargo.getInstantCredit().getEncipheredCardData().getTruncatedAcctNumber() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE, JournalConstantsIfc.ACCOUNT_NUMBER_LABEL,
data, journalLocale));
if (cargo.getZipCode() != null)
{
sb.append(Util.EOL);
data = new Object[] { cargo.getZipCode() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.ZIP_LABEL, data, journalLocale));
}
if (cargo.getHomePhone() != null)
{
sb.append(Util.EOL);
data = new Object[] { cargo.getHomePhone() };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.PHONE_NUMBER_LABEL, data, journalLocale));
}
if (cargo.getSsn() != null)
{
sb.append(Util.EOL);
data = new Object[] { MASKED_SOCIAL_SECURITY_NUMBER };
sb.append(I18NHelper.getString(I18NConstantsIfc.EJOURNAL_TYPE,
JournalConstantsIfc.SOCIAL_SECURITY_NUMBER_LABEL, data, journalLocale));
}
sb.append(Util.EOL);
journal.journal(sb.toString());
}
}
}
| [
"Ignitiv021@Ignitiv021-PC"
] | Ignitiv021@Ignitiv021-PC |
2d98341212929e75a20279038876005b8d21ce92 | 013b3febb1233983da0f9424037683cd011990bb | /Opdrachten AP/src/Opd15/Car.java | fba5255f6e47605b1a13f91cda1c2bb437c67c9b | [] | no_license | vlreinier/AP | c7df54b6937b8d4b406a14a3c7d63f033a4bc83f | faab2eaed9ed10f541a922f3590e610a49b67305 | refs/heads/master | 2022-02-01T16:24:02.484699 | 2019-07-03T18:23:22 | 2019-07-03T18:23:22 | 195,106,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package Opd15;
public class Car {
private String type;
private double priceperday;
public Car(String type, double priceperday){
this.type = type;
this.priceperday = priceperday;
}
public String getType() {
return type;
}
public double getPriceperday() {
return priceperday;
}
public String toString(){
return this.type;
}
}
| [
"43336873+vlreinier@users.noreply.github.com"
] | 43336873+vlreinier@users.noreply.github.com |
74aa5e4b9f3e9f19f1b21442aec8daf8d2ed1259 | 9c39465a935c4a55a17d825de7604e9527d09988 | /src/main/java/ai/wealth/boot/initiator/controller/PrimaryController.java | c15232a4de89f85d1858a7fb42b6af78e428473b | [] | no_license | xorasysgen/initiator-api | 88329ddcf0ab807b2e850a9e75a38506aadadcde | e7bcad9647c61938ab427f8e700526d3f476503e | refs/heads/master | 2020-06-29T00:46:00.709629 | 2019-11-14T11:31:12 | 2019-11-14T11:31:12 | 200,389,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,392 | java | package ai.wealth.boot.initiator.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import ai.wealth.boot.initiator.dto.ServerStatus;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/api")
public class PrimaryController {
//https://api.wealthkernel.com/swagger/v2/index.html
@ResponseBody
@ApiOperation(value = "Get Server information", notes="no addition parameters required", response=ServerStatus.class)
@GetMapping("/info")
public ServerStatus root() {
return new ServerStatus();
}
@ResponseBody
@ApiOperation(value = "say hi", notes="addition parameters required", response=String.class)
@GetMapping("/{name}")
@HystrixCommand(fallbackMethod = "fallbackMethodFailure")
public String hi(@PathVariable("name") String name) {
if(name!=null && !name.equals("name"))
return "Hello " + name;
else
throw new RuntimeException("Name should not be null");
}
public String fallbackMethodFailure(@PathVariable("name") String name) {
return "Home failue due to Name should not be null";
}
}
| [
"xorasysgen@yahoo.com"
] | xorasysgen@yahoo.com |
66a4c570d5b4ec463329a7b987d8c491f21f1c30 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_5fc9d09e386a298265876b8a331f735c5b47333b/HashingUtils/8_5fc9d09e386a298265876b8a331f735c5b47333b_HashingUtils_t.java | ad07b92eae26ce71b84596c9df9e917244cce8b7 | [] | 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 | 3,101 | java | /*
Copyright 2011 Monits
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.monits.commons;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Hashing utilities.
*
* @author Franco Zeoli <fzeoli@monits.com>
* @copyright 2011 Monits
* @license Apache 2.0 License
* @version Release: 1.0.0
* @link http://www.monits.com/
* @since 1.0.0
*/
public class HashingUtils {
/**
* Retrieves the file hashed by the given hashing algorithm.
* @param filename The path to the file to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
* @throws FileNotFoundException
*/
public static String getFileHash(String filename, HashingAlgorithm algorithm) throws FileNotFoundException {
return getHash(new FileInputStream(filename), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The string to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(String input, HashingAlgorithm algorithm) {
return getHash(new ByteArrayInputStream(input.getBytes()), algorithm);
}
/**
* Retrieves the given input string hashed with the given hashing algorithm.
* @param input The source from which to read the input to hash.
* @param algorithm Which hashing algorithm to use.
* @return The resulting hash
*/
public static String getHash(InputStream input, HashingAlgorithm algorithm) {
byte[] buffer = new byte[1024];
try {
MessageDigest algo = MessageDigest.getInstance(algorithm.getName());
int readBytes;
do {
readBytes = input.read(buffer);
algo.update(buffer, 0, readBytes);
} while (readBytes == buffer.length);
byte messageDigest[] = algo.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String token = Integer.toHexString(0xFF & messageDigest[i]);
// Make sure each is exactly 2 chars long
if (token.length() < 2) {
hexString.append("0");
}
hexString.append(token);
}
return hexString.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
ef7e1c6d24297fa8d6c3a9b6e77959c91f5a86ef | 1b4c3ec7953f6d1aea55c7a400d8fd08f17d6a8b | /src/main/java/com/example/mapper/base2/BusiAccountMapper.java | 81e61df76e5523be1c588fce1cca2cc992b2320b | [] | no_license | 82253452/bestMVC | d9dd07294501ed5a21c1f936a3f254e695bad4fc | 3d3169897647f6f7b235a33998af8037571e7496 | refs/heads/master | 2020-03-25T10:48:56.480524 | 2018-08-06T11:48:10 | 2018-08-06T11:48:10 | 143,706,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.example.mapper.base2;
import com.example.entity.BusiAccount;
import tk.mybatis.mapper.common.Mapper;
public interface BusiAccountMapper extends Mapper<BusiAccount> {
} | [
"82253452@qq.com"
] | 82253452@qq.com |
3aee48672b5807ee47c1e496f97ab114ee7233e6 | 1ecfedc980ac8c052bd4ce1e7f9edb5764b2fede | /appHotelito/src/main/java/com/hotelito/model/Habitacion.java | dd991d03b6551215631579bbc055584275647c71 | [] | no_license | ramirezdchris/appHotelitoService | d4fa7782773fbfeb584393dfd5f527f53e615014 | ad380b964806906965a31f474d9547ac001c0c8c | refs/heads/master | 2022-12-30T07:51:23.871663 | 2020-10-19T00:12:24 | 2020-10-19T00:12:24 | 296,516,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,278 | java | package com.hotelito.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "habitacion")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class Habitacion implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_habitacion")
private int idHabitacion;
@Column(name = "nombre_habitacion")
private String nombreHabitacion;
@Column(name ="estado")
private int estadoHabitacion;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name ="tipo_habitacion")
private TipoHabitacion tipoHabitacion;
public Habitacion() {
super();
}
public Habitacion(int idHabitacion, String nombreHabitacion, int estadoHabitacion,
TipoHabitacion tipoHabitacion) {
super();
this.idHabitacion = idHabitacion;
this.nombreHabitacion = nombreHabitacion;
this.estadoHabitacion = estadoHabitacion;
this.tipoHabitacion = tipoHabitacion;
}
public int getIdHabitacion() {
return idHabitacion;
}
public void setIdHabitacion(int idHabitacion) {
this.idHabitacion = idHabitacion;
}
public String getNombreHabitacion() {
return nombreHabitacion;
}
public void setNombreHabitacion(String nombreHabitacion) {
this.nombreHabitacion = nombreHabitacion;
}
public int getEstadoHabitacion() {
return estadoHabitacion;
}
public void setEstadoHabitacion(int estadoHabitacion) {
this.estadoHabitacion = estadoHabitacion;
}
public TipoHabitacion getTipoHabitacion() {
return tipoHabitacion;
}
public void setTipoHabitacion(TipoHabitacion tipoHabitacion) {
this.tipoHabitacion = tipoHabitacion;
}
@Override
public String toString() {
return "Habitacion [idHabitacion=" + idHabitacion + ", nombreHabitacion=" + nombreHabitacion
+ ", estadoHabitacion=" + estadoHabitacion + ", tipoHabitacion=" + tipoHabitacion + "]";
}
}
| [
"ramirezd.christian@gmail.com"
] | ramirezd.christian@gmail.com |
44057f7febaa6713cc07d4cbae143ce4ba00e6db | 033ac515e37b7902f347502a8cc4501877faa439 | /src/main/java/com/example/task1/entity/Product.java | c26f8f22f7d55a1f2845cfca5985208ac25b17f2 | [] | no_license | Ibrohimjon2151/WareHouse | 05c00823fded7fd0e6759a2165f7cfebed36bfcf | 9abd0b47c702183617ba5978fb2e14a284dc1b02 | refs/heads/master | 2023-08-01T21:42:02.993439 | 2021-10-03T08:19:54 | 2021-10-03T08:19:54 | 413,017,784 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 503 | java | package com.example.task1.entity;
import com.example.task1.entity.template.AbcNameEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
@EqualsAndHashCode(callSuper = true)
@Data
public class Product extends AbcNameEntity {
private int code;
@OneToOne
private Measurment measurment;
@ManyToOne
Category category;
@ManyToOne
Attachment attechmant;
}
| [
"ibrohimjonyursunov50@gmail.com"
] | ibrohimjonyursunov50@gmail.com |
dbad81cd3087dea51e5024e889486ff59ed23e99 | fc90aea788f27ad5283b3724987151d35d91db1b | /aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/SolutionVersion.java | d0887ebe3c62c3897b7a1923aa897c63bca3021b | [
"Apache-2.0"
] | permissive | countVladimir/aws-sdk-java | bc63a06bbb51d93fb60e736e8b72fe75dbea5d48 | 631354f54ad5c41fa038217b1bda8161ab8d93e2 | refs/heads/master | 2023-02-12T17:31:12.240017 | 2021-01-07T22:44:04 | 2021-01-07T22:44:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 40,916 | java | /*
* Copyright 2016-2021 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.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* An object that provides information about a specific version of a <a>Solution</a>.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/SolutionVersion" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SolutionVersion implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ARN of the solution version.
* </p>
*/
private String solutionVersionArn;
/**
* <p>
* The ARN of the solution.
* </p>
*/
private String solutionArn;
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*/
private Boolean performHPO;
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*/
private Boolean performAutoML;
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*/
private String recipeArn;
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*/
private String eventType;
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*/
private String datasetGroupArn;
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*/
private SolutionConfig solutionConfig;
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*/
private Double trainingHours;
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*/
private String trainingMode;
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*/
private TunedHPOParams tunedHPOParams;
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*/
private String status;
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*/
private String failureReason;
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*/
private java.util.Date creationDateTime;
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*/
private java.util.Date lastUpdatedDateTime;
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @param solutionVersionArn
* The ARN of the solution version.
*/
public void setSolutionVersionArn(String solutionVersionArn) {
this.solutionVersionArn = solutionVersionArn;
}
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @return The ARN of the solution version.
*/
public String getSolutionVersionArn() {
return this.solutionVersionArn;
}
/**
* <p>
* The ARN of the solution version.
* </p>
*
* @param solutionVersionArn
* The ARN of the solution version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionVersionArn(String solutionVersionArn) {
setSolutionVersionArn(solutionVersionArn);
return this;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @param solutionArn
* The ARN of the solution.
*/
public void setSolutionArn(String solutionArn) {
this.solutionArn = solutionArn;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @return The ARN of the solution.
*/
public String getSolutionArn() {
return this.solutionArn;
}
/**
* <p>
* The ARN of the solution.
* </p>
*
* @param solutionArn
* The ARN of the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionArn(String solutionArn) {
setSolutionArn(solutionArn);
return this;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @param performHPO
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public void setPerformHPO(Boolean performHPO) {
this.performHPO = performHPO;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @return Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public Boolean getPerformHPO() {
return this.performHPO;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @param performHPO
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withPerformHPO(Boolean performHPO) {
setPerformHPO(performHPO);
return this;
}
/**
* <p>
* Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is <code>false</code>.
* </p>
*
* @return Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default is
* <code>false</code>.
*/
public Boolean isPerformHPO() {
return this.performHPO;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @param performAutoML
* When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public void setPerformAutoML(Boolean performAutoML) {
this.performAutoML = performAutoML;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @return When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public Boolean getPerformAutoML() {
return this.performAutoML;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @param performAutoML
* When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withPerformAutoML(Boolean performAutoML) {
setPerformAutoML(performAutoML);
return this;
}
/**
* <p>
* When true, Amazon Personalize searches for the most optimal recipe according to the solution configuration. When
* false (the default), Amazon Personalize uses <code>recipeArn</code>.
* </p>
*
* @return When true, Amazon Personalize searches for the most optimal recipe according to the solution
* configuration. When false (the default), Amazon Personalize uses <code>recipeArn</code>.
*/
public Boolean isPerformAutoML() {
return this.performAutoML;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @param recipeArn
* The ARN of the recipe used in the solution.
*/
public void setRecipeArn(String recipeArn) {
this.recipeArn = recipeArn;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @return The ARN of the recipe used in the solution.
*/
public String getRecipeArn() {
return this.recipeArn;
}
/**
* <p>
* The ARN of the recipe used in the solution.
* </p>
*
* @param recipeArn
* The ARN of the recipe used in the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withRecipeArn(String recipeArn) {
setRecipeArn(recipeArn);
return this;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @param eventType
* The event type (for example, 'click' or 'like') that is used for training the model.
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @return The event type (for example, 'click' or 'like') that is used for training the model.
*/
public String getEventType() {
return this.eventType;
}
/**
* <p>
* The event type (for example, 'click' or 'like') that is used for training the model.
* </p>
*
* @param eventType
* The event type (for example, 'click' or 'like') that is used for training the model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withEventType(String eventType) {
setEventType(eventType);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
*/
public void setDatasetGroupArn(String datasetGroupArn) {
this.datasetGroupArn = datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @return The Amazon Resource Name (ARN) of the dataset group providing the training data.
*/
public String getDatasetGroupArn() {
return this.datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the dataset group providing the training data.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withDatasetGroupArn(String datasetGroupArn) {
setDatasetGroupArn(datasetGroupArn);
return this;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @param solutionConfig
* Describes the configuration properties for the solution.
*/
public void setSolutionConfig(SolutionConfig solutionConfig) {
this.solutionConfig = solutionConfig;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @return Describes the configuration properties for the solution.
*/
public SolutionConfig getSolutionConfig() {
return this.solutionConfig;
}
/**
* <p>
* Describes the configuration properties for the solution.
* </p>
*
* @param solutionConfig
* Describes the configuration properties for the solution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withSolutionConfig(SolutionConfig solutionConfig) {
setSolutionConfig(solutionConfig);
return this;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @param trainingHours
* The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
*/
public void setTrainingHours(Double trainingHours) {
this.trainingHours = trainingHours;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @return The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
*/
public Double getTrainingHours() {
return this.trainingHours;
}
/**
* <p>
* The time used to train the model. You are billed for the time it takes to train a model. This field is visible
* only after Amazon Personalize successfully trains a model.
* </p>
*
* @param trainingHours
* The time used to train the model. You are billed for the time it takes to train a model. This field is
* visible only after Amazon Personalize successfully trains a model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withTrainingHours(Double trainingHours) {
setTrainingHours(trainingHours);
return this;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @see TrainingMode
*/
public void setTrainingMode(String trainingMode) {
this.trainingMode = trainingMode;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @return The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @see TrainingMode
*/
public String getTrainingMode() {
return this.trainingMode;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingMode
*/
public SolutionVersion withTrainingMode(String trainingMode) {
setTrainingMode(trainingMode);
return this;
}
/**
* <p>
* The scope of training used to create the solution version. The <code>FULL</code> option trains the solution
* version based on the entirety of the input solution's training data, while the <code>UPDATE</code> option
* processes only the training data that has changed since the creation of the last solution version. Choose
* <code>UPDATE</code> when you want to start recommending items added to the dataset without retraining the model.
* </p>
* <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* </important>
*
* @param trainingMode
* The scope of training used to create the solution version. The <code>FULL</code> option trains the
* solution version based on the entirety of the input solution's training data, while the
* <code>UPDATE</code> option processes only the training data that has changed since the creation of the
* last solution version. Choose <code>UPDATE</code> when you want to start recommending items added to the
* dataset without retraining the model.</p> <important>
* <p>
* The <code>UPDATE</code> option can only be used after you've created a solution version with the
* <code>FULL</code> option and the training solution uses the <a>native-recipe-hrnn-coldstart</a>.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingMode
*/
public SolutionVersion withTrainingMode(TrainingMode trainingMode) {
this.trainingMode = trainingMode.toString();
return this;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @param tunedHPOParams
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
*/
public void setTunedHPOParams(TunedHPOParams tunedHPOParams) {
this.tunedHPOParams = tunedHPOParams;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @return If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
*/
public TunedHPOParams getTunedHPOParams() {
return this.tunedHPOParams;
}
/**
* <p>
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing model.
* </p>
*
* @param tunedHPOParams
* If hyperparameter optimization was performed, contains the hyperparameter values of the best performing
* model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withTunedHPOParams(TunedHPOParams tunedHPOParams) {
setTunedHPOParams(tunedHPOParams);
return this;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @param status
* The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @return The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the solution version.
* </p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* </ul>
*
* @param status
* The status of the solution version.</p>
* <p>
* A solution version can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING
* </p>
* </li>
* <li>
* <p>
* CREATE IN_PROGRESS
* </p>
* </li>
* <li>
* <p>
* ACTIVE
* </p>
* </li>
* <li>
* <p>
* CREATE FAILED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @param failureReason
* If training a solution version fails, the reason for the failure.
*/
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @return If training a solution version fails, the reason for the failure.
*/
public String getFailureReason() {
return this.failureReason;
}
/**
* <p>
* If training a solution version fails, the reason for the failure.
* </p>
*
* @param failureReason
* If training a solution version fails, the reason for the failure.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withFailureReason(String failureReason) {
setFailureReason(failureReason);
return this;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix time) that this version of the solution was created.
*/
public void setCreationDateTime(java.util.Date creationDateTime) {
this.creationDateTime = creationDateTime;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @return The date and time (in Unix time) that this version of the solution was created.
*/
public java.util.Date getCreationDateTime() {
return this.creationDateTime;
}
/**
* <p>
* The date and time (in Unix time) that this version of the solution was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix time) that this version of the solution was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withCreationDateTime(java.util.Date creationDateTime) {
setCreationDateTime(creationDateTime);
return this;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix time) that the solution was last updated.
*/
public void setLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
this.lastUpdatedDateTime = lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @return The date and time (in Unix time) that the solution was last updated.
*/
public java.util.Date getLastUpdatedDateTime() {
return this.lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix time) that the solution was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix time) that the solution was last updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SolutionVersion withLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
setLastUpdatedDateTime(lastUpdatedDateTime);
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 (getSolutionVersionArn() != null)
sb.append("SolutionVersionArn: ").append(getSolutionVersionArn()).append(",");
if (getSolutionArn() != null)
sb.append("SolutionArn: ").append(getSolutionArn()).append(",");
if (getPerformHPO() != null)
sb.append("PerformHPO: ").append(getPerformHPO()).append(",");
if (getPerformAutoML() != null)
sb.append("PerformAutoML: ").append(getPerformAutoML()).append(",");
if (getRecipeArn() != null)
sb.append("RecipeArn: ").append(getRecipeArn()).append(",");
if (getEventType() != null)
sb.append("EventType: ").append(getEventType()).append(",");
if (getDatasetGroupArn() != null)
sb.append("DatasetGroupArn: ").append(getDatasetGroupArn()).append(",");
if (getSolutionConfig() != null)
sb.append("SolutionConfig: ").append(getSolutionConfig()).append(",");
if (getTrainingHours() != null)
sb.append("TrainingHours: ").append(getTrainingHours()).append(",");
if (getTrainingMode() != null)
sb.append("TrainingMode: ").append(getTrainingMode()).append(",");
if (getTunedHPOParams() != null)
sb.append("TunedHPOParams: ").append(getTunedHPOParams()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getFailureReason() != null)
sb.append("FailureReason: ").append(getFailureReason()).append(",");
if (getCreationDateTime() != null)
sb.append("CreationDateTime: ").append(getCreationDateTime()).append(",");
if (getLastUpdatedDateTime() != null)
sb.append("LastUpdatedDateTime: ").append(getLastUpdatedDateTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SolutionVersion == false)
return false;
SolutionVersion other = (SolutionVersion) obj;
if (other.getSolutionVersionArn() == null ^ this.getSolutionVersionArn() == null)
return false;
if (other.getSolutionVersionArn() != null && other.getSolutionVersionArn().equals(this.getSolutionVersionArn()) == false)
return false;
if (other.getSolutionArn() == null ^ this.getSolutionArn() == null)
return false;
if (other.getSolutionArn() != null && other.getSolutionArn().equals(this.getSolutionArn()) == false)
return false;
if (other.getPerformHPO() == null ^ this.getPerformHPO() == null)
return false;
if (other.getPerformHPO() != null && other.getPerformHPO().equals(this.getPerformHPO()) == false)
return false;
if (other.getPerformAutoML() == null ^ this.getPerformAutoML() == null)
return false;
if (other.getPerformAutoML() != null && other.getPerformAutoML().equals(this.getPerformAutoML()) == false)
return false;
if (other.getRecipeArn() == null ^ this.getRecipeArn() == null)
return false;
if (other.getRecipeArn() != null && other.getRecipeArn().equals(this.getRecipeArn()) == false)
return false;
if (other.getEventType() == null ^ this.getEventType() == null)
return false;
if (other.getEventType() != null && other.getEventType().equals(this.getEventType()) == false)
return false;
if (other.getDatasetGroupArn() == null ^ this.getDatasetGroupArn() == null)
return false;
if (other.getDatasetGroupArn() != null && other.getDatasetGroupArn().equals(this.getDatasetGroupArn()) == false)
return false;
if (other.getSolutionConfig() == null ^ this.getSolutionConfig() == null)
return false;
if (other.getSolutionConfig() != null && other.getSolutionConfig().equals(this.getSolutionConfig()) == false)
return false;
if (other.getTrainingHours() == null ^ this.getTrainingHours() == null)
return false;
if (other.getTrainingHours() != null && other.getTrainingHours().equals(this.getTrainingHours()) == false)
return false;
if (other.getTrainingMode() == null ^ this.getTrainingMode() == null)
return false;
if (other.getTrainingMode() != null && other.getTrainingMode().equals(this.getTrainingMode()) == false)
return false;
if (other.getTunedHPOParams() == null ^ this.getTunedHPOParams() == null)
return false;
if (other.getTunedHPOParams() != null && other.getTunedHPOParams().equals(this.getTunedHPOParams()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getFailureReason() == null ^ this.getFailureReason() == null)
return false;
if (other.getFailureReason() != null && other.getFailureReason().equals(this.getFailureReason()) == false)
return false;
if (other.getCreationDateTime() == null ^ this.getCreationDateTime() == null)
return false;
if (other.getCreationDateTime() != null && other.getCreationDateTime().equals(this.getCreationDateTime()) == false)
return false;
if (other.getLastUpdatedDateTime() == null ^ this.getLastUpdatedDateTime() == null)
return false;
if (other.getLastUpdatedDateTime() != null && other.getLastUpdatedDateTime().equals(this.getLastUpdatedDateTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSolutionVersionArn() == null) ? 0 : getSolutionVersionArn().hashCode());
hashCode = prime * hashCode + ((getSolutionArn() == null) ? 0 : getSolutionArn().hashCode());
hashCode = prime * hashCode + ((getPerformHPO() == null) ? 0 : getPerformHPO().hashCode());
hashCode = prime * hashCode + ((getPerformAutoML() == null) ? 0 : getPerformAutoML().hashCode());
hashCode = prime * hashCode + ((getRecipeArn() == null) ? 0 : getRecipeArn().hashCode());
hashCode = prime * hashCode + ((getEventType() == null) ? 0 : getEventType().hashCode());
hashCode = prime * hashCode + ((getDatasetGroupArn() == null) ? 0 : getDatasetGroupArn().hashCode());
hashCode = prime * hashCode + ((getSolutionConfig() == null) ? 0 : getSolutionConfig().hashCode());
hashCode = prime * hashCode + ((getTrainingHours() == null) ? 0 : getTrainingHours().hashCode());
hashCode = prime * hashCode + ((getTrainingMode() == null) ? 0 : getTrainingMode().hashCode());
hashCode = prime * hashCode + ((getTunedHPOParams() == null) ? 0 : getTunedHPOParams().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getFailureReason() == null) ? 0 : getFailureReason().hashCode());
hashCode = prime * hashCode + ((getCreationDateTime() == null) ? 0 : getCreationDateTime().hashCode());
hashCode = prime * hashCode + ((getLastUpdatedDateTime() == null) ? 0 : getLastUpdatedDateTime().hashCode());
return hashCode;
}
@Override
public SolutionVersion clone() {
try {
return (SolutionVersion) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.personalize.model.transform.SolutionVersionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| [
""
] | |
480b9f7cd472ac2ad2b857278c0e8a4d3d2d35eb | c314325a88074867d1058c78d69f9ca50156d0bb | /src/com/jeecms/cms/entity/assist/CmsGuestbook.java | 5f921e2e5e43d34203aadc8ee139d77361372526 | [] | no_license | zhaoshunxin/jeecmsv8 | 88bd5995c87475f568544bb131280550bf323714 | 0df764a90f4dcf54e9b23854e988b8a78a7d0bda | refs/heads/master | 2020-03-27T22:18:42.905602 | 2017-03-29T16:14:44 | 2017-03-29T16:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,343 | java | package com.jeecms.cms.entity.assist;
import java.sql.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import com.jeecms.cms.entity.assist.base.BaseCmsGuestbook;
import com.jeecms.common.util.DateUtils;
import com.jeecms.common.util.StrUtils;
public class CmsGuestbook extends BaseCmsGuestbook {
private static final long serialVersionUID = 1L;
public String getTitleHtml() {
return StrUtils.txt2htm(getTitle());
}
public String getContentHtml() {
return StrUtils.txt2htm(getContent());
}
public String getReplyHtml() {
return StrUtils.txt2htm(getReply());
}
public String getTitle() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getTitle();
} else {
return null;
}
}
public String getContent() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getContent();
} else {
return null;
}
}
public String getReply() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getReply();
} else {
return null;
}
}
public String getEmail() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getEmail();
} else {
return null;
}
}
public String getPhone() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getPhone();
} else {
return null;
}
}
public String getQq() {
CmsGuestbookExt ext = getExt();
if (ext != null) {
return ext.getQq();
} else {
return null;
}
}
public void init() {
if (getChecked() == null) {
setChecked(false);
}
if (getRecommend() == null) {
setRecommend(false);
}
if (getCreateTime() == null) {
setCreateTime(new Timestamp(System.currentTimeMillis()));
}
}
public JSONObject convertToJson()
throws JSONException{
JSONObject json=new JSONObject();
json.put("id", getId());
json.put("createTime", DateUtils.parseDateToTimeStr(getCreateTime()));
if(getReplayTime()!=null){
json.put("replayTime",DateUtils.parseDateToTimeStr(getReplayTime()));
}else{
json.put("replayTime", "");
}
json.put("recommend", getRecommend());
json.put("checked", getChecked());
if(getMember()!=null){
json.put("member", getMember().getUsername());
}else{
json.put("member", "");
}
if(getAdmin()!=null){
json.put("admin", getAdmin().getUsername());
}else{
json.put("admin", "");
}
json.put("ip", getIp());
json.put("ctg", getCtg().getName());
json.put("title", getTitle());
json.put("content", getContent());
json.put("reply", getReply());
json.put("email", getEmail());
json.put("phone", getPhone());
json.put("qq", getQq());
return json;
}
/* [CONSTRUCTOR MARKER BEGIN] */
public CmsGuestbook () {
super();
}
/**
* Constructor for primary key
*/
public CmsGuestbook (Integer id) {
super(id);
}
/**
* Constructor for required fields
*/
public CmsGuestbook (
Integer id,
com.jeecms.core.entity.CmsSite site,
com.jeecms.cms.entity.assist.CmsGuestbookCtg ctg,
String ip,
java.util.Date createTime,
Boolean checked,
Boolean recommend) {
super (
id,
site,
ctg,
ip,
createTime,
checked,
recommend);
}
/* [CONSTRUCTOR MARKER END] */
} | [
"hanebert@HanEbertdeMacBook-Pro.local"
] | hanebert@HanEbertdeMacBook-Pro.local |
f98820b2bff5dc545383f9f4b782737bae10fcc9 | 1f679719b629bd9f04b00de7f4fe2ad6502e0dfa | /src/main/java/com/shnupbups/redstonebits/block/AdvancedRedstoneConnector.java | 349896e20e1da22d18c17481bd3a5f7ab46af714 | [] | no_license | piisawheel/redstone-bits | 79ec0dda3ba9822fe443a6564603d58981b19b2a | d98ea7fbf0e2d453f44253387455ca1fab9fcf02 | refs/heads/master | 2023-02-12T01:41:17.490568 | 2021-01-14T08:48:02 | 2021-01-14T08:48:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 312 | java | package com.shnupbups.redstonebits.block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
public interface AdvancedRedstoneConnector {
default boolean connectsToRedstoneInDirection(BlockState state, Direction direction) {
return true;
}
}
| [
"shnupbups@gmail.com"
] | shnupbups@gmail.com |
3fefc3ff6047afa1d9baf741c128027fb8b24ddb | 9fb4513e077fe4d797d7db83b9970c410aac8f21 | /src/main/java/com/github/kunalk16/excel/factory/SheetFactory.java | adce75e54e3a491758e26414965d0a4f486b7c79 | [
"MIT"
] | permissive | jrpedrianes/lightExcelReader | 23555189790689c2134147fb53a4bd30bc6d5457 | 4d5a82feccf66763fa9a65b3db7261905a933402 | refs/heads/master | 2022-12-31T14:06:56.609564 | 2020-10-17T13:16:20 | 2020-10-17T13:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,513 | java | package com.github.kunalk16.excel.factory;
import com.github.kunalk16.excel.factory.extractor.RowByNumberExtractor;
import com.github.kunalk16.excel.factory.filter.NonEmptyRowFilter;
import com.github.kunalk16.excel.model.factory.ExcelSheet;
import com.github.kunalk16.excel.model.jaxb.sharedstrings.SharedStringType;
import com.github.kunalk16.excel.model.jaxb.worksheet.SheetDataType;
import com.github.kunalk16.excel.model.jaxb.worksheet.WorkSheetType;
import com.github.kunalk16.excel.model.user.Row;
import com.github.kunalk16.excel.model.user.Sheet;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class SheetFactory {
static Sheet create(SharedStringType sharedStrings, WorkSheetType workSheet, String sheetName) {
return Optional.ofNullable(getRows(sharedStrings, workSheet))
.map(new RowByNumberExtractor())
.map(rowByNumber -> new ExcelSheet(rowByNumber, sheetName))
.orElse(null);
}
private static List<Row> getRows(SharedStringType sharedStrings, WorkSheetType workSheet) {
return Optional.ofNullable(workSheet)
.map(WorkSheetType::getSheetData)
.map(SheetDataType::getRows)
.orElse(Collections.emptyList())
.stream()
.map(row -> RowFactory.create(sharedStrings, row))
.filter(new NonEmptyRowFilter())
.collect(Collectors.toList());
}
}
| [
"kkdthunlshd@gmail.com"
] | kkdthunlshd@gmail.com |
f8a691ec022c0ea7b4ce13cec233a1c88e69ec27 | b34a077d7f0dcd5dbb7c88f9d7df69d7d4dba6e1 | /src/main/java/org/Webgatherer/Controller/Base/EntryBase.java | f27f2a243c7dcaa429af80279eb7b6ab39319dd4 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | rickdane/WebGatherer---Scraper-and-Analyzer | 138b15c25d47ada5f14133ffc73d4f6df62ef314 | 6385db5e4a485132a4241a9670c62741545d8c90 | refs/heads/master | 2016-09-05T11:32:19.227440 | 2012-01-20T08:12:54 | 2012-01-20T08:12:54 | 2,817,230 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 791 | java | package org.Webgatherer.Controller.Base;
import com.google.gson.Gson;
import org.Webgatherer.Controller.EntityTransport.EntryTransport;
import org.Webgatherer.Utility.Service.WebServiceClient;
/**
* @author Rick Dane
*/
public class EntryBase {
protected static WebServiceClient webServiceClient = new WebServiceClient("http://localhost:8080/springservicesmoduleroo/entrys");
protected static String webServiceContentType = "application/json";
protected static void persistEntry(String data) {
EntryTransport entryTransport = new EntryTransport();
entryTransport.setDescription(data);
Gson gson = new Gson();
String jsonData = gson.toJson(entryTransport);
webServiceClient.servicePost("", jsonData, webServiceContentType);
}
}
| [
"rick_developer@gmx.com"
] | rick_developer@gmx.com |
e3c0878e2aba424be1fe8e8a8b252b856cb9b8c9 | fd14b901fe3887ab5cc18301ad688a238feec358 | /src/org/ric/strukdat/project/Main.java | 19c47840d96b3dd02c9a6c98980d68dfb0802446 | [
"MIT"
] | permissive | angelbirth/calc | 484f1157716699d422ca94fe93d71f969ad14d5b | efa58414c55c0874b4e184a696ac2195e76c5757 | refs/heads/master | 2021-01-22T18:10:31.561992 | 2014-10-27T04:16:02 | 2014-10-27T04:16:02 | 25,800,643 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 959 | java | package org.ric.strukdat.project;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
if (args.length > 0) try {
if (!args[0].equals("-")) {
FileInputStream file = new FileInputStream(args[0]);
System.setIn(file);
}
} catch (FileNotFoundException e1) {
System.err.println("File tidak ditemukan.");
System.exit(1);
}
System.out
.println("Hai! Masukkan ekspresi matematika untuk dievaluasi:");
Scanner s = new Scanner(System.in);
try {
Evaluator e = new Evaluator(s.nextLine());
System.out.printf("Hasil perhitungannya adalah %f", e.evaluate());
} catch (IllegalArgumentException ex) {
System.err.println(ex.getMessage());
}
s.close();
}
}
| [
"ricky.ason@gmail.com"
] | ricky.ason@gmail.com |
a4b308a19a9eacb7d2605280447a30344d6fc1b3 | c72ab33625ef4565755406e59e732fc677c6eec7 | /DirectExchange-starter-code/Producer-starter-project/springboot-rabbitmq/src/main/java/com/poc/springbootrabbitmq/config/RabbitMQConfig.java | ec4d3f6b6c9f37112d0ed2cc7305c5ef1b3c0e47 | [] | no_license | Anand450623/RabbitMq | ebc474d7731482a0bffab647b7c49721045247ca | 8670aa4b3c72594269f8a13922c321a347e0be33 | refs/heads/master | 2023-04-27T23:17:12.333137 | 2019-10-04T19:00:24 | 2019-10-04T19:00:24 | 182,010,278 | 0 | 0 | null | 2023-04-14T17:48:52 | 2019-04-18T03:32:04 | Java | UTF-8 | Java | false | false | 1,142 | java | package com.poc.springbootrabbitmq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig
{
@Value("${queueName}")
String queueName;
@Value("${exchangeName}")
String exchange;
@Value("${routingkey}")
private String routingkey;
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
DirectExchange exchange() {
return new DirectExchange(exchange);
}
@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
| [
"ak450623@gmail.com"
] | ak450623@gmail.com |
c097fa2d106081e3550fa5e540ceb9ebbf5081eb | cd9d753ecb5bd98e5e1381bc7bd2ffbd1eacc04d | /src/main/java/leecode/dfs/Solution39.java | 87dd6b124063c8bc17353211d49839d1b5c886f3 | [] | no_license | never123450/aDailyTopic | ea1bcdec840274442efa1223bf6ed33c0a394d3d | 9b17d34197a3ef2a9f95e8b717cbf7904c8dcfe4 | refs/heads/master | 2022-08-06T15:49:25.317366 | 2022-07-24T13:47:07 | 2022-07-24T13:47:07 | 178,113,303 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,457 | java | package leecode.dfs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @description: https://leetcode-cn.com/problems/combination-sum/
* 组合总和
* @author: xwy
* @create: 2021年08月12日16:42:26
**/
public class Solution39 {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) return null;
List<List<Integer>> lists = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
// 配合 begin 用于去重,保证数字是有小到大的顺序选择的
Arrays.sort(candidates);
dfs(0, target, candidates, nums, lists);
return lists;
}
/**
* @param begin 从哪个位置的数开始选取(用于去重,保证数字是有小到大的顺序选择的)
* @param remain 还剩多少凑够 target
* @param candidates
* @param nums
* @param lists
*/
private void dfs(int begin, int remain, int[] candidates, List<Integer> nums, List<List<Integer>> lists) {
if (remain == 0) {
lists.add(new ArrayList<>(nums));
return;
}
for (int i = begin; i < candidates.length; i++) {
if (remain < candidates[i]) return;
nums.add(candidates[i]);
dfs(i, remain - candidates[i], candidates, nums, lists);
nums.remove(nums.size() - 1);
}
}
} | [
"845619585@qq.com"
] | 845619585@qq.com |
8c8927cded582c902fd5a257227a8d8037994e3f | c28e9356ee849c2a52a787cb12f2b4a3f27b5a0e | /app/src/main/java/hakan_akkurt_matthias_will/de/to_do_list/dialogs/DatePickerFragment.java | ff51d26753b8406e279315ab9119a8299e276726 | [] | no_license | HakanAkkurt/To-Do-List | 34f49a4cad2b68146341d9c75ed33cf5972bedc8 | 0142204b8d9ce3178b1ecd87e4da0b904b82a295 | refs/heads/master | 2021-04-29T07:33:26.755442 | 2017-01-31T20:23:15 | 2017-01-31T20:23:15 | 77,949,787 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,117 | java | package hakan_akkurt_matthias_will.de.to_do_list.dialogs;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
/**
* Created by Hakan Akkurt on 19.01.2017.
*/
public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener listener;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this.listener, year, month, day);
}
@Override
public void onAttach(final Activity activity) {
if (activity instanceof DatePickerDialog.OnDateSetListener) {
this.listener = (DatePickerDialog.OnDateSetListener) activity;
}
super.onAttach(activity);
}
} | [
"Hakan_Akkurt@hotmail.de"
] | Hakan_Akkurt@hotmail.de |
1372f2a5fe9a9a31a9a30ee66e77fac0174f05c6 | 432816063f9d6e7ab90f5d3728dffaf42e73bc22 | /src/main/java/com/srichell/microservices/ratelimit/pojos/ApiKey.java | cf7d5ed047c6b8ae732d6b42cf5377a30c8a09a6 | [] | no_license | srichell/RateLimitingApis | 7b1173fa236af5ed185388158e85675799d94cba | 8a6e99207cadc18483141b6c74b8c77e8fc482a4 | refs/heads/master | 2021-01-11T12:28:05.651399 | 2016-12-18T17:25:57 | 2016-12-18T17:25:57 | 76,622,197 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 917 | java | package com.srichell.microservices.ratelimit.pojos;
/**
* Created by Sridhar Chellappa on 12/17/16.
*/
/*
* This class is an Abstraction for API keys. As of now, it just uses a plain string but
* it can be extended out to any other Data Type
*/
public class ApiKey {
private final String apiKey;
public ApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKey() {
return apiKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ApiKey)) return false;
ApiKey apiKey1 = (ApiKey) o;
return getApiKey().equals(apiKey1.getApiKey());
}
@Override
public int hashCode() {
return getApiKey().hashCode();
}
@Override
public String toString() {
return "ApiKey{" +
"apiKey='" + apiKey + '\'' +
'}';
}
}
| [
"sridhar.chellappa@target.com"
] | sridhar.chellappa@target.com |
11f1a5622cebe22befd76b264339e9061724afa2 | 4da36b1f914659d6c685f88e1db8e705b8913f64 | /src/main/java/com/morben/restapi/service/impl/ProfileServiceImpl.java | 846678cf1eb0e9ebca1cff31ee25375f24691cdf | [] | no_license | OrbenMichele/rest-api | 6a9d12465de670a5e8b148e61af95c4d13f615e3 | 6e881864333f4403da65592bb63d9b590f049a14 | refs/heads/master | 2023-04-06T12:30:55.579621 | 2021-04-12T11:18:44 | 2021-04-12T11:18:44 | 356,342,660 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,097 | java | package com.morben.restapi.service.impl;
import com.morben.restapi.gateway.repository.ProfileRepository;
import com.morben.restapi.model.Profile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class ProfileServiceImpl {
@Autowired
private ProfileRepository profileRepository;
public Profile save(Profile profile) {
return profileRepository.save(profile);
}
public Optional<Profile> findById(UUID id) {
return profileRepository.findById(id);
}
public List<Profile> findByAll() {
return profileRepository.findAll();
}
public void deleteById(UUID id) {
profileRepository.deleteById(id);
}
public Profile update(Profile pessoa, UUID id) {
Profile profileSaved = this.findById(id).get();
BeanUtils.copyProperties(pessoa, profileSaved, "id");
return profileRepository.save(profileSaved);
}
}
| [
"micheleorben@gmail.com"
] | micheleorben@gmail.com |
d36d763cf2f191dd2d92bb039bdc537535f844e6 | 10ad8ca683618d071b6fb44887d2053123adaf51 | /src/main/java/model/Food.java | 3e8a21c07836c9e8e3ff5dd6ec6bd1a72537cebf | [] | no_license | masinogns/neo | 2e9e2fe6bed6ee7b38b822f18e2cb41f2cc45be7 | b9bf62baf1411331f826cab69cc03fe0b952d7d9 | refs/heads/master | 2021-09-01T09:30:08.799902 | 2017-12-26T07:53:11 | 2017-12-26T07:53:11 | 107,079,186 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,645 | java | package model;
import javax.persistence.*;
/**
* Created by adaeng on 2017. 12. 12..
*/
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@Column(name = "phone_number")
private String phoneNum;
@Column
private String address;
@Column
private double point;
@Column(name = "photo_url")
private String photoUrl;
@Column
private String lat;
@Column
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getPoint() {
return point;
}
public void setPoint(double point) {
this.point = point;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
| [
"dldlrwjs12@gmail.com"
] | dldlrwjs12@gmail.com |
f2224442ec162bd2508f4a13ca6a8527f7ea0e92 | 61385e624304cd1a38903d7ee60ca27196f0a984 | /3D Game(GDX Lib)/core/src/com/project/managers/EnemyAnimations.java | 15748ee5256b52c7085e4333027c923f7adf5a65 | [] | no_license | markoknezevic/Personal_projects | a8590e9a29432a7aaaf12f7ca3dbbc0029b46574 | e3427ee5371902eb9ea3f6b2ee45a58925e48e7c | refs/heads/master | 2020-04-16T08:56:08.122755 | 2019-07-23T21:56:19 | 2019-07-23T21:56:19 | 165,444,238 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,221 | java | package com.project.managers;
public class EnemyAnimations
{
public static final String [] __ATTACK_ANIMATION__ = new String[]
{
"Armature|attack1_l",
"Armature|attack1_r",
"Armature|attack2",
"Armature|attack3"
};
public static final String [] __DEAD_ANIMATION__ = new String[]
{
"Armature|dead1",
"Armature|dead2",
"Armature|dead3"
};
public static final String [] __HURT_ANIMATION__ = new String[]
{
"Armature|hurt",
"Armature|hurt_b",
"Armature|hurt_head",
"Armature|hurt_l",
"Armature|hurt_r"
};
public static final String [] __WALK_ANIMATION__ = new String[]
{
"Armature|walk",
"Armature|walk2"
};
public static final String __IDLE_ANIMATION__ = "Armature|idle";
public static final String __RUN_ANIMATION__ = "Armature|run";
public static final String __ENTER_ANIMATION__ = "Armature|enter_side";
}
| [
"you@example.com"
] | you@example.com |
ec324c28c1d94cb635ae43f45d0cced5977a1210 | c357a9c2748010f4c525929ccc2e4c8b5532ce3f | /jenkins/core/src/main/java/jenkins/model/Jenkins.java | 9be495e00105716761128c3763b5fefa3baa0f26 | [
"MIT"
] | permissive | jbbr245/mp3 | c9dfec24abe360906ded37ee6911e380179bd110 | 1db95a68c9a888092ecd7be6da120161780683d2 | refs/heads/master | 2023-01-05T11:29:52.236583 | 2020-10-31T00:35:26 | 2020-10-31T00:35:26 | 308,404,137 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149,212 | java | /*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.init.TerminatorFinder;
import hudson.lifecycle.Lifecycle;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.logging.LogRecorderManager;
import hudson.markup.EscapedMarkupFormatter;
import hudson.markup.MarkupFormatter;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.LoadStatistics;
import hudson.model.ManagementLink;
import hudson.model.Messages;
import hudson.model.ModifiableViewGroup;
import hudson.model.NoFingerprintMatch;
import hudson.model.Node;
import hudson.model.OverallLoadStatistics;
import hudson.model.PaneStatusProperties;
import hudson.model.Project;
import hudson.model.Queue;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.WorkspaceCleanupThread;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.remoting.Callable;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.BasicAuthenticationFilter;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.NamingThreadFactory;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.security.SecurityListener;
import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.Timer;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static hudson.Util.*;
import static hudson.init.InitMilestone.*;
import hudson.util.LogTaskListener;
import static java.util.logging.Level.*;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback,
ModifiableViewGroup, AccessControlled, DescriptorByNameOwner,
ModelObjectWithContextMenu, ModelObjectWithChildren {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Jenkins whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Jenkins.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Jenkins.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* Disables the remember me on this computer option in the standard login screen.
*
* @since 1.534
*/
private volatile boolean disableRememberMe;
/**
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean();
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Jenkins system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
private void updateAndTrim() {
updateComputerList();
trimLabels();
}
/**
* Legacy store of the set of installed cluster nodes.
* @deprecated in favour of {@link Nodes}
*/
@Deprecated
protected transient volatile NodeList slaves;
/**
* The holder of the set of installed cluster nodes.
*
* @since 1.607
*/
private transient final Nodes nodes = new Nodes(this);
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Jenkins.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
@CheckForNull Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public @CheckForNull Jenkins getInstance() {
return theInstance;
}
};
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Gets the {@link Jenkins} singleton.
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new java.util.Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
if (UDPBroadcastThread.PORT != -1) {
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e);
}
}
dnsMultiCast = new DNSMultiCast(this);
Timer.get().scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS);
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c, new LogTaskListener(LOGGER, INFO));
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
try {
l.onLoaded();
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, null, x);
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**
* Returns a secret key that survives across container start/stop.
* <p>
* This value is useful for implementing some of the security features.
*
* @deprecated
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
*/
@Deprecated
public String getSecretKey() {
return secretKey;
}
/**
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
* @since 1.308
* @deprecated
* See {@link #getSecretKey()}.
*/
@Deprecated
public SecretKey getSecretKeyAsAES128() {
return Util.toAes128Key(secretKey);
}
/**
* Returns the unique identifier of this Jenkins that has been historically used to identify
* this Jenkins to the outside world.
*
* <p>
* This form of identifier is weak in that it can be impersonated by others. See
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
* that can be challenged and verified.
*
* @since 1.498
*/
@SuppressWarnings("deprecation")
public String getLegacyInstanceId() {
return Util.getDigestOf(getSecretKey());
}
/**
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<SCM> getScm(String shortClassName) {
return findDescriptor(shortClassName,SCM.all());
}
/**
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
return findDescriptor(shortClassName,RepositoryBrowser.all());
}
/**
* Gets the builder descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Builder> getBuilder(String shortClassName) {
return findDescriptor(shortClassName, Builder.all());
}
/**
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
return findDescriptor(shortClassName, BuildWrapper.all());
}
/**
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<Publisher> getPublisher(String shortClassName) {
return findDescriptor(shortClassName, Publisher.all());
}
/**
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
*/
public TriggerDescriptor getTrigger(String shortClassName) {
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
}
/**
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
*/
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
return findDescriptor(shortClassName, RetentionStrategy.all());
}
/**
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
*/
public JobPropertyDescriptor getJobProperty(String shortClassName) {
// combining these two lines triggers javac bug. See issue #610.
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
return (JobPropertyDescriptor) d;
}
/**
* @deprecated
* UI method. Not meant to be used programatically.
*/
@Deprecated
public ComputerSet getComputer() {
return new ComputerSet();
}
/**
* Exposes {@link Descriptor} by its name to URL.
*
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
* this just doesn't scale.
*
* @param id
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
* @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast)
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix
public Descriptor getDescriptor(String id) {
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances());
for (Descriptor d : descriptors) {
if (d.getId().equals(id)) {
return d;
}
}
Descriptor candidate = null;
for (Descriptor d : descriptors) {
String name = d.getId();
if (name.substring(name.lastIndexOf('.') + 1).equals(id)) {
if (candidate == null) {
candidate = d;
} else {
throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId());
}
}
}
return candidate;
}
/**
* Alias for {@link #getDescriptor(String)}.
*/
public Descriptor getDescriptorByName(String id) {
return getDescriptor(id);
}
/**
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
* <p>
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
* you'll get the same instance that this method returns.
*/
public Descriptor getDescriptor(Class<? extends Describable> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.clazz==type)
return d;
return null;
}
/**
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
*
* @throws AssertionError
* If the descriptor is missing.
* @since 1.326
*/
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
Descriptor d = getDescriptor(type);
if (d==null)
throw new AssertionError(type+" is missing its descriptor");
return d;
}
/**
* Gets the {@link Descriptor} instance in the current Jenkins by its type.
*/
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
for( Descriptor d : getExtensionList(Descriptor.class) )
if(d.getClass()==type)
return type.cast(d);
return null;
}
/**
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
*/
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
return findDescriptor(shortClassName,SecurityRealm.all());
}
/**
* Finds a descriptor that has the specified name.
*/
private <T extends Describable<T>>
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
String name = '.'+shortClassName;
for (Descriptor<T> d : descriptors) {
if(d.clazz.getName().endsWith(name))
return d;
}
return null;
}
protected void updateComputerList() {
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
}
/** @deprecated Use {@link SCMListener#all} instead. */
@Deprecated
public CopyOnWriteList<SCMListener> getSCMListeners() {
return scmListeners;
}
/**
* Gets the plugin object from its short name.
*
* <p>
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
* of the plugin class.
*/
public Plugin getPlugin(String shortName) {
PluginWrapper p = pluginManager.getPlugin(shortName);
if(p==null) return null;
return p.getPlugin();
}
/**
* Gets the plugin object from its class.
*
* <p>
* This allows easy storage of plugin information in the plugin singleton without
* every plugin reimplementing the singleton pattern.
*
* @param clazz The plugin class (beware class-loader fun, this will probably only work
* from within the jpi that defines the plugin class, it may or may not work in other cases)
*
* @return The plugin instance.
*/
@SuppressWarnings("unchecked")
public <P extends Plugin> P getPlugin(Class<P> clazz) {
PluginWrapper p = pluginManager.getPlugin(clazz);
if(p==null) return null;
return (P) p.getPlugin();
}
/**
* Gets the plugin objects from their super-class.
*
* @param clazz The plugin class (beware class-loader fun)
*
* @return The plugin instances.
*/
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
List<P> result = new ArrayList<P>();
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
result.add((P)w.getPlugin());
}
return Collections.unmodifiableList(result);
}
/**
* Synonym for {@link #getDescription}.
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Gets the markup formatter used in the system.
*
* @return
* never null.
* @since 1.391
*/
public @Nonnull MarkupFormatter getMarkupFormatter() {
MarkupFormatter f = markupFormatter;
return f != null ? f : new EscapedMarkupFormatter();
}
/**
* Sets the markup formatter used in the system globally.
*
* @since 1.391
*/
public void setMarkupFormatter(MarkupFormatter f) {
this.markupFormatter = f;
}
/**
* Sets the system message.
*/
public void setSystemMessage(String message) throws IOException {
this.systemMessage = message;
save();
}
public FederatedLoginService getFederatedLoginService(String name) {
for (FederatedLoginService fls : FederatedLoginService.all()) {
if (fls.getUrlName().equals(name))
return fls;
}
return null;
}
public List<FederatedLoginService> getFederatedLoginServices() {
return FederatedLoginService.all();
}
public Launcher createLauncher(TaskListener listener) {
return new LocalLauncher(listener).decorateFor(this);
}
public String getFullName() {
return "";
}
public String getFullDisplayName() {
return "";
}
/**
* Returns the transient {@link Action}s associated with the top page.
*
* <p>
* Adding {@link Action} is primarily useful for plugins to contribute
* an item to the navigation bar of the top page. See existing {@link Action}
* implementation for it affects the GUI.
*
* <p>
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
* {@code Jenkins.getInstance().getActions().add(...)}.
*
* @return
* Live list where the changes can be made. Can be empty but never null.
* @since 1.172
*/
public List<Action> getActions() {
return actions;
}
/**
* Gets just the immediate children of {@link Jenkins}.
*
* @see #getAllItems(Class)
*/
@Exported(name="jobs")
public List<TopLevelItem> getItems() {
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
return new ArrayList(items.values());
}
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
for (TopLevelItem item : items.values()) {
if (item.hasPermission(Item.READ))
viewableItems.add(item);
}
return viewableItems;
}
/**
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
* <p>
* This method is efficient, as it doesn't involve any copying.
*
* @since 1.296
*/
public Map<String,TopLevelItem> getItemMap() {
return Collections.unmodifiableMap(items);
}
/**
* Gets just the immediate children of {@link Jenkins} but of the given type.
*/
public <T> List<T> getItems(Class<T> type) {
List<T> r = new ArrayList<T>();
for (TopLevelItem i : getItems())
if (type.isInstance(i))
r.add(type.cast(i));
return r;
}
/**
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
* and filter them by the given type.
*/
public <T extends Item> List<T> getAllItems(Class<T> type) {
return Items.getAllItems(this, type);
}
/**
* Gets all the items recursively.
*
* @since 1.402
*/
public List<Item> getAllItems() {
return getAllItems(Item.class);
}
/**
* Gets a list of simple top-level projects.
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
* (That will also consider the caller's permissions.)
* If you really want to get just {@link Project}s at top level, ignoring permissions,
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
*/
@Deprecated
public List<Project> getProjects() {
return Util.createSubList(items.values(),Project.class);
}
/**
* Gets the names of all the {@link Job}s.
*/
public Collection<String> getJobNames() {
List<String> names = new ArrayList<String>();
for (Job j : getAllItems(Job.class))
names.add(j.getFullName());
return names;
}
public List<Action> getViewActions() {
return getActions();
}
/**
* Gets the names of all the {@link TopLevelItem}s.
*/
public Collection<String> getTopLevelItemNames() {
List<String> names = new ArrayList<String>();
for (TopLevelItem j : items.values())
names.add(j.getName());
return names;
}
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* Gets the read-only list of all {@link View}s.
*/
@Exported
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
public synchronized void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
/**
* Returns the primary {@link View} that renders the top-page of Jenkins.
*/
@Exported
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
this.primaryView = v.getViewName();
}
public ViewsTabBar getViewsTabBar() {
return viewsTabBar;
}
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
this.viewsTabBar = viewsTabBar;
}
public Jenkins getItemGroup() {
return this;
}
public MyViewsTabBar getMyViewsTabBar() {
return myViewsTabBar;
}
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
this.myViewsTabBar = myViewsTabBar;
}
/**
* Returns true if the current running Jenkins is upgraded from a version earlier than the specified version.
*
* <p>
* This method continues to return true until the system configuration is saved, at which point
* {@link #version} will be overwritten and Jenkins forgets the upgrade history.
*
* <p>
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
* if the installation upgraded from pre-1.301, pass in "1.300.*"
*
* @since 1.301
*/
public boolean isUpgradedFromBefore(VersionNumber v) {
try {
return new VersionNumber(version).isOlderThan(v);
} catch (IllegalArgumentException e) {
// fail to parse this version number
return false;
}
}
/**
* Gets the read-only list of all {@link Computer}s.
*/
public Computer[] getComputers() {
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
Arrays.sort(r,new Comparator<Computer>() {
@Override public int compare(Computer lhs, Computer rhs) {
if(lhs.getNode()==Jenkins.this) return -1;
if(rhs.getNode()==Jenkins.this) return 1;
return lhs.getName().compareTo(rhs.getName());
}
});
return r;
}
@CLIResolver
public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) {
if(name.equals("(master)"))
name = "";
for (Computer c : computers.values()) {
if(c.getName().equals(name))
return c;
}
return null;
}
/**
* Gets the label that exists on this system by the name.
*
* @return null if name is null.
* @see Label#parseExpression(String) (String)
*/
public Label getLabel(String expr) {
if(expr==null) return null;
expr = hudson.util.QuotedStringTokenizer.unquote(expr);
while(true) {
Label l = labels.get(expr);
if(l!=null)
return l;
// non-existent
try {
labels.putIfAbsent(expr,Label.parseExpression(expr));
} catch (ANTLRException e) {
// laxly accept it as a single label atom for backward compatibility
return getLabelAtom(expr);
}
}
}
/**
* Returns the label atom of the given name.
* @return non-null iff name is non-null
*/
public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) {
if (name==null) return null;
while(true) {
Label l = labels.get(name);
if(l!=null)
return (LabelAtom)l;
// non-existent
LabelAtom la = new LabelAtom(name);
if (labels.putIfAbsent(name, la)==null)
la.load();
}
}
/**
* Gets all the active labels in the current system.
*/
public Set<Label> getLabels() {
Set<Label> r = new TreeSet<Label>();
for (Label l : labels.values()) {
if(!l.isEmpty())
r.add(l);
}
return r;
}
public Set<LabelAtom> getLabelAtoms() {
Set<LabelAtom> r = new TreeSet<LabelAtom>();
for (Label l : labels.values()) {
if(!l.isEmpty() && l instanceof LabelAtom)
r.add((LabelAtom)l);
}
return r;
}
public Queue getQueue() {
return queue;
}
@Override
public String getDisplayName() {
return Messages.Hudson_DisplayName();
}
public List<JDK> getJDKs() {
if(jdks==null)
jdks = new ArrayList<JDK>();
return jdks;
}
/**
* Gets the JDK installation of the given name, or returns null.
*/
public JDK getJDK(String name) {
if(name==null) {
// if only one JDK is configured, "default JDK" should mean that JDK.
List<JDK> jdks = getJDKs();
if(jdks.size()==1) return jdks.get(0);
return null;
}
for (JDK j : getJDKs()) {
if(j.getName().equals(name))
return j;
}
return null;
}
/**
* Gets the slave node of the give name, hooked under this Jenkins.
*/
public @CheckForNull Node getNode(String name) {
return nodes.getNode(name);
}
/**
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
*/
public Cloud getCloud(String name) {
return clouds.getByName(name);
}
protected Map<Node,Computer> getComputerMap() {
return computers;
}
/**
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
public List<Node> getNodes() {
return nodes.getNodes();
}
/**
* Adds one more {@link Node} to Jenkins.
*/
public void addNode(Node n) throws IOException {
nodes.addNode(n);
}
/**
* Removes a {@link Node} from Jenkins.
*/
public void removeNode(@Nonnull Node n) throws IOException {
nodes.removeNode(n);
}
public void setNodes(final List<? extends Node> n) throws IOException {
nodes.setNodes(n);
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
return nodeProperties;
}
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
return globalNodeProperties;
}
/**
* Resets all labels and remove invalid ones.
*
* This should be called when the assumptions behind label cache computation changes,
* but we also call this periodically to self-heal any data out-of-sync issue.
*/
/*package*/ void trimLabels() {
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
Label l = itr.next();
resetLabel(l);
if(l.isEmpty())
itr.remove();
}
}
/**
* Binds {@link AdministrativeMonitor}s to URL.
*/
public AdministrativeMonitor getAdministrativeMonitor(String id) {
for (AdministrativeMonitor m : administrativeMonitors)
if(m.id.equals(id))
return m;
return null;
}
public NodeDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
public static final class DescriptorImpl extends NodeDescriptor {
@Extension
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
public String getDisplayName() {
return "";
}
@Override
public boolean isInstantiable() {
return false;
}
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
return FormValidation.validateNonNegativeInteger(value);
}
public FormValidation doCheckRawBuildsDir(@QueryParameter String value) {
// do essentially what expandVariablesForDirectory does, without an Item
String replacedValue = expandVariablesForDirectory(value,
"doCheckRawBuildsDir-Marker:foo",
Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo");
File replacedFile = new File(replacedValue);
if (!replacedFile.isAbsolute()) {
return FormValidation.error(value + " does not resolve to an absolute path");
}
if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) {
return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects");
}
if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) {
// make sure platform can handle colon
try {
File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar");
tmp.delete();
} catch (IOException e) {
return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead");
}
}
File d = new File(replacedValue);
if (!d.isDirectory()) {
// if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to
d = d.getParentFile();
while (!d.exists()) {
d = d.getParentFile();
}
if (!d.canWrite()) {
return FormValidation.error(value + " does not exist and probably cannot be created");
}
}
return FormValidation.ok();
}
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
public Object getDynamic(String token) {
return Jenkins.getInstance().getDescriptor(token);
}
}
/**
* Gets the system default quiet period.
*/
public int getQuietPeriod() {
return quietPeriod!=null ? quietPeriod : 5;
}
/**
* Sets the global quiet period.
*
* @param quietPeriod
* null to the default value.
*/
public void setQuietPeriod(Integer quietPeriod) throws IOException {
this.quietPeriod = quietPeriod;
save();
}
/**
* Gets the global SCM check out retry count.
*/
public int getScmCheckoutRetryCount() {
return scmCheckoutRetryCount;
}
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
save();
}
@Override
public String getSearchUrl() {
return "";
}
@Override
public SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add("configure", "config","configure")
.add("manage")
.add("log")
.add(new CollectionSearchIndex<TopLevelItem>() {
protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); }
protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); }
})
.add(getPrimaryView().makeSearchIndex())
.add(new CollectionSearchIndex() {// for computers
protected Computer get(String key) { return getComputer(key); }
protected Collection<Computer> all() { return computers.values(); }
})
.add(new CollectionSearchIndex() {// for users
protected User get(String key) { return User.get(key,false); }
protected Collection<User> all() { return User.getAll(); }
})
.add(new CollectionSearchIndex() {// for views
protected View get(String key) { return getView(key); }
protected Collection<View> all() { return views; }
});
}
public String getUrlChildPrefix() {
return "job";
}
/**
* Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}.
*
* <p>
* This method first tries to use the manually configured value, then
* fall back to {@link #getRootUrlFromRequest}.
* It is done in this order so that it can work correctly even in the face
* of a reverse proxy.
*
* @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /}
* @since 1.66
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a>
*/
public @Nullable String getRootUrl() {
String url = JenkinsLocationConfiguration.get().getUrl();
if(url!=null) {
return Util.ensureEndsWith(url,"/");
}
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null)
return getRootUrlFromRequest();
return null;
}
/**
* Is Jenkins running in HTTPS?
*
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
* in the reverse proxy.
*/
public boolean isRootUrlSecure() {
String url = getRootUrl();
return url!=null && url.startsWith("https");
}
/**
* Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}.
*
* <p>
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
* this one uses the current request to reconstruct the URL. The benefit is
* that this is immune to the configuration mistake (users often fail to set the root URL
* correctly, especially when a migration is involved), but the downside
* is that unless you are processing a request, this method doesn't work.
*
* <p>Please note that this will not work in all cases if Jenkins is running behind a
* reverse proxy which has not been fully configured.
* Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set.
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a>
* shows some examples of configuration.
* @since 1.263
*/
public @Nonnull String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread");
}
StringBuilder buf = new StringBuilder();
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
int index = host.indexOf(':');
int port = req.getServerPort();
if (index == -1) {
// Almost everyone else except Nginx put the host and port in separate headers
buf.append(host);
} else {
// Nginx uses the same spec as for the Host header, i.e. hostanme:port
buf.append(host.substring(0, index));
if (index + 1 < host.length()) {
try {
port = Integer.parseInt(host.substring(index + 1));
} catch (NumberFormatException e) {
// ignore
}
}
// but if a user has configured Nginx with an X-Forwarded-Port, that will win out.
}
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if (port != ("https".equals(scheme) ? 443 : 80)) {
buf.append(':').append(port);
}
buf.append(req.getContextPath()).append('/');
return buf.toString();
}
/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}
public File getRootDir() {
return root;
}
public FilePath getWorkspaceFor(TopLevelItem item) {
for (WorkspaceLocator l : WorkspaceLocator.all()) {
FilePath workspace = l.locate(item, this);
if (workspace != null) {
return workspace;
}
}
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
}
public File getBuildDirFor(Job job) {
return expandVariablesForDirectory(buildsDir, job);
}
private File expandVariablesForDirectory(String base, Item item) {
return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath()));
}
@Restricted(NoExternalUse.class)
static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) {
return Util.replaceMacro(base, ImmutableMap.of(
"JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(),
"ITEM_ROOTDIR", itemRootDir,
"ITEM_FULLNAME", itemFullName, // legacy, deprecated
"ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251
}
public String getRawWorkspaceDir() {
return workspaceDir;
}
public String getRawBuildsDir() {
return buildsDir;
}
@Restricted(NoExternalUse.class)
public void setRawBuildsDir(String buildsDir) {
this.buildsDir = buildsDir;
}
@Override public @Nonnull FilePath getRootPath() {
return new FilePath(getRootDir());
}
@Override
public FilePath createPath(String absolutePath) {
return new FilePath((VirtualChannel)null,absolutePath);
}
public ClockDifference getClockDifference() {
return ClockDifference.ZERO;
}
@Override
public Callable<ClockDifference, IOException> getClockDifferenceCallable() {
return new MasterToSlaveCallable<ClockDifference, IOException>() {
public ClockDifference call() throws IOException {
return new ClockDifference(0);
}
};
}
/**
* For binding {@link LogRecorderManager} to "/log".
* Everything below here is admin-only, so do the check here.
*/
public LogRecorderManager getLog() {
checkPermission(ADMINISTER);
return log;
}
/**
* A convenience method to check if there's some security
* restrictions in place.
*/
@Exported
public boolean isUseSecurity() {
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
}
public boolean isUseProjectNamingStrategy(){
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
/**
* If true, all the POST requests to Jenkins would have to have crumb in it to protect
* Jenkins from CSRF vulnerabilities.
*/
@Exported
public boolean isUseCrumbs() {
return crumbIssuer!=null;
}
/**
* Returns the constant that captures the three basic security modes in Jenkins.
*/
public SecurityMode getSecurity() {
// fix the variable so that this code works under concurrent modification to securityRealm.
SecurityRealm realm = securityRealm;
if(realm==SecurityRealm.NO_AUTHENTICATION)
return SecurityMode.UNSECURED;
if(realm instanceof LegacySecurityRealm)
return SecurityMode.LEGACY;
return SecurityMode.SECURED;
}
/**
* @return
* never null.
*/
public SecurityRealm getSecurityRealm() {
return securityRealm;
}
public void setSecurityRealm(SecurityRealm securityRealm) {
if(securityRealm==null)
securityRealm= SecurityRealm.NO_AUTHENTICATION;
this.useSecurity = true;
IdStrategy oldUserIdStrategy = this.securityRealm == null
? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load
: this.securityRealm.getUserIdStrategy();
this.securityRealm = securityRealm;
// reset the filters and proxies for the new SecurityRealm
try {
HudsonFilter filter = HudsonFilter.get(servletContext);
if (filter == null) {
// Fix for #3069: This filter is not necessarily initialized before the servlets.
// when HudsonFilter does come back, it'll initialize itself.
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
} else {
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
filter.reset(securityRealm);
LOGGER.fine("Security is now fully set up");
}
if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) {
User.rekey();
}
} catch (ServletException e) {
// for binary compatibility, this method cannot throw a checked exception
throw new AcegiSecurityException("Failed to configure filter",e) {};
}
}
public void setAuthorizationStrategy(AuthorizationStrategy a) {
if (a == null)
a = AuthorizationStrategy.UNSECURED;
useSecurity = true;
authorizationStrategy = a;
}
public boolean isDisableRememberMe() {
return disableRememberMe;
}
public void setDisableRememberMe(boolean disableRememberMe) {
this.disableRememberMe = disableRememberMe;
}
public void disableSecurity() {
useSecurity = null;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
authorizationStrategy = AuthorizationStrategy.UNSECURED;
}
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
if(ns == null){
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
}
projectNamingStrategy = ns;
}
public Lifecycle getLifecycle() {
return Lifecycle.get();
}
/**
* Gets the dependency injection container that hosts all the extension implementations and other
* components in Jenkins.
*
* @since 1.433
*/
public Injector getInjector() {
return lookup(Injector.class);
}
/**
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
*
* @param extensionType
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
* but that's not a hard requirement.
* @return
* Can be an empty list but never null.
* @see ExtensionList#lookup
*/
@SuppressWarnings({"unchecked"})
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
return extensionLists.get(extensionType);
}
/**
* Used to bind {@link ExtensionList}s to URLs.
*
* @since 1.349
*/
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
}
/**
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
* kind of {@link Describable}.
*
* @return
* Can be an empty list but never null.
*/
@SuppressWarnings({"unchecked"})
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
return descriptorLists.get(type);
}
/**
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
*
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
*/
public void refreshExtensions() throws ExtensionRefreshException {
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
for (ExtensionFinder ef : finders) {
if (!ef.isRefreshable())
throw new ExtensionRefreshException(ef+" doesn't support refresh");
}
List<ExtensionComponentSet> fragments = Lists.newArrayList();
for (ExtensionFinder ef : finders) {
fragments.add(ef.refresh());
}
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
while (!newFinders.isEmpty()) {
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
newFinders.addAll(ecs.find(ExtensionFinder.class));
delta = ExtensionComponentSet.union(delta, ecs);
}
for (ExtensionList el : extensionLists.values()) {
el.refresh(delta);
}
for (ExtensionList el : descriptorLists.values()) {
el.refresh(delta);
}
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
Action a = ea.getInstance();
if (!actions.contains(a)) actions.add(a);
}
}
/**
* Returns the root {@link ACL}.
*
* @see AuthorizationStrategy#getRootACL()
*/
@Override
public ACL getACL() {
return authorizationStrategy.getRootACL();
}
/**
* @return
* never null.
*/
public AuthorizationStrategy getAuthorizationStrategy() {
return authorizationStrategy;
}
/**
* The strategy used to check the project names.
* @return never <code>null</code>
*/
public ProjectNamingStrategy getProjectNamingStrategy() {
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
}
/**
* Returns true if Jenkins is quieting down.
* <p>
* No further jobs will be executed unless it
* can be finished while other current pending builds
* are still in progress.
*/
@Exported
public boolean isQuietingDown() {
return isQuietingDown;
}
/**
* Returns true if the container initiated the termination of the web application.
*/
public boolean isTerminating() {
return terminating;
}
/**
* Gets the initialization milestone that we've already reached.
*
* @return
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
* never returns null.
*/
public InitMilestone getInitLevel() {
return initLevel;
}
public void setNumExecutors(int n) throws IOException {
if (this.numExecutors != n) {
this.numExecutors = n;
updateComputerList();
save();
}
}
/**
* {@inheritDoc}.
*
* Note that the look up is case-insensitive.
*/
@Override public TopLevelItem getItem(String name) throws AccessDeniedException {
if (name==null) return null;
TopLevelItem item = items.get(name);
if (item==null)
return null;
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please login to access job " + name);
}
return null;
}
return item;
}
/**
* Gets the item by its path name from the given context
*
* <h2>Path Names</h2>
* <p>
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
* relative path name in the file system is, against the given context.
* <p>For compatibility, as a fallback when nothing else matches, a simple path
* like {@code foo/bar} can also be treated with {@link #getItemByFullName}.
* @param context
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
* @since 1.406
*/
public Item getItem(String pathName, ItemGroup context) {
if (context==null) context = this;
if (pathName==null) return null;
if (pathName.startsWith("/")) // absolute
return getItemByFullName(pathName);
Object/*Item|ItemGroup*/ ctx = context;
StringTokenizer tokens = new StringTokenizer(pathName,"/");
while (tokens.hasMoreTokens()) {
String s = tokens.nextToken();
if (s.equals("..")) {
if (ctx instanceof Item) {
ctx = ((Item)ctx).getParent();
continue;
}
ctx=null; // can't go up further
break;
}
if (s.equals(".")) {
continue;
}
if (ctx instanceof ItemGroup) {
ItemGroup g = (ItemGroup) ctx;
Item i = g.getItem(s);
if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER
ctx=null; // can't go up further
break;
}
ctx=i;
} else {
return null;
}
}
if (ctx instanceof Item)
return (Item)ctx;
// fall back to the classic interpretation
return getItemByFullName(pathName);
}
public final Item getItem(String pathName, Item context) {
return getItem(pathName,context!=null?context.getParent():null);
}
public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) {
Item r = getItem(pathName, context);
if (type.isInstance(r))
return type.cast(r);
return null;
}
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
return getItem(pathName,context!=null?context.getParent():null,type);
}
public File getRootDirFor(TopLevelItem child) {
return getRootDirFor(child.getName());
}
private File getRootDirFor(String name) {
return new File(new File(getRootDir(),"jobs"), name);
}
/**
* Gets the {@link Item} object by its full name.
* Full names are like path names, where each name of {@link Item} is
* combined by '/'.
*
* @return
* null if either such {@link Item} doesn't exist under the given full name,
* or it exists but it's no an instance of the given type.
* @throws AccessDeniedException as per {@link ItemGroup#getItem}
*/
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException {
StringTokenizer tokens = new StringTokenizer(fullName,"/");
ItemGroup parent = this;
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
while(true) {
Item item = parent.getItem(tokens.nextToken());
if(!tokens.hasMoreTokens()) {
if(type.isInstance(item))
return type.cast(item);
else
return null;
}
if(!(item instanceof ItemGroup))
return null; // this item can't have any children
if (!item.hasPermission(Item.READ))
return null; // TODO consider DISCOVER
parent = (ItemGroup) item;
}
}
public @CheckForNull Item getItemByFullName(String fullName) {
return getItemByFullName(fullName,Item.class);
}
/**
* Gets the user of the given name.
*
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
* @see User#get(String,boolean)
*/
public @CheckForNull User getUser(String name) {
return User.get(name,hasPermission(ADMINISTER));
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
return createProject(type, name, true);
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
return itemGroupMixIn.createProject(type,name,notify);
}
/**
* Overwrites the existing item by new one.
*
* <p>
* This is a short cut for deleting an existing job and adding a new one.
*/
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
String name = item.getName();
TopLevelItem old = items.get(name);
if (old ==item) return; // noop
checkPermission(Item.CREATE);
if (old!=null)
old.delete();
items.put(name,item);
ItemListener.fireOnCreated(item);
}
/**
* Creates a new job.
*
* <p>
* This version infers the descriptor from the type of the top-level item.
*
* @throws IllegalArgumentException
* if the project of the given name already exists.
*/
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
}
/**
* Called by {@link Job#renameTo(String)} to update relevant data structure.
* assumed to be synchronized on Jenkins by the caller.
*/
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
items.remove(oldName);
items.put(newName,job);
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(job, oldName, newName);
}
/**
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
*/
public void onDeleted(TopLevelItem item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : views)
v.onJobRenamed(item, item.getName(), null);
}
@Override public boolean canAdd(TopLevelItem item) {
return true;
}
@Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
items.put(name, item);
return item;
}
@Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException {
items.remove(item.getName());
}
public FingerprintMap getFingerprintMap() {
return fingerprintMap;
}
// if no finger print matches, display "not found page".
public Object getFingerprint( String md5sum ) throws IOException {
Fingerprint r = fingerprintMap.get(md5sum);
if(r==null) return new NoFingerprintMatch(md5sum);
else return r;
}
/**
* Gets a {@link Fingerprint} object if it exists.
* Otherwise null.
*/
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
return fingerprintMap.get(md5sum);
}
/**
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(root,"config.xml"));
}
public int getNumExecutors() {
return numExecutors;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode m) throws IOException {
this.mode = m;
save();
}
public String getLabelString() {
return fixNull(label).trim();
}
@Override
public void setLabelString(String label) throws IOException {
this.label = label;
save();
}
@Override
public LabelAtom getSelfLabel() {
return getLabelAtom("master");
}
public Computer createComputer() {
return new Hudson.MasterComputer();
}
private synchronized TaskBuilder loadTasks() throws IOException {
File projectsDir = new File(root,"jobs");
if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) {
if(projectsDir.exists())
throw new IOException(projectsDir+" is not a directory");
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
}
File[] subdirs = projectsDir.listFiles();
final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>());
TaskGraphBuilder g = new TaskGraphBuilder();
Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
public void run(Reactor session) throws Exception {
XmlFile cfg = getConfigFile();
if (cfg.exists()) {
// reset some data that may not exist in the disk file
// so that we can take a proper compensation action later.
primaryView = null;
views.clear();
// load from disk
cfg.unmarshal(Jenkins.this);
}
// if we are loading old data that doesn't have this field
if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) {
nodes.setNodes(slaves);
slaves = null;
} else {
nodes.load();
}
clouds.setOwner(Jenkins.this);
}
});
for (final File subdir : subdirs) {
g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
public void run(Reactor session) throws Exception {
if(!Items.getConfigFile(subdir).exists()) {
//Does not have job config file, so it is not a jenkins job hence skip it
return;
}
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
items.put(item.getName(), item);
loadedNames.add(item.getName());
}
});
}
g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() {
public void run(Reactor reactor) throws Exception {
// anything we didn't load from disk, throw them away.
// doing this after loading from disk allows newly loaded items
// to inspect what already existed in memory (in case of reloading)
// retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one
// hopefully there shouldn't be too many of them.
for (String name : items.keySet()) {
if (!loadedNames.contains(name))
items.remove(name);
}
}
});
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
public void run(Reactor session) throws Exception {
rebuildDependencyGraph();
{// recompute label objects - populates the labels mapping.
for (Node slave : nodes.getNodes())
// Note that not all labels are visible until the slaves have connected.
slave.getAssignedLabels();
getAssignedLabels();
}
// initialize views by inserting the default view if necessary
// this is both for clean Jenkins and for backward compatibility.
if(views.size()==0 || primaryView==null) {
View v = new AllView(Messages.Hudson_ViewName());
setViewOwner(v);
views.add(0,v);
primaryView = v.getViewName();
}
if (useSecurity!=null && !useSecurity) {
// forced reset to the unsecure mode.
// this works as an escape hatch for people who locked themselves out.
authorizationStrategy = AuthorizationStrategy.UNSECURED;
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
} else {
// read in old data that doesn't have the security field set
if(authorizationStrategy==null) {
if(useSecurity==null)
authorizationStrategy = AuthorizationStrategy.UNSECURED;
else
authorizationStrategy = new LegacyAuthorizationStrategy();
}
if(securityRealm==null) {
if(useSecurity==null)
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
else
setSecurityRealm(new LegacySecurityRealm());
} else {
// force the set to proxy
setSecurityRealm(securityRealm);
}
}
// Initialize the filter with the crumb issuer
setCrumbIssuer(crumbIssuer);
// auto register root actions
for (Action a : getExtensionList(RootAction.class))
if (!actions.contains(a)) actions.add(a);
}
});
return g;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
}
/**
* Called to shut down the system.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
public void cleanUp() {
for (ItemListener l : ItemListener.all())
l.onBeforeShutdown();
try {
final TerminatorFinder tf = new TerminatorFinder(
pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader());
new Reactor(tf).execute(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
} catch (InterruptedException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
e.printStackTrace();
} catch (ReactorException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to execute termination",e);
}
Set<Future<?>> pending = new HashSet<Future<?>>();
terminating = true;
for( Computer c : computers.values() ) {
c.interrupt();
killComputer(c);
pending.add(c.disconnect(null));
}
if(udpBroadcastThread!=null)
udpBroadcastThread.shutdown();
if(dnsMultiCast!=null)
dnsMultiCast.close();
interruptReloadThread();
java.util.Timer timer = Trigger.timer;
if (timer != null) {
timer.cancel();
}
// TODO: how to wait for the completion of the last job?
Trigger.timer = null;
Timer.shutdown();
if(tcpSlaveAgentListener!=null)
tcpSlaveAgentListener.shutdown();
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
pluginManager.stop();
if(getRootDir().exists())
// if we are aborting because we failed to create JENKINS_HOME,
// don't try to save. Issue #536
getQueue().save();
threadPoolForLoad.shutdown();
for (Future<?> f : pending)
try {
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // someone wants us to die now. quick!
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
} catch (TimeoutException e) {
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
}
LogFactory.releaseAll();
theInstance = null;
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if (url.equals(token) || url.equals('/' + token))
return a;
}
for (Action a : getManagementLinks())
if(a.getUrlName().equals(token))
return a;
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(this);
try {
checkPermission(ADMINISTER);
JSONObject json = req.getSubmittedForm();
workspaceDir = json.getString("rawWorkspaceDir");
buildsDir = json.getString("rawBuildsDir");
systemMessage = Util.nullify(req.getParameter("system_message"));
jdks.clear();
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
boolean result = true;
for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified())
result &= configureDescriptor(req,json,d);
version = VERSION;
save();
updateComputerList();
if(result)
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
else
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
} finally {
bc.commit();
}
}
/**
* Gets the {@link CrumbIssuer} currently in use.
*
* @return null if none is in use.
*/
public CrumbIssuer getCrumbIssuer() {
return crumbIssuer;
}
public void setCrumbIssuer(CrumbIssuer issuer) {
crumbIssuer = issuer;
}
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.sendRedirect("foo");
}
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
// collapse the structure to remain backward compatible with the JSON structure before 1.
String name = d.getJsonSafeClassName();
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
json.putAll(js);
return d.configure(req, js);
}
/**
* Accepts submission from the node configuration page.
*/
@RequirePOST
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(ADMINISTER);
BulkChange bc = new BulkChange(this);
try {
JSONObject json = req.getSubmittedForm();
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
if (mbc!=null)
mbc.configure(req,json);
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
} finally {
bc.commit();
}
updateComputerList();
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getPrimaryView().doSubmitDescription(req, rsp);
}
@RequirePOST // TODO does not seem to work on _either_ overload!
public synchronized HttpRedirect doQuietDown() throws IOException {
try {
return doQuietDown(false,0);
} catch (InterruptedException e) {
throw new AssertionError(); // impossible
}
}
@CLIMethod(name="quiet-down")
@RequirePOST
public HttpRedirect doQuietDown(
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
synchronized (this) {
checkPermission(ADMINISTER);
isQuietingDown = true;
}
if (block) {
long waitUntil = timeout;
if (timeout > 0) waitUntil += System.currentTimeMillis();
while (isQuietingDown
&& (timeout <= 0 || System.currentTimeMillis() < waitUntil)
&& !RestartListener.isAllReady()) {
Thread.sleep(1000);
}
}
return new HttpRedirect(".");
}
@CLIMethod(name="cancel-quiet-down")
@RequirePOST // TODO the cancel link needs to be updated accordingly
public synchronized HttpRedirect doCancelQuietDown() {
checkPermission(ADMINISTER);
isQuietingDown = false;
getQueue().scheduleMaintenance();
return new HttpRedirect(".");
}
public HttpResponse doToggleCollapse() throws ServletException, IOException {
final StaplerRequest request = Stapler.getCurrentRequest();
final String paneId = request.getParameter("paneId");
PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId);
return HttpResponses.forwardToPreviousPage();
}
/**
* Backward compatibility. Redirect to the thread dump.
*/
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
rsp.sendRedirect2("threadDump");
}
/**
* Obtains the thread dump of all slaves (including the master.)
*
* <p>
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
*/
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
checkPermission(ADMINISTER);
// issue the requests all at once
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
for (Computer c : getComputers()) {
try {
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
} catch(Exception e) {
LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage());
}
}
if (toComputer() == null) {
future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel));
}
// if the result isn't available in 5 sec, ignore that.
// this is a precaution against hang nodes
long endTime = System.currentTimeMillis() + 5000;
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
try {
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
} catch (Exception x) {
StringWriter sw = new StringWriter();
x.printStackTrace(new PrintWriter(sw,true));
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
}
}
return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r));
}
@RequirePOST
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
return itemGroupMixIn.createTopLevelItem(req, rsp);
}
/**
* @since 1.319
*/
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
return itemGroupMixIn.createProjectFromXML(name, xml);
}
@SuppressWarnings({"unchecked"})
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
return itemGroupMixIn.copy(src, name);
}
// a little more convenient overloading that assumes the caller gives us the right type
// (or else it will fail with ClassCastException)
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
return (T)copy((TopLevelItem)src,name);
}
@RequirePOST
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(View.CREATE);
addView(View.create(req,rsp, this));
}
/**
* Check if the given name is suitable as a name
* for job, view, etc.
*
* @throws Failure
* if the given name is not good
*/
public static void checkGoodName(String name) throws Failure {
if(name==null || name.length()==0)
throw new Failure(Messages.Hudson_NoName());
if(".".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName("."));
if("..".equals(name.trim()))
throw new Failure(Messages.Jenkins_NotAllowedName(".."));
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch)) {
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
}
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
throw new Failure(Messages.Hudson_UnsafeChar(ch));
}
// looks good
}
/**
* Makes sure that the given name is good as a job name.
* @return trimmed name if valid; throws Failure if not
*/
private String checkJobName(String name) throws Failure {
checkGoodName(name);
name = name.trim();
projectNamingStrategy.checkName(name);
if(getItem(name)!=null)
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
// looks good
return name;
}
private static String toPrintableName(String name) {
StringBuilder printableName = new StringBuilder();
for( int i=0; i<name.length(); i++ ) {
char ch = name.charAt(i);
if(Character.isISOControl(ch))
printableName.append("\\u").append((int)ch).append(';');
else
printableName.append(ch);
}
return printableName.toString();
}
/**
* Checks if the user was successfully authenticated.
*
* @see BasicAuthenticationFilter
*/
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active)
if(req.getUserPrincipal()==null) {
// authentication must have failed
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// the user is now authenticated, so send him back to the target
String path = req.getContextPath()+req.getOriginalRestOfPath();
String q = req.getQueryString();
if(q!=null)
path += '?'+q;
rsp.sendRedirect2(path);
}
/**
* Called once the user logs in. Just forward to the top page.
* Used only by {@link LegacySecurityRealm}.
*/
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
if(req.getUserPrincipal()==null) {
rsp.sendRedirect2("noPrincipal");
return;
}
// TODO fire something in SecurityListener?
String from = req.getParameter("from");
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
return;
}
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
if(url!=null) {
// if the login redirect is initiated by Acegi
// this should send the user back to where s/he was from.
rsp.sendRedirect2(url);
return;
}
rsp.sendRedirect2(".");
}
/**
* Logs out the user.
*/
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String user = getAuthentication().getName();
securityRealm.doLogout(req, rsp);
SecurityListener.fireLoggedOut(user);
}
/**
* Serves jar files for JNLP slave agents.
*/
public Slave.JnlpJar getJnlpJars(String fileName) {
return new Slave.JnlpJar(fileName);
}
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
}
/**
* Reloads the configuration.
*/
@CLIMethod(name="reload-configuration")
@RequirePOST
public synchronized HttpResponse doReload() throws IOException {
checkPermission(ADMINISTER);
// engage "loading ..." UI and then run the actual task in a separate thread
servletContext.setAttribute("app", new HudsonIsLoading());
new Thread("Jenkins config reload thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
reload();
} catch (Exception e) {
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
new JenkinsReloadFailed(e).publish(servletContext,root);
}
}
}.start();
return HttpResponses.redirectViaContextPath("/");
}
/**
* Reloads the configuration synchronously.
*/
public void reload() throws IOException, InterruptedException, ReactorException {
executeReactor(null, loadTasks());
User.reload();
servletContext.setAttribute("app", this);
}
/**
* Do a finger-print check.
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
/**
* For debugging. Expose URL to perform GC.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
@RequirePOST
public void doGc(StaplerResponse rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
System.gc();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("GCed");
}
/**
* End point that intentionally throws an exception to test the error behaviour.
* @since 1.467
*/
public void doException() {
throw new RuntimeException();
}
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
ContextMenu menu = new ContextMenu().from(this, request, response);
for (MenuItem i : menu.items) {
if (i.url.equals(request.getContextPath() + "/manage")) {
// add "Manage Jenkins" subitems
i.subMenu = new ContextMenu().from(this, request, response, "manage");
}
}
return menu;
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getViewUrl(),view.getDisplayName());
}
return menu;
}
/**
* Obtains the heap dump.
*/
public HeapDump getHeapDump() throws IOException {
return new HeapDump(this,FilePath.localChannel);
}
/**
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
System.out.println("Creating artificial OutOfMemoryError situation");
List<Object> args = new ArrayList<Object>();
while (true)
args.add(new byte[1024*1024]);
}
/**
* Binds /userContent/... to $JENKINS_HOME/userContent.
*/
public DirectoryBrowserSupport doUserContent() {
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
}
/**
* Perform a restart of Jenkins, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*/
@CLIMethod(name="restart")
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET")) {
req.getView(this,"_restart.jelly").forward(req,rsp);
return;
}
restart();
if (rsp != null) // null for CLI
rsp.sendRedirect2(".");
}
/**
* Queues up a restart of Jenkins for when there are no builds running, if we can.
*
* This first replaces "app" to {@link HudsonIsRestarting}
*
* @since 1.332
*/
@CLIMethod(name="safe-restart")
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
checkPermission(ADMINISTER);
if (req != null && req.getMethod().equals("GET"))
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
safeRestart();
return HttpResponses.redirectToDot();
}
/**
* Performs a restart.
*/
public void restart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
servletContext.setAttribute("app", new HudsonIsRestarting());
new Thread("restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// give some time for the browser to load the "reloading" page
Thread.sleep(5000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
/**
* Queues up a restart to be performed once there are no builds currently running.
* @since 1.332
*/
public void safeRestart() throws RestartNotSupportedException {
final Lifecycle lifecycle = Lifecycle.get();
lifecycle.verifyRestartable(); // verify that Jenkins is restartable
// Quiet down so that we won't launch new builds.
isQuietingDown = true;
new Thread("safe-restart thread") {
final String exitUser = getAuthentication().getName();
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
servletContext.setAttribute("app",new HudsonIsRestarting());
// give some time for the browser to load the "reloading" page
LOGGER.info("Restart in 10 seconds");
Thread.sleep(10000);
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
for (RestartListener listener : RestartListener.all())
listener.onRestart();
lifecycle.restart();
} else {
LOGGER.info("Safe-restart mode cancelled");
}
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
}
}
}.start();
}
@Extension @Restricted(NoExternalUse.class)
public static class MasterRestartNotifyier extends RestartListener {
@Override
public void onRestart() {
Computer computer = Jenkins.getInstance().toComputer();
if (computer == null) return;
RestartCause cause = new RestartCause();
for (ComputerListener listener: ComputerListener.all()) {
listener.onOffline(computer, cause);
}
}
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return true;
}
private static class RestartCause extends OfflineCause.SimpleOfflineCause {
protected RestartCause() {
super(Messages._Jenkins_IsRestarting());
}
}
}
/**
* Shutdown the system.
* @since 1.161
*/
@CLIMethod(name="shutdown")
@RequirePOST
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
checkPermission(ADMINISTER);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
if (rsp!=null) {
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
PrintWriter w = rsp.getWriter();
w.println("Shutting down");
w.close();
}
System.exit(0);
}
/**
* Shutdown the system safely.
* @since 1.332
*/
@CLIMethod(name="safe-shutdown")
@RequirePOST
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
checkPermission(ADMINISTER);
isQuietingDown = true;
final String exitUser = getAuthentication().getName();
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
new Thread("safe-exit thread") {
@Override
public void run() {
try {
ACL.impersonate(ACL.SYSTEM);
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
exitUser, exitAddr));
// Wait 'til we have no active executors.
doQuietDown(true, 0);
// Make sure isQuietingDown is still true.
if (isQuietingDown) {
cleanUp();
System.exit(0);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
}
}
}.start();
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
}
/**
* Gets the {@link Authentication} object that represents the user
* associated with the current request.
*/
public static @Nonnull Authentication getAuthentication() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
// on Tomcat while serving the login page, this is null despite the fact
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
// run the request through filters when this is the login request.
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
if(a==null)
a = ANONYMOUS;
return a;
}
/**
* For system diagnostics.
* Run arbitrary Groovy script.
*/
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL());
}
/**
* Run arbitrary Groovy script and return result as plain text.
*/
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL());
}
/**
* @since 1.509.1
*/
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException {
// ability to run arbitrary script is dangerous
acl.checkPermission(RUN_SCRIPTS);
String text = req.getParameter("script");
if (text != null) {
if (!"POST".equals(req.getMethod())) {
throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
}
if (channel == null) {
throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
}
try {
req.setAttribute("output",
RemotingDiagnostics.executeGroovy(text, channel));
} catch (InterruptedException e) {
throw new ServletException(e);
}
}
view.forward(req, rsp);
}
/**
* Evaluates the Jelly script submitted by the client.
*
* This is useful for system administration as well as unit testing.
*/
@RequirePOST
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(RUN_SCRIPTS);
try {
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
new JellyRequestDispatcher(this,script).forward(req,rsp);
} catch (JellyException e) {
throw new ServletException(e);
}
}
/**
* Sign up for the user account.
*/
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if (getSecurityRealm().allowsSignup()) {
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
return;
}
req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp);
}
/**
* Changes the icon size by changing the cookie
*/
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null)
throw new ServletException();
Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs));
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
}
@RequirePOST
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
FingerprintCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
@RequirePOST
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
WorkspaceCleanupThread.invoke();
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/plain");
rsp.getWriter().println("Invoked");
}
/**
* If the user chose the default JDK, make sure we got 'java' in PATH.
*/
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
if(!value.equals(JDK.DEFAULT_NAME))
// assume the user configured named ones properly in system config ---
// or else system config should have reported form field validation errors.
return FormValidation.ok();
// default JDK selected. Does such java really exist?
if(JDK.isDefaultJDKValid(Jenkins.this))
return FormValidation.ok();
else
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
}
/**
* Makes sure that the given name is good as a job name.
*/
public FormValidation doCheckJobName(@QueryParameter String value) {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
checkPermission(Item.CREATE);
if(fixEmpty(value)==null)
return FormValidation.ok();
try {
checkJobName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Checks if a top-level view with the given name exists and
* make sure that the name is good as a view name.
*/
public FormValidation doCheckViewName(@QueryParameter String value) {
checkPermission(View.CREATE);
String name = fixEmpty(value);
if (name == null)
return FormValidation.ok();
// already exists?
if (getView(name) != null)
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name));
// good view name?
try {
checkGoodName(name);
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
return FormValidation.ok();
}
/**
* Checks if a top-level view with the given name exists.
* @deprecated 1.512
*/
@Deprecated
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if(view==null) return FormValidation.ok();
if(getView(view)==null)
return FormValidation.ok();
else
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
/**
* Serves static resources placed along with Jelly view files.
* <p>
* This method can serve a lot of files, so care needs to be taken
* to make this method secure. It's not clear to me what's the best
* strategy here, though the current implementation is based on
* file extensions.
*/
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
String path = req.getRestOfPath();
// cut off the "..." portion of /resources/.../path/to/file
// as this is only used to make path unique (which in turn
// allows us to set a long expiration date
path = path.substring(path.indexOf('/',1)+1);
int idx = path.lastIndexOf('.');
String extension = path.substring(idx+1);
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
URL url = pluginManager.uberClassLoader.getResource(path);
if(url!=null) {
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
rsp.serveFile(req,url,expires);
return;
}
}
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
* This set is mutable to allow plugins to add additional extensions.
*/
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
));
/**
* Checks if container uses UTF-8 to decode URLs. See
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
*/
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
// expected is non-ASCII String
final String expected = "\u57f7\u4e8b";
final String value = fixEmpty(request.getParameter("value"));
if (!expected.equals(value))
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
return FormValidation.ok();
}
/**
* Does not check when system default encoding is "ISO-8859-1".
*/
public static boolean isCheckURIEncodingEnabled() {
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
}
/**
* Rebuilds the dependency map.
*/
public void rebuildDependencyGraph() {
DependencyGraph graph = new DependencyGraph();
graph.build();
// volatile acts a as a memory barrier here and therefore guarantees
// that graph is fully build, before it's visible to other threads
dependencyGraph = graph;
dependencyGraphDirty.set(false);
}
/**
* Rebuilds the dependency map asynchronously.
*
* <p>
* This would keep the UI thread more responsive and helps avoid the deadlocks,
* as dependency graph recomputation tends to touch a lot of other things.
*
* @since 1.522
*/
public Future<DependencyGraph> rebuildDependencyGraphAsync() {
dependencyGraphDirty.set(true);
return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() {
@Override
public DependencyGraph call() throws Exception {
if (dependencyGraphDirty.get()) {
rebuildDependencyGraph();
}
return dependencyGraph;
}
}, 500, TimeUnit.MILLISECONDS);
}
public DependencyGraph getDependencyGraph() {
return dependencyGraph;
}
// for Jelly
public List<ManagementLink> getManagementLinks() {
return ManagementLink.all();
}
/**
* Exposes the current user to <tt>/me</tt> URL.
*/
public User getMe() {
User u = User.current();
if (u == null)
throw new AccessDeniedException("/me is not available when not logged in");
return u;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* Plugins who wish to contribute boxes on the side panel can add widgets
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
*/
public List<Widget> getWidgets() {
return widgets;
}
public Object getTarget() {
try {
checkPermission(READ);
} catch (AccessDeniedException e) {
String rest = Stapler.getCurrentRequest().getRestOfPath();
if(rest.startsWith("/login")
|| rest.startsWith("/logout")
|| rest.startsWith("/accessDenied")
|| rest.startsWith("/adjuncts/")
|| rest.startsWith("/error")
|| rest.startsWith("/oops")
|| rest.startsWith("/signup")
|| rest.startsWith("/tcpSlaveAgentListener")
// TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
|| rest.startsWith("/federatedLoginService/")
|| rest.startsWith("/securityRealm"))
return this; // URLs that are always visible without READ permission
for (String name : getUnprotectedRootActions()) {
if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) {
return this;
}
}
throw e;
}
return this;
}
/**
* Gets a list of unprotected root actions.
* These URL prefixes should be exempted from access control checks by container-managed security.
* Ideally would be synchronized with {@link #getTarget}.
* @return a list of {@linkplain Action#getUrlName URL names}
* @since 1.495
*/
public Collection<String> getUnprotectedRootActions() {
Set<String> names = new TreeSet<String>();
names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA
// TODO consider caching (expiring cache when actions changes)
for (Action a : getActions()) {
if (a instanceof UnprotectedRootAction) {
names.add(a.getUrlName());
}
}
return names;
}
/**
* Fallback to the primary view.
*/
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* This method checks all existing jobs to see if displayName is
* unique. It does not check the displayName against the displayName of the
* job that the user is configuring though to prevent a validation warning
* if the user sets the displayName to what it currently is.
* @param displayName
* @param currentJobName
*/
boolean isDisplayNameUnique(String displayName, String currentJobName) {
Collection<TopLevelItem> itemCollection = items.values();
// if there are a lot of projects, we'll have to store their
// display names in a HashSet or something for a quick check
for(TopLevelItem item : itemCollection) {
if(item.getName().equals(currentJobName)) {
// we won't compare the candidate displayName against the current
// item. This is to prevent an validation warning if the user
// sets the displayName to what the existing display name is
continue;
}
else if(displayName.equals(item.getDisplayName())) {
return false;
}
}
return true;
}
/**
* True if there is no item in Jenkins that has this name
* @param name The name to test
* @param currentJobName The name of the job that the user is configuring
*/
boolean isNameUnique(String name, String currentJobName) {
Item item = getItem(name);
if(null==item) {
// the candidate name didn't return any items so the name is unique
return true;
}
else if(item.getName().equals(currentJobName)) {
// the candidate name returned an item, but the item is the item
// that the user is configuring so this is ok
return true;
}
else {
// the candidate name returned an item, so it is not unique
return false;
}
}
/**
* Checks to see if the candidate displayName collides with any
* existing display names or project names
* @param displayName The display name to test
* @param jobName The name of the job the user is configuring
*/
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
@QueryParameter String jobName) {
displayName = displayName.trim();
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Current job name is " + jobName);
}
if(!isNameUnique(displayName, jobName)) {
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
}
else if(!isDisplayNameUnique(displayName, jobName)){
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
}
else {
return FormValidation.ok();
}
}
public static class MasterComputer extends Computer {
protected MasterComputer() {
super(Jenkins.getInstance());
}
/**
* Returns "" to match with {@link Jenkins#getNodeName()}.
*/
@Override
public String getName() {
return "";
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public String getDisplayName() {
return Messages.Hudson_Computer_DisplayName();
}
@Override
public String getCaption() {
return Messages.Hudson_Computer_Caption();
}
@Override
public String getUrl() {
return "computer/(master)/";
}
public RetentionStrategy getRetentionStrategy() {
return RetentionStrategy.NOOP;
}
/**
* Will always keep this guy alive so that it can function as a fallback to
* execute {@link FlyweightTask}s. See JENKINS-7291.
*/
@Override
protected boolean isAlive() {
return true;
}
/**
* Report an error.
*/
@Override
public HttpResponse doDoDelete() throws IOException {
throw HttpResponses.status(SC_BAD_REQUEST);
}
@Override
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
}
@Override
public boolean hasPermission(Permission permission) {
// no one should be allowed to delete the master.
// this hides the "delete" link from the /computer/(master) page.
if(permission==Computer.DELETE)
return false;
// Configuration of master node requires ADMINISTER permission
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
}
@Override
public VirtualChannel getChannel() {
return FilePath.localChannel;
}
@Override
public Charset getDefaultCharset() {
return Charset.defaultCharset();
}
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
return logRecords;
}
@RequirePOST
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this computer never returns null from channel, so
// this method shall never be invoked.
rsp.sendError(SC_NOT_FOUND);
}
protected Future<?> _connect(boolean forceReconnect) {
return Futures.precomputed(null);
}
/**
* {@link LocalChannel} instance that can be used to execute programs locally.
*
* @deprecated as of 1.558
* Use {@link FilePath#localChannel}
*/
@Deprecated
public static final LocalChannel localChannel = FilePath.localChannel;
}
/**
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
return j != null ? j.lookup.get(type) : null;
}
/**
* Live view of recent {@link LogRecord}s produced by Jenkins.
*/
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
/**
* Thread-safe reusable {@link XStream}.
*/
public static final XStream XSTREAM;
/**
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
*/
public static final XStream2 XSTREAM2;
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
/**
* Thread pool used to load configuration in parallel, to improve the start up time.
* <p>
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
*/
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
TWICE_CPU_NUM, TWICE_CPU_NUM,
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load"));
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver="?";
VERSION = ver;
context.setAttribute("version",ver);
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
RESOURCE_PATH = "";
else
RESOURCE_PATH = "/static/"+SESSION_HASH;
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
}
/**
* Version number of this Jenkins.
*/
public static String VERSION="?";
/**
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
* (such as when Jenkins is run with "mvn hudson-dev:run")
*/
public static VersionNumber getVersion() {
try {
return new VersionNumber(VERSION);
} catch (NumberFormatException e) {
try {
// for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate.
int idx = VERSION.indexOf(' ');
if (idx>0)
return new VersionNumber(VERSION.substring(0,idx));
} catch (NumberFormatException _) {
// fall through
}
// totally unparseable
return null;
} catch (IllegalArgumentException e) {
// totally unparseable
return null;
}
}
/**
* Hash of {@link #VERSION}.
*/
public static String VERSION_HASH;
/**
* Unique random token that identifies the current session.
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
*
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
*/
public static String SESSION_HASH;
/**
* Prefix to static resources like images and javascripts in the war file.
* Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String RESOURCE_PATH = "";
/**
* Prefix to resources alongside view scripts.
* Strings like "/resources/VERSION", which avoids Jenkins to pick up
* stale cache when the user upgrades to a different version.
* <p>
* Value computed in {@link WebAppMain}.
*/
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
/**
* @deprecated No longer used.
*/
@Deprecated
public static boolean FLYWEIGHT_SUPPORT = true;
/**
* Tentative switch to activate the concurrent build behavior.
* When we merge this back to the trunk, this allows us to keep
* this feature hidden for a while until we iron out the kinks.
* @see AbstractProject#isConcurrentBuild()
* @deprecated as of 1.464
* This flag will have no effect.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public static boolean CONCURRENT_BUILD = true;
/**
* Switch to enable people to use a shorter workspace name.
*/
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
/**
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
*/
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
/**
* {@link Authentication} object that represents the anonymous user.
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
* expect the singleton semantics. This is just a convenient instance.
*
* @since 1.343
*/
public static final Authentication ANONYMOUS;
static {
try {
ANONYMOUS = new AnonymousAuthenticationToken(
"anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
XSTREAM = XSTREAM2 = new XStream2();
XSTREAM.alias("jenkins", Jenkins.class);
XSTREAM.alias("slave", DumbSlave.class);
XSTREAM.alias("jdk", JDK.class);
// for backward compatibility with <1.75, recognize the tag name "view" as well.
XSTREAM.alias("view", ListView.class);
XSTREAM.alias("listView", ListView.class);
XSTREAM2.addCriticalField(Jenkins.class, "securityRealm");
XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy");
// this seems to be necessary to force registration of converter early enough
Mode.class.getEnumConstants();
// double check that initialization order didn't do any harm
assert PERMISSIONS != null;
assert ADMINISTER != null;
} catch (RuntimeException e) {
// when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause.
// see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847
// As we don't know where the first exception will go, let's also send this to logging so that
// we have a known place to look at.
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to load Jenkins.class", e);
throw e;
}
}
}
| [
"70719171+jbbr245@users.noreply.github.com"
] | 70719171+jbbr245@users.noreply.github.com |
dedbab9d2b09b4280d5f0e4eaefc69d06cc38132 | 3a7c8cca1af3ac5e831b3e4616a4b052bf5d9f1f | /app/src/main/java/com/example/dimpychhabra/capo/getCapo_Frag1.java | 526cdc4db381ab4f0bbe937fa42f3376fb7468f2 | [] | no_license | dimpy-chhabra/Capo_CarPoolingApp | d7bc86db106f3e22952798091e2784c5bf7e54bb | 759f592f59b68d28db2a11d69b4905ee23abf378 | refs/heads/master | 2021-08-24T02:10:06.048133 | 2017-12-07T15:46:33 | 2017-12-07T15:46:33 | 95,385,569 | 9 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,724 | java | package com.example.dimpychhabra.capo;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
/*
*Project : CAPO, fully created by
* Dimpy Chhabra, IGDTUW, BTech, IT
* Second year (as of 2017)
* Expected Class of 2019
* Please do not circulate as your own
* Criticism is appreciated to work on memory leaks and bugs
* Contact Info : Find me on Linked in : linkedin.com/in/dimpy-chhabra
*
*/
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class getCapo_Frag1 extends Fragment {
private static View view;
private static Button button;
private static EditText to;
private static FragmentManager fragmentManager;
public getCapo_Frag1() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_get_capo__frag1, container, false);
initViews();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String To;
To = to.getText().toString().trim().toUpperCase() ;
if (To.equals("")) {
Log.e("in lets capo frag1", " equals null");
new CustomToast().Show_Toast(getActivity(), view, "Please enter details in order to proceed.");
} else {
Fragment fragment = new getCapo_Frag2();
Bundle bundle = new Bundle();
bundle.putString("to:", To);
fragment.setArguments(bundle);
fragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.right_enter, R.anim.left_out)
.replace(R.id.frameContainer, fragment,
BaseActivity.getCapo_Frag2)
.commit();
}
}
});
return view;
}
private void initViews() {
fragmentManager = getActivity().getSupportFragmentManager();
button = (Button) view.findViewById(R.id.b1);
to = (EditText) view.findViewById(R.id.to);
}
} | [
"dimpychhabra@yahoo.co.uk"
] | dimpychhabra@yahoo.co.uk |
076850fb4c07500e68526b7f78243fc248b8c9c1 | 91d08b76658bc7dbda1b00b4cf4d3a5c4fa34dbb | /app/src/androidTest/java/com/example/viewpagertabs/ExampleInstrumentedTest.java | f91bed1c39bc783751e5f6386a36f9251e4da503 | [] | no_license | Utkarsh3118/ViewPagerExample-Tab-view- | 0575b98b696f417949ddd0e5f9277864f853a410 | d8a132dd45005f8e60558163b194325ef5810da9 | refs/heads/master | 2021-04-01T18:05:34.935891 | 2020-03-18T10:52:23 | 2020-03-18T10:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package com.example.viewpagertabs;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.viewpagertabs", appContext.getPackageName());
}
}
| [
"jadhavutkarsh3118@gmail.com"
] | jadhavutkarsh3118@gmail.com |
d8a829b6a315a8cc2c533e455bc4093fc808b04e | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/serge-rider--dbeaver/1d991820142f8df66b9f9fde2d28c2bbb603a84a/after/MySQLDialect.java | 911b2085bc1f922463c2e794fd1f2f0bf8785c5f | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,899 | java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ext.mysql.model;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCSQLDialect;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.Arrays;
import java.util.Collections;
/**
* MySQL dialect
*/
class MySQLDialect extends JDBCSQLDialect {
public static final String[] MYSQL_NON_TRANSACTIONAL_KEYWORDS = ArrayUtils.concatArrays(
BasicSQLDialect.NON_TRANSACTIONAL_KEYWORDS,
new String[]{
"USE", "SHOW",
"CREATE", "ALTER", "DROP",
"EXPLAIN", "DESCRIBE", "DESC" }
);
public MySQLDialect() {
super("MySQL");
}
public void initDriverSettings(JDBCDataSource dataSource, JDBCDatabaseMetaData metaData) {
super.initDriverSettings(dataSource, metaData);
//addSQLKeyword("STATISTICS");
Collections.addAll(tableQueryWords, "EXPLAIN", "DESCRIBE", "DESC");
addFunctions(Arrays.asList("SLEEP"));
}
@Nullable
@Override
public String getScriptDelimiterRedefiner() {
return "DELIMITER";
}
@NotNull
@Override
public String escapeString(String string) {
return string.replace("'", "''").replace("\\", "\\\\");
}
@NotNull
@Override
public String unEscapeString(String string) {
return string.replace("''", "'").replace("\\\\", "\\");
}
@NotNull
@Override
public MultiValueInsertMode getMultiValueInsertMode() {
return MultiValueInsertMode.GROUP_ROWS;
}
@Override
public boolean supportsAliasInSelect() {
return true;
}
@Override
public boolean supportsCommentQuery() {
return true;
}
@Override
public String[] getSingleLineComments() {
return new String[] { "-- ", "#" };
}
@Override
public String getTestSQL() {
return "SELECT 1";
}
@NotNull
protected String[] getNonTransactionKeywords() {
return MYSQL_NON_TRANSACTIONAL_KEYWORDS;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
986fe688be410ea5b83d612e2779dea518adf1bc | 5073dec48ac09dddf3c1a0ab78d6167849c7df4e | /51/GroupDataGenerator.java | 4535ae4ca0fd52b43cbe5f71b073224635a05065 | [
"Apache-2.0"
] | permissive | regina311/38 | 998ff2250a503f3e7e321c7e5bf862af06d2e5dd | 6a8228f338c01781aab5ef930509dd0fd5a9c908 | refs/heads/master | 2020-04-29T18:36:14.044483 | 2015-07-20T06:38:11 | 2015-07-20T06:38:11 | 39,001,925 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,759 | java | package com.example.tests;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GroupDataGenerator {
public static void main(String[] args) throws IOException {
if (args.length <3){
System.out.println("parametr 3 need");
return;
}
int amount = Integer.parseInt(args[0]);
File file= new File(args[1]);
String format = args[2];
if (file.exists()) {
System.out.println("file exist,please remove it manually"+ file );
return;
}
List<GroupData>groups = generateRandomGroups(amount);
if ("csv".equals(format)){
saveGroupsToCsvFile(groups, file);
}else if ("xml".equals(format))
{
saveGroupsToXmlFile(groups, file);
} else {
System.out.println("unknown format"+ format);
return;
}
}
private static void saveGroupsToXmlFile(List<GroupData> groups, File file) {
}
private static void saveGroupsToCsvFile(List<GroupData> groups, File file) throws IOException {
FileWriter writer = new FileWriter(file);
for (GroupData group:groups){
writer.write(group.getName()+"," + group.getHeader()+"," +group.getFooter()+"\n");
}
writer.close();
}
public static List<GroupData> generateRandomGroups(int amount) {
List<GroupData> list = new ArrayList<GroupData>();
for (int i=0;i<amount; i++){
GroupData group = new GroupData()
.withName(generateRandomString())
.withHeader(generateRandomString())
.withFooter(generateRandomString());
list.add( group);
}
return list;
}
public static String generateRandomString(){
Random rnd = new Random();
if (rnd.nextInt(3)==0){
return "";
} else {
return "test"+rnd.nextInt();
}
}
}
| [
"mr-gorosheka@rambler.ru"
] | mr-gorosheka@rambler.ru |
2a09430e6b38d7e556ec865b1af1a1fffba9db5a | 5d174c325b60f3797cf6993f30d02929081a64b6 | /teddy-backend/src/main/java/br/com/teddy/store/dto/ErrorDTO.java | 4e0dfbc82db7a8c939843e7b8c786c2e106871c9 | [] | no_license | diy-coder/teddy-world | 71ee9a746ee3ac78ef092db48e636a326f6db44e | 5edebc0eb3aaab50204a241b83af264119b18088 | refs/heads/main | 2023-08-01T09:34:26.468772 | 2021-09-14T22:58:37 | 2021-09-14T22:58:37 | 410,641,570 | 0 | 3 | null | 2021-09-26T19:20:25 | 2021-09-26T19:20:25 | null | UTF-8 | Java | false | false | 392 | java | package br.com.teddy.store.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class ErrorDTO extends AttrResponseDTO {
private boolean hasError = true;
private String message;
public ErrorDTO(String message) {
this.message = message;
}
}
| [
"anacarolinq.ng@gmail.com"
] | anacarolinq.ng@gmail.com |
e9fe879b1811a3d264ac71498469aa29b58fe5c3 | 064cda386fc5850f7d859ca5aefd0c648acf061d | /src/bj2699/Main.java | 431e358dd8ba401d04c160678f381f034438c4b7 | [] | no_license | potionk/baekjoon | b0de5473bb2b324da404cd29e3b1d265c496f304 | fdbdccb75e5b4efc87fcb8788045d57b5b27454c | refs/heads/master | 2023-08-17T10:36:53.440645 | 2023-08-16T14:40:59 | 2023-08-16T14:40:59 | 195,223,018 | 8 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,440 | java | package bj2699;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int tc = Integer.parseInt(br.readLine());
while (tc-- > 0) {
int N = Integer.parseInt(br.readLine());
LinkedList<Point> points = new LinkedList<>();
for (int i = 0; i < N; i += 5) {
String[] pointInfo = br.readLine().split(" ");
for (int j = 0; j < pointInfo.length; j += 2) {
points.add(new Point(Integer.parseInt(pointInfo[j + 1]), Integer.parseInt(pointInfo[j])));
}
}
points.sort(Comparator.comparing(Point::getY).reversed().thenComparing(Point::getX));
Point p0 = points.pollFirst();
points.sort((p1, p2) -> ccwCompare(ccw(p0, p1, p2)));
points.addFirst(p0);
convexHull(points, bw);
}
br.close();
bw.close();
}
public static int convexHull(LinkedList<Point> points, BufferedWriter bw) throws IOException {
Stack<Point> stack = new Stack<>();
stack.push(points.pollFirst());
stack.push(points.pollFirst());
while (!points.isEmpty()) {
Point p3 = points.pop();
while (stack.size() >= 2 && ccw(p3, stack.get(stack.size() - 1), stack.get(stack.size() - 2)) <= 0) {
stack.pop();
}
stack.push(p3);
}
bw.write(stack.size() + "\n");
for (Point p : stack) {
bw.write(p.x + " " + p.y + "\n");
}
return stack.size();
}
public static long ccw(Point a, Point b, Point c) {
return a.x * b.y + b.x * c.y + c.x * a.y - b.x * a.y - c.x * b.y - a.x * c.y;
}
public static int ccwCompare(long ccw) {
if (ccw > 0) {
return 1;
} else if (ccw == 0) {
return 0;
} else {
return -1;
}
}
private static class Point {
long x;
long y;
public Point(long y, long x) {
this.y = y;
this.x = x;
}
public long getX() {
return x;
}
public long getY() {
return y;
}
}
} | [
"potionkr@gmail.com"
] | potionkr@gmail.com |
740756dd2e7885967555b98fff4032df61205565 | 748598e40201b8176deb013b04ea782cc1735698 | /src/unidad7/Ejercicio2.java | f34912eb5cef869fa365f342a1ec6c462b500758 | [] | no_license | tammy-creator/ejercicios2eval | f31c5e3ea55e3f53d8befb91863e0b7a9b7d0c1c | d546a017fa31627cb45ec392918a552f34aeb1cf | refs/heads/master | 2023-05-26T19:18:39.871059 | 2021-06-16T12:38:59 | 2021-06-16T12:38:59 | 347,685,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package unidad7;
public class Ejercicio2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Electrodomestico[] electrodomesticos=new Electrodomestico[3];
electrodomesticos[0]=new Lavadora(150,2,"B",25,9);
electrodomesticos[1]=new Frigorifico(185,2,"A",52);
electrodomesticos[2]=new Televisor(220,2,"C",15,50,"DVB-T");
for(Electrodomestico e:electrodomesticos) {
System.out.println(e.toString());
}
}
}
| [
"ttorresvega@gmail.com"
] | ttorresvega@gmail.com |
0a008731d1aea1e341a815282f26aecf02cbdf94 | 3b5d3a99c0bcf4c62d32861b8a16fd2082ff58d2 | /Elibrary/src/main/java/com/elib/services/Bookservices.java | 78ac1563c006d44f3cb100f177131ee05e5af836 | [] | no_license | MestryNikhil/SpringBootProject | b068d2db82c9d2d3aeb095dc5e92da3e750ef56a | a607f38aa619c205c4c37f047b6940cef2ea5612 | refs/heads/master | 2020-03-13T12:20:22.852679 | 2018-05-22T12:10:05 | 2018-05-22T12:10:05 | 131,117,236 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package com.elib.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elib.dao.BookRepository;
import com.elib.models.Book;
@Service
public class Bookservices {
@Autowired
private BookRepository bookRepository;
public void saveBook(Book book) {
bookRepository.save(book);
}
public List<Book> findAllBooks() {
List<Book> books=new ArrayList<Book>();
for (Book book : bookRepository.findAll()) {
books.add(book);
}
return books;
}
public void deleteBook(long id) {
bookRepository.delete(id);
}
public Book findOneBook(long id) {
return bookRepository.findOne(id);
}
}
| [
"Nikhil@DESKTOP-EH8LM9O"
] | Nikhil@DESKTOP-EH8LM9O |
830873c5a4d31008f02474ad11f377bd4dc6d4e5 | 180e78725121de49801e34de358c32cf7148b0a2 | /dataset/protocol1/repairnator/learning/5092/NopolStatus.java | 455c00775c0c600ce0939c94123bc84a0eeab936 | [] | no_license | ASSERT-KTH/synthetic-checkstyle-error-dataset | 40e8d1e0a7ebe7f7711def96a390891a6922f7bd | 40c057e1669584bfc6fecf789b5b2854660222f3 | refs/heads/master | 2023-03-18T12:50:55.410343 | 2019-01-25T09:54:39 | 2019-01-25T09:54:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | package fr.inria.spirals.repairnator.process.nopol;
/**
* Created by urli on 16/02/2017.
*/
public enum NopolStatus {
NOTLAUNCHED, RUNNING, NOPATCH, TIMEOUT, PATCH, EXCEPTION
}
| [
"bloriot97@gmail.com"
] | bloriot97@gmail.com |
6d520d7c5d27670579f4b3b6e7f6f2d0d5b490e3 | 2fbfa1a2755ffa379c880f8f9d784a445ef79133 | /src/main/java/com/saving/myapp/config/JacksonConfiguration.java | 50716aed3cd4e6595556e76017228104378b60cb | [] | no_license | yogenmah04/friendsSaving | c96cdec1019a70996b8e61a134d0d99f8172ab0e | c6d76d939ba5520c8eedbf7c9fd35300d4aa8a1b | refs/heads/master | 2022-04-18T03:21:54.711921 | 2020-04-14T03:14:07 | 2020-04-14T03:14:07 | 255,498,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,642 | java | package com.saving.myapp.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@Configuration
public class JacksonConfiguration {
/**
* Support for Java date and time API.
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
1f97bcb3ff6bfa14a5078f2acd17af539e6b569c | 6acb7ca99d361e78b1624b299d7e85982d36cc98 | /Tanks Project/src/sprites/Bullet.java | 45b099b93887ed8a90b964950ad2a795531eaad1 | [] | no_license | jakobh7/Tanks | 24737a0bfa426a6d513da8343fe4acbe70d923eb | 4ba1c29cfcbec208c437563639636ee1847c5ffe | refs/heads/master | 2021-01-10T10:30:52.354520 | 2016-04-06T00:30:49 | 2016-04-06T00:30:49 | 55,183,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 744 | java | package sprites;
import javafx.scene.image.Image;
import main.ImageManager;
import main.Tanks;
public class Bullet extends Character {
private int bounces;
public Bullet(double initx, double inity, double initdx, double initdy){
super(initx, inity, initdx, initdy);
height = Tanks.BULLETSIZE;
width = Tanks.BULLETSIZE;
bounces = 0;
}
@Override
protected Image getImage() {
if(state == 0){return ImageManager.getBullet();}
else
return ImageManager.getExplosion(explosionNum);
}
public void reverseDx(){
super.reverseDx();
bounces++;
}
public void reverseDy(){
super.reverseDy();
bounces++;
}
public void update(){
super.update();
if(state == 0){
if(bounces > 1){
this.explode();
}
}
}
}
| [
"jakobh7@aol.com"
] | jakobh7@aol.com |
aa61c8954f571d8823d81252dc9a56c5769258d2 | 752d91d350aecb70e9cbf7dd0218ca034af652fa | /Winjit Deployment/Backend Source Code/src/main/java/com/fullerton/olp/wsdao/SoapLoggingInterceptor.java | d5a8c5c26b24787aff70466739ac1a7e1b80ee82 | [] | no_license | mnjdby/TEST | 5d0c25cf42eb4212f87cd4d23d1386633922f67e | cc2278c069e1711d4bd3f0a42eb360ea7417a6e7 | refs/heads/master | 2020-03-11T08:51:52.533185 | 2018-04-17T11:31:46 | 2018-04-17T11:31:46 | 129,894,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,653 | java | package com.fullerton.olp.wsdao;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptorAdapter;
import org.springframework.ws.context.MessageContext;
public class SoapLoggingInterceptor extends ClientInterceptorAdapter {
final static Logger log = LoggerFactory.getLogger(SoapLoggingInterceptor.class);
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
System.out.println("Request :");
try {
messageContext.getRequest().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
System.out.println("\nResponse : ");
try {
messageContext.getResponse().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
try {
messageContext.getResponse().writeTo(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException {
log.info("=========================API CALL COMPLETED=========================");
}
} | [
"165016@fullertonindia.local"
] | 165016@fullertonindia.local |
92f2527715b41a193631646217c41afb9cf74d7d | e71f5d45a2dc979abcdd0295661fc48725aadf21 | /MJCompiler/src/rs/ac/bg/etf/pp1/ast/MyFactorNew.java | 757b6cd50c5df46341005909636a572b527ee84f | [] | no_license | jokara/MicroJava-Compiler | eb7cce205934495639bb4dc4d64f6b9ce2879674 | 70c345f637f392176c370fe89d65bc33d6852901 | refs/heads/main | 2023-03-17T22:39:03.328731 | 2021-03-06T16:02:07 | 2021-03-06T16:02:07 | 345,133,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,299 | java | // generated with ast extension for cup
// version 0.8
// 27/0/2020 20:37:8
package rs.ac.bg.etf.pp1.ast;
public class MyFactorNew extends Factor {
private Type Type;
public MyFactorNew (Type Type) {
this.Type=Type;
if(Type!=null) Type.setParent(this);
}
public Type getType() {
return Type;
}
public void setType(Type Type) {
this.Type=Type;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
public void childrenAccept(Visitor visitor) {
if(Type!=null) Type.accept(visitor);
}
public void traverseTopDown(Visitor visitor) {
accept(visitor);
if(Type!=null) Type.traverseTopDown(visitor);
}
public void traverseBottomUp(Visitor visitor) {
if(Type!=null) Type.traverseBottomUp(visitor);
accept(visitor);
}
public String toString(String tab) {
StringBuffer buffer=new StringBuffer();
buffer.append(tab);
buffer.append("MyFactorNew(\n");
if(Type!=null)
buffer.append(Type.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
buffer.append(tab);
buffer.append(") [MyFactorNew]");
return buffer.toString();
}
}
| [
"48447893+jokara@users.noreply.github.com"
] | 48447893+jokara@users.noreply.github.com |
866ac32d5e5d2ac0b1945e3fb31a75ff38e4b2a0 | 15202a875f903dbb6e2468518ae52b8726d1484b | /newUiproject/src/externalservices/Localservicetest.java | 068eb70936c51ed32eac365edccdd98f2736028b | [] | no_license | mohanpalsg/uiappcode | 948a67c73067a308f02944e5ac8d359aea914884 | 183355b42539f81cbaad8965141380f4553ed3dd | refs/heads/master | 2020-03-20T18:48:30.044483 | 2018-10-06T05:41:11 | 2018-10-06T05:41:11 | 137,605,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,647 | java | package externalservices;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import dataobjects.StrategyinvestResult;
public class Localservicetest {
private LookupExternalService lkupextsrvc;
private String serviceurl;
public Localservicetest()
{
lkupextsrvc = new LookupExternalService();
serviceurl = "http://localhost:8080/restclear-0.0.1-SNAPSHOT/restservices/rest/";
}
public void callDataUpdate() {
// TODO Auto-generated method stub
lkupextsrvc.callDataUpdate(serviceurl);
}
public void callRTUpdate() {
// TODO Auto-generated method stub
lkupextsrvc.callRTUpdate(serviceurl);
}
public ArrayList<StrategyinvestResult> lookUpInvestTrend(String diff) {
// TODO Auto-generated method stub
return lookUpInvestTrend(serviceurl,diff);
}
private ArrayList<StrategyinvestResult> lookUpInvestTrend(String serviceurl, String diff) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ArrayList<StrategyinvestResult> resultobj = new ArrayList<StrategyinvestResult>();
try
{
URL url = new URL(serviceurl+"InvestTrendHandlerService?diff="+diff+"&code=MuttonBriyani");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output="",result="";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
result = result+output;
}
System.out.println(result);
Gson gson = new Gson();
resultobj = new ArrayList<StrategyinvestResult> (Arrays.asList(gson.fromJson(result, StrategyinvestResult[].class)));
System.out.println("Converted");
// conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println(resultobj.size());
return resultobj;
}
public ArrayList<StrategyinvestResult> lookUpInvestWave(String diff) {
// TODO Auto-generated method stub
return lookUpInvestWave(serviceurl,diff);
}
private ArrayList<StrategyinvestResult> lookUpInvestWave(String serviceurl2, String diff) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ArrayList<StrategyinvestResult> resultobj = new ArrayList<StrategyinvestResult>();
try
{
URL url = new URL(serviceurl+"InvestWaveHandlerService?diff="+diff+"&code=MuttonBriyani");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output="",result="";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
result = result+output;
}
System.out.println(result);
Gson gson = new Gson();
resultobj = new ArrayList<StrategyinvestResult> (Arrays.asList(gson.fromJson(result, StrategyinvestResult[].class)));
System.out.println("Converted");
// conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println(resultobj.size());
return resultobj;
}
}
| [
"citmo@DESKTOP-mohan"
] | citmo@DESKTOP-mohan |
02479ac0846f8c1f89a8f3eeb566768cea8fccfb | 8c01e11d3ed60645028d6dec02c8ae6b7a7d9be7 | /src/main/java/it/polimi/ingsw/networking/message/DiscardLeaderMessage.java | 7817ab4df217c52461ceb159169a0c68c8356de7 | [
"MIT"
] | permissive | cicabuca/ingswAM2021-Arbasino-Azzara-Bianco | 8477478c0d84e70cd9f032587e45bf9e768f1946 | adc996af03afdaaf76d9a35142499dd68c6c80d6 | refs/heads/main | 2023-06-26T19:13:33.734995 | 2021-07-31T12:09:57 | 2021-07-31T12:09:57 | 342,601,408 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package it.polimi.ingsw.networking.message;
/**
* Packet used to send to the server the will of the player to discard a certain LeaderCard
* It contains the index of the Leader Card he wants to discard (human readable)
*/
public class DiscardLeaderMessage extends Client2Server {
private static final long serialVersionUID = 2247524166072279266L;
private final int index;
public DiscardLeaderMessage(int index) {
this.index = index;
}
public int getLeaderIndex() {
return index;
}
}
| [
"alessandro2.bianco@mail.polimi.it"
] | alessandro2.bianco@mail.polimi.it |
ffcdad04ea8bc33586596289dcdc9ccd1a86bf8b | d1e863475c7df48e001f2ddd0544774fda114ddf | /Breeze/src/main/java/com/carmensol/data/Data/NewPolicyDetail.java | 9980a24d51e6ef9e6c18b3cdddc94cd1601244f3 | [] | no_license | ramandeepcarmen/BreezeAutomation | 95b7d19f36b62bd03211ecc2b7093d76c02bff60 | 080d59deab8bca13a8ada72c9c4dd05c61b107ce | refs/heads/master | 2021-08-07T18:34:43.414475 | 2020-03-22T12:40:56 | 2020-03-22T12:40:56 | 249,161,342 | 0 | 0 | null | 2021-04-26T20:04:59 | 2020-03-22T10:39:17 | HTML | UTF-8 | Java | false | false | 2,194 | java | package com.carmensol.data.Data;
public interface NewPolicyDetail
{
//Test data for test case 1915
String EffectiveDate1915 = "03/26/2021";
String EffectiveDate1915_ = "04/26/2021";
String ExpirationDate1915 = "03/25/2022";
String BusinessType1915 = "Individual";
String Company1915 = "James River Insurance";
String Division1915 = "General Casualty";
String GroupLine1915 ="Comm'l General Liab";
String PolicyType1915 = "Primary";
String ReinsuranceType1915 = "1 - Primary";
String HomeState1915 = "Alaska";
String UnderWriter1915 = "Ramandeep Singh";
String PolicyLimit1915 ="10000";
String MEP1915="20";
String BrokerAgent = "10671";
String BillingType1915 = "GROUP";
//Test data for Test case 669
String BrokerAgentN669 = "20271";
String BrokerageAgency669 = "AmWINS Brokerage of Alabama";
//Test data for Test case 666
String BrokerageAgency666 = "amwins insurance";
//Test data for Test case 683
String BrokerageAgency683 = "hhhhh";
//Test data for 865 and 870 and 875
String Name1 = "Ramandeep";
String Name2 = "Singh";
String EmailAddress = "rsingh3@jamesriverins.com";
String Address1 = "Address1";
String Address2 = "Address2";
String State = "IN";
String City = "Allen";
String CityField = "City1";
String ZipCodeField = "1234";
String ZipCode ="46755";
String Name1_ = "Ramandeep1";
String AddressType = "Foreign";
String Country = "Australia";
//Test data for 935
String PolicyType935 = "Excess";
String AttachmentPoint935 = "1";
String TotalInsurableValue935 = "2";
String PartOfLimit935 = "3";
String AutoAttachmentPoint935 = "4";
//Test data for 934
String CommisionOverrideRate934 ="5";
String PolicyType934 = "Primary";
//Test data for 731 and 735
String BrokerNumber731="21023";
String SubBrokerageAgency731="all";
//Test data for 751
String SubBrokerAgency751="12890";
//Test data for 762
String BrokerAgentN762 = "21023";
String SubBrokerAgentN762 = "17084";
//TestData for 6474
String EffectiveDate6474 = "11/26/2018 ";
}
| [
"62109774+ramandeepcarmen@users.noreply.github.com"
] | 62109774+ramandeepcarmen@users.noreply.github.com |
79ac4b615da1f7aebb8ce5c9209c171022632c42 | b71e1f190701a54a324f6bf51ae29cd411d21556 | /src/main/java/com/tcs/appointment/Appointment/exception/UserNotFoundException.java | bb63d4b71a20a15b213fe1732bed191a52399be6 | [] | no_license | hussaint93/appoint | d5455dcbd9cd7e68710710358fcfef5d1e0ece4c | c3b6e71b7750fb796fbd0bcf32a5793e040601fe | refs/heads/main | 2023-07-10T09:51:04.034416 | 2021-08-27T13:04:20 | 2021-08-27T13:04:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 185 | java | package com.tcs.appointment.Appointment.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
| [
"tcssadriwalla@gmail.com"
] | tcssadriwalla@gmail.com |
279b6ff25ec019bdc7276cc6471185c7df39665c | 0e4db26d6db14d16d4dcb30aea81ecfd7120baa7 | /app/src/main/java/com/example/avengersassemble/model/ItemsDao.java | be657f1e39714d7fb2141881c2cab8f8a8c14be8 | [] | no_license | harsh4723/AvengersAssemble | a3d466f4b392ef52a8baa0dddb492205faf4fc4d | 5523fc57d61f629aa639658a170f77cc7ed45b91 | refs/heads/master | 2023-01-25T00:27:07.974679 | 2020-11-19T07:23:02 | 2020-11-19T07:23:02 | 313,925,615 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | package com.example.avengersassemble.model;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface ItemsDao {
@Insert
void insertAll(ListItem items);
@Delete
void delete(ListItem item);
@Query("SELECT * FROM listitem")
List<ListItem> getAllItems();
@Query("SELECT * FROM listitem WHERE localid = :itemId")
ListItem getItem(int itemId);
@Query("DELETE FROM listitem")
void deleteAllItems();
} | [
"harsh4723@rediffmail.com"
] | harsh4723@rediffmail.com |
814805431cbc966fc59c8548b991154ec760719d | 2dffa4174257fa1319c1a09f78f6537de347ef7c | /src/OfficeHours/Practice_03_02_2021/PersonInfo.java | 7f81779631d7a02a13983a6371642523f21867fb | [] | no_license | VolodymyrPodoinitsyn/java-programming | a618ac811691028ce31377d5e0aa85b558e87388 | 2fae5d86a9c120fdb682fd8c1841b4f88c137183 | refs/heads/master | 2023-05-14T14:45:11.224117 | 2021-06-07T18:11:27 | 2021-06-07T18:11:27 | 374,758,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 774 | java | package OfficeHours.Practice_03_02_2021;
public class PersonInfo {
public static void main(String[] args) {
//Variable
String name, fullBirthDay, favoriteQuote;
byte age;
char gender;
boolean student;
short numberOfSiblings;
long favoriteNumbers;
int numberOfSeasons, year;
double birthDay;
// Assigment of data
name = "Volodymyr";
age = 38;
gender = 'M';
student = true;
numberOfSiblings = 5;
favoriteNumbers = 3L;
numberOfSeasons = 4;
birthDay = 3.2;
year = 2021;
fullBirthDay = "" + birthDay + "." + year;
favoriteQuote = "Have a good mindset";
System.out.println(fullBirthDay);
}
}
| [
"podoinitsynvladimir@gmail.com"
] | podoinitsynvladimir@gmail.com |
956835176a2f7ab8b6ca0baa27e4b580dde97b58 | 53727b3aec2bfe585d3a68eff70822d45b216767 | /src/crudv2projetolb3/Servlet.java | 0702598e69bea8fca5328a28885559fe0454cb08 | [] | no_license | MatheussAlves/projetoLAB3 | 50245beb4a62a04149dc402b51990d4034b76a20 | 2f9e2ae6825ba4a921e3a03c95b36a4be1c3e52e | refs/heads/master | 2021-08-22T07:40:24.726985 | 2017-11-29T17:02:18 | 2017-11-29T17:02:18 | 112,502,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,908 | java | package crudv2projetolb3;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.ucb.DAO.UsuarioDAO;
import br.ucb.entidades.Usuario;
/**
* Servlet implementation class Servlet
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String email = request.getParameter("email");
String senha = request.getParameter("senha");
Usuario user = new Usuario();
user.setEmail(email);
user.setLogin(login);
user.setSenha(senha);
new UsuarioDAO().salvar(user);
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<h3> DADOS ENVIADOS </h3>");
out.print("<h2> email: "+email+"</h2>");
out.print("<h2> login: "+login+"</h2>");
out.print("<h2> senha: "+senha+"</h2>");
out.print("<a href='index.html' > <button>Voltar</button> </a><br>");
//out.print("<input type='button' url='index.html'> voltar </input><br>");
out.print("</html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"matheusalves31@hotmail.com"
] | matheusalves31@hotmail.com |
9e2ac10445d538b670756f1606cafc9b4f03cda5 | 86801f77ee9328ce1f07ffae3a1f5684cfc103c0 | /src/main/java/com/juniorstart/juniorstart/model/audit/UserDateAudit.java | 8e6a00b1d33e91e704ef0938278bd4bb13bcdee9 | [] | no_license | Ejden/juniorstart-backend | dec2dce270e7cffbce198ef92e67310c0bfee085 | e623c6d164e25faf025ab5afe00506ac462c9bda | refs/heads/master | 2022-12-27T23:58:58.390379 | 2020-09-01T14:59:31 | 2020-09-01T14:59:31 | 291,681,797 | 1 | 0 | null | 2020-08-31T10:13:27 | 2020-08-31T10:13:27 | null | UTF-8 | Java | false | false | 564 | java | package com.juniorstart.juniorstart.model.audit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
@JsonIgnoreProperties(
value = {"createdBy", "updatedBy"},
allowGetters = true
)
@Data
public abstract class UserDateAudit extends DateAudit {
@CreatedBy
private Long createdBy;
@LastModifiedBy
private Long updatedBy;
} | [
"grzeszczesny14@gmail.com"
] | grzeszczesny14@gmail.com |
379d523575857cd84af5b465bceb63dbc0c3669e | 6d3ea5e5c45f074537ed2ba85f02ba4e9cede5ad | /src/cn/com/shxt/dialog/SearchSeat.java | a04dd201dc22b13f46034cefa9fcc6fa1fe9c13e | [] | no_license | viviant1224/rcpMovieSys | 15cf38d4bb22206924589b17c8a8474e26866af9 | 4ed7bae24e3d9de501132ea8d9089fc53a69aa50 | refs/heads/master | 2021-01-10T01:29:48.658989 | 2016-03-02T13:11:49 | 2016-03-02T13:11:49 | 52,963,544 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 8,118 | java | package cn.com.shxt.dialog;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.SWTResourceManager;
import cn.com.shxt.tools.DbUtils;
public class SearchSeat extends Dialog {
protected Object result;
protected Shell shell;
private String id;
private String lie;
private String row;
private String roomname;
private static int crow;
private static int clie;
private Label lblNewLabel;
public static List myList = new ArrayList();
private String[] sss;
private boolean canUse = false;
private DbUtils db = new DbUtils();
/**
* Create the dialog.
*
* @param parent
* @param style
*/
public SearchSeat(Shell parent, int style) {
super(parent, style);
setText("SWT Dialog");
}
/**
* Open the dialog.
*
* @return the result
*/
public Object open(String id, String roomname) {
this.id = id;
this.roomname = roomname;
List<Map<String, Object>> list = db
.query("select lie,row from showroom where id = '" + id + "' ");
row = list.get(0).get("row").toString();
lie = list.get(0).get("lie").toString();
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
// 判断放映厅是否有上映电影
public boolean panduan() {
boolean a = false;
List<Map<String, Object>> list_1 = db
.query("select roomname from sell");
System.out.println("size=========" + list_1.size());
for (int i = 0; i < list_1.size(); i++) {
if (list_1.size() != 0) {
if (list_1.get(i).get("roomname").toString().equals(roomname)) {
a = true;
break;
}
}
}
return a;
}
/**
* Create contents of the dialog.
*/
private void createContents() {
shell = new Shell(getParent(), SWT.CLOSE);
shell.setSize(794, 579);
shell.setText("\u67E5\u770B\u5EA7\u4F4D");
final MessageBox box = new MessageBox(shell);
Label label = new Label(shell, SWT.NONE);
label.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
label.setBounds(570, 65, 61, 17);
label.setText("\u6E29\u99A8\u63D0\u793A:");
Label lblNewLabel_1 = new Label(shell, SWT.WRAP);
lblNewLabel_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
lblNewLabel_1.setBounds(570, 93, 215, 73);
lblNewLabel_1
.setText(" \u53CC\u51FB\uFF1A \u7EF4\u4FEE\u5EA7\u4F4D\u3001\u5355\u51FB\uFF1A\u6062\u590D\u5EA7\u4F4D \uFF08\u5982\u679C\u8BE5\u653E\u6620\u5385\u5DF2\u6709\u4E0A\u6620\u7535\u5F71\uFF0C\u4E0D\u80FD\u5BF9\u6B64\u653E\u6620\u5385\u7684\u72B6\u6001\u8FDB\u884C\u66F4\u6539\uFF01\uFF09");
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setBackground(SWTResourceManager
.getColor(SWT.COLOR_BLACK));
lblNewLabel_2.setBounds(47, 28, 502, 29);
lblNewLabel_2.setText("New Label");
Label label_1 = new Label(shell, SWT.NONE);
label_1.setBounds(10, 10, 61, 17);
label_1.setText("\u5C4F\u5E55\uFF1A");
Label label_2 = new Label(shell, SWT.NONE);
label_2.setBounds(10, 78, 45, 17);
label_2.setText("\u5EA7\u4F4D\uFF1A");
Label lblNewLabel_3 = new Label(shell, SWT.NONE);
lblNewLabel_3.setText("\u5165\u53E3");
lblNewLabel_3
.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
lblNewLabel_3.setBounds(0, 112, 31, 34);
int j = 0;
int k = 0;
for (int crow = 1; crow <= Integer.parseInt(row); crow++) {
for (int clie = 1; clie <= Integer.parseInt(lie); clie++) {
final String s = "" + crow + " " + clie;
final String[] ss = s.split(" ");
// System.out.println("crow="+ss[0]);
// System.out.println("clie="+ss[1]);
final Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("微软雅黑", 14, SWT.BOLD));
lblNewLabel.setText(ss[0] + "-" + ss[1]);
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname + "' " + " and row = '" + ss[0]
+ "' and lie = '" + ss[1] + "'");
if (list.get(0).get("state").toString().equals("可用")) {
// db.update("update zuowei set state = '不可用' where row = '"+ss[0]+"' and lie = '"+ss[1]+"'");
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/QQ\u622A\u56FE20130615161817.jpg"));
} else if (list.get(0).get("state").toString().equals("维修")) {
// db.update("update zuowei set state = '可用' where row = '"+ss[0]+"' and lie = '"+ss[1]+"'");
lblNewLabel
.setBackgroundImage(ResourceManager.getPluginImage(
"rcpyingyuanxitong", "icons/bu.jpg"));
}
//
lblNewLabel.setBounds(102 + k * 60, 109 + j * 60, 39, 43);
lblNewLabel.addMouseListener(new MouseAdapter() {
@Override
/**
* @描述: 设置座位
* @作者:黄威威
* @版本:0.9
* @开发时间:2013-6-04上午11:20:59
*/
public void mouseDoubleClick(MouseEvent e) {
System.out.println("crow=" + ss[0]);
System.out.println("clie=" + ss[1]);
String str = "" + ss[0] + " " + ss[1];
if (panduan()) {
box.setText("系统消息");
box.setMessage("该放映厅已有上映电影,不能维修,请过段时间再操作");
box.open();
} else {
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '"
+ ss[1]
+ "'");
if (list.get(0).get("state").equals("可用")) {
myList.add(str);
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/bu.jpg"));
box.setText("系统消息");
box.setMessage("座位维修");
box.open();
db.update("update zuowei set state = '维修' where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '" + ss[1] + "'");
}
System.out.println("" + myList);
}
}
public void mouseDown(MouseEvent e) {
System.out.println("crow=" + ss[0]);
System.out.println("clie=" + ss[1]);
String str = "" + ss[0] + " " + ss[1];
if (panduan()) {
box.setText("系统消息");
box.setMessage("该放映厅已有上映电影,不能维修,请过段时间再操作");
box.open();
} else {
List<Map<String, Object>> list = db
.query("select state from zuowei where roomname = '"
+ roomname
+ "' "
+ " and row = '"
+ ss[0]
+ "' and lie = '"
+ ss[1]
+ "'");
if (list.get(0).get("state").equals("维修")) {
myList.remove(str);
lblNewLabel.setBackgroundImage(ResourceManager
.getPluginImage("rcpyingyuanxitong",
"icons/QQ\u622A\u56FE20130615161817.jpg"));
db.update("update zuowei set state = '可用' where roomname = '"
+ roomname
+ "' and row = '"
+ ss[0]
+ "' and lie = '" + ss[1] + "'");
box.setText("系统消息");
box.setMessage("座位恢复");
box.open();
}
}
System.out.println("" + myList);
}
});
if (k % Integer.parseInt(lie) == Integer.parseInt(lie) - 1) {
j++;
k = -1;
}
k++;
}
}
}
}
| [
"18686672327@163.com"
] | 18686672327@163.com |
de2e210c07696d39447a2d47e90b226979f86bd3 | dbe3e1cde0bc5110e9cc5e9837d8c1ccab301b77 | /app/src/main/java/ptrekaindo/absensi/assets/models/Shift.java | d177af70f0fbf83d4bbe13abcfbc3f105a42898a | [] | no_license | TamaraDhea/AbsensiOnlineREKA | fe6a83726faa00ecc770d61c385fa5d37802eaf1 | 83be67fa8a715626d77ddefacf1a03c44f248399 | refs/heads/master | 2022-12-29T07:43:34.333965 | 2020-10-21T01:43:01 | 2020-10-21T01:43:01 | 305,872,591 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,052 | java | package ptrekaindo.absensi.assets.models;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Shift implements Serializable {
@SerializedName("id_shift")
private String idShift;
@SerializedName("nama_shift")
private String namaShift;
@SerializedName("jam_mulai")
private String jamMulai;
@SerializedName("jam_selesai")
private String jamSelesai;
public String getIdShift() {
return idShift;
}
public void setIdShift(String idShift) {
this.idShift = idShift;
}
public String getNamaShift() {
return namaShift;
}
public void setNamaShift(String namaShift) {
this.namaShift = namaShift;
}
public String getJamMulai() {
return jamMulai;
}
public void setJamMulai(String jamMulai) {
this.jamMulai = jamMulai;
}
public String getJamSelesai() {
return jamSelesai;
}
public void setJamSelesai(String jamSelesai) {
this.jamSelesai = jamSelesai;
}
}
| [
"tamaradhea67@gmail.com"
] | tamaradhea67@gmail.com |
2b99c25e22b1b43f8eaa8e1ec29249da68064082 | 6772404a102b2f98b02dcada7e46f1c98befc02f | /src/test/java/org/opensearch/security/ResolveAPITests.java | bdf5fca06e2d06ba7bb4898a0c9a65822b0bbea6 | [
"Apache-2.0"
] | permissive | xuezhou25/security | 5e3ac02288c5f4889fc78694680eba5763af0e67 | 0fc713b80a85078d10b518fa6b9c1de0259fcc0c | refs/heads/main | 2023-08-29T01:10:41.724046 | 2021-10-20T04:11:31 | 2021-10-20T04:11:31 | 419,181,230 | 0 | 0 | Apache-2.0 | 2021-10-20T04:11:08 | 2021-10-20T04:11:07 | null | UTF-8 | Java | false | false | 9,300 | java | /*
* Copyright 2020 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://www.apache.org/licenses/LICENSE-2.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 org.opensearch.security;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.client.transport.TransportClient;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.security.test.DynamicSecurityConfig;
import org.opensearch.security.test.SingleClusterTest;
import org.opensearch.security.test.helper.rest.RestHelper;
public class ResolveAPITests extends SingleClusterTest {
protected final Logger log = LogManager.getLogger(this.getClass());
@Test
public void testResolveDnfofFalse() throws Exception {
Settings settings = Settings.builder().build();
setup(settings);
setupIndices();
final RestHelper rh = nonSslRestHelper();
RestHelper.HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertContains(res, "*vulcangov*");
assertContains(res, "*starfleet*");
assertContains(res, "*klingonempire*");
assertContains(res, "*xyz*");
assertContains(res, "*role01_role02*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*klingonempire*");
assertNotContains(res, "*xyz*");
assertNotContains(res, "*role01_role02*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
}
@Test
public void testResolveDnfofTrue() throws Exception {
final Settings settings = Settings.builder().build();
setup(Settings.EMPTY, new DynamicSecurityConfig().setConfig("config_dnfof.yml"), settings);
setupIndices();
final RestHelper rh = nonSslRestHelper();
RestHelper.HttpResponse res;
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertContains(res, "*vulcangov*");
assertContains(res, "*starfleet*");
assertContains(res, "*klingonempire*");
assertContains(res, "*xyz*");
assertContains(res, "*role01_role02*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*klingonempire*");
assertNotContains(res, "*xyz*");
assertNotContains(res, "*role01_role02*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*kirk*");
assertContains(res, "*starfleet*");
assertContains(res, "*public*");
assertContains(res, "*xyz*");
Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
assertNotContains(res, "*xception*");
assertNotContains(res, "*erial*");
assertNotContains(res, "*mpty*");
assertNotContains(res, "*vulcangov*");
assertNotContains(res, "*kirk*");
assertNotContains(res, "*public*");
assertNotContains(res, "*xyz*");
assertContains(res, "*starfleet*");
assertContains(res, "*starfleet_academy*");
assertContains(res, "*starfleet_library*");
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executeGetRequest("_resolve/index/vulcangov*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode());
log.debug(res.getBody());
}
private void setupIndices() {
try (TransportClient tc = getInternalTransportClient()) {
tc.admin().indices().create(new CreateIndexRequest("copysf")).actionGet();
tc.index(new IndexRequest("vulcangov").type("kolinahr").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet_academy").type("students").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("starfleet_library").type("public").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("klingonempire").type("ships").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("public").type("legends").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("spock").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("kirk").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("role01_role02").type("type01").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.index(new IndexRequest("xyz").type("doc").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("starfleet","starfleet_academy","starfleet_library").alias("sf"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("klingonempire","vulcangov").alias("nonsf"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("public").alias("unrestricted"))).actionGet();
tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(IndicesAliasesRequest.AliasActions.add().indices("xyz").alias("alias1"))).actionGet();
}
}
}
| [
"vrozov@users.noreply.github.com"
] | vrozov@users.noreply.github.com |
0f8e30af20ed4f98da7ac0eb96cb3ee0eef68253 | a3dbab2349c9d34a9c0f762420b3ce0423a865b9 | /JavaStudy/src/B06_BreakContinue.java | c52c6223b61fa92b188106c2fe974b036b5ffed9 | [] | no_license | ParkCheonhyuk/JavaStudy | 0caa6b970d79742bf77110beeba8b00dc418a2d4 | ef2ee4419a972ff914021bfda64324c014e057d6 | refs/heads/main | 2023-06-12T00:27:43.804312 | 2021-07-08T12:43:08 | 2021-07-08T12:43:08 | 381,996,901 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 882 | java |
public class B06_BreakContinue {
public static void main(String[] args) {
/*
# break
- 반복문 내부에서 사용하면 속해있는 반복문을 하나만 탈출한다
- switch문은 내부에서 사용하면 switch문을 탈출한다
# continue
- 반복문 내부에서 사용하면 다음 번 반복으로 바로 넘어간다
- continue를 만난 시점에서 밑에 있는 반복문 블록은 모두 무시된다
*/
for(int i = 0; i < 10; i++) {
if (i==3 || i==4) {
continue;
}
System.out.println(i);
}
System.out.println("===========");
for(int i = 0; i < 10; i++) {
if (i==3 || i==4) {
break;
}
System.out.println(i);
}
// # for문의 무한 반복
for(int i = 0; true ; ++i) {
if(i == 1000) {
break;
}
System.out.println(i);
}
}
}
| [
"1103-22@host.docker.internal"
] | 1103-22@host.docker.internal |
000be4d6aeb8d81034a844385117f7b5fe5b7733 | e4cb5e99b95d8c05195bf01286318931ad5e66a6 | /modules/services/services-api/src/main/java/com/liferay/training/bookmarks/model/BookmarkModel.java | c0fcfc385cb67c4dae99ad7d540413d6b145e727 | [] | no_license | mahmoudhtayem87/LR-Bookmarks | 5d3cbc19c3ec06c7ce4c779a3170346e0c650242 | ac88f5bc95f56713c3d5cc577b93e6734b737d7c | refs/heads/master | 2023-08-30T12:26:35.321861 | 2021-10-24T08:20:46 | 2021-10-24T08:20:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,776 | java | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.training.bookmarks.model;
import com.liferay.portal.kernel.bean.AutoEscape;
import com.liferay.portal.kernel.model.BaseModel;
import com.liferay.portal.kernel.model.GroupedModel;
import com.liferay.portal.kernel.model.ShardedModel;
import com.liferay.portal.kernel.model.StagedAuditedModel;
import java.util.Date;
import org.osgi.annotation.versioning.ProviderType;
/**
* The base model interface for the Bookmark service. Represents a row in the "BOOKMARK_Bookmark" database table, with each column mapped to a property of this class.
*
* <p>
* This interface and its corresponding implementation <code>com.liferay.training.bookmarks.model.impl.BookmarkModelImpl</code> exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in <code>com.liferay.training.bookmarks.model.impl.BookmarkImpl</code>.
* </p>
*
* @author Brian Wing Shun Chan
* @see Bookmark
* @generated
*/
@ProviderType
public interface BookmarkModel
extends BaseModel<Bookmark>, GroupedModel, ShardedModel,
StagedAuditedModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. All methods that expect a bookmark model instance should use the {@link Bookmark} interface instead.
*/
/**
* Returns the primary key of this bookmark.
*
* @return the primary key of this bookmark
*/
public long getPrimaryKey();
/**
* Sets the primary key of this bookmark.
*
* @param primaryKey the primary key of this bookmark
*/
public void setPrimaryKey(long primaryKey);
/**
* Returns the uuid of this bookmark.
*
* @return the uuid of this bookmark
*/
@AutoEscape
@Override
public String getUuid();
/**
* Sets the uuid of this bookmark.
*
* @param uuid the uuid of this bookmark
*/
@Override
public void setUuid(String uuid);
/**
* Returns the bookmark ID of this bookmark.
*
* @return the bookmark ID of this bookmark
*/
public long getBookmarkId();
/**
* Sets the bookmark ID of this bookmark.
*
* @param bookmarkId the bookmark ID of this bookmark
*/
public void setBookmarkId(long bookmarkId);
/**
* Returns the group ID of this bookmark.
*
* @return the group ID of this bookmark
*/
@Override
public long getGroupId();
/**
* Sets the group ID of this bookmark.
*
* @param groupId the group ID of this bookmark
*/
@Override
public void setGroupId(long groupId);
/**
* Returns the company ID of this bookmark.
*
* @return the company ID of this bookmark
*/
@Override
public long getCompanyId();
/**
* Sets the company ID of this bookmark.
*
* @param companyId the company ID of this bookmark
*/
@Override
public void setCompanyId(long companyId);
/**
* Returns the user ID of this bookmark.
*
* @return the user ID of this bookmark
*/
@Override
public long getUserId();
/**
* Sets the user ID of this bookmark.
*
* @param userId the user ID of this bookmark
*/
@Override
public void setUserId(long userId);
/**
* Returns the user uuid of this bookmark.
*
* @return the user uuid of this bookmark
*/
@Override
public String getUserUuid();
/**
* Sets the user uuid of this bookmark.
*
* @param userUuid the user uuid of this bookmark
*/
@Override
public void setUserUuid(String userUuid);
/**
* Returns the user name of this bookmark.
*
* @return the user name of this bookmark
*/
@AutoEscape
@Override
public String getUserName();
/**
* Sets the user name of this bookmark.
*
* @param userName the user name of this bookmark
*/
@Override
public void setUserName(String userName);
/**
* Returns the create date of this bookmark.
*
* @return the create date of this bookmark
*/
@Override
public Date getCreateDate();
/**
* Sets the create date of this bookmark.
*
* @param createDate the create date of this bookmark
*/
@Override
public void setCreateDate(Date createDate);
/**
* Returns the modified date of this bookmark.
*
* @return the modified date of this bookmark
*/
@Override
public Date getModifiedDate();
/**
* Sets the modified date of this bookmark.
*
* @param modifiedDate the modified date of this bookmark
*/
@Override
public void setModifiedDate(Date modifiedDate);
/**
* Returns the title of this bookmark.
*
* @return the title of this bookmark
*/
@AutoEscape
public String getTitle();
/**
* Sets the title of this bookmark.
*
* @param title the title of this bookmark
*/
public void setTitle(String title);
/**
* Returns the description of this bookmark.
*
* @return the description of this bookmark
*/
@AutoEscape
public String getDescription();
/**
* Sets the description of this bookmark.
*
* @param description the description of this bookmark
*/
public void setDescription(String description);
/**
* Returns the url of this bookmark.
*
* @return the url of this bookmark
*/
@AutoEscape
public String getUrl();
/**
* Sets the url of this bookmark.
*
* @param url the url of this bookmark
*/
public void setUrl(String url);
} | [
"68419183+mahmoudhtayem@users.noreply.github.com"
] | 68419183+mahmoudhtayem@users.noreply.github.com |
d63ab5f3425fbf3f1a980d9c90eb6d1e46d8968c | a22499902c4f1ca38e39e17891451655b261e591 | /src/CF1091_A.java | 1fcb506ddf096afaef62290afb88f3be939b2251 | [] | no_license | krishnadwypayan/Codeforces | 7753b0dd023cea0a9a6df81b16ba9eb1f3dc0e75 | 67090e5c61b789da0465e452737406090b48a135 | refs/heads/master | 2020-04-09T01:23:24.493273 | 2018-12-31T17:48:11 | 2018-12-31T17:48:11 | 159,902,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 606 | java | import java.util.Scanner;
public class CF1091_A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int y = scanner.nextInt(), b = scanner.nextInt(), r = scanner.nextInt();
int min = Math.min(y, Math.min(b, r));
int ans = 0;
if (min == r) {
ans += r + r-1 + r-2;
}
else if (min == b) {
r = Math.min(r, b+1);
ans += r + r-1 + r-2;
}
else {
r = Math.min(r, y+2);
ans += r + r-1 + r-2;
}
System.out.println(ans);
}
}
| [
"krishnadwypayan12@gmail.com"
] | krishnadwypayan12@gmail.com |
1a655ccf9894ad8d1eff15bbc47c011bff34db20 | afece0e242a522d603ba0d231a07901753a00810 | /ext/processor/src/main/java/org/omnifaces/serve/ext/processor/RootProcessor.java | c0a50d5b138a98dd9621829d7909a2f1aac95eb9 | [
"BSD-2-Clause"
] | permissive | omnifaces/omniserve | 24dc34c270873a7deacc27daf3742c178470a220 | bc7c07cdc166931eecbe3771239657c088d39419 | refs/heads/master | 2021-01-09T20:38:01.962253 | 2016-06-17T15:11:14 | 2016-06-17T15:11:14 | 61,379,983 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 197 | java | /*
* Copyright (c) 2016 OmniFaces.org. All Rights Reserved.
*/
package org.omnifaces.serve.ext.processor;
/**
* The root processor.
*/
public class RootProcessor extends ServeTagProcessor {
}
| [
"arjan.tijms@kizitos.com"
] | arjan.tijms@kizitos.com |
8b9b33a0065ec00685d8e3271240f94c5b8dc21a | a568d522706ef1e2f4c848d4956a1acc80006b41 | /ZizonBulls/src/main/java/com/java/dao/nanumDAOImpl.java | 71820708be2f5befa69bf266a77dba92d63b837d | [] | no_license | noruyam/academy_project | 4a95a823d1fe941f202f8be4c105ed31219ca3b9 | 809b4a0e7398a356958bcd9fd436090bc6a94d34 | refs/heads/master | 2023-08-13T04:52:43.975970 | 2021-10-15T05:05:43 | 2021-10-15T05:05:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,483 | java | package com.java.dao;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.domain.nanumVO;
@Repository("nanumDAO")
public class nanumDAOImpl implements namumDAO{
@Autowired
private SqlSessionTemplate mybatis;
@Override
public void insertBoard(nanumVO vo) {
// System.out.println(vo.getTitle());
System.out.println(">>>> nanumDAO.insertBoard() 호출");
mybatis.insert("nanumDAO.insertBoard",vo);
}
@Override
public void updateBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.updateBoard() 호출");
mybatis.update("nanumDAO.updateBoard",vo);
}
@Override
public void deleteBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.deleteBoard() 호출");
mybatis.delete("nanumDAO.deleteBoard",vo);
}
@Override
public nanumVO getBoard(nanumVO vo) {
System.out.println(">>>> nanumDAO.getBoard() 호출");
return mybatis.selectOne("nanumDAO.getBoard",vo);
}
@Override
public List<nanumVO> getBoardList() {
System.out.println(">>>> nanumDAO.getBoardList() 호출");
// BoardMapper.xml占쎈퓠 namespace
return mybatis.selectList("nanumDAO.getBoardList");
}
@Override
public void updatecnt(nanumVO vo) {
System.out.println(">>>> nanumDAO.getBoardList() 호출");
mybatis.update("nanumDAO.updatecnt",vo);
}
}
| [
"qkr2633911@gmail.com"
] | qkr2633911@gmail.com |
9e8abcdaec13ddfec0c03a0fbabc323187c53180 | 12a99ab3fe76e5c7c05609c0e76d1855bd051bbb | /src/main/java/com/alipay/api/domain/DisplayConfig.java | 85fa4fd5e441553a652a4fa1c6abf694a892eff9 | [
"Apache-2.0"
] | permissive | WindLee05-17/alipay-sdk-java-all | ce2415cfab2416d2e0ae67c625b6a000231a8cfc | 19ccb203268316b346ead9c36ff8aa5f1eac6c77 | refs/heads/master | 2022-11-30T18:42:42.077288 | 2020-08-17T05:57:47 | 2020-08-17T05:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 977 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 券的描述信息
*
* @author auto create
* @since 1.0, 2017-06-05 11:25:25
*/
public class DisplayConfig extends AlipayObject {
private static final long serialVersionUID = 3448669554245311969L;
/**
* 券的宣传语
含圈人的直领活动,且投放渠道选择了支付成功页或店铺的情况下必填
*/
@ApiField("slogan")
private String slogan;
/**
* 券的宣传图片文件ID
含圈人的直领活动,且投放渠道选择了店铺的情况下必填
*/
@ApiField("slogan_img")
private String sloganImg;
public String getSlogan() {
return this.slogan;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public String getSloganImg() {
return this.sloganImg;
}
public void setSloganImg(String sloganImg) {
this.sloganImg = sloganImg;
}
}
| [
"ben.zy@antfin.com"
] | ben.zy@antfin.com |
db66227045d438c2e857c876a265730cd776cefa | 4e1171126b279c65da624092fd49b0713d26f596 | /src/test/java/com/ashwin/java/SwaggerDemoApplicationTests.java | 85a1438fccc554b5016765dcda2a92db048a1860 | [] | no_license | ashwindmk/springboot_swagger_demo | 8ba794502acd62c1d2c8130a5ecd0776f96dc446 | 0edf43ea676c65d3455bf7d2b22e70ce532ed265 | refs/heads/master | 2022-12-24T08:51:18.198541 | 2020-09-26T09:19:02 | 2020-09-26T09:19:02 | 298,774,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 212 | java | package com.ashwin.java;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SwaggerDemoApplicationTests {
@Test
void contextLoads() {
}
}
| [
"ashwin.dinesh01@gmail.com"
] | ashwin.dinesh01@gmail.com |
d4a84e4fc8e6c41f86c80d5a8dd0e1925780759b | a15e6dae62a010e202d604ee0a703ecff0e364be | /src/main/java/code/swt/Menus.java | dff5704983640f1c5f9de88274d0bdcb327d0877 | [] | no_license | zhangzhef/java4 | 0ede3e1599a2c4767ce5baf9391e8feeb7d5a020 | e914642df32a7f5bc53155b6b2d7699d7d25487e | refs/heads/master | 2021-01-11T10:55:48.181391 | 2016-12-11T11:58:50 | 2016-12-11T11:58:50 | 76,162,456 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,479 | java | package code.swt;//: swt/Menus.java
// Fun with menus.
import swt.util.*;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import java.util.*;
import net.mindview.util.*;
public class Menus implements SWTApplication {
private static Shell shell;
public void createContents(Composite parent) {
shell = parent.getShell();
Menu bar = new Menu(shell, SWT.BAR);
shell.setMenuBar(bar);
Set<String> words = new TreeSet<String>(
new TextFile("Menus.java", "\\W+"));
Iterator<String> it = words.iterator();
while(it.next().matches("[0-9]+"))
; // Move past the numbers.
MenuItem[] mItem = new MenuItem[7];
for(int i = 0; i < mItem.length; i++) {
mItem[i] = new MenuItem(bar, SWT.CASCADE);
mItem[i].setText(it.next());
Menu submenu = new Menu(shell, SWT.DROP_DOWN);
mItem[i].setMenu(submenu);
}
int i = 0;
while(it.hasNext()) {
addItem(bar, it, mItem[i]);
i = (i + 1) % mItem.length;
}
}
static Listener listener = new Listener() {
public void handleEvent(Event e) {
System.out.println(e.toString());
}
};
void
addItem(Menu bar, Iterator<String> it, MenuItem mItem) {
MenuItem item = new MenuItem(mItem.getMenu(),SWT.PUSH);
item.addListener(SWT.Selection, listener);
item.setText(it.next());
}
public static void main(String[] args) {
SWTConsole.run(new Menus(), 600, 200);
}
} ///:~
| [
"zzf016"
] | zzf016 |
6b60d324628244d147d15a90d5708c613aa85ba8 | e000510f5be13b52585f8299a01bb28da12304d1 | /SpringExample/src/main/java/info/_7chapters/spring/core/coreContainer/_12InstanceFactory/TestBean.java | 64716326871cc3bccfe84e1e0777da2f8130a43a | [] | no_license | 7chapters/springexample | a3d823af2e1ef5bb46c716de5091547241b62777 | bcb7fa945054b04007cba8fda9787b90df9557cb | refs/heads/master | 2021-01-22T23:58:27.026291 | 2013-05-18T04:02:31 | 2013-05-18T04:02:31 | 8,123,390 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package info._7chapters.spring.core.coreContainer._12InstanceFactory;
public class TestBean {
String msg;
public TestBean() {
super();
// TODO Auto-generated constructor stub
}
TestBean(String msg) {
this.msg = msg;
System.out.println("Constructor of TestBean class invoked");
}
public String toString() //to dispaly results
{
return msg;
}
}
| [
"jayram.rout@7chapters.info"
] | jayram.rout@7chapters.info |
409f0bc32f962d68873878033d97e65611394707 | 99243d1d8b3d3bf161585f29c1cab11eec4ae1bc | /app/src/main/java/com/alion/accessibility/AccessibilityMainActivity.java | 88369415dd34cb08a6d4f601b7ea740272ebc4fa | [] | no_license | alion2015/AlionApplication | 9c7ca30277c93a620ed6c8ab1828753a68c71270 | c5304c3abaf3474db2aaf9c253c24a139f6a7322 | refs/heads/master | 2020-03-28T22:47:37.455433 | 2019-06-28T07:33:50 | 2019-06-28T07:33:50 | 149,258,464 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,632 | java | package com.alion.accessibility;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.alion.myapplication.R;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import static com.alion.accessibility.utils.AccessibilityUtil.jumpToSettingPage;
public class AccessibilityMainActivity extends Activity implements View.OnClickListener {
private View mOpenSetting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accessibility_main);
initView();
AccessibilityOperator.getInstance().init(this);
test();
}
private void test() {
}
private void initView() {
mOpenSetting = findViewById(R.id.open_accessibility_setting);
mOpenSetting.setOnClickListener(this);
findViewById(R.id.accessibility_find_and_click).setOnClickListener(this);
}
@Override
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.open_accessibility_setting:
jumpToSettingPage(this);
break;
case R.id.accessibility_find_and_click:
Intent intent = new Intent();
intent.setClassName("com.jifen.qukan", "com.jifen.qkbase.main.MainActivity");
startActivity(intent);
break;
}
}
}
| [
"Gz20150721"
] | Gz20150721 |
47deafec269298bc32d058efc3a0964242043f97 | d9b101ddb27677614fdf78eb7e0e7d2e9b2cf98c | /src/main/java/com/jiannei/duxin/controller/RoleResourceController.java | 1bdb90856be96b992acf3aa24e4b3da9a50e2a0e | [] | no_license | songbw/duxin | 8ef4d8297e97be0e209ff36ce23450643a59f38b | 03dcc20641e355715c2627e7e727943d64e7b810 | refs/heads/master | 2021-03-22T02:13:07.029675 | 2018-02-08T07:30:33 | 2018-02-08T07:30:33 | 119,036,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,885 | java | package com.jiannei.duxin.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jiannei.duxin.service.IRoleResourceService;
import com.jiannei.duxin.dto.ResultBean;
import com.jiannei.duxin.query.RoleResourceQueryBean;
import com.jiannei.duxin.dto.RoleResourceDTO;
import com.jiannei.duxin.dto.SystemStatus;
import org.springframework.stereotype.Controller;
/**
* <p>
* 角色资源表 前端控制器
* </p>
*
* @author Songbw
* @since 2018-01-26
*/
@Controller
@RequestMapping("/duxin/roleResource")
public class RoleResourceController {
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(RoleResourceController.class);
@Autowired
private IRoleResourceService service;
@RequestMapping(value = "/page", method = RequestMethod.POST)
@ResponseBody
public ResultBean pageQuery(@RequestBody RoleResourceQueryBean queryBean) {
if (queryBean.getPageSize() <= 0) {
queryBean.setPageSize(20);
}
if (queryBean.getPageNo() < 0) {
queryBean.setPageNo(0);
}
ResultBean resultBean = new ResultBean();
try {
resultBean = service.listByPage(queryBean);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public ResultBean add(@RequestBody RoleResourceDTO dto) {
ResultBean resultBean = new ResultBean();
// if (StringUtils.isEmpty(usersDTO.getUsername())) {
// resultBean.setFailMsg(200101,"用户名不能为空");
// return resultBean;
// }
// if (StringUtils.isEmpty(usersDTO.getPassword())) {
// resultBean.setFailMsg(200102,"密码不能为空");
// return resultBean;
// }
try {
resultBean = service.insert(dto);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.PUT)
@ResponseBody
public ResultBean update(@RequestBody RoleResourceDTO dto) {
ResultBean resultBean = new ResultBean();
// if (StringUtils.isEmpty(usersDTO.getId())) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.update(dto);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.DELETE)
@ResponseBody
public ResultBean delete(int id) {
ResultBean resultBean = new ResultBean();
// if (id == 0) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.delete(id);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public ResultBean get(int id) {
ResultBean resultBean = new ResultBean();
// if (id == 0) {
// resultBean.setFailMsg(200104,"ID不能为空");
// return resultBean;
// }
try {
resultBean = service.get(id);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
/**
* 根据角色ID获取资源ID
*
* @param roleId
* @return
*/
@RequestMapping(value = "/role", method = RequestMethod.GET)
@ResponseBody
public ResultBean getByRole(int roleId) {
ResultBean resultBean = new ResultBean();
if (roleId == 0) {
resultBean.setFailMsg(SystemStatus.ROLEID_IS_NULL);
return resultBean;
}
try {
resultBean = service.getByRole(roleId);
} catch (Exception e) {
log.error(e.getMessage());
resultBean.setFailMsg(SystemStatus.SERVER_ERROR);
return resultBean;
}
return resultBean;
}
}
| [
"song@smartautotech.com"
] | song@smartautotech.com |
dd8a7338bc36eca1db719207d33afa1d9603d14d | 418972d25f6d574bbc019c37b71d0cd93b6d9402 | /demo/src/main/java/de/quist/app/maps/example/MultiMapDemoActivity.java | 60155da31f2da1e7a4d4e260893835e2c56ef8d3 | [
"Apache-2.0"
] | permissive | tomquist/android-maps-abstraction | 37e950961a85cfa33d97769ac59b78d709f219d4 | eb5b133a4ba44cf2aa0a68daf610203a704a3c27 | refs/heads/master | 2021-01-10T00:53:29.109312 | 2015-03-21T13:10:59 | 2015-03-21T13:10:59 | 31,922,864 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,048 | java | /*
* Copyright (C) 2012 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 de.quist.app.maps.example;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
/**
* This shows how to create a simple activity with multiple maps on screen.
*/
public class MultiMapDemoActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multimap_demo);
}
}
| [
"tom@quist.de"
] | tom@quist.de |
7014bab75c1fa7184e2b017bce91d5b94868a4a5 | 2cd51fb172ae3beab919879064869ea941140824 | /src/main/java/com/mycompany/myapp/repository/search/BloodSearchRepository.java | aad9d11f37dce6067432908d739fbda1dd62f884 | [] | no_license | dedechandran/jhipster-21-points | 7dfa60e989aa2a6e61d4af19190f096ea6814d85 | 0de03e29503d500875a9cfe21b26dc8d1694aace | refs/heads/master | 2020-04-27T20:44:16.727772 | 2019-03-09T08:33:24 | 2019-03-09T08:33:24 | 176,039,650 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 330 | java | package com.mycompany.myapp.repository.search;
import com.mycompany.myapp.domain.Blood;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the Blood entity.
*/
public interface BloodSearchRepository extends ElasticsearchRepository<Blood, Long> {
}
| [
"dedechandra852.dc@gmail.com"
] | dedechandra852.dc@gmail.com |
4dfdd8bb1a268b10249431f7c337fc11c1087198 | 3714974b546f7fddeeea54d84b543c3b350a7583 | /myProjects/MGTV/src/com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson.java | 0f26403d6012e0e2b4e76bbfe50c893d02896112 | [] | no_license | lubing521/ideaProjects | 57a8dadea5c0d8fc3e478c7829e6897dce242bde | 5fd85e6dbe1ede8f094de65226de41321c1d0683 | refs/heads/master | 2022-01-18T23:10:05.057971 | 2018-10-26T12:27:00 | 2018-10-26T12:27:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,721 | java | package com.starcor.core.parser.json;
import com.starcor.core.domain.UserCenterInfo;
import com.starcor.core.interfaces.IXmlParser;
import java.io.InputStream;
public class GetUserCenterInfoSAXParserJson<Result>
implements IXmlParser<Result>
{
UserCenterInfo info = new UserCenterInfo();
public Result parser(InputStream paramInputStream)
{
return null;
}
// ERROR //
public Result parser(byte[] paramArrayOfByte)
{
// Byte code:
// 0: aload_1
// 1: ifnonnull +5 -> 6
// 4: aconst_null
// 5: areturn
// 6: new 27 java/lang/String
// 9: dup
// 10: aload_1
// 11: invokespecial 30 java/lang/String:<init> ([B)V
// 14: astore_2
// 15: ldc 32
// 17: new 34 java/lang/StringBuilder
// 20: dup
// 21: invokespecial 35 java/lang/StringBuilder:<init> ()V
// 24: ldc 37
// 26: invokevirtual 41 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 29: aload_2
// 30: invokevirtual 41 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 33: invokevirtual 45 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 36: invokestatic 51 com/starcor/core/utils/Logger:i (Ljava/lang/String;Ljava/lang/String;)V
// 39: new 53 org/json/JSONObject
// 42: dup
// 43: aload_2
// 44: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 47: astore 4
// 49: aload 4
// 51: ldc 58
// 53: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 56: ifeq +17 -> 73
// 59: aload_0
// 60: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 63: aload 4
// 65: ldc 58
// 67: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 70: putfield 69 com/starcor/core/domain/UserCenterInfo:state Ljava/lang/String;
// 73: aload 4
// 75: ldc 71
// 77: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 80: ifeq +17 -> 97
// 83: aload_0
// 84: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 87: aload 4
// 89: ldc 71
// 91: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 94: putfield 73 com/starcor/core/domain/UserCenterInfo:reason Ljava/lang/String;
// 97: aload 4
// 99: ldc 75
// 101: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 104: ifeq +345 -> 449
// 107: new 53 org/json/JSONObject
// 110: dup
// 111: aload 4
// 113: ldc 75
// 115: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 118: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 121: astore 5
// 123: aload 5
// 125: ldc 77
// 127: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 130: istore 6
// 132: iload 6
// 134: ifeq +23 -> 157
// 137: aload_0
// 138: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 141: aload 5
// 143: ldc 77
// 145: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 148: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 151: invokevirtual 87 java/lang/Integer:intValue ()I
// 154: putfield 90 com/starcor/core/domain/UserCenterInfo:err I
// 157: aload 5
// 159: ldc 92
// 161: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 164: ifeq +17 -> 181
// 167: aload_0
// 168: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 171: aload 5
// 173: ldc 92
// 175: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 178: putfield 94 com/starcor/core/domain/UserCenterInfo:status Ljava/lang/String;
// 181: aload 5
// 183: ldc 96
// 185: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 188: ifeq +261 -> 449
// 191: new 53 org/json/JSONObject
// 194: dup
// 195: aload 5
// 197: ldc 96
// 199: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 202: invokespecial 56 org/json/JSONObject:<init> (Ljava/lang/String;)V
// 205: astore 7
// 207: aload 7
// 209: ldc 98
// 211: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 214: istore 8
// 216: iload 8
// 218: ifeq +23 -> 241
// 221: aload_0
// 222: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 225: aload 7
// 227: ldc 98
// 229: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 232: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 235: invokevirtual 87 java/lang/Integer:intValue ()I
// 238: putfield 101 com/starcor/core/domain/UserCenterInfo:vipId I
// 241: aload 7
// 243: ldc 103
// 245: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 248: ifeq +17 -> 265
// 251: aload_0
// 252: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 255: aload 7
// 257: ldc 103
// 259: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 262: putfield 106 com/starcor/core/domain/UserCenterInfo:vipName Ljava/lang/String;
// 265: aload 7
// 267: ldc 108
// 269: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 272: istore 9
// 274: iload 9
// 276: ifeq +23 -> 299
// 279: aload_0
// 280: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 283: aload 7
// 285: ldc 108
// 287: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 290: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 293: invokevirtual 87 java/lang/Integer:intValue ()I
// 296: putfield 111 com/starcor/core/domain/UserCenterInfo:viPower I
// 299: aload 7
// 301: ldc 113
// 303: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 306: istore 10
// 308: iload 10
// 310: ifeq +23 -> 333
// 313: aload_0
// 314: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 317: aload 7
// 319: ldc 113
// 321: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 324: invokestatic 118 java/lang/Float:valueOf (Ljava/lang/String;)Ljava/lang/Float;
// 327: invokevirtual 122 java/lang/Float:floatValue ()F
// 330: putfield 125 com/starcor/core/domain/UserCenterInfo:balance F
// 333: aload 7
// 335: ldc 127
// 337: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 340: ifeq +17 -> 357
// 343: aload_0
// 344: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 347: aload 7
// 349: ldc 127
// 351: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 354: putfield 130 com/starcor/core/domain/UserCenterInfo:loginaccount Ljava/lang/String;
// 357: aload 7
// 359: ldc 132
// 361: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 364: istore 11
// 366: iload 11
// 368: ifeq +23 -> 391
// 371: aload_0
// 372: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 375: aload 7
// 377: ldc 132
// 379: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 382: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 385: invokevirtual 87 java/lang/Integer:intValue ()I
// 388: putfield 135 com/starcor/core/domain/UserCenterInfo:vipEndDays I
// 391: aload 7
// 393: ldc 137
// 395: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 398: ifeq +17 -> 415
// 401: aload_0
// 402: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 405: aload 7
// 407: ldc 137
// 409: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 412: putfield 140 com/starcor/core/domain/UserCenterInfo:vipEndDate Ljava/lang/String;
// 415: aload 7
// 417: ldc 142
// 419: invokevirtual 62 org/json/JSONObject:has (Ljava/lang/String;)Z
// 422: istore 12
// 424: iload 12
// 426: ifeq +23 -> 449
// 429: aload_0
// 430: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 433: aload 7
// 435: ldc 142
// 437: invokevirtual 66 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String;
// 440: invokestatic 83 java/lang/Integer:valueOf (Ljava/lang/String;)Ljava/lang/Integer;
// 443: invokevirtual 87 java/lang/Integer:intValue ()I
// 446: putfield 144 com/starcor/core/domain/UserCenterInfo:account_type I
// 449: aload_0
// 450: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 453: areturn
// 454: astore 18
// 456: aload_0
// 457: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 460: iconst_0
// 461: putfield 90 com/starcor/core/domain/UserCenterInfo:err I
// 464: goto -307 -> 157
// 467: astore_3
// 468: aload_3
// 469: invokevirtual 147 org/json/JSONException:printStackTrace ()V
// 472: goto -23 -> 449
// 475: astore 17
// 477: aload_0
// 478: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 481: iconst_0
// 482: putfield 101 com/starcor/core/domain/UserCenterInfo:vipId I
// 485: goto -244 -> 241
// 488: astore 16
// 490: aload_0
// 491: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 494: iconst_0
// 495: putfield 111 com/starcor/core/domain/UserCenterInfo:viPower I
// 498: goto -199 -> 299
// 501: astore 15
// 503: aload_0
// 504: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 507: fconst_0
// 508: putfield 125 com/starcor/core/domain/UserCenterInfo:balance F
// 511: goto -178 -> 333
// 514: astore 14
// 516: aload_0
// 517: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 520: iconst_0
// 521: putfield 135 com/starcor/core/domain/UserCenterInfo:vipEndDays I
// 524: goto -133 -> 391
// 527: astore 13
// 529: aload_0
// 530: getfield 18 com/starcor/core/parser/json/GetUserCenterInfoSAXParserJson:info Lcom/starcor/core/domain/UserCenterInfo;
// 533: iconst_0
// 534: putfield 144 com/starcor/core/domain/UserCenterInfo:account_type I
// 537: goto -88 -> 449
//
// Exception table:
// from to target type
// 137 157 454 java/lang/Exception
// 6 73 467 org/json/JSONException
// 73 97 467 org/json/JSONException
// 97 132 467 org/json/JSONException
// 137 157 467 org/json/JSONException
// 157 181 467 org/json/JSONException
// 181 216 467 org/json/JSONException
// 221 241 467 org/json/JSONException
// 241 265 467 org/json/JSONException
// 265 274 467 org/json/JSONException
// 279 299 467 org/json/JSONException
// 299 308 467 org/json/JSONException
// 313 333 467 org/json/JSONException
// 333 357 467 org/json/JSONException
// 357 366 467 org/json/JSONException
// 371 391 467 org/json/JSONException
// 391 415 467 org/json/JSONException
// 415 424 467 org/json/JSONException
// 429 449 467 org/json/JSONException
// 456 464 467 org/json/JSONException
// 477 485 467 org/json/JSONException
// 490 498 467 org/json/JSONException
// 503 511 467 org/json/JSONException
// 516 524 467 org/json/JSONException
// 529 537 467 org/json/JSONException
// 221 241 475 java/lang/Exception
// 279 299 488 java/lang/Exception
// 313 333 501 java/lang/Exception
// 371 391 514 java/lang/Exception
// 429 449 527 java/lang/Exception
}
}
/* Location: C:\Users\THX\Desktop\aa\aa\反编译工具包\out\classes_dex2jar.jar
* Qualified Name: com.starcor.core.parser.json.GetUserCenterInfoSAXParserJson
* JD-Core Version: 0.6.2
*/ | [
"hiram@finereport.com"
] | hiram@finereport.com |
c9bb8c38eaf286580957b83ebadc5ca48a621a61 | 96838da3527b4d8bf3b4c6f3916f8a8995a91b53 | /src/main/java/com/selectica/Base/eclm/definitions/CNDABO/CNDASignature/scripts/SetIntSignerEmail.java | 2ea11ddb64230b7affd7f46ed21584f053fdf12d | [] | no_license | LeoSigal/Phil | b5d2c50a07774a93f58a60ccdba6845f4577edc9 | 2e71214fcde15202c52efdcc7ebdfcc418d1730d | refs/heads/master | 2021-01-10T18:38:52.007604 | 2019-04-19T03:59:31 | 2019-04-19T03:59:31 | 36,754,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,876 | java | package com.selectica.Base.eclm.definitions.CNDABO.CNDASignature.scripts;
import com.selectica.Base.stubs.ContractInfoComponent;
import com.selectica.config.Config;
import com.selectica.config.ConfigKeys;
import com.selectica.rcfscripts.AbstractDataWriteScript;
import com.selectica.rcfutils.RCFUserWrapper;
/**
* Created by vshilkin on 27.04.2015.
*/
public class SetIntSignerEmail extends AbstractDataWriteScript<String> {
/*
<![CDATA[
result = "";
var ndaIsStandardContract = thisBundle.getParameterValueObjectFromAnyComponent("ReqCNDADetails", "isStandardContract");
var useEsign = Packages.com.selectica.config.Config.getPropertyAsBoolean(Packages.com.selectica.config.ConfigKeys.ESIGNATURE_ENABLED);
if (useEsign != null && ndaIsStandardContract != null &&
(useEsign.toString().equalsIgnoreCase("true") || useEsign.toString().equalsIgnoreCase("yes")) &&
"yes".equalsIgnoreCase(ndaIsStandardContract.toString())) {
result = root.getValue("user").getUserWrapper().getEmail();
}
]]>
*/
@Override
public String process() throws Exception {
String useEsignProp = Config.getProperty(ConfigKeys.ESIGNATURE_ENABLED); //@todo move to RCFHelper !
boolean useEsign = "true".equalsIgnoreCase(useEsignProp);
ContractInfoComponent info = getHelper().getInfoComponentStub();
boolean isStandardContract = "yes".equalsIgnoreCase(info.getIsStandardContract());
if (useEsign && isStandardContract) {
String cpName = info.getCpName();
if (cpName != null && !cpName.isEmpty()) {
RCFUserWrapper userWrapper = getHelper().getRCFUserWrapper();
return userWrapper.getEmail();
}
}
return null;
}
}
| [
"user@rcfproj.aws.selectica.net"
] | user@rcfproj.aws.selectica.net |
ed5e2993fe9f89d16e0dd5ff487fe4da28432934 | 78b6e133c361d4277b4073c94fe205f92b83ca98 | /src/main/java/com/xiaoshu/dao/MessageTempleMapper.java | 00ad1013ebc88412bd1b0a2e96ec48bb853df229 | [] | no_license | barrysandy/rabbitmq | 375763a78e5c35d7a75780ef4893f8279c089bbb | d4482d74c26c32aeaaedf7c83f4b8cafcb94b951 | refs/heads/master | 2020-03-16T04:42:39.145664 | 2018-09-05T22:40:03 | 2018-09-05T22:40:03 | 132,517,379 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,513 | java | package com.xiaoshu.dao;
import com.xiaoshu.entity.MessageTemple;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 标准版 */
public interface MessageTempleMapper {
/** save one */
@Insert("INSERT INTO message_temple (ID,COMMODITY_ID,TEMPLE_NAME, TEMPLE_ID,TEMPLE_TYPE, CREATE_TIME, UPDATE_TIME, DESC_M, STATUS ,SIGN) " +
"VALUES(#{id},#{commodityId},#{templeName},#{templeId},#{templeType},#{createTime},#{updateTime},#{descM},#{status},#{sign} )")
Integer save(MessageTemple bean);
/** update templeId */
@Update("UPDATE message_temple SET TEMPLE_ID=#{templeId},UPDATE_TIME=#{updateTime} where ID = #{id}")
Integer updateCodeStateAndCreateTimeById(@Param("templeId") Integer templeId ,@Param("updateTime") String updateTime, @Param("id") String id);
/** update all */
@Update("UPDATE message_temple SET COMMODITY_ID=#{commodityId},TEMPLE_NAME=#{templeName},TEMPLE_ID=#{templeId},TEMPLE_TYPE=#{templeType},CREATE_TIME=#{createTime},UPDATE_TIME=#{updateTime},DESC_M=#{descM}," +
"STATUS=#{status},SIGN=#{sign} WHERE ID=#{id} ")
Integer updateAll(MessageTemple bean);
/** delete ById */
@Delete("DELETE FROM message_temple WHERE ID=#{id}")
Integer deleteById(@Param("id") String id);
/** 按照 商品 id 查询 短信模板集合 */
@Select("SELECT * FROM message_temple WHERE COMMODITY_ID = #{commodityId}")
List<MessageTemple> listByCommodityId(@Param("commodityId") Integer commodityId);
/** select ByID */
@Select("SELECT * FROM message_temple WHERE ID = #{id}")
MessageTemple getById(@Param("id") String id);
/**
* 查询列表
* @param index 分页开始
* @param pageSize 分页每页最大数
* @param key 关键字
* @return 返回订单集合
* @throws Exception 抛出异常
*/
List<MessageTemple> listByKey(@Param("index") int index, @Param("pageSize") int pageSize, @Param("key") String key,@Param("status") Integer status, @Param("commodityId") Integer commodityId);
/**
* 统计
* @param key 关键字
* @return 返回数量
* @throws Exception 抛出异常
*/
Integer countByKey(@Param("key") String key,@Param("status") Integer status, @Param("commodityId") Integer commodityId);
/** 按照模板类型和商品ID统计模板数 用于查询某个类型的模板是否存在 */
@Select("SELECT COUNT(ID) FROM message_temple WHERE TEMPLE_TYPE = #{templeType} AND COMMODITY_ID = #{commodityId}")
Integer countByTTypeAndCId(@Param("templeType") String templeType, @Param("commodityId") Integer commodityId);
}
| [
"865815412@qq.com"
] | 865815412@qq.com |
7bb4b41057e346be953db95b83c4bd533cec8f9f | 5055dcd80cc1d40cf9a67a51ae20581ad1ed54d0 | /src/main/java/com/jk/faces/util/JKJsfUtil.java | 1e22ecd643e48fe818b7c535fa3cdecab5d6c911 | [
"Apache-2.0"
] | permissive | srikantha2/jk-faces | 00231f42614190778819865c487a058d0f67825e | 3abe304aaa17409651511ef0454dcc822f2016dc | refs/heads/master | 2020-12-25T23:36:16.023520 | 2016-05-16T19:02:31 | 2016-05-16T19:02:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,244 | java | /*
* Copyright 2002-2016 Jalal Kiswani.
*
* 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.jk.faces.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.StateHelper;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitContext;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.lifecycle.LifecycleFactory;
import javax.faces.view.ViewDeclarationLanguage;
import javax.faces.view.facelets.FaceletContext;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.Assert;
import com.jk.annotations.Author;
import com.jk.exceptions.handler.ExceptionUtil;
import com.jk.faces.components.TagAttributeConstants;
import com.jk.util.ConversionUtil;
/**
* <B>JSFUtil</B> is class that contains JSF helpful methods, that helps to
* search, edit or manipulate JSF contents.
*
* @author Jalal H. Kiswani
* @version 1.0
*/
@Author(name = "Jalal Kiswani", date = "3/9/2014", version = "1.0")
public class JKJsfUtil {
/** The Constant CHECKSUM_POSTFIX. */
private static final String CHECKSUM_POSTFIX = "-checksum";
/** The logger. */
private static Logger logger = Logger.getLogger(JKJsfUtil.class.getName());
/**
* add String <code>contents</code> in HTML row.
*
* @param contents
* the contents
* @param colSpan
* the col span
* @param style
* the style
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void addFullRow(final String contents, final int colSpan, final String style) throws IOException {
if (contents != null) {
final ResponseWriter writer = JKJsfUtil.context().getResponseWriter();
writer.startElement("tr", null);
writer.startElement("td", null);
writer.writeAttribute("align", "center", null);
writer.writeAttribute("colspan", colSpan, null);
writer.writeAttribute("class", style, null);
writer.writeText(contents, null);
writer.endElement("td");
writer.endElement("tr");
}
}
/**
* add component <code>comp</code> in HTML row.
*
* @param comp
* the comp
* @param colSpan
* the col span
* @param style
* the style
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void addFullRow(final UIComponent comp, final int colSpan, final String style) throws IOException {
if (comp != null) {
final ResponseWriter writer = JKJsfUtil.context().getResponseWriter();
writer.startElement("tr", null);
writer.startElement("td", null);
// TODO : convert the following to use the TagConstants class
JKJsfUtil.writeAttribue(comp, "align", "center");
JKJsfUtil.writeAttribue(comp, "colspan", colSpan);
JKJsfUtil.writeAttribue(comp, "styleClass", "class", style);
comp.encodeAll(JKJsfUtil.context());
writer.endElement("td");
writer.endElement("tr");
}
}
/**
* Appends value to an existing attribute in component
* <code>component</code>.
*
* @param component
* the component
* @param sourceKey
* the source key
* @param targetKey
* the target key
* @param valueToAppend
* the value to append
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void appendAttribute(final UIComponent component, final String sourceKey, final String targetKey, final String valueToAppend)
throws IOException {
String value = (String) component.getAttributes().get(sourceKey);
if (value == null) {
value = valueToAppend;
} else {
value = value.concat(" ").concat(valueToAppend);
}
JKJsfUtil.context().getResponseWriter().writeAttribute(targetKey, value, null);
}
/**
* Builds the view.
*
* @param context
* the context
* @param viewId
* the view id
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String buildView(final FacesContext context, final String viewId) throws IOException {
final UIViewRoot view = JKJsfUtil.createView(viewId);
view.encodeAll(FacesContext.getCurrentInstance());
final ResponseWriter originalWriter = context.getResponseWriter();
final StringWriter writer = new StringWriter();
try {
context.setResponseWriter(context.getRenderKit().createResponseWriter(writer, "text/html", "UTF-8"));
view.encodeAll(context);
} finally {
if (originalWriter != null) {
context.setResponseWriter(originalWriter);
}
}
return writer.toString();
}
/**
* Builds the view.
*
* @param viewId
* the view id
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String buildView(final String viewId) throws IOException {
return JKJsfUtil.buildView(FacesContext.getCurrentInstance(), viewId);
}
/**
* Calculate checksum.
*
* @param component
* the component
* @return the long
*/
public static long calculateChecksum(final UIComponent component) {
try {
final Checksum checksumHandler = new CRC32();
final UIFacesVisitor visitors = JKJsfUtil.visitComponent(component);
final List<UIInput> inputs = visitors.getInputs();
for (final UIInput uiInput : inputs) {
if (uiInput.getValue() == null) {
checksumHandler.update("null".getBytes(), 0, 0);
} else {
final byte[] bytes = uiInput.getValue().toString().getBytes("UTF-8");
checksumHandler.update(bytes, 0, bytes.length);
}
}
return checksumHandler.getValue();
} catch (final Exception e) {
ExceptionUtil.handle(e);
// unreachable
return -1;
}
}
/**
* Calculate current view checksum.
*
* @return the long
*/
public static long calculateCurrentViewChecksum() {
return JKJsfUtil.calculateChecksum(FacesContext.getCurrentInstance().getViewRoot());
}
/**
* Clear view states.
*/
public static void clearViewStates() {
JKJsfUtil.getViewMap().clear();
}
/**
* Context.
*
* @return the faces context
*/
private static FacesContext context() {
return FacesContext.getCurrentInstance();
}
/*
*
*/
/**
* Creates the method expression.
*
* @param expression
* the expression
* @param returnType
* the return type
* @return the method expression
*/
public static MethodExpression createMethodExpression(final String expression, final Class<?> returnType) {
Assert.assertNotNull(expression);
// TODO : check the below line????
JKJsfUtil.logger.fine("createMethodEpression:".concat(expression));
final FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory().createMethodExpression(context.getELContext(), expression, returnType, new Class[0]);
}
/**
* Creates the value exception.
*
* @param value
* the value
* @return the value expression
*/
public static ValueExpression createValueException(final String value) {
return JKJsfUtil.createValueException(value, Object.class);
}
/**
* Creates the value exception.
*
* @param value
* the value
* @param clas
* the clas
* @return the value expression
*/
public static ValueExpression createValueException(final String value, final Class<?> clas) {
final ExpressionFactory expressionFactory = JKJsfUtil.getExpressionFactory();
if (expressionFactory != null) {
final ELContext elContext = FacesContext.getCurrentInstance().getELContext();
final ValueExpression ve1 = expressionFactory.createValueExpression(elContext, value, clas);
return ve1;
} else {
final ELContext elContext = FacesContext.getCurrentInstance().getELContext();
final ValueExpression ve1 = FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(elContext,
value, clas);
return ve1;
}
}
/**
* Creates the value exception with value.
*
* @param originalValue
* the original value
* @return the value expression
*/
public static ValueExpression createValueExceptionWithValue(final Object originalValue) {
return FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(originalValue,
originalValue.getClass());
}
/**
* Creates the view.
*
* @param viewId
* the view id
* @return the UI view root
*/
public static UIViewRoot createView(final String viewId) {
final FacesContext facesContext = FacesContext.getCurrentInstance();
final ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
final UIViewRoot view = viewHandler.createView(facesContext, viewId);
try {
viewHandler.getViewDeclarationLanguage(facesContext, viewId).buildView(facesContext, view);
} catch (final IOException e) {
throw new RuntimeException(e);
}
return view;
}
/**
* Error.
*
* @param message
* the message
*/
public static void error(final String message) {
final FacesMessage msg = new FacesMessage(message);
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* Evaluate expression to object.
*
* @param el
* the el
* @return the object
*/
public static Object evaluateExpressionToObject(final String el) {
if (el == null) {
return null;
}
final Application application = FacesContext.getCurrentInstance().getApplication();
return application.evaluateExpressionGet(FacesContext.getCurrentInstance(), el, Object.class);
}
/**
* Evaluate expression to object.
*
* @param valueExpression
* the value expression
* @return the object
*/
public static Object evaluateExpressionToObject(final ValueExpression valueExpression) {
if (valueExpression == null) {
return null;
}
return JKJsfUtil.evaluateExpressionToObject(valueExpression.getExpressionString());
}
/**
* Attempts to find a value associated with the specified <code>key</code> ,
* using the <code> stateHelper </code> if no such value is found it gets
* the attribute value, in component <code>component</code> with Key
* <code>key</code> if the attribute's value is <code>null</code> it return
* <code>null</code>.
*
* @param component
* the component
* @param stateHelper
* the state helper
* @param key
* the key
* @return {@link Object}
*/
public static Object getAttribute(final UIComponent component, final StateHelper stateHelper, final String key) {
final Object value = stateHelper.eval(key);
return value == null ? JKJsfUtil.getAttribute(component, key, null) : value;
}
/**
* gets the attribute value, in component <code>uiComponent</code> with Key
* <code>key</code> if the attribute's value is <code>null</code> it return
* the value of <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @return the attribute
*/
public static Object getAttribute(final UIComponent component, final String key, final Object defaultValue) {
final Object value = component.getAttributes().get(key);
return value == null ? defaultValue : value;
}
/**
* gets the attribute <code>Boolean</code> value, in component
* <code>uiComponent</code> with Key <code>key</code> </br>
* if the attribute's value is <code>null</code> it return the value of
* <code>defaultValue</code>.
*
* @param uiComponent
* the ui component
* @param key
* the key
* @param defaultValue
* the default value
* @return attribute value
*/
public static boolean getBooleanAttribute(final UIComponent uiComponent, final String key, final boolean defaultValue) {
return new Boolean(JKJsfUtil.getAttribute(uiComponent, key, defaultValue).toString());
}
/**
* Gets the checksum key.
*
* @param currentView
* the current view
* @return the checksum key
*/
private static String getChecksumKey(final String currentView) {
return currentView.concat(JKJsfUtil.CHECKSUM_POSTFIX);
}
/**
* Gets the component attribute.
*
* @param comp
* the comp
* @param attributeName
* the attribute name
* @return the component attribute
*/
public static Object getComponentAttribute(final UIComponent comp, final String attributeName) {
final Map map = JKJsfUtil.getComponentMap(comp);
return map.get(attributeName);
}
/**
* Gets the component map.
*
* @param comp
* the comp
* @return the component map
*/
private static Map getComponentMap(final UIComponent comp) {
final Map<String, Map<String, Map>> viewMap = JKJsfUtil.getViewMap();
Map componentMap = viewMap.get(comp.getClientId());
if (componentMap == null) {
componentMap = new HashMap();
viewMap.put(comp.getClientId(), componentMap);
}
return componentMap;
}
/**
* Gets the current view.
*
* @return the current view
*/
public static String getCurrentView() {
Object viewName = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(TagAttributeConstants.CURRENT_VIEW);
if (viewName != null) {
return viewName.toString();
}
viewName = FacesContext.getCurrentInstance().getAttributes().get(TagAttributeConstants.CURRENT_VIEW);
if (viewName != null) {
return viewName.toString();
}
return FacesContext.getCurrentInstance().getViewRoot().getViewId();
}
/**
* Gets the current view original checksum.
*
* @return the current view original checksum
*/
public static long getCurrentViewOriginalChecksum() {
final String currentView = JKJsfUtil.getCurrentView();
if (currentView == null) {
throw new IllegalStateException("current view is null");
}
final String key = JKJsfUtil.getChecksumKey(currentView);
final Object object = JKJsfUtil.getSessionMap().get(key);
if (object == null) {
throw new IllegalStateException("key : ".concat(key).concat(" not found on sessino ,call saveCurrentViewChecksum before this"));
}
return (Long) object;
}
/**
* Gets the expression factory.
*
* @return the expression factory
*/
public static ExpressionFactory getExpressionFactory() {
if (JKJsfUtil.getFaceletsContext() != null) {
return JKJsfUtil.getFaceletsContext().getExpressionFactory();
} else {
return null;
}
}
/**
* Gets the facelets context.
*
* @return the facelets context
*/
public static FaceletContext getFaceletsContext() {
return (FaceletContext) FacesContext.getCurrentInstance().getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
}
/**
* gets the attribute <code>int</code> value, in component
* <code>uiComponent</code> with Key <code>key</code> </br>
* if the attribute's value is <code>null</code> it return the value of
* <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @return attribute value
*/
public static int getIntegerAttribute(final UIComponent component, final String key, final Object defaultValue) {
return new Integer(JKJsfUtil.getAttribute(component, key, defaultValue).toString());
}
/**
* gets JSF information like JSF version and Faces context.
*
* @return the JSF info
*/
public static Map<String, Object> getJSFInfo() {
final LinkedHashMap<String, Object> details = new LinkedHashMap<String, Object>();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final ViewHandler viewHandler = application.getViewHandler();
final ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, context.getViewRoot().getViewId());
final LifecycleFactory LifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
details.put("JSF-Version", FacesContext.class.getPackage().getImplementationVersion());
details.put("JSF-Version-Package", FacesContext.class.getPackage().getName());
details.put("FacesContext", context.getClass());
details.put("Application", application.getClass());
details.put("ViewHandler", viewHandler.getClass());
details.put("ViewDeclarationLanguage", vdl.getClass());
details.put("LifecycleFactory", LifecycleFactory.getClass());
return details;
}
/**
* Gets the request attribute as boolean.
*
* @param key
* the key
* @param defaultValue
* the default value
* @return the request attribute as boolean
*/
public static boolean getRequestAttributeAsBoolean(final String key, final Object defaultValue) {
final Object value = JKJsfUtil.getRequestMap().get(key);
return ConversionUtil.toBoolean(value == null ? defaultValue : value);
}
/**
* Gets the request map.
*
* @return the request map
*/
public static Map<String, Object> getRequestMap() {
return FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
}
/**
* Gets the session map.
*
* @return the session map
*/
public static Map<String, Object> getSessionMap() {
return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
}
/**
* Gets the view map.
*
* @return the view map
*/
private static Map<String, Map<String, Map>> getViewMap() {
final String viewName = JKJsfUtil.getCurrentView();
Map<String, Map<String, Map>> viewMap = (Map) JKJsfUtil.getSessionMap().get(viewName);
if (viewMap == null) {
viewMap = new HashMap<>();
JKJsfUtil.getSessionMap().put(viewName, viewMap);
}
return viewMap;
}
/**
* Checks if is JS f22.
*
* @return true, if is JS f22
*/
public static boolean isJSF22() {
final String version = FacesContext.class.getPackage().getImplementationVersion();
if (version != null) {
return version.startsWith("2.2");
} else {
// fallback
try {
Class.forName("javax.faces.flow.Flow");
return true;
} catch (final ClassNotFoundException ex) {
return false;
}
}
}
/**
* Save current view checksum.
*/
public static void saveCurrentViewChecksum() {
final String currentView = JKJsfUtil.getCurrentView();
if (currentView == null) {
throw new IllegalStateException("current view is null");
}
final long checksum = JKJsfUtil.calculateCurrentViewChecksum();
JKJsfUtil.getSessionMap().put(JKJsfUtil.getChecksumKey(currentView), checksum);
}
/**
* Sets the component attribute.
*
* @param comp
* the comp
* @param attributeName
* the attribute name
* @param atributeValue
* the atribute value
*/
public static void setComponentAttribute(final UIComponent comp, final String attributeName, final Object atributeValue) {
final Map componentMap = JKJsfUtil.getComponentMap(comp);
componentMap.put(attributeName, atributeValue);
System.err.println("Set Compnent Attribute : " + attributeName + " : " + atributeValue);
}
/**
* Sets the request attribute.
*
* @param key
* the key
* @param value
* the value
*/
public static void setRequestAttribute(final String key, final Object value) {
JKJsfUtil.getRequestMap().put(key, value);
}
/**
* Sets the session attribute.
*
* @param key
* the key
* @param value
* the value
*/
public static void setSessionAttribute(final String key, final Object value) {
JKJsfUtil.getSessionMap().put(key, value);
}
/**
* Success.
*
* @param message
* the message
*/
public static void success(final String message) {
final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", message);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* Visit view.
*
* @param component
* the component
* @return the UI view visitor
*/
public static UIFacesVisitor visitComponent(final UIComponent component) {
final UIFacesVisitor visitor = new UIFacesVisitor();
component.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()), visitor);
return visitor;
}
/**
* Visit current view.
*
* @return the UI faces visitor
*/
public static UIFacesVisitor visitCurrentView() {
return JKJsfUtil.visitComponent(FacesContext.getCurrentInstance().getViewRoot());
}
/**
* Visit view.
*
* @param viewId
* the view id
* @return the UI view visitor
*/
public static UIFacesVisitor visitView(final String viewId) {
final UIViewRoot view = JKJsfUtil.createView(viewId);
final UIFacesVisitor visitor = new UIFacesVisitor();
view.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()), visitor);
return visitor;
}
/**
* Warning.
*
* @param message
* the message
*/
public static void warning(final String message) {
final FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", message);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/**
* writes an attribute to component <code>component</code> with key
* <code>key</code> and default value <code>defaultValue</code>.
*
* @param component
* the component
* @param key
* the key
* @param defaultValue
* the default value
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void writeAttribue(final UIComponent component, final String key, final Object defaultValue) throws IOException {
JKJsfUtil.writeAttribue(component, key, null, defaultValue);
}
/**
* reads the value of with Key <code>sourceKey</code> in component
* <code>component</code>, then gets the response writer and add attribute
* with with Key <code>targetKey</code> and value equal to the retrieved
* previous value in case the retrieved value equal null then the value of
* <code>defaultValue</code> will be used instead Also in case
* <code>targetKey</code> equal null then <code>sourceKey</code> will be
* used instead.
*
* @param component
* the component
* @param sourceKey
* the attribute's key in the UI component
* @param targetKey
* the attribute's key that will be used to add the attribute
* @param defaultValue
* the default value
* @throws IOException
* if an input/output error occurs during response writing
*/
public static void writeAttribue(final UIComponent component, final String sourceKey, final String targetKey, final Object defaultValue)
throws IOException {
final Object value = JKJsfUtil.getAttribute(component, sourceKey, defaultValue);
JKJsfUtil.context().getResponseWriter().writeAttribute(targetKey == null ? sourceKey : targetKey, value, null);
}
/**
*
* @param keepAttributes
*/
public static void invalidateSession(String... keepAttributes) {
if (FacesContext.getCurrentInstance() != null) {
// original map
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = new HashMap(context.getSessionMap());
context.invalidateSession();
HttpSession session = (HttpSession) context.getSession(true);
// restore original attributes
for (String attribute : keepAttributes) {
session.setAttribute(attribute, sessionMap.get(attribute));
}
}
}
public static String getLocalNameFromQName(final String qName) {
final String[] split = qName.split(":");
return split.length == 2 ? split[1] : split[0];
}
public static String getNamespaceLetterFromQName(final String qName) {
final String[] split = qName.split(":");
if (split.length == 1) {
return null;
}
return split[0];
}
public static UIComponent findComponentInRoot(String id) {
UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
UIComponent root = facesContext.getViewRoot();
component = findComponent(root, id);
}
return component;
}
public static UIComponent findComponent(UIComponent base, String id) {
if (id.equals(base.getId()))
return base;
UIComponent kid = null;
UIComponent result = null;
Iterator kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
kid = (UIComponent) kids.next();
if (id.equals(kid.getId())) {
result = kid;
break;
}
result = findComponent(kid, id);
if (result != null) {
break;
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////
public static List<UIComponent> findComponents(UIComponent parent, Class type) {
List<UIComponent> result = new Vector<>();
List<UIComponent> children = parent.getChildren();
for (UIComponent uiComponent : children) {
if (uiComponent.getClass().equals(type)) {
result.add(uiComponent);
}
result.addAll(findComponents(uiComponent, type));
}
return result;
}
/**
*
* @return
*/
public static String getRemoteHostName() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
HttpServletRequest httpServletRequest = (HttpServletRequest) facesContext.getExternalContext().getRequest();
String ip = httpServletRequest.getHeader("X-FORWARDED-FOR");
if (ip == null) {
ip = httpServletRequest.getRemoteAddr();
}
return ip;
}
return null;
}
/**
*
* @param path
* @throws IOException
*/
public static void redirect(String path) throws IOException {
FacesContext currentInstance = FacesContext.getCurrentInstance();
if (currentInstance != null) {
// ExternalContext externalContext =
// currentInstance.getExternalContext();
// HttpServletRequest request = (HttpServletRequest)
// externalContext.getRequest();
// HttpServletResponse response = (HttpServletResponse)
// externalContext.getResponse();
redirect(path, null, null);
} else {
throw new IllegalStateException("your are calling redirect assuming FacesContext is there!!!");
}
}
/**
* add full
*
* @param string
* @param request
* @param response
* relative to context
* @throws IOException
*/
public static void redirect(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
FacesContext currentInstance = FacesContext.getCurrentInstance();
if (currentInstance != null) {
request = (HttpServletRequest) currentInstance.getExternalContext().getRequest();
response = (HttpServletResponse) currentInstance.getExternalContext().getResponse();
}
String fullPath = request.getContextPath() + path;
// if (currentInstance != null) {
// }
String facesRequest = request.getHeader("Faces-Request");
if (facesRequest != null && "partial/ajax".equals(facesRequest)) {
if (currentInstance != null) {
currentInstance.getExternalContext().redirect(fullPath);
currentInstance.responseComplete();
} else {
// // It's a JSF ajax request.
// // the below will useful in case of ajax requests which
// doesn't
// // Recognize redirect
response.setContentType("text/xml");
response.getWriter().append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", fullPath);
}
} else {
// normal full request
response.sendRedirect(fullPath);
}
}
public static void forceClearCache(ServletResponse resp) {
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP
// 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
}
| [
"kiswanij@yahoo.com"
] | kiswanij@yahoo.com |
21fb1c690ba31d758f7096f571177dbb7a321d99 | 7163c53ca8e57976e43daaa7d592921954f9759c | /task06.Book/src/main/java/by/matmux/dao/query/sort_query/SortTitleQuery.java | 97a3dd04c00bf00fbc62cbe687b03080638cd235 | [] | no_license | Akello32/10_JavaST_2020_Task- | ef516fb8211f3eacda1a42ab1dbee4f904e97e2f | 6913621527f5dfff29b21e8932ebbe0525da58cb | refs/heads/master | 2023-02-03T11:16:43.833394 | 2020-12-03T21:27:36 | 2020-12-03T21:27:36 | 297,306,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 674 | java | package by.matmux.dao.query.sort_query;
import by.matmux.beans.Book;
import by.matmux.dao.query.BookQuery;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Set;
public class SortTitleQuery implements BookQuery {
/**
* Implementation of sorting the repository of books by name
* @param storage - book storage
* @return ArrayList with sorted books
*/
@Override
public ArrayList<Book> query(final Set<Book> storage) {
ArrayList<Book> result = new ArrayList<>(storage);
Comparator<Book> comparator = Comparator.comparing(Book::getTitle);
result.sort(comparator);
return result;
}
}
| [
"matmux23@gmail.com"
] | matmux23@gmail.com |
e33828e6bbf3b2e0dfd8a9c28901eb180e630399 | 0676e1bf8e0d6a657847c3f31765ba5107ceb2ad | /src/main/java/com/BookServer2/myProject/BookServiceImpl.java | cee33221e1d8518fe67fb4344e070125d1e35801 | [] | no_license | MarchenkoMark/myProject | d6f9eb514cdb2dcddc5fdf2c48b593ddbff80218 | db439cb7bfb63323b0ede6e8b8f4cd6506390bab | refs/heads/master | 2022-12-11T10:30:03.068057 | 2020-09-10T12:50:39 | 2020-09-10T12:50:39 | 294,370,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 486 | java | package com.BookServer2.myProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("productService")
public class BookServiceImpl implements BookService{
@Qualifier("bookRepository")
@Autowired
private BookRepository bookRepository;
@Override
public Iterable<Book> findAll() {
return bookRepository.findAll();
}
}
| [
"markwalikdj@gmail.com"
] | markwalikdj@gmail.com |
6e64a00249fb8450be4f2d1d712cc4aa9fd389af | 72912736267d698a95b6a67410ee73ae7885cf92 | /iatmi/iatmi-DTO/src/main/java/com/ia/tmi/iatmi/dto/PaseDTO.java | e51cefed9592768b91c2add971bf7f263ff7acba | [] | no_license | Fradantim/IA_PINAMAR | 36885d3561eb01b518756b9e8e25f5b581b0325a | a1762592168296155f51081b30504bc5aca66f32 | refs/heads/master | 2020-08-22T18:54:09.059072 | 2019-10-25T20:43:57 | 2019-10-25T20:43:57 | 216,460,477 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 588 | java | package com.ia.tmi.iatmi.dto;
public class PaseDTO {
private Integer id;
private String nombre;
private Float precio;
public PaseDTO(Integer id, Float precio, String nombre) {
this.id = id;
this.precio = precio;
this.nombre = nombre;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Float getPrecio() {
return precio;
}
public void setPrecio(Float precio) {
this.precio = precio;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| [
"fradantim@pop-os.localdomain"
] | fradantim@pop-os.localdomain |
0bc4d11544ec98e3c2c2e3112e9fda8bf57c1e56 | 09bf3a76211471818bf3fc7f43ac9fada06ab5e6 | /hackathon/catalog/src/main/java/com/hackathon/catalog/utils/exception/InvalidPaginationException.java | 1a2556012cd47489fe7e82eaffc4597a93255784 | [] | no_license | AmanMoglix/moglixGroup | e76febb085af390fb9a76f416b3c602f7eeee186 | 0993801dcbd5a2c6d4476a7cf3b1c7d5af0aa6c2 | refs/heads/master | 2023-08-31T00:55:47.026305 | 2021-10-17T06:35:13 | 2021-10-17T06:35:13 | 408,688,399 | 1 | 6 | null | 2021-09-30T13:34:18 | 2021-09-21T04:35:48 | Java | UTF-8 | Java | false | false | 495 | java | package com.hackathon.catalog.utils.exception;
public class InvalidPaginationException extends RuntimeException {
private static final long serialVersionUID = 5861310537366163L;
public InvalidPaginationException(final String message, final Throwable cause) {
super(message, cause);
}
public InvalidPaginationException(final String message) {
super(message);
}
public InvalidPaginationException(final Throwable cause) {
super(cause);
}
}
| [
"aman.katiyar@moglix.com"
] | aman.katiyar@moglix.com |
88708b6167bd8f3b8489a303bcdb227e80502c40 | 582d7f619b8460c75ed07bbd013ba5165ebd40f3 | /src/arena/BattleBotArena.java | 549c8ecb36a03fcec8d4f125e19a19c34473cc51 | [] | no_license | 1mozolacal/BattleBots3_0Teams | 7d88de0a851f5402722bdde681645d041c59a3a9 | 7da8e6515458a3d762a0d4905d71aa4e8e716b03 | refs/heads/master | 2020-08-10T09:19:51.735839 | 2017-12-11T21:49:35 | 2017-12-11T21:49:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 84,281 | java | package arena;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.LinkedList;
import java.awt.BasicStroke;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.math.*;
import arena.Bullet.BulletType;
import bots.*;
import roles.*;
import java.util.ArrayList;
/**
* <b>Introduction</b>
* <br><br>
* This class implements a multi-agent competitive game application. Players contribute a
* single Java class that defines a "Bot", and these Bots battle each other in a
* multiple round tournament under the control of a BattleBotsArena object. For instructions
* on how to create a Bot, see the documentation in
* the class named <i>Bot</i>. For instructions on how to add Bots to the arena,
* see the documentation for the <i>fullReset()</i> method in this class.<br><br>
*
* <b>The Game Engine</b><br><br>
*
* The Arena attempts to run at 30 frames per second, but the actual frame rate may be
* lower on slower systems. At each frame, the arena does the following for each
* Bot b that is still alive and not <i>overheated</i>:
*
*<ol><li>Gets the team name using <i>b.getTeamName()</i></li>
*
* <li>Gets the next move using <i>b.getMove(BotInfo, boolean, BotInfo[], BotInfo[], Bullet[])</i></li>
*
* <li>Processes the move only if it is legal (i.e. moves are allowed only if no collisions; bullets and messages are allowed only if the max number of bullets is not exceeded)</li>
*
* <li>If the move was SEND_MESSAGE, calls <i>b.outGoingMessage()</i> to get the message from the Bot, then broadcasts it to all live Bots using <i>b.incomingMessage(int, msg)</i></li>
*
* <li>Draws each Bot using <i>b.draw(Graphics)</i></li></ol>
* <br>
* <b>Timing</b><br><br>
*
* The clock records real time in seconds regardless of the actual number of frames
* that have been processed. The clock will run faster when the play is sped up to x2,
* x4, or x8 (do this by mousing over the clock and using the scroll wheel). However, depending
* on the speed of your computer, you may not get 2x, 4x, or 8x as many frames in that time,
* so you should test your Bots at regular speed whenever possible. <br><br>
*
* <b>Bot Movement</b> <br><br>
*
* The arena allows each Bot to move vertically or horizontally at a set speed,
* to fire bullets horizontally or vertically, and to send messages. The speeds
* of the Bots and Bullets are configurable using static constants. The number
* of messages that can be sent is capped, as is the number of bullets that each
* Bot can have on screen at a time (Bot's names show in red when they are
* unable to fire, and a message is broadcast by the referee when a Bot's
* messaging is capped).<br><br>
*
* <b>Info Passed to the Bots</b><br><br>
*
* When asking for a Bot's move, the arena passes an array of Bullets, arrays
* of info concerning live and dead Bots, a boolean indicating whether the Bot
* is currently able to shoot, and a single object containing the public
* information about the Bot itself (see the abstract class Bot for more info
* on all this). No Bot is ever given any access to any internal variables or
* data structures of the arena, the Bullets, or other Bots. <br><br>
*
* <b>Collisions</b> <br><br>
*
* The size of a Bot is defined by the constant <i>Bot.RADIUS</i>. The centre point
* of each Bot is defined as <i>(x+Bot.Radius, y+Bot.RADIUS)</i>, where x and y are
* the top left corner of a square in which the bot is inscribed. The width
* and height of each Bot is <i>Bot.RADIUS * 2</i>. Each Bot has a circular collision
* mask in a radius of Bot.RADIUS from this centre point. Bullets have a single
* point collision mask (the pixel at the front of the Bullet) and are created one
* pixel over from the edge of the Bot that fired them, in the middle of the side
* from which they were fired (i.e. vertical bullets have an x coordinate of
* <i>x+Bot.Radius</i> and horizontal bullets have a y coordinate of <i>y+Bot.RADIUS</i>).
* Two bots have collided if the euclidean distance between their centre points is
* equal to <i>Bot.RADIUS*2</i> or less).<br><br>
*
* <b>Bot CPU Usage</b> <br><br>
*
* Processor time is monitored using calls to <i>System.nanoTime()</i> any time
* a Bot method is used (i.e. for drawing, getting the next move, getting the bot's
* name and team name, message processing, etc.) This is not perfect, but it does
* give an approximate estimate of how
* much CPU each Bot is consuming. A small number of points per round are awarded
* for low CPU usage (see <i>Scoring</i> below). If the cumulative CPU time for any
* Bot exceeds 2 seconds (configurable using the static constants), the Bot will
* <i>overheat</i> and become disabled. At this point, the Bot is replaced by a stock image
* symbol and there will be no more method calls to that particular Bot for
* the remainder of the round.<br><br>
*
* <b>Buggy Bots</b><br><br>
*
* When a Bot throws an exception, the exception is caught by the system and a
* scoring penalty is applied (defined by static constants in this class).<br><br>
*
* <b>Dead Bots</b><br><br>
*
* When a Bot is destroyed, it is replaced with a "dead bot" icon and becomes
* an obstacle on the course. There will be no more method calls to that
* particular Bot for the remainder of the round.<br><br>
*
* <b>Scoring</b><br><br>
*
* Bots are awarded points for each kill (whether or not they are alive when their bullet
* hits), and points for each second they stay alive in the round. The round ends
* after a set time, or after there are 1 or fewer Bots left. If a Bot is left at the
* end of the round, it is awarded time points based for the entire length the round
* would have been if it had continued. Point values are increased each each round.<br><br>
*
* In addition to these base points, there are penalties for each exception thrown, and
* there is a small bonus for low CPU equal to two points minus the number of seconds of
* CPU time used. This bonus allows ties to be broken (e.g. if two Bots each kill four
* other Bots and survive to the end of the round, it is usually possible to declare a
* winner based on CPU time). <br><br>
*
* Five Bots are dropped after each round, until six or fewer Bots are left. So if the
* game starts with 16 Bots(the default) there will be 3 rounds of play. (16 bots, 11 bots,
* and 6 bots respectively).<br><br>
*
* All scoring values and other numbers mentioned in this section can be configured using
* the static constants of this class. In addition, the game can
* be played so that the winning Bot is the one with the highest cumulative score at the
* end of multiple rounds, or it can be the Bot that wins the final round.<br><br>
*
* <b>Debugging Features</b><br><br>
*
* The arena contains a number of features to aid debugging. The screen that comes up
* when the Arena is first run is a "Test Mode" screen that allows you to track CPU time
* and exceptions, view the name and team of each Bot, and check that drawing and
* movement is within the allowed limits. There is also a DEBUG flag that can be
* set to TRUE to view statistics while the game is on. The game can be sped up
* to make it easier to view the outcome of each test match quickly (see the
* notes under <i>Timing</i> above), and pausing the game provides just over one
* second of instant replay to watch your Bots' actions in more detail. Finally,
* there is a "HumanBot" character that you can control with the keyboard to further
* test your Bots' performance.<br><br>
*
*
* @version 1.0 (March 3, 2011) - Initial Release
* @version <br>1.1 (March 10, 2011) - Added correction factor for system.nanoTime(), fixed bug in messaging (was cutting off last character of every message)
* @version <br>1.2 (March 24, 2011) - Added ready flag used in paint and paintBuffer to avoid exceptions from a race condition on startup
* @version <br>1.3 (March 28, 2011) - Load starting team names at beginning of match, icons updated (thanks to Mike Stuart for the new dead bot icon)
* @version <br>1.4 (March 28, 2011) - Improvements in how info is passed to bots: a. Only temp arrays are passed (so bots can't sabotage them); b. A deep copy
* of the BotInfo array for live bots is passed, so that all Bots get the exact same snapshot of where the Bots are (thanks
* to Zong Li for helping uncover the latter issue)
* @version <br>1.5 (March 31, 2011) - Moved bullet processing out of the Bot loop -- now bots are moved first, then bullets are moved (thanks again to Zong Li
* for pointing out this issue)
* @version <br>1.6 (May 30, 2011) - Shuts off sound on stop/destroy now
* @version <br>2.0 (August 9, 2011) - Converted to an application that can be JAR'ed -- the mouse wheel was not working well when embedded in a web page
* @version <br>2.1 (November 30, 2011) - Fixed audio bug
* @author Sam Scott
*
* @version <br>2.2 (April 20, 2015) - Rowbottom added modulus to select extra bots. Sentries excluded.
* Changed BOT_SPEED to 2 to prevent bots hanging on deadBots
*
* @version <br>3.0 (November 15, 2015) - Rowbottom added limited ammo functionality. Bots start out with limited ammo and cannot fire if numBullets < 1
* @version <br>3.1 (November 16, 2015) - Rowbottom extends limited ammo functionality so that liveBots can pickup used ammo off deadBots.
* @version<br>3.2 (November 15, 2015) - Rowbottom changed game parameters to enhance gameplay and extend rounds change scoring
* @version <br>3.3(Mar 2017) - Rowbottom increased bullet size for visibility and made multiple aestetic changes such as showing the round number and cummulative score
* @version <br>3.4(Mar 30 2017) - Rowbottom completed changes and improved stability
* @version <br>4.0(Mar 31 2017) - Added Role class, Roles interface and RoleType enum
* @version <br>4.1(Apr 1 2017) - Added GUI elements
* color ring for teams, arc amount shows health, number shows ammo left
*
*/
public class BattleBotArena extends JPanel implements MouseListener, MouseWheelListener, MouseMotionListener, ActionListener, Runnable {
/**
* Set to TRUE for debugging output
*/
public static final boolean DEBUG = true;
/**
* @author rowbottomn
* used to allow for unlimited distance to use healing and supplying
*/
public static final boolean OMNI_SPECIALS = true;
//***********************************************
// MAIN SET OF CONSTANTS AVAILABLE TO THE BOTS...
//***********************************************
/**
* Rowbottom For bot to request to stay in position
*/
public static final int STAY = 0;
/**
* For bot to request a move up
*/
public static final int UP = 1;
/**
* For bot to request a move down
*/
public static final int DOWN = 2;
/**
* For bot to request a move left
*/
public static final int LEFT = 3;
/**
* For bot to request a move right
*/
public static final int RIGHT = 4;
/**
* For bot to request a bullet fired up
*/
public static final int FIREUP = 5;
/**
* For bot to request a bullet fired down
*/
public static final int FIREDOWN = 6;
/**
* For bot to request a bullet fired left
*/
public static final int FIRELEFT = 7;
/**
* For bot to request a bullet fired right
*/
public static final int FIRERIGHT = 8;
/**
* For bot to request to use its special move
*/
public static final int SPECIAL = 9;
/**
* For bot to request a message send. If allowed, the arena will respond with a call to the bot's outGoingMessage() method.
*/
public static final int SEND_MESSAGE = 10;
/**
* Rowbottom team chat messages are not capped
*/
public static final int SEND_TEAM = 11;
/**
* Rowbottom for send a team messagea bot to request healing, this will send a special message to the
*/
public static final int REQUEST_HEALING = 12;
/**
* Rowbottom for a bot to request ammo
*/
public static final int REQUEST_AMMO = 13;
/**
* Right edge of the screen
*/
public static final int RIGHT_EDGE = 700; // also arena panel width
/**
* Bottom edge of the screen
*/
public static final int BOTTOM_EDGE = 500; // arena panel height is this constant + TEXT_BUFFER
/**
* Left edge of the screen
*/
public static final int LEFT_EDGE = 0;
/**
* Top edge of the screen
*/
public static final int TOP_EDGE = 10;
/**
* The "bot id" that indicates a system message
*/
public static final int SYSTEM_MSG = -1;
//*****************************************
// GAME CONFIGURATION - CHANGE WITH CAUTION
// BOTS ALSO HAVE ACCESS TO THESE CONSTANTS
//*****************************************
/**
* points per kill
*/
public static final int KILL_SCORE = 5;//Rowbottom changed from 5
/**
* survival points
*/
public static final double POINTS_PER_SECOND = 0.05;//Rowbottom changed from 0.1
/**
* healing points
*/
public static final double POINTS_PER_HEAL = 10;//Rowbottom changed from 0.1
/**
* points per unused second of processor time (mostly for breaking ties)
*/
public static final int EFFICIENCY_BONUS = 1;
/**
* points off per exception caught
*/
public static final int ERROR_PENALTY = 1;// Rowbottom changed from 5
/**
* true = scores between rounds are cumulative
* false = highest scoring Bot in last round is declared the winner
*/
public static final boolean CUMULATIVE_SCORING = true;
/**
* Number of bots to drop out per round
*/
public static final int ELIMINATIONS_PER_ROUND = 0;//Rowbottom changed from 5
/**
* Round time, in seconds
*/
public static final int TIME_LIMIT = 100;
/**
* TIME_LIMIT / SECS_PER_MSG = Number of messages allowed per round
*/
public static final double SECS_PER_MSG = 0.5; //
/**
* CPU limit per Bot per round
*/
public static final double PROCESSOR_LIMIT = 2.0;
/**
* Total number of Bots in round 1 (if you have fewer than this, the rest of the spots
* in the array will be filled with Drones, RandBots, and Sentries).
*/
public static final int NUM_BOTS = 16;
/**
* Rowbottom
* Not used*Number of bullets on screen at once for each bot
*/
public static final int NUM_BULLETS = 4;
/**
* Bot speed in pixels/frame
*/
public static final double BOT_SPEED = 2.0;
/**
* Bullet speed in pixels/frame
*/
public static final double BULLET_SPEED = 8;
/**
* Maximum message length
*/
public static final int MAX_MESSAGE_LENGTH = 200;
/**
* Initial ammo as part of limited ammo functionality
* !Passed to the botInfo for its value.
*/
public static final int BULLETS_LEFT = 20;//ROWBOTTOM Ammo!
/**
* When ELIMINATIONS_PER_ROUND is set to 0 then
* NUM_ROUNDS determines the final round
*/
public static final int NUM_ROUNDS = 20;//ROWBOTTOM Rounds will be NUM_ROUNDS
//**************************************
// OTHER ARENA CONSTANTS -- DON'T CHANGE
//**************************************
/**
* Size of message area at bottom of screen.
*/
private static final int TEXT_BUFFER = 100;
/**
* @author Rowbottom
*
*/
public static final int TEAM_SIZE = 4;
/**
* How fast the clock flashes when game paused
*/
private final int PAUSE_FLASH_TIME = 8;
/**
* How fast the red circles flash in test mode
*/
private final int FLASH_TIME = 10;
/**
* State constant to signal we are between rounds
*/
private final int WAIT_TO_START = 1;
/**
* State constant to signal that the game is on
*/
private final int GAME_ON = 2;
/**
* State constant to signal that we are between rounds
*/
private final int GAME_OVER = 3;
/**
* State constant to signal that the game is paused
*/
private final int GAME_PAUSED = 4;
/**
* State constant to signal game over and winner declared
*/
private final int WINNER = 5;
/**
* State constant to signal we are in test mode (starts in this mode)
*/
private final int TEST_MODE = 6;
/**
* Size of the bot names
*/
private final int NAME_FONT = 10;
/**
* Size of the stats font (stats displayed at end of each round)
*/
private final int STATS_FONT = 15;
/**
* Number of frames in the buffer for instant replay (limited by heap size)
*/
private final int NUM_FRAMES = 40;
/**
* Ticks per frame in replay mode. Higher for a slower replay.
*/
private final int REPLAY_SPEED = 2;
/**
* How many frames to hold on the last frame before restarting the instant replay.
*/
private final int END_FRAME_COUNT = 15;
/**
* File name for fanfare sound (plays at start of round)
*/
private final String fanfareSoundFile = "FightLikeARobot.wav";
/**
* File name for shot sound
*/
private final String shotSoundFile = "Shot.wav";
/**
* File name for robot death sound
*/
private final String deathSoundFile = "Death.wav";
/**
* File name for drone sound during game
*/
private final String droneSoundFile = "def_star2.wav";
/**
* File name for opening sound (plays during opening screen)
*/
private final String openSoundFile = "crystalcastles.wav";
/**
* File name for stop sound (plays when pausing game)
*/
private final String stopSoundFile = "qix.wav";
/**
* File name for game over sound
*/
private final String gameOverSoundFile = "GameOver.wav";
/**
* File name for overheat sound
*/
private final String overheatSoundFile = "dp_frogger_squash.wav";
//**************************************
// OTHER ARENA VARIABLES -- DON'T CHANGE
//**************************************
/**
* If set to true, the arena will display Bot Ammo during the game.
*/
private boolean showAmmo = true;
/**
* If set to true, the arena will display Bot scores during the game.
*/
private boolean showScores = false;
/**
* If set to true, the arena will display Bot names during the game.
*/
private boolean showNames = false;
/**
* Rowbottom Teams are displayed by color now so not needed
* If set to true, the arena will display Bot team names during the game.
*/
//private boolean showTeams = false;
/**
* Rowbottom Color array used to store the teams visually
*
*/
Color [] teamColors = new Color[]{Color.GREEN, Color.BLUE, Color.RED, Color.YELLOW};
/**
* Toggles sound effects on and off
*/
private boolean soundOn = true;
/**
* The current speed multiplier
*/
private int speed = 8;//changed from 1
/**
* Controls the flashing if the game is paused
*/
private int pauseCount = 0;
/**
* The winner of the game
*/
private int winnerID = -1;
/**
* Countdown to the start of the game ("Fight like a robot!")
*/
private int countDown = -1;
/**
* Counter for flashing the clock in pause mode
*/
private int flashCounter = 0;
/**
* The bot we are dragging (test mode)
*/
private int gotBot = -1;
/**
* For dragging a bot (test mode)
*/
private int forceBotX, forceBotY, mouseInitialX, mouseInitialY;
/**
* The main state variable - controls what phase of the game we are at (see the State constants)
*/
private int state = WAIT_TO_START; // state variable
/**
* Used when going into test mode - false while bots are being set up, constructors called, etc.
*/
private boolean ready = false;
/**
* The current round
*/
private int round = 0;
/**
* which message is displayed first - for scrolling messages
*/
private int firstMessage = 0;
/**
* Double-buffering
*/
private Image buffer;
/**
* Dead Bot image
*/
private Image deadBot;
/**
* Overheated Bot image
*/
private Image overheated;
/**
* For timing the game length
*/
private long startTime;
/**
* For continuing correct timing after a pause
*/
private long pauseTime;
/**
* On some machines, System.nanoTime() returns incorrect results. For example, on one machine
* System.currentTimeMillis() shows 10 seconds elapsed while System.nanoTime() consistently shows
* 4.5 seconds elapsed for the same time period. The more reliable millisecond timing is used
* for the game clock, however for timing CPU usage of the Bots, we need a higher grain than 1ms.
* So System.nanoTime() is used, but a correction factor is computed in a thread spawned at
* startup time, and this becomes a multiplier for the number of ns that System.nanoTime() reports
* has elapsed.
*/
private double nanoTimeCorrection = 1;
/**
* Total time played
*/
private double timePlayed = 0;
/**
* Object for formatting decimals
*/
private DecimalFormat df = new DecimalFormat("0.0"), df2 = new DecimalFormat("0.000");
/**
* The main game engine timer
*/
private Timer gameTimer;
/**
* Main array of Bot objects. Note that bots, botsInfo, and bullets are related arrays - bullets[i]
* gives the array of bullets owned by bot[i], and botsInfo[i] gives the public info
* for bot[i].
*/
private Bot[] bots = new Bot[NUM_BOTS];
/**
* Array of public info regarding the Bots - this is how information is passed to
* the Bots in getMove(). Done this way so the Bots don't have access to each others'
* internal states. Note that bots, botsInfo, and bullets are related arrays - bullets[i]
* gives the array of bullets owned by bot[i], and botsInfo[i] gives the public info
* for bot[i].
*/
private BotInfo[] botsInfo = new BotInfo[NUM_BOTS];
/**
* The bullets. Note that bots, botsInfo, and bullets are related arrays - bullets[i]
* gives the array of bullets owned by bot[i], and botsInfo[i] gives the public info
* for bot[i].
* V3.0 Rowbottom the array of bullets needs to be as large as the attacks numBullets
*/
private Bullet[][] bullets = new Bullet[NUM_BOTS][Role.ATTACK_BULLETS];
/** @author Rowbottom
* Inner class which supports the roles modification to the bots and the arena code.
* The array is set as copies of the Role reported to the arena by each bot.
* A copy must be made so that the bot does not have access to its role variables and methods.
**/
private Role[] botRoles = new Role[NUM_BOTS];
/**
* Number of bots remaining in the round.
*/
private int botsLeft = NUM_BOTS;
/**
* Message buffer
*/
private LinkedList<String> messages = new LinkedList<String>();
/**
* Team messages let the medic and support know who needs help
*/
private String teamMsg;
/**
* The images to use in instant replay. This is a circular buffer.
*/
private Image[] replayImages = new Image[NUM_FRAMES];
/**
* The latest frame. The head pointer of the circular buffer called replayImages.
*/
private int replayEndFrame = 0;
/**
* In instant replay mode, this is the frame we are currently presenting.
*/
private int replayCurrentFrame = 0;
/**
* Counter for holding on the last frame before resetting the instant replay.
*/
private int endFrameCounter = 0;
/**
* Counter for deciding when to advance the frame during an instant replay.
*/
private int replayCounter = 0;
/**
* This is a buffer that holds the images the Bots are requesting to load.
* Since bots don't have access to the arena as an image observer, the images
* in this list are painted off screen until g.drawImage() returns true. This
* ensures that all images get loaded ASAP whether the Bots are using them
* or not, and that callbacks happen and trigger a repaint when images are
* loaded.
*/
private LinkedList<Image> imagesToLoad = new LinkedList<Image>();
/**
* Holds an audioclip for arena sound.
*/
AudioClip death, fanfare, shot, drone, open, stop, gameOver, overheat;
//***************************************
// METHODS YOU NEED TO CHANGE
//***************************************
/**
* This method is called at the start of each new game, before the test mode
* screen comes up. It creates all the Bots that will participate in the game,
* and resets a few game constants.
*
* NOTE: This is where you add your own bots. See the instructions in the
* method below...
*/
private void fullReset()
{
ready = false; // Signals to the paint methods that the Bots are not set up yet
if (soundOn) open.play(); // Play the fanfare
state = TEST_MODE; // We start in test mode
gameTimer.start(); // start the timer thread if necessary
bots = new Bot[NUM_BOTS]; // the bots
round = 0; // pre-game is round 0
// *** HUMAN TEST BOT CREATION
// *** Comment the next two lines out if you don't want to use the
// *** HumanBot (under user control)
//bots[0] = new HumanBot();
//addKeyListener((HumanBot)bots[0]);
// ******************************
// *** INSERT PLAYER BOTS HERE. Use any array numbers you like
// *** as the bots will be shuffled again later.
// *** Any empty spots will be filled with standard arena bots.
// bots[9] = new AIBot();
//bots[0] = new Bott(); //blend
//bots[1] = new ZuccBot();//ben
//bots[2] = new The4992Bot();//calvin
// *******************************
// Remaining slots filled with Drones, RandBots, and sentryBots.
int c = 1;
for (int i=0; i<NUM_BOTS; i++)
{
//if there is an empty space fill it with sentries
if (bots[i] == null)
{
/**
* @rowbottom
* below places the randbot at different roles to test the effect
*/
if ((i+i/TEAM_SIZE)%TEAM_SIZE ==0)
bots[i] = new RandBot();
// else if (c%2 ==1)
// bots[i] = new RandBot();
else{
// {
bots[i] = new TestBot();
//c=0;
}
c++;
}
}
botRoles = getRoles(bots);//Rowbottom get the roles from the bots
reset(); // calls the between-round reset method
}
//***************************************
// METHODS YOU SHOULD *NOT* CHANGE
//***************************************
/**
* Main method to create and display the arena
* @param args unused
*/
public static void main(String[] args)
{
JFrame frame = new JFrame();//set up the frame
BattleBotArena panel = new BattleBotArena();//instantiate the arena
frame.setContentPane(panel);//create the frame panel
frame.pack();
frame.setTitle("BattleBots");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
panel.init();
panel.requestFocusInWindow();
}
/**
* One-time setup for images, sounds, listeners, buffers, and game timer.
**/
public BattleBotArena ()
{
// start the calibration timer (see run method below for more info)
(new Thread(this)).start();
// create the game thread
gameTimer = new Timer(1000/30/speed,this);
// sounds
URL location = getClass().getClassLoader().getResource("sounds/"+fanfareSoundFile);
fanfare = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+shotSoundFile);
shot = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+deathSoundFile);
death = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+droneSoundFile);
drone = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+openSoundFile);
open = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+stopSoundFile);
stop = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+gameOverSoundFile);
gameOver = Applet.newAudioClip(location);
location = getClass().getClassLoader().getResource("sounds/"+overheatSoundFile);
overheat = Applet.newAudioClip(location);
// images
deadBot = Toolkit.getDefaultToolkit ().getImage (getClass().getClassLoader().getResource("images/dead.png"));
overheated = Toolkit.getDefaultToolkit ().getImage (getClass().getClassLoader().getResource("images/overheated.png"));
// Listeners for mouse input
addMouseListener (this);
addMouseMotionListener (this);
addMouseWheelListener (this);
// Set size of panel and make it focusable
setPreferredSize(new Dimension(700, 600));
setFocusable(true);
}
private void init()
{
// Paint buffer and instant replay array
for (int i = 0; i<NUM_FRAMES; i++)
replayImages[i] = createImage(RIGHT_EDGE, BOTTOM_EDGE);
buffer = createImage(RIGHT_EDGE, BOTTOM_EDGE+TEXT_BUFFER);
// Set up the bots and the game
fullReset();
}
/**
* Reset for a new round. Called between rounds, and also after a full reset.
*/
private void reset()
{
HelperMethods.say("reseting");
timePlayed = 0; // reset the clock
round ++; // advance the round
botsLeft = NUM_BOTS; // put all the bots back in the game
messages = new LinkedList<String>();// clear the messag buffer
//Rowbottom No longer needed as positions are set by the team placement
/*// shuffle the bots
for (int i=0; i<NUM_BOTS*10; i++)
{
int b1 = (int)(Math.random()*NUM_BOTS);
int b2 = (int)(Math.random()*NUM_BOTS);
Bot temp = bots[b1];
bots[b1] = bots[b2];
bots[b2] = temp;
BotInfo temp2 = botsInfo[b1];
botsInfo[b1] = botsInfo[b2];
botsInfo[b2] = temp2;
}
*/
// Clear the array of public Bot info. (This is the info given to the Bots when making their moves.)
BotInfo[] newBotsInfo = new BotInfo[NUM_BOTS];
Role[] newBotRoles = new Role[NUM_BOTS];
if (state == TEST_MODE) // we are restarting. everything is reset
{
int xScale = (RIGHT_EDGE-Bot.RADIUS*4)/Math.max(NUM_BOTS-1,1); // this spaces them out so they don't rez on top of each other
int yScale = (BOTTOM_EDGE-Bot.RADIUS*4)/5;
int[][] grid = new int[NUM_BOTS][5];
for (int i = 0; i < NUM_BOTS; i++)
{
//bots[i].assignNumber(i); // assign new numbers
int x = (int)(Math.random()*NUM_BOTS);
int y = (int)(Math.random()*5);
newBotRoles[i] = new Role(botRoles[i].getRole());
newBotsInfo[i] = new BotInfo(x*xScale + Bot.RADIUS, y*yScale + Bot.RADIUS, i, bots[i].getName(), newBotRoles[i]); // create new BotInfo object to keep track of bot's stats
// HelperMethods.say("role"+newBotRoles[i].getRole());
//Rowbottom as of 3.0 teams are no longer newBotsInfo[i].setTeamName(bots[i].getTeamName()); // get start of game team names
newBotsInfo[i].setTeamName("Team"+(i/TEAM_SIZE+1));//Rowbottom teams are set by the order in the bot array
if (grid[x][y] == 1)
i--;
else
grid[x][y] = 1;
}
}
else
{
//Rowbottom placement is by teams now and manual
int[] xs = new int[]{
//team 1 top left corner (3 & 5 right, 7 & 9 down)
3*Bot.RADIUS,7*Bot.RADIUS, 3*Bot.RADIUS,7*Bot.RADIUS,
//team 2 top right corner(7 & 9 left, 3 & 5 down)
RIGHT_EDGE - 19*Bot.RADIUS,RIGHT_EDGE - 15*Bot.RADIUS,
RIGHT_EDGE - 19*Bot.RADIUS,RIGHT_EDGE - 15*Bot.RADIUS,
//team 3 bottom left corner(7 & 9 right, 3 & 5 up)
13*Bot.RADIUS, 17*Bot.RADIUS,13*Bot.RADIUS, 17*Bot.RADIUS,
//team 4 bottom right corner(3 & 5 left, 7 & 9 up)
RIGHT_EDGE - 9*Bot.RADIUS,RIGHT_EDGE - 5*Bot.RADIUS,
RIGHT_EDGE - 9*Bot.RADIUS,RIGHT_EDGE - 5*Bot.RADIUS
};
int[] ys = new int[]{
//team 1 (3 & 5 in, 7 & 9 down)
14*Bot.RADIUS,18*Bot.RADIUS, 18*Bot.RADIUS,14*Bot.RADIUS,
//team 2 (7 & 9 left, 3 & 5 down)
8*Bot.RADIUS, 4*Bot.RADIUS,4*Bot.RADIUS, 8*Bot.RADIUS,
//team 3 bottom left corner(7 & 9 right, 3 & 5 up)
BOTTOM_EDGE - 5*Bot.RADIUS,BOTTOM_EDGE - 9*Bot.RADIUS,
BOTTOM_EDGE - 9*Bot.RADIUS,BOTTOM_EDGE - 5*Bot.RADIUS,
//team 4 bottom right corner(3 & 5 left, 7 & 9 up)
BOTTOM_EDGE - 19*Bot.RADIUS,BOTTOM_EDGE - 15*Bot.RADIUS,
BOTTOM_EDGE - 15*Bot.RADIUS,BOTTOM_EDGE - 19*Bot.RADIUS
};
for (int i = 0; i < NUM_BOTS; i++)
{
//Not needed anymorebots[i].assignNumber(i); // assign new numbers
//make new botInfo objects and roles, note that these will have health and ammo values depending on roles
newBotRoles[i] = new Role(botRoles[i].getRole());
newBotsInfo[i] = new BotInfo(xs[i], ys[i], i, botsInfo[i].getName(), newBotRoles[i]);
//Rowbottom as of 3.0 teams are no longer newBotsInfo[i].setTeamName(bots[i].getTeamName()); // get start of game team names
newBotsInfo[i].setTeamName("Team"+(i/TEAM_SIZE+1));//Rowbottom teams are set by the order in the bot array
if (botsInfo[i] != null && CUMULATIVE_SCORING && round > 1)
newBotsInfo[i].setCumulativeScore(botsInfo[i].getCumulativeScore()+botsInfo[i].getScore());
if (botsInfo[i] != null && (botsInfo[i].isOut() || botsInfo[i].isOutNextRound()))
{
newBotsInfo[i].knockedOut();
botsLeft--;
}
//System.out.println(bots[i].getName()+ " "+newBotsInfo[i].getName()+" "+newBotsInfo[i].isOut());
}
}
botsInfo = newBotsInfo;
botRoles = newBotRoles;
// load the images & call the newRound message for the bots
for (int i = 0; i < NUM_BOTS; i++)
{
loadImages (i);
// BOT METHOD CALL - timed and exceptions caught
long startThink = System.nanoTime();
try {
bots[i].newRound();
}
catch (Exception e)
{
botsInfo[i].exceptionThrown(e);
}
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
}
bullets = new Bullet[NUM_BOTS][Role.ATTACK_BULLETS]; // init the bullets array
ready = true; // tell the paint method we're good to go
// In test mode, spam the message area with these instructions
if (state == TEST_MODE)
{
sendMessage(-1,"Battle Bots 3.0");
sendMessage(-1,"------------------------------------------------");
sendMessage(-1,"Developed in 2011 as a programming challenge for");
sendMessage(-1,"grade 12 (ICS4U) students.");
sendMessage(-1,"Modified in 2015 to add ammo limits ");
sendMessage(-1,"Modified in 2017 to add team roles ");
sendMessage(-1,"Each bot is in its own class, and is under its own control. Bots");
sendMessage(-1,"declare their names once at the beginning, and are assigned into teams");
sendMessage(-1,"they can no longer change allegiances throughout the game.");
sendMessage(-1," ");
sendMessage(-1,"Bots choose their actions 30 times per second. If the action is");
sendMessage(-1,"legal, the arena allows it. The arena processes all collisions and");
sendMessage(-1,"handles all the scoring. Bots do not have direct access to the code ");
sendMessage(-1,"or instance variables of the other bots, the bullets, or the arena.");
sendMessage(-1,"Bots can send broadcast messages to one another, and periodically");
sendMessage(-1,"receive messages from the referee. All messaging appears in this");
sendMessage(-1,"window.");
sendMessage(-1," ");
sendMessage(-1,"All exceptions are caught and counted, with a scoring penalty for");
sendMessage(-1,"each one. CPU use is monitored and bots will overheat and become");
sendMessage(-1,"disabled when they go over the limit. Tie-breaking points are");
sendMessage(-1,"awarded for low CPU use.");
sendMessage(-1," ");
sendMessage(-1,"Use the menu buttons on the right to control the view and the sound.");
sendMessage(-1,"When the game is on, click the clock to pause and view the instant ");
sendMessage(-1,"replay, or mouse over the clock and use the scroll wheel to speed up ");
sendMessage(-1,"and slow down the game. Use the scroll wheel in this message window");
sendMessage(-1,"to view old messages.");
sendMessage(-1," ");
sendMessage(-1,"HAVE FUN!");
sendMessage(-1,"------------------------------------------------");
sendMessage(-1," ");
sendMessage(-1,"Hello. I am your referee.");
sendMessage(-1,"We are currently in test mode.");
sendMessage(-1,"Draw test - Each bot should be in a red circle.");
sendMessage(-1,"Move test - Bots can be dragged with the mouse.");
sendMessage(-1,"Code test - Numbers show exceptions and processor time.");
sendMessage(-1,"Scroll up to see more info and credits.");
}
}
/**
* Loads images for the bots
* @param botNum
*/
private void loadImages(int botNum)
{
String[] imagePaths = null; // file names
Image[] images = null; // images
// 1. get the image names
// BOT METHOD CALL - timed and exceptions caught
long startThink = System.nanoTime();
try {
imagePaths = bots[botNum].imageNames();
} catch (Exception e) {
botsInfo[botNum].exceptionThrown(e);
}
botsInfo[botNum].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
// 2. load the images if there are any to load
if (imagePaths != null)
{
images = new Image[imagePaths.length];
for (int i=0; i<imagePaths.length; i++)
{
try {
images[i] = Toolkit.getDefaultToolkit ().getImage (getClass().getClassLoader().getResource("images/"+imagePaths[i]));
imagesToLoad.add(images[i]);
} catch (Exception e) {
botsInfo[botNum].exceptionThrown(e);
}
}
// 3. pass the messages to the Bot
// BOT METHOD CALL - timed and exceptions caught
startThink = System.nanoTime();
try {
bots[botNum].loadedImages(images);
} catch (Exception e) {
botsInfo[botNum].exceptionThrown(e);
}
botsInfo[botNum].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
}
}
/**
* This method is for the thread computes the correction factor for System.nanoTime(). See
* the documentation of the field "nanoTimeCorrection" for more information. The thread is
* spawned by the init() method, and should be complete and no longer running after about 20s.
*/
public void run()
{
//pause for setup
try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
//repeatedly test ms and ns timers for 1 second intervals and compute the
//correction for System.nanoTime() assuming currentTimeMillis() is accurate
double totalms = 0, totalns = 0;
for (int i=0; i<10; i++)
{
double start = System.currentTimeMillis();
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
totalms += (System.currentTimeMillis()-start)/1000.0;
//System.out.println("millisecond timer ... "+totalms);
start = System.nanoTime();
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
totalns += (System.nanoTime()-start)/1000000000.0;
//System.out.println("nanosecond timer ... "+totalns);
nanoTimeCorrection = totalms/totalns;
if (DEBUG)
System.out.println("nanoTimeCorrection after "+(i+1)+" seconds = "+nanoTimeCorrection);
}
requestFocus();
}
/**
* The main game method - called by the timer. Handles all the
* mechanics of the game, the replay mode, and the test mode screen.
*/
public void actionPerformed(ActionEvent ace)
{
// **** are we moving bots around?
if (state == GAME_ON && countDown <= 0 || state == TEST_MODE && ready)
{
if (state != TEST_MODE) // advance the timer or...
{
long timeNow = System.currentTimeMillis();
timePlayed += (timeNow - startTime)/1000.0*speed;
startTime = timeNow;
}
else // ...flash the red rings around the bots in test mode
{
flashCounter--;
if (flashCounter < 0)
flashCounter = FLASH_TIME;
}
// **** game over?
if (state != TEST_MODE && (timePlayed >= TIME_LIMIT || botsLeft <= 1))
{
state = GAME_OVER;
//resetGameSpeed();
endFrameCounter = END_FRAME_COUNT; // start the instant replay
replayCurrentFrame = replayEndFrame;
drone.stop(); // stop the sound
if (soundOn)
gameOver.play();
if (botsLeft == 1) // if there is a bot left, update its score
for (int i=0; i<NUM_BOTS; i++)
if (botsInfo[i].isDead() == false && botsInfo[i].isOut() == false)
{
botsInfo[i].setScore(currentScore(i, true));
break;
}
// knock out up to ELIMINATIONS_PER_ROUND bots
int knockedOut = 0;
int totalOut = 0;
BotInfo[] sortedBots = sortedBotInfoArray(false);
for (int i=0; i<NUM_BOTS && knockedOut<ELIMINATIONS_PER_ROUND; i++)
{
if (!sortedBots[i].isOut())
{
sortedBots[i].outNextRound();
knockedOut++;
}
totalOut++;
}
// find the winner
sortedBots = sortedBotInfoArray(true);
winnerID = sortedBots[0].getBotNumber();
if (totalOut >= NUM_BOTS-1 || round >= NUM_ROUNDS) // is this the last round?
{
sendMessage(-1,"Final round complete. "+sortedBots[0].getName()+" is the winner.");
state = WINNER;
}
else
if (CUMULATIVE_SCORING) // different message depending on scoring type
sendMessage(-1,"Round "+round+" complete. "+sortedBots[0].getName()+" is leading.");
//ROWBOTTOM
if (round < NUM_ROUNDS && ELIMINATIONS_PER_ROUND == 0) // clicked on the wait to start message bar
{
if (soundOn)
fanfare.play();
countDown = 60;
startTime = System.currentTimeMillis();
gameTimer.start();
if (round == NUM_ROUNDS)
sendMessage(SYSTEM_MSG,"Final Round starting. Good luck!");
else
sendMessage(SYSTEM_MSG,"Round "+round+" starting. Good luck!");
state = GAME_ON;
reset();
}
else
sendMessage(-1,"Round "+round+" complete. "+sortedBots[0].getName()+" is the winner.");
}
else //**** GAME IS ON
{
// A. increment the circular replay buffer
if (++replayEndFrame == NUM_FRAMES)
replayEndFrame = 0;
// B. create copies of all the bullet and Bot info to pass to each
// Bot when getting their moves
LinkedList<Bullet> bulletList = new LinkedList<Bullet>();
BotInfo[] liveBots = new BotInfo[botsLeft];
Role[] liveRoles = new Role[botsLeft];
int nextLiveBotIndex = 0;
BotInfo[] deadBots = new BotInfo[NUM_BOTS-(round-1)*ELIMINATIONS_PER_ROUND-botsLeft];
int nextDeadBotIndex = 0;
for (int j=0; j<NUM_BOTS; j++)
{
if (!botsInfo[j].isOut())
if (!botsInfo[j].isDead())
liveBots[nextLiveBotIndex++] = botsInfo[j];//copying THE REFERENCES of the alive bots into a smaller array
else
deadBots[nextDeadBotIndex++] = botsInfo[j].copy(); // important to deep copy or else some
// bots will get info about the current move
// for some of the other bots
int bulletCount =0;
for (int k=0; k<botRoles[j].getNumBullet(); k++){
if (bullets[j][k] != null)//l&&bullets[j][k].type == BulletType.BULLET)
{
bulletList.add(bullets[j][k]);
bulletCount++;
}
}
}
// C. process moves for each bot
for (int i = 0; i<NUM_BOTS; i++)
{
// only move bot if it's active
if (!botsInfo[i].isOverheated() && !botsInfo[i].isDead() && !botsInfo[i].isOut())
{
// Update Bot's Score
botsInfo[i].setScore(currentScore(i, false));
// Check think time to see if over limit
if (botsInfo[i].getThinkTime() > PROCESSOR_LIMIT && state != TEST_MODE)
{
botsInfo[i].overheated();
if (soundOn)
overheat.play();
sendMessage(SYSTEM_MSG, botsInfo[i].getName()+" overheated - CPU limit exceeded.");
}
else //bot still alive! Process move
{
long startThink = System.nanoTime();
// 1. Rowbottom No longer supporting changing teamsGet bot team name
/*// BOT METHOD CALL - timed and exceptions caught
try {
botsInfo[i].setTeamName(bots[i].getTeamName());
}
catch(Exception e)
{
botsInfo[i].exceptionThrown(e);
}
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
*/
// ***********************
// 2. set up to get the next move
// 2a. Can the current bot shoot?
BotInfo currentBot = botsInfo[i].copy(); // current Bot
currentBot.setRole(botRoles[i].getRole());
currentBot.setBulletsLeft(botRoles[i].getBulletsLeft());
currentBot.setHealth(botRoles[i].getHealth());
//HelperMethods.say("currentrole"+currentBot.getRole());
//Role currentRole = botRoles[i];
boolean shotOK = false; // can shoot?
boolean specialOK= false;
int bulletCount = 0;
for (int j=0; j<botRoles[i].getNumBullet(); j++)
{
if (bullets[i][j] == null && botRoles[i].getBulletsLeft() > 0){
shotOK = true;
//rowbottom specifiying whether each class can use their special
if (botRoles[i].getRole() == RoleType.MEDIC || botRoles[i].getRole() == RoleType.SUPPORT){
specialOK = true;
}
else if (botRoles[i].getRole() == RoleType.TANK){
bulletCount ++;
}
}
if (bulletCount > 2&&botRoles[i].getRole() == RoleType.TANK){
specialOK = true;
}
}
//System.out.println("Bot"+i+"'s bullets"+currentBot.getBulletsLeft()+","+shotOK);
// 2b. The bots have to be passed temp arrays of bullets so they can't
// mess them up (e.g. by setting array entries to null)
Bullet[] cleanBulletArray = new Bullet[bulletList.size()];
int cleanBAIndex = 0;
Iterator<Bullet> it = bulletList.iterator();
while (it.hasNext())
cleanBulletArray[cleanBAIndex++] = it.next();
// 2c. For the same reason, they must get temp arrays of live and dead bots too.
// We also remove the current bot from the list of livebots here.
BotInfo[] cleanLiveBotsArray = new BotInfo[liveBots.length-1];
int k = 0;
for (int j=0; j<liveBots.length; j++)
if (liveBots[j].getBotNumber() != currentBot.getBotNumber())
cleanLiveBotsArray[k++] = liveBots[j].copy(botRoles[i]);//this ensures the other roles do not get extra info
BotInfo[] cleanDeadBotsArray = new BotInfo[deadBots.length];
for (int j=0; j<deadBots.length; j++)
cleanDeadBotsArray[j] = deadBots[j];
// 3. now, get the move
int move = -1;
// BOT METHOD CALL - timed and exceptions caught
startThink = System.nanoTime();
try {
// HelperMethods.say("currentRole"+currentBot.getRole());
move = bots[i].getMove(currentBot, shotOK, cleanLiveBotsArray, cleanDeadBotsArray, cleanBulletArray);
}
catch(Exception e)
{
botsInfo[i].exceptionThrown(e);
}
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
botsInfo[i].setLastMove(move);
// 4. Process the move
switch(move)
{
case UP:
botsInfo[i].setY(botsInfo[i].getY()-BOT_SPEED);
break;
case DOWN:
botsInfo[i].setY(botsInfo[i].getY()+BOT_SPEED);
break;
case LEFT:
botsInfo[i].setX(botsInfo[i].getX()-BOT_SPEED);
break;
case RIGHT:
botsInfo[i].setX(botsInfo[i].getX()+BOT_SPEED);
break;
case FIREUP:
for (int j=0; j<botRoles[i].getNumBullet(); j++) // looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
bullets[i][j] = new Bullet(botsInfo[i].getX()+Bot.RADIUS, botsInfo[i].getY()-1, 0, -BULLET_SPEED);
botRoles[i].fireBullet();//reduce the amount of bullets by one.
if (state != TEST_MODE)
if (soundOn)
shot.play();
break;
}
break;
case FIREDOWN:
for (int j=0; j<botRoles[i].getNumBullet(); j++)// looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
bullets[i][j] = new Bullet(botsInfo[i].getX()+Bot.RADIUS, botsInfo[i].getY()+Bot.RADIUS * 2 + 1, 0, BULLET_SPEED);
botRoles[i].fireBullet();//reduce the amount of bullets by one.
if (state != TEST_MODE)
if (soundOn)
shot.play();
break;
}
break;
case FIRELEFT:
for (int j=0; j<botRoles[i].getNumBullet(); j++)// looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
bullets[i][j] = new Bullet(botsInfo[i].getX()-1, botsInfo[i].getY()+Bot.RADIUS, -BULLET_SPEED, 0);
botRoles[i].fireBullet();//decreases ammo count
if (state != TEST_MODE)
if (soundOn)
shot.play();
break;
}
break;
case FIRERIGHT:
for (int j=0; j<botRoles[i].getNumBullet(); j++)// looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
bullets[i][j] = new Bullet(botsInfo[i].getX()+Bot.RADIUS * 2 + 1, botsInfo[i].getY()+Bot.RADIUS, BULLET_SPEED, 0);
botRoles[i].fireBullet();//decreases ammo count
if (state != TEST_MODE)
if (soundOn)
shot.play();
break;
}
break;
case SEND_MESSAGE:
String msg = null;
// get the message
// BOT METHOD CALL - timed and exceptions caught
startThink = System.nanoTime();
try {
msg = bots[i].outgoingMessage();
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// make sure they are not over the limit
if (botsInfo[i].getNumMessages() < TIME_LIMIT/SECS_PER_MSG && state != TEST_MODE)
sendMessage(i, msg); // send the message
}
catch (Exception e)
{
botsInfo[i].exceptionThrown(e);
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
}
// ***********************
break;
case SPECIAL:
if (!specialOK){
//HelperMethods.say("Bot"+i+botsInfo[i].getName()+" cannot use special");
}
else{
//if tank
if (botRoles[i].getRole() == RoleType.TANK){
int ydir = 0;
int xdir = 0;
if (botsInfo[i].getLastMove()%4 == 1){//up or fire up
ydir = -1;
}
else if (botsInfo[i].getLastMove()%4 == 2){//down or fireDown
ydir = 1;
}
else if (botsInfo[i].getLastMove()%4 == 3){//left or fireright
xdir = -1;
}
else if (botsInfo[i].getLastMove()%4 == 0){//right or fireRight
xdir = 1;
}
for (int f = 0; f < Role.TANK_BULLETS; f++){
bullets[i][f] = new Bullet(botsInfo[i].getX()+Bot.RADIUS+xdir*(Bot.RADIUS+1)+(Bot.RADIUS*(f-1)*Math.abs(ydir)), botsInfo[i].getY()+Bot.RADIUS+ydir*(Bot.RADIUS+1)+(Bot.RADIUS*(f-1)*Math.abs(xdir)), xdir*BULLET_SPEED, ydir*BULLET_SPEED);
botRoles[i].fireBullet();//decreases ammo count
}
}
else if (botRoles[i].getRole() == RoleType.MEDIC){
BotInfo target = bots[i].getTarget() ;
if ( target == null){
HelperMethods.say("WTF");
}
double d = Math.sqrt(Math.pow(botsInfo[i].getX()-target.getX(),2)+Math.pow(botsInfo[i].getY()-target.getY(),2));
if (d <= (double)Bot.RADIUS*Math.sqrt(2)|| OMNI_SPECIALS){
for (int j=0; j<botRoles[i].getNumBullet(); j++){// looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
//HelperMethods.say("Health before "+botRoles[target.getBotNumber()].getHealth());
botRoles[target.getBotNumber()].heal();
bullets[i][j] = new Bullet(BulletType.HEAL);
botRoles[i].fireBullet();//reduce the amount of bullets by one.
}
//HelperMethods.say("after "+botRoles[target.getBotNumber()].getHealth());
}//end for
}//end if inrange
}
else if (botRoles[i].getRole() == RoleType.SUPPORT){
BotInfo target = bots[i].getTarget();
//HelperMethods.say("Bullets before "+target.getBulletsLeft());
double d = Math.sqrt(Math.pow(botsInfo[i].getX()-target.getX(),2)+Math.pow(botsInfo[i].getY()-target.getY(),2));
if (d <= Bot.RADIUS*Math.sqrt(2)|| OMNI_SPECIALS){
for (int j=0; j<botRoles[i].getNumBullet(); j++){// looks for the first unused bullet slot
if (bullets[i][j] == null&&botRoles[i].getBulletsLeft()>0)
{
HelperMethods.say("Bullets before "+target.getBulletsLeft());
botRoles[target.getBotNumber()].supply();
bullets[i][j] = new Bullet(BulletType.SUPPLY);
botRoles[i].fireBullet();//reduce the amount of bullets by one.
}
}//end for
HelperMethods.say("after "+target.getBulletsLeft());
}//end if inrange
}
}//end else
}//end switch
// 5. Bot collisions
if (move == UP || move == DOWN || move == LEFT || move == RIGHT|| move == SPECIAL) // if a move was made...
{
// 5a. other bots
for (int j=0; j<NUM_BOTS; j++)
{
if (j!=i && !botsInfo[i].isOut()) // don't collide with self or bots that are out
{
double d = Math.sqrt(Math.pow(botsInfo[i].getX()-botsInfo[j].getX(),2)+Math.pow(botsInfo[i].getY()-botsInfo[j].getY(),2));
if (d < Bot.RADIUS*2)
{
//Rowbottom this part handles touching other bots and looting bodies
//left here but modified to allow for classes to use heal and supply
//if (botsInfo[j].getBulletsLeft()>0&&botsInfo[j].isDead()){
//botsInfo[i].setBulletsLeft(botsInfo[i].getBulletsLeft()+botsInfo[j].getBulletsLeft());
// botsInfo[j].setBulletsLeft(0);
// }
// reverse the previous move on collision
if (move == UP)
botsInfo[i].setY(botsInfo[i].getY()+BOT_SPEED);
else if (move == DOWN)
botsInfo[i].setY(botsInfo[i].getY()-BOT_SPEED);
else if (move == LEFT)
botsInfo[i].setX(botsInfo[i].getX()+BOT_SPEED);
else if (move == RIGHT)
botsInfo[i].setX(botsInfo[i].getX()-BOT_SPEED);
break;
}
// else if (d < Bot.RADIUS*2.9 && move == SPECIAL){//allow supply and heal on diagonals
// if (botRoles[i].getRole() == RoleType.MEDIC){
// botRoles[bots[i].getTarget().getBotNumber()].heal();
// }
// else if (botRoles[i].getRole() == RoleType.SUPPORT){
// botRoles[bots[i].getTarget().getBotNumber()].supply();
// }
//
// }
}
}
// 5b. wall collisions - reset the bot to be inside the boundaries
if (botsInfo[i].getX() < LEFT_EDGE)
botsInfo[i].setX(LEFT_EDGE);
if (botsInfo[i].getX() > RIGHT_EDGE-Bot.RADIUS*2)
botsInfo[i].setX(RIGHT_EDGE-Bot.RADIUS*2);
if (botsInfo[i].getY() < TOP_EDGE)
botsInfo[i].setY(TOP_EDGE);
if (botsInfo[i].getY() > BOTTOM_EDGE-Bot.RADIUS*2)
botsInfo[i].setY(BOTTOM_EDGE-Bot.RADIUS*2);
}
}
}
// 6. in test mode, force a bot move
if (state == TEST_MODE && gotBot == i)
{
botsInfo[i].setX(forceBotX);
botsInfo[i].setY(forceBotY);
}
}
// D. Process the bullet moves/collisions
for (int i=0; i<NUM_BOTS; i++)
for (int k=0; k<botRoles[i].getNumBullet(); k++)
{
if (bullets[i][k] != null ){
if (bullets[i][k].type == BulletType.BULLET)
{
bullets[i][k].moveOneStep();
// 6a. destroy bullet if off screen
if (bullets[i][k].getX() < LEFT_EDGE || bullets[i][k].getX() > RIGHT_EDGE ||
bullets[i][k].getY() < TOP_EDGE || bullets[i][k].getY() > BOTTOM_EDGE)
{
bullets[i][k] = null;
}
else // 6b. otherwise, check for bot collisions
{
if (state != TEST_MODE) // not if in test mode
{
for (int j = 0; j<NUM_BOTS; j++)
{
if (!botsInfo[j].isOut() && i != j)
{
double d = Math.sqrt(Math.pow(bullets[i][k].getX()-(botsInfo[j].getX()+Bot.RADIUS),2)+Math.pow(bullets[i][k].getY()-(botsInfo[j].getY()+Bot.RADIUS),2));
if (d < Bot.RADIUS) // hit something
{
bullets[i][k] = null; // no more bullet
if (botsInfo[j].isDead() == false) // kill bot if possible
{
//if the victim has health then subtract 1
if (botRoles[j].getHealth()>1){
botRoles[j].wound();
//HelperMethods.say("Ouch!");
}
else {
if (soundOn){
death.play();
}
botsInfo[i].addKill();
botsInfo[j].killed(botsInfo[i].getName());
botsInfo[j].setTimeOfDeath(timePlayed);
botsInfo[j].setScore(currentScore(j,false)); // final score of dead bot
//botsInfo[i].setScore(currentScore(i,false));
botsLeft--;
sendMessage(SYSTEM_MSG, botsInfo[j].getName()+" destroyed by "+botsInfo[i].getName()+".");
}
}//if the bot was alive
break; // only one collision per bullet
}//if a bot was hit
}
}//end for loop to check for collisions
}//end if not test mode
}//else check collisions
}//if its a bullet
else {
//checks and ticks down the cooldown on the special bullets
bullets[i][k].coolDownTick();
// HelperMethods.say("OMG, this actually works!"+bullets[i][k].getCoolDown());
if (bullets[i][k].coolDownTick()){
// HelperMethods.say("OMG, this actually works!");
bullets[i][k] = null;
}
}//end else its a special
}//end if not null
}//end for loop bullets
}//end active game
// paint the screen
paintBuffer();
}//end active game
// *** paused or instant replay mode?
else if (state == GAME_PAUSED || state == GAME_OVER || state == WINNER)
{
if (--pauseCount <= 0)
pauseCount = PAUSE_FLASH_TIME;
if (++replayCounter >= this.REPLAY_SPEED)
{
replayCounter = 0;
if (replayCurrentFrame == replayEndFrame && endFrameCounter > 0)
endFrameCounter--;
else
{
if (++replayCurrentFrame >= NUM_FRAMES)
replayCurrentFrame = 0;
if (replayCurrentFrame == replayEndFrame)
endFrameCounter = END_FRAME_COUNT;
}
}
// paint the screen
repaint();
}
else // countdown to the start
{
if (++replayEndFrame >= NUM_FRAMES)
replayEndFrame = 0;
countDown--;
if (countDown == 0)
{
startTime = System.currentTimeMillis();
if (soundOn)
drone.loop();
}
// paint the screen
paintBuffer();
}
}
/**
* Sends a broadcast message to the bots.
* @param id Message sender
* @param msg Message
*/
private void sendMessage(int id, String msg)
{
if (msg != null && !msg.equals(""))
{
msg = msg.substring(0,Math.min(MAX_MESSAGE_LENGTH,msg.length()));
// send the message to the bots
for (int i = 0; i<NUM_BOTS; i++)
if (!botsInfo[i].isDead() && !botsInfo[i].isOut() && !botsInfo[i].isOverheated())
{
// BOT METHOD CALL - timed and exceptions caught
long startThink = System.nanoTime();
try {
bots[i].incomingMessage(id, msg);
}
catch(Exception e)
{
botsInfo[i].exceptionThrown(e);
}
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
}
// echo the message to the screen
if (id >= 0)
{
botsInfo[id].sentMessage(); // increment messages sent by bot
messages.addFirst(botsInfo[id].getName()+": "+msg);
// check if over limit
if (botsInfo[id].getNumMessages() >= TIME_LIMIT/SECS_PER_MSG)
sendMessage(-1,"Messages capped for "+botsInfo[id].getName());
}
else
messages.addFirst("Referee: "+msg);
// reset the scroll every time a message sent
firstMessage = 0;
}
}
/**
* Computes the score for a given bot
* @param botNum The bot to compute score for
* @param gameOver Whether or not the game is over (full score alloted in this case)
* @return The score
*/
@SuppressWarnings("unused")
private double currentScore(int botNum, boolean gameOver)
{
double score;
//Rowbottom handling score so that it does not increase bonuses by round
if (ELIMINATIONS_PER_ROUND==0){
score = KILL_SCORE * botsInfo[botNum].getNumKills() - ERROR_PENALTY * botsInfo[botNum].getNumExceptions() + EFFICIENCY_BONUS * (PROCESSOR_LIMIT - botsInfo[botNum].getThinkTime());
if (score < 0)
score = 0;
if (gameOver)
score += TIME_LIMIT * POINTS_PER_SECOND;
else
{
if (botsInfo[botNum].getTimeOfDeath() > 0)
score += botsInfo[botNum].getTimeOfDeath()*POINTS_PER_SECOND;
else
score += timePlayed*POINTS_PER_SECOND;
}
}
else{
score = KILL_SCORE * botsInfo[botNum].getNumKills() * (round+1.0)/2 - ERROR_PENALTY * botsInfo[botNum].getNumExceptions() + EFFICIENCY_BONUS * (PROCESSOR_LIMIT - botsInfo[botNum].getThinkTime());
if (score < 0)
score = 0;
if (gameOver)
score += TIME_LIMIT * POINTS_PER_SECOND * (round+1.0)/2;
else
{
if (botsInfo[botNum].getTimeOfDeath() > 0)
score += botsInfo[botNum].getTimeOfDeath()*POINTS_PER_SECOND*(round+1.0)/2;
else
score += timePlayed*POINTS_PER_SECOND*(round+1.0)/2;
}
}
return score < 0?0:score;
}
/**
* Sorts the botInfo array by score.
* @param descending If true, sorts in descending order. Ascending otherwise
* @return the sorted array
*/
private BotInfo[] sortedBotInfoArray(boolean descending)
{
// Create a new array for sorting
BotInfo[] newInfos = new BotInfo[NUM_BOTS];
for (int i=0; i<NUM_BOTS; i++)
{
newInfos[i] = botsInfo[i];
}
// Bubblesort. I know, I know...
for (int i=NUM_BOTS-1; i>0; i--)
for (int j=1; j<=i; j++)
{
double score1 = newInfos[j].getScore()+newInfos[j].getCumulativeScore();
double score2 = newInfos[j-1].getScore()+newInfos[j-1].getCumulativeScore();
if (descending && score1 > score2
|| !descending && score1 < score2
|| descending && score1 == score2 && !(newInfos[j].isOut()
|| newInfos[j].isOutNextRound()) && (newInfos[j-1].isOut()||newInfos[j-1].isOutNextRound())
)
{
BotInfo temp = newInfos[j-1];
newInfos[j-1] = newInfos[j];
newInfos[j] = temp;
}
}
// return the sorted array
return newInfos;
}
/**
* Increases the game speed (
*/
private void changeGameSpeed()
{
if (speed < 8)
speed *= 2;
gameTimer.setDelay(1000/30/speed);
}
/**
* Decreases the game speed
*/
private void changeGameSpeedDown()
{
if (speed > 1)
speed /= 2;
gameTimer.setDelay(1000/30/speed);
}
/**
* Resets the game speed
*/
private void resetGameSpeed()
{
speed = 1;
gameTimer.setDelay(1000/30/speed);
}
/**
* This method paints the bots and bullets for the game area into
* the instant replay buffer. Then it calls a repaint to trigger
* a call to the paint method which displays this buffer to the
* screen.
*/
private void paintBuffer()
{
//System.out.println("painting");
if (ready) // avoid race condition on startup
{
// get the next image from the rotating instant replay buffer
Graphics g = replayImages[replayEndFrame].getGraphics();
Graphics2D g2D = (Graphics2D)(g); //Rowbottom
// a little trick to get imageobserver callbacks when the bot images are loaded
// may not be necessary any more in 2.0
if (imagesToLoad.size() > 0)
{
LinkedList<Image> newImagesToLoad = new LinkedList<Image>();
Iterator<Image> i = imagesToLoad.iterator();
while (i.hasNext())
{
Image image = i.next();
if (!g.drawImage(image,-10000,-10000,this))
newImagesToLoad.add(image);
}
imagesToLoad = newImagesToLoad;
}
// clear the screen
g.setColor(Color.black);
g.fillRect(0,0,RIGHT_EDGE,BOTTOM_EDGE+TEXT_BUFFER);
// Draw the bots & their bullets
for (int i=0; i<NUM_BOTS; i++)
{
if (!botsInfo[i].isOut()) // skip bots that are out
if (botsInfo[i].isDead()) // dead bot
g.drawImage(deadBot, (int)(botsInfo[i].getX()+0.5), (int)(botsInfo[i].getY()+0.5), Bot.RADIUS*2, Bot.RADIUS*2, this);
else if (botsInfo[i].isOverheated()) // overheated bot
g.drawImage(overheated, (int)(botsInfo[i].getX()+0.5), (int)(botsInfo[i].getY()+0.5), Bot.RADIUS*2, Bot.RADIUS*2, this);
else // active bot
{
// BOT METHOD CALL - timed and exceptions caught
long startThink = System.nanoTime();
try {
if (state == GAME_ON){
//Rowbottom draw the health if active mode
//set the team colour
g2D.setColor(teamColors[i/TEAM_SIZE]);
g2D.setStroke(new BasicStroke(3F)); // set stroke width of 5
g2D.drawArc((int)(botsInfo[i].getX()-2), (int)(botsInfo[i].getY()-2),
Bot.RADIUS*2+4, Bot.RADIUS*2+4,0,(int)(360*(botRoles[i].getHealth()/(double)botRoles[i].getMaxHealth())));
}
bots[i].draw(g, (int)(botsInfo[i].getX()+0.5), (int)(botsInfo[i].getY()+0.5));
}
catch(Exception e)
{
botsInfo[i].exceptionThrown(e);
}
botsInfo[i].setThinkTime((System.nanoTime()-startThink)*nanoTimeCorrection);
// ***********************
// special test mode output
if (state == TEST_MODE)
{
if (flashCounter < FLASH_TIME/2)
{
g.setColor(Color.red);
g.drawOval((int)(botsInfo[i].getX()+0.5)-1, (int)(botsInfo[i].getY()+0.5)-1, Bot.RADIUS*2+2, Bot.RADIUS*2+2);
}
if (state == TEST_MODE)
{
g.setFont(new Font("MonoSpaced",Font.PLAIN,NAME_FONT));
g.setColor(Color.gray);
g.drawString(""+botsInfo[i].getNumExceptions(), (int)(botsInfo[i].getX()+0.5)+Bot.RADIUS*2+2, (int)(botsInfo[i].getY()+0.5)+Bot.RADIUS);
g.drawString(""+df2.format(botsInfo[i].getThinkTime()), (int)(botsInfo[i].getX()+0.5)+Bot.RADIUS*2+2, (int)(botsInfo[i].getY()+0.5)+Bot.RADIUS+NAME_FONT);
}
}
}
// bullets for bot i
for (int j=0; j<botRoles[i].getNumBullet(); j++)
{
if (bullets[i][j] != null){
// bullets[i][j].draw(g);
bullets[i][j].draw(g2D);//rowbottom
}
}
}
// draw the bot titles
// these are drawn last so they're on top of the other bots
for (int i=0; i<NUM_BOTS; i++)
{
if (botsInfo[i].isDead() == false && botsInfo[i].isOut() == false)
{
g.setFont(new Font("MonoSpaced",Font.PLAIN,NAME_FONT));
// default is red, but goes to gray if they can take a shot
g.setColor(new Color (170,42,42));
if (!botsInfo[i].isOverheated())
for (int j=0; j<botRoles[i].getNumBullet(); j++)
if (bullets[i][j] == null)
{
g.setColor(Color.gray);
break;
}
// get and display the bots title
String title = "";
if (showNames)
title = botsInfo[i].getName();
else if (showScores)
title = ""+df.format(botsInfo[i].getCumulativeScore());//Rowbottom
else if (showAmmo)
title = ""+botRoles[i].getBulletsLeft();
// x calculation based on x-width of 0.5 font size with a one pixel spacer between letters
g.drawString(title, (int)(botsInfo[i].getX()+Bot.RADIUS-(title.length()/2.0*(NAME_FONT*0.5+1))+0.5), (int)(botsInfo[i].getY()-1+0.5));
}
}
// trigger a paint event
repaint();
}
}
/**
* This method prints out the stats for each robot in sorted order.
* Used at the end of each round, and also during the game when the
* DEBUG flag is set.
* @param g The Graphics object to draw on
*/
private void printStats(Graphics g)
{
BotInfo[] newInfos = sortedBotInfoArray(true);
int xOffset = 5;
int yOffset = 50;
if (state != WAIT_TO_START)
{
g.setColor(new Color(60,60,60,130));
g.fillRect(0, yOffset-STATS_FONT-5, RIGHT_EDGE, STATS_FONT*(NUM_BOTS+1)+10+24);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD,24));
g.drawString("Stats for Round "+round, (RIGHT_EDGE+LEFT_EDGE)/2-120, yOffset);
yOffset += 24;
g.setFont(new Font("MonoSpaced",Font.PLAIN,STATS_FONT));
g.drawString("Name Team Round Total Time Errors Messages Processor Killed By",xOffset,yOffset);
for (int i=0; i<NUM_BOTS; i++)
{
String output = pad(newInfos[i].getName(), 8, false) + " " + pad(newInfos[i].getTeamName(),8, false)+" ";
output += (newInfos[i].isOut()?" ":pad(df.format(newInfos[i].getScore()),5, true))+" "+pad(df.format(newInfos[i].getScore()+newInfos[i].getCumulativeScore()),5, true)+" ";
if (!newInfos[i].isOut())
{
output += (newInfos[i].isDead()?pad(df.format(newInfos[i].getTimeOfDeath()),5,true):(state == GAME_OVER || state == WINNER?pad(df.format(TIME_LIMIT),5,true):pad(df.format(timePlayed),5,true)))+" ";
output += pad(""+newInfos[i].getNumExceptions(),6,true)+" "+pad(""+newInfos[i].getNumMessages(),4,true)+" ";
output += pad(df2.format(newInfos[i].getThinkTime()),8, true)+" "+pad(newInfos[i].getKilledBy(),8,false);
}
if (newInfos[i].isDead() && state != GAME_OVER && state != WINNER || newInfos[i].isOut() || state == GAME_OVER && newInfos[i].isOutNextRound() || state == WINNER && i != 0)
g.setColor(Color.gray);
else
g.setColor(Color.lightGray);
g.drawString(output,xOffset,yOffset+STATS_FONT+i*STATS_FONT);
}
}
}
/**
* Special string padding method for printStats
* @param s The string to pad
* @param n The target length
* @param rightJust Right justify if true, otherwise left justify.
* @return The padded string
*/
private String pad(String s, int n, boolean rightJust)
{
if (s == null)
s = "";
int l = s.length();
for (int i=l; i < n; i++)
if (rightJust)
s = " " + s;
else
s = s + " ";
l = s.length();
if (l > n)
s = s.substring(0, n);
return s;
}
/**
* Paints the screen. Assumes that paintBuffer() has been called recently
* to paint the current game state into the instant replay buffer.
* @param g The Graphics context
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (ready) // avoid race condition on startup
{
// switch g to the offline buffer (double-buffering)
//Graphics g2 = g;
//g = buffer.getGraphics();
// black out hte screen
g.setColor(Color.black);
g.fillRect(0,0,getWidth(),getHeight());
// draw the main window
if (state == GAME_PAUSED || state == GAME_OVER || state == WINNER)
g.drawImage(replayImages[replayCurrentFrame], 0, 0, this); // draws from the instant replay buffer
else
g.drawImage(replayImages[replayEndFrame], 0, 0, this); // draws the latest frame if game is on
// Message bars
if (state == GAME_PAUSED)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(0, BOTTOM_EDGE - 30, RIGHT_EDGE, 26);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD, 20));
g.drawString("Game Paused. Showing Instant Replay.",10,BOTTOM_EDGE - 10);
}
else if (state == GAME_OVER)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(0, BOTTOM_EDGE - 30, RIGHT_EDGE, 26);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD, 20));
if (CUMULATIVE_SCORING)
g.drawString(botsInfo[winnerID].getName()+" Leading After "+round+" Round"+(round>1?"s":"")+". Click This Bar to Continue.",10,BOTTOM_EDGE - 10);
else
g.drawString(botsInfo[winnerID].getName()+" Wins Round "+round+". Click This Bar to Continue.",10,BOTTOM_EDGE - 10);
printStats(g);
}
else if (state == WINNER)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(0, BOTTOM_EDGE - 30, RIGHT_EDGE, 26);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD, 20));
if (CUMULATIVE_SCORING)
g.drawString(botsInfo[winnerID].getName()+" Wins after "+round+" Round"+(round>1?"s":"")+"! Click This Bar to Restart.",10,BOTTOM_EDGE - 10);
else
g.drawString(botsInfo[winnerID].getName()+" Wins the Final Round! Click This Bar to Restart.",10,BOTTOM_EDGE - 10);
printStats(g);
}
else if (state == TEST_MODE)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(0, BOTTOM_EDGE - 30, RIGHT_EDGE, 26);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD, 20));
g.drawString("Welcome to Battle Bots. Click This Bar to Start.",10,BOTTOM_EDGE-10);
}
else if (state == WAIT_TO_START)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(0, BOTTOM_EDGE - 30, RIGHT_EDGE, 26);
g.setColor(Color.white);
g.setFont(new Font("MonoSpaced",Font.BOLD, 22));
if (botsLeft <= ELIMINATIONS_PER_ROUND+1)
g.drawString("Click This Bar to Start the Final Round.",10,BOTTOM_EDGE - 10);
else
g.drawString("Click This Bar to Start Round "+round+".",10,BOTTOM_EDGE - 10);
// display the rules
g.setColor(Color.white);
if (round == 1)
{
g.setFont(new Font("MonoSpaced",Font.BOLD, 80));
g.drawString("Battle", RIGHT_EDGE-350, TOP_EDGE+90);
g.drawString("Bots", RIGHT_EDGE-300, TOP_EDGE+160);
}
else
{
g.setFont(new Font("MonoSpaced",Font.BOLD, 80));
if (botsLeft <= ELIMINATIONS_PER_ROUND+1)
{
g.drawString("Final", RIGHT_EDGE-300, TOP_EDGE+90);
g.drawString("Round", RIGHT_EDGE-300, TOP_EDGE+160);
}
else
{
g.drawString("Round", RIGHT_EDGE-300, TOP_EDGE+90);
g.drawString("*"+round+"*", RIGHT_EDGE-250, TOP_EDGE+160);
}
}
g.setFont(new Font("MonoSpaced",Font.BOLD, 22));
int y = (TOP_EDGE+BOTTOM_EDGE)/2;
g.drawString("The Rules", 10, y);
g.setColor(Color.lightGray);
g.setFont(new Font("MonoSpaced",Font.PLAIN, 14));
y+=16;
if (round == 1)
g.drawString("- "+NUM_BOTS+" robots to start",10,y);
else
g.drawString("- "+(NUM_BOTS-ELIMINATIONS_PER_ROUND*(round-1))+" robots left",10,y);
y+=15;
g.drawString("- each round lasts "+TIME_LIMIT+" seconds",10,y);
y+=15;
g.drawString("- "+ELIMINATIONS_PER_ROUND+" robots eliminated each round",10,y);
y+=15;
g.drawString("- each robot can have a limited amount of bullets active at once",10,y);
y+=15;
g.drawString("- each robot can send "+(int)(TIME_LIMIT/SECS_PER_MSG)+" messages per round",10,y);
y+=15;
g.drawString("- each robot has "+PROCESSOR_LIMIT+" seconds of processor time",10,y);
y+=26;
g.setFont(new Font("MonoSpaced",Font.BOLD, 22));
g.setColor(Color.white);
g.drawString("Scoring", 10, y);
g.setFont(new Font("MonoSpaced",Font.PLAIN, 14));
g.setColor(Color.lightGray);
y+=16;
g.drawString("- "+df.format(KILL_SCORE*(round+1.0)/2)+" points per kill, "+df.format(POINTS_PER_SECOND*(round+1.0)/2*10)+" points per 10 seconds of survival",10,y);
y+=15;
g.drawString("- "+EFFICIENCY_BONUS+" point bonus for each unused second of processor time",10,y);
y+=15;
g.drawString("- "+ERROR_PENALTY+" point penalty for each exception thrown",10,y);
y+=15;
if (CUMULATIVE_SCORING)
g.drawString("- scores accumulate from round to round",10,y);
else
g.drawString("- robots' scores are reset between rounds",10,y);
}
// the menu
if (showNames)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(RIGHT_EDGE-125, BOTTOM_EDGE+56, 49, 18);
g.setColor(new Color(40,40,40,175));
g.drawRect(RIGHT_EDGE-125, BOTTOM_EDGE+56, 49, 18);
}
else if (showAmmo)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(RIGHT_EDGE-125, BOTTOM_EDGE+76, 49, 18);
g.setColor(new Color(40,40,40,175));
g.drawRect(RIGHT_EDGE-125, BOTTOM_EDGE+76, 49, 18);
}
else if (showScores)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(RIGHT_EDGE-74, BOTTOM_EDGE+56, 54, 18);
g.setColor(new Color(40,40,40,175));
g.drawRect(RIGHT_EDGE-74, BOTTOM_EDGE+56, 54, 18);
}
if (soundOn)
{
g.setColor(new Color(60,60,60,175));
g.fillRect(RIGHT_EDGE-74, BOTTOM_EDGE+76, 54, 18);
g.setColor(new Color(40,40,40,175));
g.drawRect(RIGHT_EDGE-74, BOTTOM_EDGE+76, 54, 18);
}
g.setColor(Color.gray);
g.setFont(new Font("MonoSpaced",Font.BOLD, 14));
g.drawString("Roles Scores", RIGHT_EDGE-120, BOTTOM_EDGE+69);
g.drawString("Ammo Sounds", RIGHT_EDGE-120, BOTTOM_EDGE+89);
// the time clock
if (state != GAME_PAUSED || pauseCount < PAUSE_FLASH_TIME/2)
{
g.setColor(Color.gray);
g.setFont(new Font("MonoSpaced",Font.BOLD, 30));//rowbottom
g.drawString(""+pad(df.format(Math.abs(TIME_LIMIT-timePlayed)),5,true),RIGHT_EDGE-152,BOTTOM_EDGE+40);
g.setFont(new Font("MonoSpaced",Font.BOLD, 10));//rowbottom
g.drawString("round "+round+" of "+ NUM_ROUNDS,RIGHT_EDGE-100,BOTTOM_EDGE+10);//rowbottom
if (speed != 1)
{
g.setFont(new Font("MonoSpaced",Font.BOLD, 10));
g.drawString("x"+speed,RIGHT_EDGE-12,BOTTOM_EDGE+40);
}
}
// the message area
g.setFont(new Font("MonoSpaced",Font.PLAIN, 12));
int offSet = 14;
int counter = 0;
double fade = 1;
Iterator<String> i = messages.iterator();
while (i.hasNext() && counter < 6 + firstMessage)
{
String msg = i.next();
if (counter >= firstMessage)
{
if (msg.startsWith("Referee"))
g.setColor(new Color((int)(128*fade),(int)(128*fade),(int)(128*fade)));
else
g.setColor(new Color((int)(128*fade),(int)(128*fade),0));
g.drawString(msg.substring(0,Math.min(77,msg.length())),10,BOTTOM_EDGE+TEXT_BUFFER - offSet);
offSet += 14;
//fade /= 1.15;
}
counter++;
}
// print the stats if in debug mode
if (DEBUG && state != TEST_MODE && state != GAME_OVER && state != WINNER )
printStats(g);
// draw the lines to separate screen areas
g.setColor(Color.gray);
g.drawLine(0, BOTTOM_EDGE+1, getWidth(), BOTTOM_EDGE+1);
g.drawLine(0, TOP_EDGE-1, getWidth(), TOP_EDGE-1);
g.drawLine(RIGHT_EDGE-145,BOTTOM_EDGE+1,RIGHT_EDGE-145,getHeight());
g.drawLine(RIGHT_EDGE-145,BOTTOM_EDGE+50,getWidth(),BOTTOM_EDGE+50);
// dump the offline buffer to the screen (double-buffering)
//g2.drawImage(buffer,0,0,this);
}
}
/**
* Handles user's mouse clicks on the menu buttons, the time clock,
* and the "click here" bars.
* @param e The MouseEvent
*/
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) // left button only
{
if (e.getY()<BOTTOM_EDGE) // click is on the playing field
{
if (state == WAIT_TO_START && (e.getY()>BOTTOM_EDGE-30)) // clicked on the wait to start message bar
{
if (soundOn)
fanfare.play();
countDown = 60;//where does this impact?
startTime = System.currentTimeMillis();
gameTimer.start();
if (botsLeft <= ELIMINATIONS_PER_ROUND+1)
sendMessage(SYSTEM_MSG,"Final Round starting. Good luck!");
else
sendMessage(SYSTEM_MSG,"Round "+round+" starting. Good luck!");
state = GAME_ON;
}
else if (state == GAME_OVER && e.getY()>BOTTOM_EDGE-30) // clicked on the click for next round bar
{
if (soundOn)
stop.play();
gameTimer.stop();
timePlayed = 0;
state = WAIT_TO_START;
reset();
}
else if (state == WINNER && e.getY()>BOTTOM_EDGE-30) // clicked on the reset bar
fullReset();
else if (state == TEST_MODE) // in test mode
{
// check for and process bot grabs
gotBot = -1;
for (int i=0; i<NUM_BOTS; i++)
{
if (e.getX() > botsInfo[i].getX() && e.getX() < botsInfo[i].getX()+Bot.RADIUS*2 &&
e.getY() > botsInfo[i].getY() && e.getY() < botsInfo[i].getY()+Bot.RADIUS*2)
{
gotBot = i;
forceBotX = (int)(botsInfo[i].getX()+0.5);
forceBotY = (int)(botsInfo[i].getY()+0.5);
mouseInitialX = e.getX();
mouseInitialY = e.getY();
}
}
// if no bot grab, check if on the "click to start" bar
if (gotBot == -1 && e.getY()>BOTTOM_EDGE-30)
{
if (soundOn)
stop.play();
gameTimer.stop();
state = WAIT_TO_START;
round = 0;
reset();
}
}
}
// click is on the lower message/menu area
else if(e.getX()>=RIGHT_EDGE-145 && e.getY() < BOTTOM_EDGE+50) // click on clock
{
if (state == GAME_PAUSED) // unpause
{
if (soundOn)
drone.loop();
startTime = System.currentTimeMillis();
state = GAME_ON;
}
else if (state == GAME_ON && countDown <= 0) // pause
{
drone.stop();
if (soundOn)
stop.play();
pauseTime = System.nanoTime();
pauseCount = PAUSE_FLASH_TIME;
replayCurrentFrame = replayEndFrame;
endFrameCounter = END_FRAME_COUNT;
state = GAME_PAUSED;
resetGameSpeed();
}
}
else if(e.getX()>=RIGHT_EDGE-125 && e.getX()<=RIGHT_EDGE-125+49)// clicked on names or teams button
{
if (e.getY()>=BOTTOM_EDGE+56)
if (e.getY()>=BOTTOM_EDGE+76) // ammo button
{
if (showAmmo)
showAmmo = false;
else
{
showAmmo = true;
showScores = false;
showNames = false;
}
}
else if (showNames) // names button
showNames = false;
else
{
showNames = true;
showScores = false;
showAmmo = false;
}
}
else if(e.getX()>=RIGHT_EDGE-74 && e.getX()<=RIGHT_EDGE-69+55)// clicked on sound or scores button
{
if (e.getY()>=BOTTOM_EDGE+56)
if (e.getY()>=BOTTOM_EDGE+76) // sound
{
if (soundOn)
{
soundOn = false;
drone.stop();
}
else
{
if (state == GAME_ON)
drone.loop();
soundOn = true;
}
}
else if (showScores) // scores
showScores = false;
else
{
showScores = true;
showNames = false;
showAmmo = false;
}
}
// paint the screen
paintBuffer();
}
}
/**
* @author Rowbottom
* method gets the roles frm the bots
*/
protected Role[] getRoles(Bot[] bots){
Role[] tempRoles = new Role[bots.length];
for (int i = 0 ; i < bots.length; i++){
tempRoles[i] = bots[i].getRole();
if (tempRoles[i] == null){
tempRoles[i] = new Role();
}
}
return tempRoles;
}
/**
* When a mouse button is released, release any grabbed bot.
* @param e The MouseEvent
*/
public void mouseReleased(MouseEvent e) {
gotBot = -1;
}
/**
* Scroll event. Scroll the messages or change game speed depending on
* location of the mouse.
* @param e The MouseWheelEvent
*/
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getY() >= BOTTOM_EDGE && e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
{
if(e.getX()>=RIGHT_EDGE-145 && e.getY() < BOTTOM_EDGE+50) // change game speed
{
if (state == GAME_ON)
if (e.getWheelRotation() < 0)
changeGameSpeed();
else
changeGameSpeedDown();
}
else if (e.getX()< RIGHT_EDGE-145) // message window scroll
{
firstMessage -= e.getWheelRotation();
if (firstMessage < 0)
firstMessage = 0;
else if (firstMessage > messages.size()-6)
firstMessage = Math.max(0,messages.size()-6);
}
}
// paint the screen
paintBuffer();
}
/**
* Drag a grabbed bot if there is one. The actual force move is processed in
* actionPerformed(). Here we just update the offset that the mouse has moved.
* @param e The MouseEvent
*/
public void mouseDragged(MouseEvent e) {
if (state == TEST_MODE)
{
forceBotX += e.getX()-mouseInitialX;
forceBotY += e.getY()-mouseInitialY;
mouseInitialX = e.getX();
mouseInitialY = e.getY();
}
}
/**
* Unused interface method
*/
public void mouseClicked(MouseEvent e) {}
/**
* Unused interface method
*/
public void mouseEntered(MouseEvent e) {}
/**
* Unused interface mthod
*/
public void mouseExited(MouseEvent e) {}
/**
* Unused interface method
*/
public void mouseMoved(MouseEvent arg0) {}
}
| [
"rowbottomn@hdsb.ca"
] | rowbottomn@hdsb.ca |
d55291b11da8b7fc14e62f908063f88f4a418fac | 22cea9dc711c6ff2be711824e55c1f6fd4c75675 | /android/app/src/main/java/com/lettersgame/MainApplication.java | 3b8cb87c9996d4af3ac79a5a8e58ee5bd70e97c3 | [] | no_license | LaurenceM10/letters-game | b84695f54f121fd22719d4bb95f27d88924868ca | 4620cf71edafe6295f39a9ea82c4cd73a8185fd3 | refs/heads/main | 2023-07-12T10:00:51.065817 | 2021-08-17T10:55:55 | 2021-08-17T10:55:55 | 395,711,343 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,605 | java | package com.lettersgame;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.lettersgame.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| [
"laurenmontenegro10@gmail.com"
] | laurenmontenegro10@gmail.com |
dc2ba1d435e6237e92dae840b3d9b97ec78face1 | 77916a24b7c0e6468c34aeb4399263d0317f69d8 | /src/main/java/frc/robot/subsystems/DistanceSensor.java | 28dd16ec2a0f63e154a1432a11ffed619126dd57 | [] | no_license | FRCTeam3543/Robot2020 | 503cc59893a81c3697e8f3e70fe803743eb16678 | 7d171037cc82a843873aa02d8538f64d7bb836dc | refs/heads/master | 2020-12-09T08:55:30.104401 | 2020-03-10T21:00:45 | 2020-03-10T21:00:45 | 233,255,645 | 1 | 0 | null | 2020-03-08T10:50:23 | 2020-01-11T15:47:36 | Java | UTF-8 | Java | false | false | 882 | java | package frc.robot.subsystems;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SendableRegistry;
public class DistanceSensor extends Subsystem {
final AnalogInput leftSensor;
final AnalogInput rightSensor;
public DistanceSensor() {
super();
this.setName("Distance sensor");
leftSensor = new AnalogInput(Config.ULTRASOUND_LEFT);
SendableRegistry.setName(leftSensor, "Left Distance Sensor");
rightSensor = new AnalogInput(Config.ULTRASOUND_RIGHT);
SendableRegistry.setName(rightSensor, "Right Distance Sensor");
}
@Override
protected void initDefaultCommand() {
}
public void initOperatorInterface() {
//LiveWindow.add(this);
addChild(leftSensor);
addChild(rightSensor);
}
}
| [
"31746539+NiftyCoderAlex@users.noreply.github.com"
] | 31746539+NiftyCoderAlex@users.noreply.github.com |
52778b8b154a28ee4f9f4e0df58806ed46054e78 | cd12861d7bedb820b2440efb42acf8ba1b4f5436 | /FragmentDemo/app/src/main/java/com/nareshit/fragmentdemo/MainActivity.java | 4e15193e39d1b46e6c58d490064c515138597435 | [] | no_license | nagasaimanoj/Android-Coaching-NareshIT | 05ee2000ae48cef502599d768c62524916d1c582 | 378b221b250fdb19ccc1ff574fcaba790aaba89a | refs/heads/master | 2018-11-27T05:04:28.055030 | 2018-09-05T07:37:42 | 2018-09-05T07:37:42 | 96,038,265 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,123 | java | package com.nareshit.fragmentdemo;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.nareshit.fragmentdemo.fragments.DetailsFragment;
import com.nareshit.fragmentdemo.fragments.GamesFragment;
import com.nareshit.fragmentdemo.fragments.MoviesFragment;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView tvMovies,tvGames,tvDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMovies = (TextView) findViewById(R.id.tvMovies);
tvGames = (TextView) findViewById(R.id.tvGames);
tvDetails = (TextView) findViewById(R.id.tvDetails);
tvDetails.setOnClickListener(this);
tvMovies.setOnClickListener(this);
tvGames.setOnClickListener(this);
Fragment fragment = new MoviesFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContainer,fragment);
fragmentTransaction.commit();
}
@Override
public void onClick(View view)
{
Fragment fragment = null;
switch (view.getId())
{
case R.id.tvMovies:
fragment = new MoviesFragment();
break;
case R.id.tvGames:
fragment = new GamesFragment();
break;
case R.id.tvDetails:
fragment = new DetailsFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContainer,fragment);
fragmentTransaction.commit();
}
}
| [
"nagasai.g9@gmail.com"
] | nagasai.g9@gmail.com |
b03f51db75c4e2fe3511f51e91e9d4666daca74f | 76e6ee98ae2b08190cdf5bfef14668b1d039812d | /dmd-admin/src/main/java/com/dmd/mall/service/impl/PmsProductAttributeServiceImpl.java | 111f1b81eadb5e0b052660f3b18461545429076e | [
"Apache-2.0"
] | permissive | qhl0505/dmd | 5853af47eaa9f24d07c2bdaf24eb482bcd1b4820 | e9b3ca850d3f53cc56f0efba30ff3dde5c65138a | refs/heads/master | 2022-06-29T10:22:34.372066 | 2019-10-10T10:05:38 | 2019-10-10T10:05:38 | 214,320,664 | 2 | 0 | Apache-2.0 | 2022-06-21T02:01:19 | 2019-10-11T01:53:24 | Java | UTF-8 | Java | false | false | 4,671 | java | package com.dmd.mall.service.impl;
import com.dmd.mall.dto.PmsProductAttributeParam;
import com.dmd.mall.dto.ProductAttrInfo;
import com.dmd.mall.mapper.PmsProductAttributeCategoryMapper;
import com.dmd.mall.mapper.PmsProductAttributeDao;
import com.dmd.mall.mapper.PmsProductAttributeMapper;
import com.dmd.mall.model.PmsProductAttribute;
import com.dmd.mall.model.PmsProductAttributeCategory;
import com.dmd.mall.model.PmsProductAttributeExample;
import com.dmd.mall.service.PmsProductAttributeService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 商品属性Service实现类
* Created by macro on 2018/4/26.
*/
@Service
public class PmsProductAttributeServiceImpl implements PmsProductAttributeService {
@Autowired
private PmsProductAttributeMapper productAttributeMapper;
@Autowired
private PmsProductAttributeCategoryMapper productAttributeCategoryMapper;
@Autowired
private PmsProductAttributeDao productAttributeDao;
@Override
public List<PmsProductAttribute> getList(Long cid, Integer type, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum, pageSize);
PmsProductAttributeExample example = new PmsProductAttributeExample();
example.setOrderByClause("sort desc");
example.createCriteria().andProductAttributeCategoryIdEqualTo(cid).andTypeEqualTo(type);
return productAttributeMapper.selectByExample(example);
}
@Override
public int create(PmsProductAttributeParam pmsProductAttributeParam) {
PmsProductAttribute pmsProductAttribute = new PmsProductAttribute();
BeanUtils.copyProperties(pmsProductAttributeParam, pmsProductAttribute);
int count = productAttributeMapper.insertSelective(pmsProductAttribute);
//新增商品属性以后需要更新商品属性分类数量
PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId());
if(pmsProductAttribute.getType()==0){
pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()+1);
}else if(pmsProductAttribute.getType()==1){
pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()+1);
}
productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory);
return count;
}
@Override
public int update(Long id, PmsProductAttributeParam productAttributeParam) {
PmsProductAttribute pmsProductAttribute = new PmsProductAttribute();
pmsProductAttribute.setId(id);
BeanUtils.copyProperties(productAttributeParam, pmsProductAttribute);
return productAttributeMapper.updateByPrimaryKeySelective(pmsProductAttribute);
}
@Override
public PmsProductAttribute getItem(Long id) {
return productAttributeMapper.selectByPrimaryKey(id);
}
@Override
public int delete(List<Long> ids) {
//获取分类
PmsProductAttribute pmsProductAttribute = productAttributeMapper.selectByPrimaryKey(ids.get(0));
Integer type = pmsProductAttribute.getType();
PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId());
PmsProductAttributeExample example = new PmsProductAttributeExample();
example.createCriteria().andIdIn(ids);
int count = productAttributeMapper.deleteByExample(example);
//删除完成后修改数量
if(type==0){
if(pmsProductAttributeCategory.getAttributeCount()>=count){
pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()-count);
}else{
pmsProductAttributeCategory.setAttributeCount(0);
}
}else if(type==1){
if(pmsProductAttributeCategory.getParamCount()>=count){
pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()-count);
}else{
pmsProductAttributeCategory.setParamCount(0);
}
}
productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory);
return count;
}
@Override
public List<ProductAttrInfo> getProductAttrInfo(Long productCategoryId) {
return productAttributeDao.getProductAttrInfo(productCategoryId);
}
}
| [
"dslcfjz06"
] | dslcfjz06 |
62cd5fa4c71f3a3f6cc377a06544f652f5fe1f92 | 5b9e623ef0dfedbd865923fe5709ff7e363581b9 | /gulimall-core/src/main/java/com/atguigu/gulimall/commons/constant/RabbitMQConstant.java | 9468bfbf71b1dd0c0fc238cb291db7be59262d3d | [] | no_license | lywcode/gulimallFinally | d56a010883eded374575a191b144bd1b63d77893 | 1f14b9c5f4050f266e264a04a227ca1ff3094fe6 | refs/heads/master | 2022-10-20T15:53:06.551028 | 2019-09-08T00:47:10 | 2019-09-08T00:47:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,095 | java | package com.atguigu.gulimall.commons.constant;
public class RabbitMQConstant {
public static final String order_exchange = "order-exchange";
public static final String order_create_event_routing_key = "order.create";
public static final String order_dead_event_routing_key = "order.dead";
public static final String order_dead_release_routing_key = "order.release";
public static final String order_pay_success_routing_key = "order.payed";
public static final String order_quick_create_routing_key = "order.quick.create";
public static final Long order_timeout = 1000*60*3L;//分钟为单位
public static final String order_queue_dead = "order-dead-queue";//过期单队列的名字
public static final String order_queue_release = "order-release-queue";//释放订单的队列
public static final String order_queue_payed = "order-payed-queue";//释放订单的队列
public static final String order_queue_qucik_create = "order-quick-create-queue";
public static final String stock_queue_sub = "stock-sub-queue";//库存扣减队列
}
| [
"wangdan991278097@163.com"
] | wangdan991278097@163.com |
27d9f7ffee9847e72ea55a3543b8716d51c866bf | b4b9e4e1c4bd1ea16a14715fa60a68a08cdd2448 | /app/src/main/java/com/programacionfacil/miappparte2rbl/Comunicacion1.java | a187d848659b80bbd1811f3110c207b8911e3bca | [] | no_license | ricardobendita/MiAppParte2RBL | 81102c4af9b8fcf9ffbe2127e1fc4e631bd92bf9 | 4e80421cd85d5c4d8b3b104e2252bc6396507e7a | refs/heads/master | 2022-12-25T23:23:58.037156 | 2020-10-10T00:11:16 | 2020-10-10T00:11:16 | 302,466,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,117 | java | package com.programacionfacil.miappparte2rbl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Comunicacion1 extends AppCompatActivity {
EditText edtnombre;
EditText edtingresomes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comunicacion1);
edtnombre=findViewById(R.id.edtnombre);
edtingresomes=findViewById(R.id.edtingresomes);
}
public void Verificar(View view){
if(edtnombre.getText().length()!=0 && edtingresomes.getText().length()!=0){
Intent intent = new Intent(this, Comunicacion2.class);
intent.putExtra("nombre", edtnombre.getText().toString());
intent.putExtra("ingresomes", Integer.parseInt(edtingresomes.getText().toString()));
startActivityForResult(intent, 1234);
}else{
Toast.makeText(this,"Debes ingresar un nombre y un ingreso mensual",Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView miresultado = findViewById(R.id.txtvalor);
if (requestCode == 1234 && resultCode == RESULT_OK) {
String res = data.getExtras().getString("resultado");
if (res.equals("aceptado"))
miresultado.setText("Esperamos que trabajar con nosotros sea de su agrado");
else
miresultado.setText("Esperemos que cambie de opinion para trabajar con nosotros");
}
if (requestCode == 3500 && resultCode == RESULT_OK) {
miresultado.setText("Visitenos en alguna de nuestras sucursales");
}
}
public void sucursales(View view) {
startActivityForResult(new Intent(this, Comunicacion3.class), 3500);
}
} | [
"ricardo.bendita@gmail.com"
] | ricardo.bendita@gmail.com |
93a83bff34c96a51f48e786bfd2e13b6fea2c52f | 5b01e35d13c9ac8890869a56dd68e64fb921b79d | /exception-handling/src/main/java/spi/services/exhandler/Interface/HandleAble.java | 4a3b61a56058adc0306652e8fddbc646c38558be | [] | no_license | rajeevkedia2003/ExceptionHandling | 520b5d533b1873df32309c272cacc99d4c9b49c3 | 7a9dd555228350314787a71b34d1b4a4601dfc6c | refs/heads/master | 2021-09-05T21:40:22.055554 | 2018-01-31T06:33:05 | 2018-01-31T06:33:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 141 | java | package spi.services.exhandler.Interface;
/**
* Created by masiaban on 6/4/17.
*/
public interface HandleAble {
boolean doHandle();
}
| [
"mahdie.asiaban@gmail.com"
] | mahdie.asiaban@gmail.com |
8e5bc0abfc2004a2d4a4aed2929689e41727b578 | 1373cdcc0bdb2c6b061c3188b18ed71659a18fd6 | /src/br/com/cliente/view/ScreenDelete.java | 273dafff3eeb809b52c06799f78868875c3d401b | [] | no_license | gustavomantovane/javacrud | b91c4bab840a2681f2b06960acfa53397a5af404 | d14ab1c320c34f19c2f5aa1ded9270b96bbf18bd | refs/heads/main | 2023-08-23T21:13:44.331067 | 2021-10-17T16:19:05 | 2021-10-17T16:19:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,185 | java | package br.com.cliente.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import br.com.cliente.dao.ClienteDAO;
import br.com.cliente.model.Cliente;
public class ScreenDelete extends JFrame {
ImageIcon img;
JLabel lblNome;
JTextField txtNome;
JLabel lblID;
JTextField txtID;
JButton btnDelete;
JButton btnBack;
public ScreenDelete() {
setTitle("JavaCRUD");
setLayout(null);
setResizable(false);
setSize(430, 420);
img = new ImageIcon(getClass().getResource("logo.png"));
setIconImage(img.getImage());
lblNome = new JLabel("Nome");
lblNome.setBounds(10, 10, 200, 20);
add(lblNome);
txtNome = new JTextField(250);
txtNome.setBounds(220, 10, 200, 20);
add(txtNome);
lblID = new JLabel("ID");
lblID.setBounds(10, 40, 200, 20);
add(lblID);
txtID = new JTextField(9);
txtID.setBounds(220, 40, 200, 20);
add(txtID);
btnDelete = new JButton("Deletar");
btnDelete.setBounds(10, 340, 200, 30);
btnDelete.addActionListener(delete);
add(btnDelete);
btnBack = new JButton("Voltar");
btnBack.setBounds(220, 340, 200, 30);
btnBack.addActionListener(back);
add(btnBack);
setVisible(true);
}
ActionListener delete = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String erros = "";
if (txtNome.getText().equalsIgnoreCase("")) {
erros += "Preencha o campo Nome \n";
}
if (txtID.getText().equalsIgnoreCase("")) {
erros += "Preencha o campo ID \n";
}
if(erros.equalsIgnoreCase("")) {
Cliente c = new Cliente();
c.setNome(txtNome.getText());
c.setID(Integer.parseInt(txtID.getText()));
ClienteDAO cDAO = new ClienteDAO();
cDAO.delete(c);
} else {
JOptionPane.showMessageDialog(null, erros);
}
}
};
ActionListener back = new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
new ScreenCRUD();
}
};
public static void main(String[] args) {
new ScreenDelete();
}
}
| [
"g_mantovani@tutanota.com"
] | g_mantovani@tutanota.com |
86bfa2e9e23784094f04c71cd0ce35124279aecf | bf6744aecaf573c6e028005d119fc1d922777b9b | /src/main/java/com/sapestore/service/ReviewService.java | 7d4709349eec8c398dde663f2c46e9c7a82dcadd | [] | no_license | gursharan1512/SapeStore | b2f45ec55d3b1e7509434afd9381ea5858923d20 | 8b39a794f61488674ffc07efe018d79297cf6d05 | refs/heads/master | 2021-09-24T14:22:55.653754 | 2018-10-10T10:25:49 | 2018-10-10T10:25:49 | 152,405,260 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,411 | java | package com.sapestore.service;
import java.util.List;
import com.sapestore.exception.SapeStoreException;
import com.sapestore.hibernate.entity.BookRatingComments;
import com.sapestore.vo.BookRatingCommentVO;
// TODO: Auto-generated Javadoc
/**
* Service interface for rating and comment functionality.
*
* @author shadab
*
*/
public interface ReviewService {
/**
* Performs adding reviews.
*
* @param reviewVO the review vo
* @throws SapeStoreException Handling exception
*/
public void addBookReview(BookRatingCommentVO reviewVO) throws SapeStoreException;
/**
* Performs adding AVERAGE rating.
*
* @param bookRating the book rating
* @param isbn the isbn
* @throws SapeStoreException Handling exception
*/
public void addAverageBookRating(Integer bookRating, String isbn) throws SapeStoreException;
/**
* Returns list of reviews of the book.
*
* @param isbn the isbn
* @return ReviewList
* @throws SapeStoreException Handling exception
*/
public List<BookRatingComments> getReviewlist(String isbn) throws SapeStoreException;
/**
* Returns list of three reviews of the book.
*
* @param isbn the isbn
* @return threeReviewList
* @throws SapeStoreException Handling exception
*/
public List<BookRatingComments> getThreeReviewslist(String isbn) throws SapeStoreException;
}
| [
"sharanghotra1512@gmail.com"
] | sharanghotra1512@gmail.com |
855f0ff63b1baf2b7e269bfc2c6f45f14f92d6bf | d241ec43cffec96c4626fb4f681ce2e5c1ca9a84 | /src/smurfRunner.java | 72706ff58fa506bbb91a6e734fb73709d79dd480 | [] | no_license | League-Level1-Student/level1-module2-JoeJoePotato | b6058d8163176250960a1b413ad7e34fc8cb7a68 | f5e654c206894d226a3fc345d65400bdfa58906f | refs/heads/master | 2020-04-09T21:26:49.280508 | 2018-12-20T02:27:19 | 2018-12-20T02:27:19 | 160,602,488 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 430 | java |
public class smurfRunner {
public static void main(String[] args) {
Smurf a= new Smurf("Handy");
a.eat();
System.out.println(a.getName());
Smurf b=new Smurf("Papa");
System.out.println(b.getName());
System.out.println(b.getHatColor());
System.out.println(b.isGirlOrBoy());
Smurf c=new Smurf("Smurfette");
System.out.println(c.getName());
System.out.println(c.getHatColor());
System.out.println(c.isGirlOrBoy());
}
}
| [
"league@WTS-iMac-11.attlocal.net"
] | league@WTS-iMac-11.attlocal.net |
e73545d31c8abd2d6300cda3b286c6bce0051d04 | 2eb5604c0ba311a9a6910576474c747e9ad86313 | /chado-pg-orm/src/org/irri/iric/chado/so/MonocistronicHome.java | 85b25802800a62ec07328553816fb976c0a31571 | [] | no_license | iric-irri/portal | 5385c6a4e4fd3e569f5334e541d4b852edc46bc1 | b2d3cd64be8d9d80b52d21566f329eeae46d9749 | refs/heads/master | 2021-01-16T00:28:30.272064 | 2014-05-26T05:46:30 | 2014-05-26T05:46:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,580 | java | package org.irri.iric.chado.so;
// Generated 05 26, 14 1:32:32 PM by Hibernate Tools 3.4.0.CR1
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
/**
* Home object for domain model class Monocistronic.
* @see org.irri.iric.chado.so.Monocistronic
* @author Hibernate Tools
*/
public class MonocistronicHome {
private static final Log log = LogFactory.getLog(MonocistronicHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new InitialContext()
.lookup("SessionFactory");
} catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException(
"Could not locate SessionFactory in JNDI");
}
}
public void persist(Monocistronic transientInstance) {
log.debug("persisting Monocistronic instance");
try {
sessionFactory.getCurrentSession().persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void attachDirty(Monocistronic instance) {
log.debug("attaching dirty Monocistronic instance");
try {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Monocistronic instance) {
log.debug("attaching clean Monocistronic instance");
try {
sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void delete(Monocistronic persistentInstance) {
log.debug("deleting Monocistronic instance");
try {
sessionFactory.getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Monocistronic merge(Monocistronic detachedInstance) {
log.debug("merging Monocistronic instance");
try {
Monocistronic result = (Monocistronic) sessionFactory
.getCurrentSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public Monocistronic findById(org.irri.iric.chado.so.MonocistronicId id) {
log.debug("getting Monocistronic instance with id: " + id);
try {
Monocistronic instance = (Monocistronic) sessionFactory
.getCurrentSession().get(
"org.irri.iric.chado.so.Monocistronic", id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Monocistronic instance) {
log.debug("finding Monocistronic instance by example");
try {
List results = sessionFactory.getCurrentSession()
.createCriteria("org.irri.iric.chado.so.Monocistronic")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
}
| [
"locem@berting-debian.ourwebserver.no-ip.biz"
] | locem@berting-debian.ourwebserver.no-ip.biz |
4a8028f179c276c0fec9d00b2970d8c3ee688d0a | 3a53421aabee5ae306f69b9f6dfcd23a9d501d63 | /communication/assignment3/A3-Android-App/src/vandy/mooc/model/services/WeatherServiceBase.java | 59b45b3f37b2556e5e695d314dad0cb41111d422 | [] | no_license | MarcoFarrier/POSA-16 | a9e8b525d65f99271c6b39b216bcf172fd8d9987 | 0ebc4174b97383eb3971bd7b4910ab266fe232b3 | refs/heads/master | 2020-12-14T09:58:10.950202 | 2016-04-28T01:11:51 | 2016-04-28T01:11:51 | 53,460,706 | 1 | 0 | null | 2016-03-09T02:13:01 | 2016-03-09T02:13:01 | null | UTF-8 | Java | false | false | 5,271 | java | package vandy.mooc.model.services;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;
import vandy.mooc.common.ExecutorServiceTimeoutCache;
import vandy.mooc.common.GenericSingleton;
import vandy.mooc.common.LifecycleLoggingService;
import vandy.mooc.model.aidl.WeatherData;
import vandy.mooc.model.aidl.WeatherDataJsonParser;
import android.util.Log;
/**
* This is the super class for both WeatherServiceSync and
* WeatherServiceAsync. It factors out fields and methods that are
* shared by both Service implementations.
*/
public class WeatherServiceBase
extends LifecycleLoggingService {
/**
* Appid needed to access the service. TODO -- fill in with your Appid.
*/
private final String mAppid = "";
/**
* URL to the Weather Service web service.
*/
private String mWeatherServiceURL =
"http://api.openweathermap.org/data/2.5/weather?&APPID="
+ mAppid + "&q=";
/**
* Default timeout is 10 seconds, after which the Cache data
* expires. In a production app this value should be much higher
* (e.g., 10 minutes) - we keep it small here to help with
* testing.
*/
private int DEFAULT_CACHE_TIMEOUT = 10;
/**
* Define a class that will cache the WeatherData since it doesn't
* change rapidly. This class is passed to the
* GenericSingleton.instance() method to retrieve the one and only
* instance of the WeatherCache.
*/
public static class WeatherCache
extends ExecutorServiceTimeoutCache<String, List<WeatherData>> {}
/**
* Hook method called when the Service is created.
*/
@Override
public void onCreate() {
super.onCreate();
// TODO -- you fill in here.
}
/**
* Hook method called when the last client unbinds from the
* Service.
*/
@Override
public void onDestroy() {
super.onDestroy();
// TODO -- you fill in here.
}
/**
* Contitionally queries the Weather Service web service to obtain
* a List of WeatherData corresponding to the @a location if it's
* been more than 10 seconds since the last query to the Weather
* Service. Otherwise, simply return the cached results.
*/
protected List<WeatherData> getWeatherResults(String location) {
Log.d(TAG,
"Looking up results in the cache for "
+ location);
// TODO -- you fill in here.
}
/**
* Actually query the Weather Service web service to get the
* current WeatherData. Usually only returns a single element in
* the List, but can return multiple elements if they are sent
* back from the Weather Service.
*/
private List<WeatherData> getResultsFromWeatherService(String location) {
// Create a List that will return the WeatherData obtained
// from the Weather Service web service.
List<WeatherData> returnList = null;
try {
// Create a URL that points to desired location the
// Weather Service.
URL url =
new URL(mWeatherServiceURL + Uri.encode(location));
final URI uri = new URI(url.getProtocol(),
url.getUserInfo(),
url.getHost(),
url.getPort(),
url.getPath(),
url.getQuery(),
url.getRef());
url = uri.toURL();
// Opens a connection to the Weather Service.
HttpURLConnection urlConnection =
(HttpURLConnection) url.openConnection();
// Sends the GET request and returns a stream containing
// the Json results.
try (InputStream in =
new BufferedInputStream(urlConnection.getInputStream())) {
// Create the parser.
final WeatherDataJsonParser parser =
new WeatherDataJsonParser();
// Parse the Json results and create List of
// WeatherData objects.
returnList = parser.parseJsonStream(in);
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
// See if we parsed any valid data.
if (returnList == null
|| returnList.size() == 0) {
Log.d(TAG,
"unable to get information about \""
+ location
+ "\"");
return null;
} else if (returnList.get(0).getMessage() != null) {
// The Weather Service returned an error message.
Log.d(TAG,
returnList.get(0).getMessage()
+ " \""
+ location
+ "\"");
return null;
} else
// Return the List of WeatherData.
return returnList;
}
}
| [
"d.schmidt@vanderbilt.edu"
] | d.schmidt@vanderbilt.edu |
99247982ec9923c3e4f434d341e1e8b388fb5a6c | 9f7be45f62fe27a5cce4f8b45dd13d719259c73d | /src/main/java/com/deo/thymeleafdbdemo/entity/Employee.java | 9c5adcc58f5c0ed87d362e487fe0c2ef8fb5ba05 | [] | no_license | deolexx/thymeleaf-db-demo | 242a5eb13496b08de43c1d469717dfac6c270a30 | 5a950280f7398638270ffa41b6d986f7e6784f58 | refs/heads/main | 2023-02-11T07:42:58.237321 | 2021-01-07T21:16:26 | 2021-01-07T21:16:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,181 | java | package com.deo.thymeleafdbdemo.entity;
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public Employee(){}
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
| [
"lukyanenko88@gmail.com"
] | lukyanenko88@gmail.com |
39ad403d7b2ff0d7d1598d869d7b96abeee7a537 | db37c937b7aa01491ab6d0bbca369e7c24dc9638 | /geotracker/server/src/main/java/ch/rasc/geotracker/GeoController.java | 553e880af360b6034485f6d7068affeda1ef03fd | [
"MIT"
] | permissive | ralscha/blog | a7fc489ec7f09d2f566873262690364c0ea05b19 | 42b117db20a5a654d7d76e11912304dcdca8fe3d | refs/heads/master | 2023-08-03T10:58:09.694000 | 2023-07-31T18:42:35 | 2023-07-31T18:42:35 | 78,191,118 | 242 | 308 | MIT | 2022-11-19T17:09:51 | 2017-01-06T08:59:53 | TypeScript | UTF-8 | Java | false | false | 2,731 | java | package ch.rasc.geotracker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ch.rasc.sse.eventbus.SseEvent;
import ch.rasc.sse.eventbus.SseEventBus;
import jakarta.servlet.http.HttpServletResponse;
@RestController
@CrossOrigin
public class GeoController {
private final ApplicationEventPublisher publisher;
private final List<Position> positions;
private final ObjectMapper objectMapper;
private final SseEventBus eventBus;
public GeoController(ApplicationEventPublisher publisher, ObjectMapper objectMapper,
SseEventBus eventBus) {
this.publisher = publisher;
this.positions = new ArrayList<>();
this.objectMapper = objectMapper;
this.eventBus = eventBus;
}
@GetMapping("/positions")
public List<Position> fetchPositions() {
return this.positions;
}
@GetMapping("/register/{id}")
public SseEmitter eventbus(@PathVariable("id") String id,
HttpServletResponse response) {
response.setHeader("Cache-Control", "no-store");
return this.eventBus.createSseEmitter(id, "pos", "clear");
}
@DeleteMapping(path = "/clear")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void clear() {
this.positions.clear();
this.publisher.publishEvent(SseEvent.ofEvent("clear"));
}
@PostMapping(path = "/pos")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void handleLocation(@RequestBody Position position)
throws JsonProcessingException {
SseEvent event = SseEvent.of("pos",
this.objectMapper.writeValueAsString(Collections.singleton(position)));
this.publisher.publishEvent(event);
this.positions.add(position);
if (this.positions.size() > 100) {
this.positions.remove(0);
}
}
@PostMapping(path = "/clienterror")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void handleError(@RequestBody String errorMessage) {
Application.logger.error(errorMessage);
}
}
| [
"ralphschaer@gmail.com"
] | ralphschaer@gmail.com |
2c00aa2ec5e4918d15614d3dee843c31a2059fc2 | b755a269f733bc56f511bac6feb20992a1626d70 | /model/model-util/src/main/java/com/qiyun/util/Ascii2NativeUtil.java | 45d893afa50ac5dcc0ae434acfb47b729610a0e4 | [] | no_license | yysStar/dubbo-zookeeper-SSM | 55df313b58c78ab2eaa3d021e5bb201f3eee6235 | e3f85dea824159fb4c29207cc5c9ccaecf381516 | refs/heads/master | 2022-12-21T22:50:33.405116 | 2020-05-09T09:20:41 | 2020-05-09T09:20:41 | 125,301,362 | 2 | 0 | null | 2022-12-16T10:51:09 | 2018-03-15T02:27:17 | Java | UTF-8 | Java | false | false | 7,961 | java | package com.qiyun.util;
/**
* 编码转换工具类
*/
public class Ascii2NativeUtil {
/**
* prefix of ascii string of native character
*/
private static String PREFIX = "\\u";
/**
* Native to ascii string. It's same as execut native2ascii.exe.
* @param str native string
* @return ascii string
*/
public static String native2Ascii(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
sb.append(char2Ascii(chars[i]));
}
return sb.toString();
}
/**
* Native character to ascii string.
* @param c native character
* @return ascii string
*/
private static String char2Ascii(char c) {
if (c > 255) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX);
int code = (c >> 8);
String tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
code = (c & 0xFF);
tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
return sb.toString();
} else {
return Character.toString(c);
}
}
/**
* Ascii to native string. It's same as execut native2ascii.exe -reverse.
* @param str ascii string
* @return native string
*/
public static String ascii2Native(String str) {
StringBuilder sb = new StringBuilder();
int begin = 0;
int index = str.indexOf(PREFIX);
while (index != -1) {
sb.append(str.substring(begin, index));
sb.append(ascii2Char(str.substring(index, index + 6)));
begin = index + 6;
index = str.indexOf(PREFIX, begin);
}
sb.append(str.substring(begin));
return sb.toString();
}
/**
* Ascii to native character.
* @param str ascii string
* @return native character
*/
private static char ascii2Char(String str) {
if (str.length() != 6) {
throw new IllegalArgumentException(
"Ascii string of a native character must be 6 character.");
}
if (!PREFIX.equals(str.substring(0, 2))) {
throw new IllegalArgumentException(
"Ascii string of a native character must start with \"\\u\".");
}
String tmp = str.substring(2, 4);
int code = Integer.parseInt(tmp, 16) << 8;
tmp = str.substring(4, 6);
code += Integer.parseInt(tmp, 16);
return (char) code;
}
// public static void main(String[] args) {
// String s = "cphData({\"data\":[{\"data\":\"1-\\u5df4\\u897f-\\u5f00\\u552e-2.95-0%-19.27%-4671301-equal-467130-1-417-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/417.png|2-\\u5fb7\\u56fd-\\u5f00\\u552e-3.50-0%-16.24%-4671302-equal-467130-2-377-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/377.png|3-\\u897f\\u73ed\\u7259-\\u5f00\\u552e-4.10-0%-13.86%-4671303-equal-467130-3-23-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/23.png|4-\\u963f\\u6839\\u5ef7-\\u5f00\\u552e-4.50-0%-12.63%-4671304-equal-467130-4-413-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/413.png|5-\\u6cd5\\u56fd-\\u5f00\\u552e-5.00-0%-11.37%-4671305-equal-467130-5-375-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/375.png|6-\\u6bd4\\u5229\\u65f6-\\u5f00\\u552e-10.00-0%-5.68%-4671306-equal-467130-6-363-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/363.png|7-\\u8461\\u8404\\u7259-\\u5f00\\u552e-15.00-0%-3.79%-4671307-equal-467130-7-1044-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/1044.png|8-\\u82f1\\u683c\\u5170-\\u5f00\\u552e-14.00-0%-4.06%-4671308-equal-467130-8-370-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/370.png|9-\\u4e4c\\u62c9\\u572d-\\u5f00\\u552e-22.00-0%-2.58%-4671309-equal-467130-9-414-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/414.png|10-\\u54e5\\u4f26\\u6bd4\\u4e9a-\\u5f00\\u552e-25.00-0%-2.27%-46713010-equal-467130-10-410-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/410.png|11-\\u514b\\u7f57\\u5730\\u4e9a-\\u5f00\\u552e-35.00-0%-1.62%-46713011-equal-467130-11-366-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/366.png|12-\\u4fc4\\u7f57\\u65af-\\u5f00\\u552e-55.00-0%-1.03%-46713012-equal-467130-12-396-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/396.png|13-\\u58a8\\u897f\\u54e5-\\u5f00\\u552e-70.00-0%-0.81%-46713013-equal-467130-13-416-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/416.png|14-\\u6ce2\\u5170-\\u5f00\\u552e-65.00-0%-0.87%-46713014-equal-467130-14-392-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/392.png|15-\\u745e\\u58eb-\\u5f00\\u552e-110.0-0%-0.52%-46713015-equal-467130-15-403-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/403.png|16-\\u4e39\\u9ea6-\\u5f00\\u552e-100.0-0%-0.57%-46713016-equal-467130-16-369-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/369.png|17-\\u585e\\u5c14\\u7ef4\\u4e9a-\\u5f00\\u552e-175.0-0%-0.32%-46713017-equal-467130-17-399-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/399.png|18-\\u745e\\u5178-\\u5f00\\u552e-200.0-0%-0.28%-46713018-equal-467130-18-402-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/402.png|19-\\u79d8\\u9c81-\\u5f00\\u552e-200.0-0%-0.28%-46713019-equal-467130-19-409-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/409.png|20-\\u65e5\\u672c-\\u5f00\\u552e-250.0-0%-0.23%-46713020-equal-467130-20-438-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/438.png|21-\\u5c3c\\u65e5\\u5229\\u4e9a-\\u5f00\\u552e-250.0-0%-0.23%-46713021-equal-467130-21-773-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/773.png|22-\\u585e\\u5185\\u52a0\\u5c14-\\u5f00\\u552e-200.0-0%-0.28%-46713022-equal-467130-22-774-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/774.png|23-\\u57c3\\u53ca-\\u5f00\\u552e-250.0-0%-0.23%-46713023-equal-467130-23-543-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/543.png|24-\\u51b0\\u5c9b-\\u5f00\\u552e-250.0-0%-0.23%-46713024-equal-467130-24-380-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/380.png|25-\\u7a81\\u5c3c\\u65af-\\u5f00\\u552e-700.0-0%-0.08%-46713025-equal-467130-25-425-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/425.png|26-\\u6fb3\\u5927\\u5229\\u4e9a-\\u5f00\\u552e-600.0-0%-0.09%-46713026-equal-467130-26-421-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/421.png|27-\\u6469\\u6d1b\\u54e5-\\u5f00\\u552e-500.0-0%-0.11%-46713027-equal-467130-27-424-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/424.png|28-\\u97e9\\u56fd-\\u5f00\\u552e-600.0-0%-0.09%-46713028-equal-467130-28-430-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/430.png|29-\\u4f0a\\u6717-\\u5f00\\u552e-600.0-0%-0.09%-46713029-equal-467130-29-440-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/440.png|30-\\u54e5\\u65af\\u8fbe\\u9ece\\u52a0-\\u5f00\\u552e-500.0-0%-0.11%-46713030-equal-467130-30-420-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/420.png|31-\\u5df4\\u62ff\\u9a6c-\\u5f00\\u552e-800.0-0%-0.07%-46713031-equal-467130-31-524-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/524.png|32-\\u6c99\\u7279-\\u5f00\\u552e-1000-0%-0.06%-46713032-equal-467130-32-434-http:\\/\\/static.sporttery.cn\\/sinaimg\\/football\\/wcp2018\\/434.png\",\"id\":\"104895\",\"p_id\":\"467130\",\"name\":\"2018\\u4e16\\u754c\\u676f\",\"odds_type\":\"CHP\"}]})";
// System.out.println(Ascii2NativeUtil.ascii2Native(s));
// }
}
| [
"qawsed1231010@126.com"
] | qawsed1231010@126.com |
34ca4e83369b8d62b3602b79918d3793af94c03f | 7cb7d11a26f978cf2230ba2da0140c9beb0c9f06 | /src/test/java/com/udpimplementation/comp445a3/PacketTest.java | f5eb5048ad56fe95d76a4ac26c311440c75d9baa | [] | no_license | sunyanl1236/UDPImplementation | 43ba2cc5efe245165b232d48c760855102682ef6 | 24e4542749db63f232a538d851e2d83d6011e21d | refs/heads/main | 2023-01-24T09:20:42.944942 | 2020-12-06T20:06:57 | 2020-12-06T20:06:57 | 314,935,887 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,142 | java | package com.udpimplementation.comp445a3;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(JUnitParamsRunner.class)
public class PacketTest {
@Test
@Parameters(method = "packets")
public void testWritePacket(Packet p, int[] expectInts) throws Exception {
byte[] expectBytes = new byte[expectInts.length];
for(int i = 0; i < expectBytes.length; i++){
expectBytes[i] = (byte)expectInts[i];
}
assertThat(p.toBytes())
.isEqualTo(expectBytes);
}
@Test
@Parameters(method = "packets")
public void testParseValidPackets(Packet expectPacket, int[] inputInts) throws Exception {
byte[] inputBytes = new byte[inputInts.length];
for(int i = 0; i < inputBytes.length; i++){
inputBytes[i] = (byte)inputInts[i];
}
Packet p = Packet.fromBytes(inputBytes);
assertThat(p.toBytes())
.isEqualTo(inputBytes);
assertThat(p.toBytes())
.isEqualTo(expectPacket.toBytes());
}
public static InetAddress addr(int ...vals) throws Exception{
assert vals.length == 4;
byte[] bytes = new byte[4];
for(int i = 0; i < vals.length; i++){
bytes[i] = (byte)vals[i];
}
return InetAddress.getByAddress(bytes);
}
@Parameterized.Parameters
public static Collection<Object[]> packets() throws Exception{
return Arrays.asList(new Object[][]{
{
new Packet.Builder()
.setType(1)
.setSequenceNumber(45)
.setPeerAddress(addr(127, 0, 0, 1))
.setPortNumber(2100)
.setPayload("Hello World".getBytes())
.create(),
new int[]{
1,
0, 0, 0, 45,
127, 0, 0, 1,
8, 52,
72,101,108,108,111,32,87,111,114,108,100
}
},
{
new Packet.Builder()
.setType(29)
.setSequenceNumber(2992122123L) //unsigned int
.setPeerAddress(addr(192, 168, 2, 125))
.setPortNumber(53201)
.setPayload("".getBytes())
.create(),
new int[]{
29,
178, 88, 41, 11,
192, 168, 2, 125,
207, 209,
}
},
});
}
} | [
"yiluliang1236@gmail.com"
] | yiluliang1236@gmail.com |
554222a8af784451ed6a30c92391033de5145bdb | 0bfdb25f3669384415c7dc232720081a05c06fd7 | /src/main/java/testClass.java | c8acb520db1821ff2ffafbb60b3b7958c00f56af | [] | no_license | ExperitestOfficial/appium-log-java | 052477c37f9b3c2cec7158127c2aa5101c543f11 | 245c7c29564a6cbd95845f0d7c649e1e83f029df | refs/heads/master | 2021-01-15T18:21:40.330140 | 2017-08-09T08:41:31 | 2017-08-09T08:41:31 | 99,779,139 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 27 | java | public class testClass {
}
| [
"nivi.mor@experitest.com"
] | nivi.mor@experitest.com |
14fb5337563dbbd5a3f686bd063e3943ee1269c2 | b4719d55c81edc570ef3eb379cbb9dca4916d5d7 | /Assignment1/src/sample/Controller.java | 05361df0188f122e693dc7737f69e828849fcc09 | [] | no_license | musabbirbaki/CSCI2020U_Assignments | bf8425cd831568d070e0bf245aae620f3a779e2c | fc57085fb0235d8af08fcd2ba8928e9b70a157d5 | refs/heads/master | 2021-04-27T10:32:13.670380 | 2018-03-09T19:48:25 | 2018-03-09T19:48:25 | 122,541,428 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,414 | java | package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.ResourceBundle;
public class Controller implements Initializable {
private Stage stage;
private String dataDirectory;
//declare table veiew
@FXML private TableView<TestFile> tableView;
//declare columns
@FXML private TableColumn<TestFile, String> filenameColumn;
// @FXML private TableColumn<TestFile, Double> spamProbabilityColumn;
@FXML private TableColumn<TestFile, String> spamProbabilityColumn;
@FXML private TableColumn<TestFile, String> actualClassColumn;
@FXML private TextField Accuracy;
@FXML private TextField Precision;
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("Starting Program\nWaiting for User to select Data directory.");
String trainFolderDirectory;
String testFolderDirectory;
//user will select the folder which contains the train and test folder
setDataDirectory();
System.out.println("Chosen directory: " + this.dataDirectory);
//get Train folder directory
trainFolderDirectory = dataDirectory + "/train";
//get Test folder directory
testFolderDirectory = dataDirectory + "/test";
//run train on Train Directory
//can read multiple ham and spam folders
Map<String, Double> probSgivenWord = Train.runTrain(trainFolderDirectory);
//run test on Test Directory
//only reads one folder for spam and ham each
//Threshold: 0.7 means a file is only considered spam if the spam probability is greater than 0.7
Test test = new Test(testFolderDirectory, probSgivenWord, 0.7);
test.runTest();
ArrayList<TestFile> tFilesHam = test.gettFilesHam();
ArrayList<TestFile> tFilesSpam = test.gettFilesSpam();
double accuracy = test.getAccuracy();
double precision = test.getPrecision();
//ObservableList<TestFile> getAllFiles = DataSource.getAllFiles(tFilesHam,tFilesSpam);
showData(tFilesHam,tFilesSpam);
this.Accuracy.setText(accuracy + "");
this.Precision.setText(precision + "");
System.out.println("Completed Testing\nShowing Results.\n");
//System.exit(0);
}
public void setStage(Stage stage) {
this.stage = stage;
}
/**
* This function allows the user to select a proper "data" directory,
* if the directory selected doesn't contain files "test" and "train"
* the user has to retry selecting the directory until "test" and "train"
* files have been found. If the user closes the directory selection
* process. The program terminates using System.exit(0).
*/
private void setDataDirectory() {
try {
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setInitialDirectory(new File("."));
File mainDirectory = directoryChooser.showDialog(this.stage);
File[] files = mainDirectory.listFiles();
boolean hasSpam = false;
boolean hasHam = false;
for (File f : files) {
if (f.isDirectory()) {
if (f.getName().toLowerCase().contains("test")) {
hasSpam = true;
}
if (f.getName().toLowerCase().contains("train")) {
hasHam = true;
}
}
}
this.dataDirectory = mainDirectory.getAbsolutePath();
if (!hasSpam && !hasHam) {
System.out.println("Please Reselect data directory.");
AlertBox.display("Error",
"This directory doesn't contain test and train files. \nPlease Reselect data directory.",
"Retry");
setDataDirectory();
}
} catch (NullPointerException n) {
AlertBox.display("Null Pointer Error",
"The program faced a Null Pointer error. \n The program will close.",
"Close Program");
System.exit(0);
} catch (Exception e) {
System.out.println(e);
setDataDirectory();
}
System.out.println("Trying Chosen directory: " + dataDirectory);
}
/**
* This method sets the cell values and sets the items in Table view
*/
private void showData(ArrayList<TestFile> tFilesHam, ArrayList<TestFile> tFilesSpam) {
filenameColumn.setCellValueFactory(new PropertyValueFactory<TestFile, String>("filename"));
// spamProbabilityColumn.setCellValueFactory(new PropertyValueFactory<TestFile, Double>("spamProbability"));
actualClassColumn.setCellValueFactory(new PropertyValueFactory<TestFile, String>("actualClass"));
spamProbabilityColumn.setCellValueFactory(new PropertyValueFactory<TestFile, String>("spamProbability"));
tableView.setItems(DataSource.getAllFiles(tFilesHam, tFilesSpam));
}
}
| [
"musabbir.a.b@hotmail.com"
] | musabbir.a.b@hotmail.com |
9db1b8f7de258ca6d8ecb1c692c29ac3df2b2e79 | acb05378f7d584b0a57bfd6beab8bad54fdac154 | /source/com/jonasreese/sound/sg/midi/Metronome.java | ebf8622d8b2e4201c7b9a47ae89d0f8156f5575c | [] | no_license | jonasreese/soundsgood | 83f5b403cf53e153f97ec24e6064c794794e9ccd | f658b5c98302a23393169d28e448cbd7d52e35e1 | refs/heads/master | 2021-01-20T22:28:51.539018 | 2013-06-10T10:03:03 | 2013-06-10T10:03:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,037 | java | /*
* Created on 10.07.2005
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code Template
*/
package com.jonasreese.sound.sg.midi;
import javax.sound.midi.Receiver;
/**
* <p>
* This interface shall be implemented by classes that perform metronome functionality.
* </p>
* @author jonas.reese
* @see com.jonasreese.sound.sg.midi.MidiRecorder
*/
public interface Metronome {
/**
* Adds a MIDI output receiver to this <code>MidiRecorder</code>. An output
* MIDI receiver receives all MIDI events that are sent to any output device.
* @param midiOutputReceiver The <code>Receiver</code> that shall receive MIDI
* events after being sent to an output device. If the given
* <code>MidiOutputReceiver</code> has already been added, this method does nothing.
*/
public void addMidiOutputReceiver( Receiver midiOutputReceiver );
/**
* Removes the given MIDI output receiver from this <code>MidiRecorder</code>.
* @param midiOutputReceiver The MIDI output receiver that shall no longer
* receive any MIDI events after being sent to an output device. If the given
* <code>Receiver</code> is not registered as MIDI output receiver, this method
* does nothing.
*/
public void removeMidiOutputReceiver( Receiver midiOutputReceiver );
/**
* Enables/disables the default MIDI click device output.
* @param defaultDeviceOutput <code>true</code> if the default device output
* shall be enabled, <code>false</code> otherwise.
*/
public void setDefaultDeviceOutputEnabled( boolean defaultDeviceOutputEnabled );
/**
* Gets the current default device output enabled state.
* @return <code>true</code> if the click is sent to the default click devices
* configured, <code>false</code> otherwise. Default value is <code>false</code>.
*/
public boolean isDefaultDeviceOutputEnabled();
/**
* Enables/disables the sending of MIDI clock events (also known as MIDI beat clock,
* MIDI timing clock).
* @param sendMidiClockEnabled Enables/disables the sending MIDI clock events.
*/
public void setSendMidiClockEnabled(boolean sendMidiClockEnabled);
/**
* Gets the MIDI clock enabled state.
* @return <code>true</code> if and only if sending of MIDI clock events is enabled.
*/
public boolean isSendMidiClockEnabled();
/**
* Starts the metronome click.
*/
public void start();
/**
* Stops the metronome click.
*/
public void stop();
/**
* Synchronizes the metronome click.
*/
public void sync();
/**
* Sets the number of beats per tact.
*/
public void setBeatsPerTact( int beatsPerTact );
/**
* Gets the number of beats per tact.
* @return The beats per tact.
*/
public int getBeatsPerTact();
/**
* Gets the tact counter. The tact counter is incremented with each tact.
* @return The tact counter.
*/
public int getTactCounter();
/**
* Gets the metronome click's running state.
* @return <code>true</code> if the metronome is running, <code>false</code>
* otherwise.
*/
public boolean isRunning();
/**
* Sets the tempo in beats per minute.
* @param tempoInBpm The metronome tempo.
*/
public void setTempoInBpm( float tempoInBpm );
/**
* Gets the tempo in beats per minute.
* @return The current tempo.
*/
public float getTempoInBpm();
/**
* Sets the tempo in microseconds per quarternote.
* @param tempoInMpq The metronome tempo.
*/
public void setTempoInMpq( float tempoInMpq );
/**
* Gets the tempo in microseconds per quarternote.
* @return The current tempo.
*/
public float getTempoInMpq();
}
| [
"jr@jonasreese.com"
] | jr@jonasreese.com |
ca3c9f55e067dce1caa0d9f06c015f6d913f2022 | 49e87616264ba3ade189c2b08a45bba0a20950d9 | /app/src/main/java/com/repayment/money/ui/activity/PayScheduleActivity.java | e9d5724fc42083dcf54c4e4eec13aaa8c8af52c8 | [] | no_license | sfysfy/HuanKuan | c5c6342ecfc1ce7e3a82621acebb4e7be96f03d1 | e716d9db141ef7986f9838f968ea93b642ada1d5 | refs/heads/master | 2021-01-22T18:33:21.581133 | 2017-08-29T02:37:06 | 2017-08-29T02:37:06 | 100,764,244 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,057 | java | package com.repayment.money.ui.activity;
import com.example.mylibrary.base.BaseActivityWithNet;
import com.repayment.money.R;
import com.repayment.money.common.Constant;
import com.repayment.money.entity.BillDetailEntity;
public class PayScheduleActivity extends BaseActivityWithNet<BillDetailEntity> {
@Override
protected void initNetData() {
}
@Override
protected void initLocalData() {
}
@Override
protected void success(BillDetailEntity entity) {
}
@Override
protected void failed(Throwable throwable) {
}
@Override
protected String gerUrl() {
// http://101.200.128.107:10028/repayment/order/findHuankuan?orderNo=2017082316215303710001
//还款状态1-已还款,0-未还款,3-还款处理中,4-还款失败
return Constant.BILL_DETAIL_URL;
}
@Override
protected int addRootView() {
return R.layout.activity_pay_schedule;
}
@Override
protected void initView() {
}
@Override
protected void initListener() {
}
}
| [
"1186265546@qq.com"
] | 1186265546@qq.com |
c54fc4a4a4c5f7d1a76fccafb5c18a0dfb1d386f | c6716b711914670345d4718ea00ff36e71d844b5 | /src/brbad/Meth.java | 8a72fd98f708ffa2bdbc8780a77c55d71aab2ecb | [] | no_license | CesarRubenAlejandro/BreakingBad-game | aa7fa7f095733c8f4d7a42f035cff81397db2ec5 | 56c306b20c85d8ebbbf65c7ec445314f6123e46a | refs/heads/master | 2021-01-13T14:19:57.441875 | 2014-03-10T20:27:36 | 2014-03-10T20:27:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,509 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package brbad;
/**
*
* @author Angela Romo, Cesar Rdz
*/
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
public class Meth extends Base {
public Meth(int posX, int posY) {
super(posX, posY);
URL bURL = this.getClass().getResource("ImagesMeth/meth_100.jpg");
Image pic0 = Toolkit.getDefaultToolkit().getImage(bURL);
URL b1URL = this.getClass().getResource("ImagesMeth/meth_101.jpg");
Image pic1 = Toolkit.getDefaultToolkit().getImage(b1URL);
URL b2URL = this.getClass().getResource("ImagesMeth/meth_102.jpg");
Image pic2 = Toolkit.getDefaultToolkit().getImage(b2URL);
URL b3URL = this.getClass().getResource("ImagesMeth/meth_103.jpg");
Image pic3 = Toolkit.getDefaultToolkit().getImage(b3URL);
URL b4URL = this.getClass().getResource("ImagesMeth/meth_104.jpg");
Image pic4 = Toolkit.getDefaultToolkit().getImage(b4URL);
URL b5URL = this.getClass().getResource("ImagesMeth/meth_105.jpg");
Image pic5 = Toolkit.getDefaultToolkit().getImage(b5URL);
URL b6URL = this.getClass().getResource("ImagesMeth/meth_106.jpg");
Image pic6 = Toolkit.getDefaultToolkit().getImage(b6URL);
URL b7URL = this.getClass().getResource("ImagesMeth/meth_107.jpg");
Image pic7 = Toolkit.getDefaultToolkit().getImage(b7URL);
URL b8URL = this.getClass().getResource("ImagesMeth/meth_108.jpg");
Image pic8 = Toolkit.getDefaultToolkit().getImage(b8URL);
URL b9URL = this.getClass().getResource("ImagesMeth/meth_109.jpg");
Image pic9 = Toolkit.getDefaultToolkit().getImage(b9URL);
URL b10URL = this.getClass().getResource("ImagesMeth/meth_110.jpg");
Image pic10 = Toolkit.getDefaultToolkit().getImage(b10URL);
anima = new Animacion();
anima.sumaCuadro(pic0, 200);
anima.sumaCuadro(pic1, 200);
anima.sumaCuadro(pic2, 200);
anima.sumaCuadro(pic3, 200);
anima.sumaCuadro(pic4, 200);
anima.sumaCuadro(pic5, 200);
anima.sumaCuadro(pic6, 200);
anima.sumaCuadro(pic7, 200);
anima.sumaCuadro(pic8, 200);
anima.sumaCuadro(pic9, 200);
anima.sumaCuadro(pic10, 200);
}
}
| [
"angela_9412@hotmail.com"
] | angela_9412@hotmail.com |
7f78e69bb4dc634a35ff0c70b10752cad7634339 | 36c6f117ec12d4916cf6625dd45563394b3d8ba7 | /app/src/main/java/hp/harsh/projectbrain/util/RxUtil.java | 41e495f37d12129d0771d672f42368112d62db84 | [] | no_license | hp-harsh/ProjectBrainAndroid | fb11d19ec3817318a1f8f1576680d3bad14a173e | b5b7819dc96a86b96f05e0245fa06c0033391686 | refs/heads/master | 2022-11-20T00:35:14.422545 | 2020-07-19T01:03:44 | 2020-07-19T01:03:44 | 278,514,658 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,616 | java | package hp.harsh.projectbrain.util;
import android.app.Activity;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import hp.harsh.projectbrain.R;
import hp.harsh.projectbrain.interfaces.SplashInterface;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class RxUtil {
public static String TAG = RxUtil.class.getSimpleName();
private static boolean mDoubleBackToExitPressedOnce = false;
private ResourceUtil mResourceUtil;
@Inject
public RxUtil(ResourceUtil resourceUtil) {
this.mResourceUtil = resourceUtil;
}
public void waitForSplashTimeOut(final SplashInterface mSplashInterface) {
Single.just(new Object())
.delay(3, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Object>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Object o) {
mSplashInterface.onSplashTimeOver();
}
@Override
public void onError(Throwable e) {
}
});
}
public void quitApp(Activity activity) {
if (activity == null) {
return;
}
if (mDoubleBackToExitPressedOnce) {
activity.finish();
}
if (!mDoubleBackToExitPressedOnce) {
mDoubleBackToExitPressedOnce = true;
ToastUtil.show(activity, mResourceUtil.getString(R.string.toast_press_to_close));
}
checkDoubleBackPressTime();
}
private void checkDoubleBackPressTime() {
Single.just(new Object())
.delay(2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver());
}
private SingleObserver<Object> getObserver() {
return new SingleObserver<Object>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Object o) {
mDoubleBackToExitPressedOnce = false;
}
@Override
public void onError(Throwable e) {
}
};
}
}
| [
"hpatel4692@gmail.com"
] | hpatel4692@gmail.com |
a50413def426227eac0accd24dc426bf10cb8ac5 | 7d6c71900be4ca6bdc2029fda4bdeb1db771cf23 | /app/src/main/java/com/mythmayor/mvvmarchitecture/utils/net/APIService.java | 4eeff9922aa47e65b9ff8017447986bbc93d0941 | [
"Apache-2.0"
] | permissive | mythmayor/MvvmArchitecture | 433bb308b2790867d5ec35b351ee061f4224c386 | e5d5c6a3b6a5adf57ccc3bbe94fc3129c3ffa31a | refs/heads/master | 2022-11-11T23:03:20.970261 | 2020-07-01T04:14:55 | 2020-07-01T04:14:55 | 276,071,086 | 4 | 3 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package com.mythmayor.mvvmarchitecture.utils.net;
import com.mythmayor.mvvmarchitecture.response.LoginResponse;
import io.reactivex.rxjava3.core.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* Created by mythmayor on 2020/6/30.
* 接口请求方法类
*/
public interface APIService {
/**
* 登录
*
* @param username 账号
* @param password 密码
* @return
*/
@FormUrlEncoded
@POST("user/login")
Observable<LoginResponse> login(@Field("username") String username, @Field("password") String password);
}
| [
"mythmayor@163.com"
] | mythmayor@163.com |
2e5c38abc6adfdbd859f339ff1ff37feaa56909d | f5748681631f5685a9d8a1bcc8b757ce39f3bdd2 | /src/com/savi/show/dto/DeviceInfo.java | f131cb53b0ba367d099304bd8247913f079d7bd7 | [] | no_license | AlexanderChou/neteye | a573e921f8868aa2420956993451037e98dbcf9a | 772f40477251477f6b865bc2c13ff4ec30237061 | refs/heads/master | 2021-01-13T00:49:13.397622 | 2016-05-08T07:31:31 | 2016-05-08T07:31:31 | 54,363,134 | 1 | 1 | null | 2016-03-31T07:43:08 | 2016-03-21T05:50:11 | Java | UTF-8 | Java | false | false | 3,062 | java | package com.savi.show.dto;
/**
* Switchbasicinfo entity. @author MyEclipse Persistence Tools
*/
public class DeviceInfo {
// Fields
private Long id;
private String name;
private String equipmentType;
private String ipv4address;
private String ipv6address;
private String description;
private String snmpVersion;
private String readCommunity;
private String writeCommunity;
private String authKey;
private String privateKey;
private Integer status;
// Constructors
/** default constructor */
public DeviceInfo() {
}
public DeviceInfo(Long id,String name,String equipmentType,String ipv4address,String ipv6address,String subnetName,Long subnetId,Integer status,
String description,String snmpVersion,String readCommunity,String writeCommunity,String authKey,
String privateKey) {
this.id = id;
this.name = name;
this.equipmentType = equipmentType;
this.ipv4address = ipv4address;
this.ipv6address = ipv6address;
this.status = status;
this.description=description;
this.snmpVersion=snmpVersion;
this.readCommunity=readCommunity;
this.writeCommunity=writeCommunity;
this.authKey=authKey;
this.privateKey=privateKey;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEquipmentType() {
return this.equipmentType;
}
public void setEquipmentType(String equipmentType) {
this.equipmentType = equipmentType;
}
public String getIpv4address() {
return this.ipv4address;
}
public void setIpv4address(String ipv4address) {
this.ipv4address = ipv4address;
}
public String getIpv6address() {
return this.ipv6address;
}
public void setIpv6address(String ipv6address) {
this.ipv6address = ipv6address;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSnmpVersion() {
return this.snmpVersion;
}
public void setSnmpVersion(String snmpVersion) {
this.snmpVersion = snmpVersion;
}
public String getReadCommunity() {
return this.readCommunity;
}
public void setReadCommunity(String readCommunity) {
this.readCommunity = readCommunity;
}
public String getWriteCommunity() {
return this.writeCommunity;
}
public void setWriteCommunity(String writeCommunity) {
this.writeCommunity = writeCommunity;
}
public String getAuthKey() {
return this.authKey;
}
public void setAuthKey(String authKey) {
this.authKey = authKey;
}
public String getPrivateKey() {
return this.privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
} | [
"290573449@qq.com"
] | 290573449@qq.com |
9825a7ee396fad2286103ca82b2bd059e68ee569 | 765bfeb8631e38a3469c012b1b106986756bd56d | /src/design/EmployeeInfo.java | 72b9a5c1752cb98b55983234701972aa2ff163f5 | [] | no_license | AbiralSwar/Midterm2019AbiralSwar | 099e72c27b6d42fe29d52dab78ec63412592c08f | 0f61d153270c01b5b51574eee7d0ebedd6e55c9f | refs/heads/master | 2020-07-22T11:56:02.308696 | 2019-09-09T03:14:01 | 2019-09-09T03:14:01 | 207,193,299 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,070 | java | package design;
import java.util.Scanner;
public class EmployeeInfo extends AbstractClass{
/*This class can be implemented from Employee interface then add additional methods in EmployeeInfo class.
* Also, Employee interface can be implemented into an abstract class.So create an Abstract class
* then inherit that abstract class into EmployeeInfo class.Once you done with designing EmployeeInfo class,
* go to FortuneEmployee class to apply all the fields and attributes.
*
* Important: YOU MUST USE the
* OOP(abstraction,Encapsulation, Inheritance and Polymorphism) concepts in every level possible.
* Use all kind of keywords(super,this,static,final........)
* Implement Nested class.
* Use Exception Handling.
*
*/
/*
* declare few static and final fields and some non-static fields
*/
static String companyName;
private String name;
private int employeeId;
private String deptName;
private static double salary;
private static int numberOfYears;
/*
* You must implement the logic for below 2 methods and
* following 2 methods are prototype as well for other methods need to be design,
* as you will come up with the new ideas.
*/
/*
* you must have multiple constructor.
* Must implement below constructor.
*/
public EmployeeInfo(int employeeId){
this.employeeId=employeeId;
}
public EmployeeInfo(String name, int employeeId){
this.name = name;
this.employeeId = employeeId;
}
public EmployeeInfo(String name, int employeeId, String deptName, double salary) {
this.name = name;
this.employeeId = employeeId;
this.deptName = deptName;
this.salary=salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getdeptName() {
return deptName;
}
public void setdeptName(String deptName) {
this.deptName = deptName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getnumberOfYears() {
return numberOfYears;
}
public void setnumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
/*
* This methods should calculate Employee bonus based on salary and performance.
* Then it will return the total yearly bonus. So you need to implement the logic.
* Hints: 10% of the salary for best performance, 8% of the salary for average performance and so on.
* You can set arbitrary number for performance.
* So you probably need to send 2 arguments.
*
*/
public static int calculateEmployeeBonus(int numberOfYearsWithCompany, double yearlySalary){
double yearlyBonus = 0.00;
if (numberOfYearsWithCompany >5) {
yearlyBonus = yearlySalary* 0.1;
} else if (numberOfYearsWithCompany <3) {
yearlyBonus = yearlySalary * 0.08;
} else {
yearlyBonus = 0;
}
return (int) yearlyBonus;
}
/*
* This methods should calculate Employee Pension based on salary and numbers of years with the company.
* Then it will return the total pension. So you need to implement the logic.
* Hints: pension will be 5% of the salary for 1 year, 10% for 2 years with the company and so on.
*
*/
public static int calculateEmployeePension(){
int total=0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter start date in format (example: May,2015): ");
String joiningDate = sc.nextLine();
System.out.println("Please enter today's date in format (example: August,2017): ");
String todaysDate = sc.nextLine();
String convertedJoiningDate = DateConversion.convertDate(joiningDate);
String convertedTodaysDate = DateConversion.convertDate(todaysDate);
//implement numbers of year from above two dates
String startYear = convertedJoiningDate.substring(convertedJoiningDate.length() - 4, convertedJoiningDate.length());
String currentYear = convertedTodaysDate.substring(convertedTodaysDate.length() - 4, convertedTodaysDate.length());
int start = Integer.parseInt(startYear);
int current = Integer.parseInt(currentYear);
//Calculate pension
numberOfYears = current - start;
if (numberOfYears >= 5) {
total = (int) (salary * .25);
} else if (numberOfYears == 4) {
total = (int) (salary * .20);
} else if (numberOfYears == 3) {
total = (int) (salary * .15);
} else if (numberOfYears == 2) {
total = (int) (salary * .10);
} else if (numberOfYears == 1) {
total = (int) (salary * .05);
} else if (numberOfYears == 0) {
total = 0;
}
System.out.println("Total pension: $" + total);
return total;
}
@Override
public int employeeId() {
return 0;
}
@Override
public String employeeName() {
return null;
}
@Override
public void assignDepartment() {
}
@Override
public int calculateSalary() {
return 0;
}
@Override
public void benefitLayout() {
}
private static class DateConversion {
public DateConversion(Months months){}
public static String convertDate(String date) {
String [] extractMonth = date.split(",");
String givenMonth = extractMonth[0];
int monthDate = whichMonth(givenMonth);
String actualDate = monthDate + "/" + extractMonth[1];
return actualDate;
}
public static int whichMonth(String givenMonth) {
Months months = Months.valueOf(givenMonth);
int date = 0;
switch (months) {
case January:
date = 1;
break;
case February:
date = 2;
break;
case March:
date = 3;
break;
case April:
date = 4;
break;
case May:
date = 5;
break;
case June:
date = 6;
break;
case July:
date = 1;
break;
case August:
date = 1;
break;
case September:
date = 1;
break;
case October:
date = 1;
break;
case November:
date = 1;
break;
case December:
date = 1;
break;
default:
date = 0;
break;
}
return date;
}
}
}
| [
"nepolian@hotmail.com"
] | nepolian@hotmail.com |
486c4197519ce8c292aba14e1ccf0d02608dbcc9 | e38a26dc54daf3a87f78021dc4764cdcdc7c2e98 | /redis/src/main/java/com/sungang/day3/operate/RedisController.java | 6a5b096e6ac46819bb2bff3b7cfc97bc87949797 | [] | no_license | sungang521/springcloud | dda72b7baf2e0cca85ba8de6d49c9d9f1677e838 | 776e1551e5e6ecdb6619ed40ebf55f50add18c52 | refs/heads/master | 2022-07-03T14:52:54.651517 | 2019-12-02T07:32:33 | 2019-12-02T07:32:33 | 189,856,384 | 0 | 0 | null | 2022-06-17T02:44:09 | 2019-06-02T14:27:54 | Java | UTF-8 | Java | false | false | 1,384 | java | package com.sungang.day3.operate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
@RestController
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/testMap")
public String test() {
redisTemplate.opsForValue().set("key1", "value1");
stringRedisTemplate.opsForValue().set("int", "1");
stringRedisTemplate.opsForValue().increment("int", 1);
Jedis jedis = (Jedis) stringRedisTemplate.getConnectionFactory().getConnection().getNativeConnection();
jedis.decr("int");
Map<String, String> hash = new HashMap<>();
hash.put("filed1", "1");
hash.put("filed2", "2");
stringRedisTemplate.opsForHash().putAll("hash", hash);
BoundHashOperations hashOperations = stringRedisTemplate.boundHashOps("hash");
hashOperations.put("filed3", "2");
return "success";
}
}
| [
"735006309@qq.com"
] | 735006309@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.