hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
b185bb712bfd0dfbe9438a9a349fa38e9606f2bd | 309 | package com.u8.server.dao;
import com.u8.server.common.UHibernateTemplate;
import com.u8.server.data.UChannelpayType;
import org.springframework.stereotype.Repository;
/**
* cp类
*/
@Repository("uChannelPayTypeDao")
public class UChannelPayTypeDao extends UHibernateTemplate<UChannelpayType, Integer>{
}
| 20.6 | 85 | 0.805825 |
a9039b29ea8194222267b5e4a31216bd63ec2a42 | 1,129 | package com.company;
import java.util.Scanner;
public class P06_SumAndProduct {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String finalN = "" + input.charAt(input.length() - 1);
int n = Integer.parseInt(input);
for (int a = 1; a <= 9; a++) {
for (int b = 9; b >= a; b--) {
for (int c = 0; c <= 9; c++) {
for (int d = 9; d >= c; d--) {
int sum = a + b + c + d;
int multip = a * b * c * d;
if (sum == multip && finalN.equals("5")) {
System.out.printf("%d%d%d%d", a, b, c, d);
return;
}
if (multip / sum == 3 && n % 3 == 0) {
System.out.printf("%d%d%d%d", d, c, b, a);
return;
}
}
}
}
}
System.out.println("Nothing found");
}
}
| 26.255814 | 70 | 0.358725 |
443e4991d9128a2d4c29b4ec22bbc60c191f3d97 | 3,384 | package com.openforce.keycloak;
import java.util.Objects;
import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.adapter.AbstractUserAdapterFederatedStorage;
/**
* Connect and maps My User with the Keycloak User.
*
* @author openFORCE
*/
public class UserAdapter extends AbstractUserAdapterFederatedStorage {
private final User user;
private final String keycloakId;
private static final Logger log = Logger.getLogger(UserAdapter.class);
public UserAdapter(KeycloakSession session, RealmModel realm, ComponentModel model, User user) {
super(session, realm, model);
this.user = user;
this.keycloakId = StorageId.keycloakId(model, user.getEmail());
this.setEnabled(user.isEnabled());
this.setEmailVerified(user.isEmailVerified());
if (user.isEmailVerified()) {
this.removeRequiredAction(RequiredAction.VERIFY_EMAIL);
} else {
this.addRequiredAction(RequiredAction.VERIFY_EMAIL);
}
if (user.isPasswordSet()) {
this.removeRequiredAction(RequiredAction.UPDATE_PASSWORD);
} else {
this.addRequiredAction(RequiredAction.UPDATE_PASSWORD);
}
this.setSingleAttribute(UserModel.LOCALE, user.getLocale());
this.setGroups();
}
/**
* Maps the user's groups with a keycloak groups.
*/
private void setGroups() {
if (user.getGroups() != null) {
for (String group : user.getGroups()) {
log.info("User " + user.getEmail() + " member of group: " + group);
if (isGroupExisting(group) && !userHasGroup(group)) {
this.joinGroup(realm.getGroups().stream()
.filter(groupModel -> groupModel.getName().equals(group)).findAny().get());
}
}
}
}
/**
* Checks if the group with the groupName exists in the realm
*
* @param groupName
* @return true if the group with groupName exists in the realm
*/
private boolean isGroupExisting(String groupName) {
return realm.getGroups().stream().anyMatch(groupModel -> groupModel.getName().equals(groupName));
}
/**
* Checks if the user in member of the group with the groupName in the realm
*
* @param groupName
* @return true if the user is member of the group with groupName
*/
private boolean userHasGroup(String groupName) {
return this.getGroups().stream().anyMatch(groupModel -> groupModel.getName().equals(groupName));
}
@Override
public String getId() {
return keycloakId;
}
/**
* Forcing email to be username.
*/
@Override
public String getUsername() {
if (Objects.nonNull(this.user)) {
return user.getEmail();
}
return null;
}
@Override
public void setUsername(String username) {
user.setEmail(username);
}
@Override
public String getEmail() {
return user.getEmail();
}
@Override
public void setEmail(String email) {
super.setEmail(email);
user.setEmail(email);
}
@Override
public String getFirstName() {
return user.getFirstName();
}
@Override
public void setFirstName(String firstName) {
super.setFirstName(firstName);
user.setFirstName(firstName);
}
@Override
public String getLastName() {
return user.getLastName();
}
@Override
public void setLastName(String lastName) {
super.setLastName(lastName);
user.setLastName(lastName);
}
}
| 25.253731 | 99 | 0.722222 |
18e8406f706022d7139b5492336d0bbc41a90d19 | 625 |
import java.util.Scanner;
public class X08_stringalong {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Now modify your program to write each word (as defined by spaces) rather than letter on a different line.
System.out.println("Please enter a sentence of text");
String str = input.nextLine();
int j = str.length();
//define an integer j where j is the length of the string
int i;
for (i = 0; i<j; i++) {
char c = str.charAt(i);
System.out.println(c);
}
}
} | 29.761905 | 120 | 0.5904 |
57c20b3256a0e2d038855b6df1c855e5c02bd65f | 15,553 | package com.melodies.bandup.setup;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.firebase.crash.FirebaseCrash;
import com.melodies.bandup.DatabaseSingleton;
import com.melodies.bandup.R;
import com.melodies.bandup.VolleySingleton;
import com.melodies.bandup.listeners.BandUpErrorListener;
import com.melodies.bandup.listeners.BandUpResponseListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* A shared class that both Genres and Instruments
* use to GET and POST data to and from the server.
*/
public class SetupShared {
int SELECTED_BORDER_SIZE = 15;
/**
* This function GETs instruments.
* @param context The context we are working in.
* @param gridView The GridView we are going to put the data into.
* @param progressBar The ProgressBar that displays when we are getting the data.
*/
public void getInstruments(Context context, GridView gridView, ProgressBar progressBar, TextView txtNoInstruments, List<String> preselected) {
progressBar.setVisibility(progressBar.VISIBLE);
DatabaseSingleton.getInstance(context).getBandUpDatabase().getInstruments(
getSetupItemsListener(context, gridView, progressBar, txtNoInstruments, preselected),
getSetupItemsErrorListener(context, txtNoInstruments, progressBar));
}
/**
* This function GETs genres.
* @param context The context we are working in.
* @param gridView The GridView we are going to put the data into.
* @param progressBar The ProgressBar that displays when we are getting the data.
*/
public void getGenres(Context context, GridView gridView, ProgressBar progressBar, TextView txtNoGenres, List<String> preselected) {
progressBar.setVisibility(progressBar.VISIBLE);
DatabaseSingleton.getInstance(context).getBandUpDatabase().getGenres(
getSetupItemsListener(context, gridView, progressBar, txtNoGenres, preselected),
getSetupItemsErrorListener(context, txtNoGenres, progressBar)
);
}
/**
* This listener is used when listening to responses to
* GET /instruments and GET /genres.
*
* The progress bar's visibility must be set before sending the request.
*
* It parses the JSON object and puts every item into an array in the DoubleListAdapter.
*
* {
* "_id":"57dafe54dcba0f51172fb163" The ID of the instrument/genre
* "name":"Drums" The name of the instrument/genre
* }
*
* @param context
* @param gridView The GridView that will be displaying the data.
* @param progressBar A ProgressBar that will be displayed when fetching data.
* @return the listener
* @see DoubleListAdapter
*/
private BandUpResponseListener getSetupItemsListener(final Context context, final GridView gridView, final ProgressBar progressBar, final TextView txtNoItems, final List<String> preselected) {
return new BandUpResponseListener() {
@Override
public void onBandUpResponse(Object response) {
if (response == "" || response == null) {
txtNoItems.setVisibility(TextView.VISIBLE);
return;
}
JSONArray responseArr = null;
if (response instanceof JSONArray) {
responseArr = (JSONArray) response;
} else {
txtNoItems.setText(context.getString(R.string.setup_no_items));
txtNoItems.setVisibility(TextView.VISIBLE);
return;
}
if (responseArr.length() == 0) {
txtNoItems.setText(context.getString(R.string.setup_no_items));
txtNoItems.setVisibility(TextView.VISIBLE);
} else {
// Create a new adapter for the GridView.
DoubleListAdapter dlAdapter = new DoubleListAdapter(context);
gridView.setAdapter(dlAdapter);
// Go through every item in the list the server sent us.
for (int i = 0; i < responseArr.length(); i++) {
try {
JSONObject item = responseArr.getJSONObject(i);
String id = item.getString("_id");
String name = item.getString("name");
DoubleListItem dlItem = new DoubleListItem(id, i, name);
if (preselected != null) {
if (preselected.contains(name)) {
dlItem.isSelected = true;
}
}
dlAdapter.addItem(dlItem);
} catch (JSONException e) {
Toast.makeText(context, R.string.matches_error_json, Toast.LENGTH_LONG).show();
FirebaseCrash.report(e);
}
}
}
progressBar.setVisibility(progressBar.GONE);
}
};
}
/**
* This error listener is used when listening to responses to
* GET /instruments and GET /genres.
*
* The progress bar's visibility must be set before sending the request.
*
* @param context The context we are working in.
* @param progressBar The ProgressBar in the view.
* @return the listener.
*/
private BandUpErrorListener getSetupItemsErrorListener(final Context context, final TextView txtNoItems, final ProgressBar progressBar) {
return new BandUpErrorListener() {
@Override
public void onBandUpErrorResponse(VolleyError error) {
txtNoItems.setText(context.getString(R.string.setup_error_fetch));
txtNoItems.setVisibility(TextView.VISIBLE);
VolleySingleton.getInstance(context).checkCauseOfError(error);
progressBar.setVisibility(progressBar.GONE);
}
};
}
/**
* This function POSTs the selected items to the server.
*
* @param c The context we are working in.
* @param dla The DoubleListAdapter we want to read from.
* @return True if all preconditions are met. False otherwise.
*/
public JSONArray prepareSelectedList(Context c, DoubleListAdapter dla) {
JSONArray selectedItems = new JSONArray();
// Go through all items in the GridView and put its IDs into an array.
for (DoubleListItem dli:dla.getDoubleList()) {
if (dli.isSelected) {
selectedItems.put(dli.id);
}
}
return selectedItems;
}
public ArrayList<String> prepareSelectedListNames(Context c, DoubleListAdapter dla) {
ArrayList selectedItems = new ArrayList();
// Go through all items in the GridView and put its IDs into an array.
for (DoubleListItem dli:dla.getDoubleList()) {
if (dli.isSelected) {
selectedItems.add(dli.name);
}
}
return selectedItems;
}
public void postInstruments(Context c, JSONArray instrumentArr) {
DatabaseSingleton.getInstance(c).getBandUpDatabase().postInstruments(
instrumentArr,
getPickListener(),
getPickErrorListener(c)
);
}
public void postGenres(Context c, JSONArray genresArr) {
DatabaseSingleton.getInstance(c).getBandUpDatabase().postGenres(
genresArr,
getPickListener(),
getPickErrorListener(c)
);
}
/**
* This listener is used when listening to responses to
* POST /instruments and POST /genres.
*
* @return the listener
*/
private BandUpResponseListener getPickListener() {
return new BandUpResponseListener() {
@Override
public void onBandUpResponse(Object response) {
}
};
}
/**
* This error listener is used when listening to responses to
* POST /instruments and POST /genres.
*
* @param context The context we are working in.
* @return the listener.
*/
private BandUpErrorListener getPickErrorListener(final Context context) {
return new BandUpErrorListener() {
@Override
public void onBandUpErrorResponse(VolleyError error) {
VolleySingleton.getInstance(context).checkCauseOfError(error);
}
};
}
/**
* This toggles the selected/deselected state of an item
* in the list when the user taps on a particular item.
*
* @param context The context we are working in.
* @param parent The parent of the adapter. (?)
* @param view The view we are working with.
* @param position The index of the item that was tapped.
*/
public void toggleItemSelection(final Context context, AdapterView<?> parent, final View view, int position) {
DoubleListItem item = (DoubleListItem) parent.getAdapter().getItem(position);
final ImageView backView = (ImageView) view.findViewById(R.id.itemBackground);
final TextView txtName = (TextView) view.findViewById(R.id.itemName);
// The border size around the DoubleListItem when it has been selected.
// This value is changed in res/values/integers.xml
int selectedPadding = context.getResources().getInteger(R.integer.setup_selected_padding);
// We need to change pixels to display pixels for it to display the same on all devices.
int selectedPaddingDp = (int) pixelsToDisplayPixels(context, selectedPadding);
GridView gv = (GridView)parent;
final int itemWidth = gv.getColumnWidth();
// The height of the DoubleListItem.
// This value is changed in res/values/integers.xml
final double itemHeight = (context.getResources().getInteger(R.integer.setup_item_height));
final double actualItemHeight = itemWidth*(itemHeight/100.0);
// We need to change pixels to display pixels for it to display the same on all devices.
int itemHeightDp = (int) actualItemHeight;
// The duration of the animation when selecting.
int animDuration = context.getResources().getInteger(R.integer.setup_select_animation_time);
// We are going to use two ValueAnimators.
// One for animating the padding change
// and one for animating the change of the text size.
ValueAnimator paddingAnimator;
ValueAnimator textSizeAnimator;
if (!item.isSelected) {
// We are going to animate the selection of the item.
// Initialize the animators with the values we want to animate from and to.
paddingAnimator = ValueAnimator.ofInt(0, selectedPaddingDp);
textSizeAnimator = ValueAnimator.ofFloat(txtName.getTextSize(), txtName.getTextSize()-(selectedPaddingDp/2));
// Set custom AnimatorUpdateListeners
paddingAnimator .addUpdateListener(this.getPaddingChangeListener(backView, view, itemHeightDp));
textSizeAnimator.addUpdateListener(this.getTextSizeChangeListener(txtName));
paddingAnimator .setDuration(animDuration);
textSizeAnimator.setDuration(animDuration);
view.setBackgroundColor(ContextCompat.getColor(context, R.color.bandUpYellow));
// Start both animators at the same time.
paddingAnimator.start();
textSizeAnimator.start();
// And finally keep track in the DoubleListItem
item.isSelected = true;
} else {
// We are going to animate the deselection of the item.
// Initialize the animators with the values we want to animate from and to.
paddingAnimator = ValueAnimator.ofInt(selectedPaddingDp, 0);
textSizeAnimator = ValueAnimator.ofFloat(txtName.getTextSize(), txtName.getTextSize()+(selectedPaddingDp/2));
// Set custom AnimatorUpdateListeners
paddingAnimator .addUpdateListener(this.getPaddingChangeListener(backView, view, itemHeightDp));
textSizeAnimator.addUpdateListener(this.getTextSizeChangeListener(txtName));
paddingAnimator.setDuration(animDuration);
textSizeAnimator.setDuration(animDuration);
// Start both animators at the same time.
paddingAnimator.start();
textSizeAnimator.start();
// And finally keep track in the DoubleListItem
item.isSelected = false;
}
}
private ValueAnimator.AnimatorUpdateListener getPaddingChangeListener(final ImageView backView, final View view, final int itemHeightDp) {
return new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// A new step of the animation has arrived.
// Let's extract it and use it.
int animVal = (Integer) valueAnimator.getAnimatedValue();
// We need to shrink the image view to give space for the padding border.
backView.setMaxHeight(itemHeightDp - (animVal * 2));
// Set the padding equally on all sides.
view.setPadding(animVal, animVal, animVal, animVal);
}
};
}
private ValueAnimator.AnimatorUpdateListener getTextSizeChangeListener(final TextView textView) {
return new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator){
// A new step of the animation has arrived.
// Let's extract it and use it.
float animVal = (Float) valueAnimator.getAnimatedValue();
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, animVal);
}
};
}
public static float pixelsToDisplayPixels(final Context context, final float px) {
return px * (context.getResources().getDisplayMetrics().density);
}
// Storing user userId in UserIdData folder, which only this app can access
public Boolean saveUserId(Context c, JSONObject response) {
try {
String id;
if (!response.isNull("userID")) {
id = response.getString("userID");
} else {
return false;
}
SharedPreferences srdPref = c.getSharedPreferences("UserIdRegister", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = srdPref.edit();
editor.putString("userID", id);
editor.apply();
return true;
} catch (JSONException e) {
FirebaseCrash.report(e);
}
return false;
}
} | 41.145503 | 196 | 0.631775 |
521710fd6ae02bb3e8cc592c142204808e7cfd34 | 16,186 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.cloud.vault.config;
import java.util.concurrent.atomic.AtomicReference;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.vault.config.VaultProperties.AppRoleProperties;
import org.springframework.cloud.vault.config.VaultProperties.AwsIamProperties;
import org.springframework.cloud.vault.config.VaultProperties.AzureMsiProperties;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.vault.authentication.AppIdAuthentication;
import org.springframework.vault.authentication.AppIdAuthenticationOptions;
import org.springframework.vault.authentication.AppIdUserIdMechanism;
import org.springframework.vault.authentication.AppRoleAuthentication;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.AppRoleAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.RoleId;
import org.springframework.vault.authentication.AppRoleAuthenticationOptions.SecretId;
import org.springframework.vault.authentication.AwsEc2Authentication;
import org.springframework.vault.authentication.AwsEc2AuthenticationOptions;
import org.springframework.vault.authentication.AwsEc2AuthenticationOptions.Nonce;
import org.springframework.vault.authentication.AwsIamAuthentication;
import org.springframework.vault.authentication.AwsIamAuthenticationOptions;
import org.springframework.vault.authentication.AwsIamAuthenticationOptions.AwsIamAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.AzureMsiAuthentication;
import org.springframework.vault.authentication.AzureMsiAuthenticationOptions;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.authentication.ClientCertificateAuthentication;
import org.springframework.vault.authentication.CubbyholeAuthentication;
import org.springframework.vault.authentication.CubbyholeAuthenticationOptions;
import org.springframework.vault.authentication.GcpComputeAuthentication;
import org.springframework.vault.authentication.GcpComputeAuthenticationOptions;
import org.springframework.vault.authentication.GcpComputeAuthenticationOptions.GcpComputeAuthenticationOptionsBuilder;
import org.springframework.vault.authentication.IpAddressUserId;
import org.springframework.vault.authentication.KubernetesAuthentication;
import org.springframework.vault.authentication.KubernetesAuthenticationOptions;
import org.springframework.vault.authentication.KubernetesServiceAccountTokenFile;
import org.springframework.vault.authentication.MacAddressUserId;
import org.springframework.vault.authentication.PcfAuthentication;
import org.springframework.vault.authentication.PcfAuthenticationOptions;
import org.springframework.vault.authentication.ResourceCredentialSupplier;
import org.springframework.vault.authentication.StaticUserId;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.support.VaultToken;
import org.springframework.web.client.RestOperations;
/**
* Factory for {@link ClientAuthentication}.
*
* @author Mark Paluch
* @author Kevin Holditch
* @author Michal Budzyn
* @since 1.1
*/
class ClientAuthenticationFactory {
private static final boolean GOOGLE_CREDENTIAL_AVAILABLE = ClassUtils.isPresent(
"com.google.api.client.googleapis.auth.oauth2.GoogleCredential",
ClientAuthenticationFactory.class.getClassLoader());
private static final boolean GOOGLE_CREDENTIALS_AVAILABLE = ClassUtils
.isPresent("com.google.auth.oauth2.GoogleCredentials", ClientAuthenticationFactory.class.getClassLoader());
private final VaultProperties vaultProperties;
private final RestOperations restOperations;
private final RestOperations externalRestOperations;
ClientAuthenticationFactory(VaultProperties vaultProperties, RestOperations restOperations,
RestOperations externalRestOperations) {
this.vaultProperties = vaultProperties;
this.restOperations = restOperations;
this.externalRestOperations = externalRestOperations;
}
/**
* @return a new {@link ClientAuthentication}.
*/
ClientAuthentication createClientAuthentication() {
switch (this.vaultProperties.getAuthentication()) {
case APPID:
return appIdAuthentication(this.vaultProperties);
case APPROLE:
return appRoleAuthentication(this.vaultProperties);
case AWS_EC2:
return awsEc2Authentication(this.vaultProperties);
case AWS_IAM:
return awsIamAuthentication(this.vaultProperties);
case AZURE_MSI:
return azureMsiAuthentication(this.vaultProperties);
case CERT:
return new ClientCertificateAuthentication(this.restOperations);
case CUBBYHOLE:
return cubbyholeAuthentication();
case GCP_GCE:
return gcpGceAuthentication(this.vaultProperties);
case GCP_IAM:
return gcpIamAuthentication(this.vaultProperties);
case KUBERNETES:
return kubernetesAuthentication(this.vaultProperties);
case PCF:
return pcfAuthentication(this.vaultProperties);
case TOKEN:
Assert.hasText(this.vaultProperties.getToken(), "Token (spring.cloud.vault.token) must not be empty");
return new TokenAuthentication(this.vaultProperties.getToken());
}
throw new UnsupportedOperationException(
String.format("Client authentication %s not supported", this.vaultProperties.getAuthentication()));
}
private ClientAuthentication appIdAuthentication(VaultProperties vaultProperties) {
VaultProperties.AppIdProperties appId = vaultProperties.getAppId();
Assert.hasText(appId.getUserId(), "UserId (spring.cloud.vault.app-id.user-id) must not be empty");
AppIdAuthenticationOptions authenticationOptions = AppIdAuthenticationOptions.builder()
.appId(vaultProperties.getApplicationName()) //
.path(appId.getAppIdPath()) //
.userIdMechanism(getAppIdMechanism(appId)).build();
return new AppIdAuthentication(authenticationOptions, this.restOperations);
}
private AppIdUserIdMechanism getAppIdMechanism(VaultProperties.AppIdProperties appId) {
try {
Class<?> userIdClass = ClassUtils.forName(appId.getUserId(), null);
return (AppIdUserIdMechanism) BeanUtils.instantiateClass(userIdClass);
}
catch (ClassNotFoundException ex) {
switch (appId.getUserId().toUpperCase()) {
case VaultProperties.AppIdProperties.IP_ADDRESS:
return new IpAddressUserId();
case VaultProperties.AppIdProperties.MAC_ADDRESS:
if (StringUtils.hasText(appId.getNetworkInterface())) {
try {
return new MacAddressUserId(Integer.parseInt(appId.getNetworkInterface()));
}
catch (NumberFormatException e) {
return new MacAddressUserId(appId.getNetworkInterface());
}
}
return new MacAddressUserId();
default:
return new StaticUserId(appId.getUserId());
}
}
}
private ClientAuthentication appRoleAuthentication(VaultProperties vaultProperties) {
AppRoleAuthenticationOptions options = getAppRoleAuthenticationOptions(vaultProperties);
return new AppRoleAuthentication(options, this.restOperations);
}
static AppRoleAuthenticationOptions getAppRoleAuthenticationOptions(VaultProperties vaultProperties) {
AppRoleProperties appRole = vaultProperties.getAppRole();
AppRoleAuthenticationOptionsBuilder builder = AppRoleAuthenticationOptions.builder()
.path(appRole.getAppRolePath());
if (StringUtils.hasText(appRole.getRole())) {
builder.appRole(appRole.getRole());
}
RoleId roleId = getRoleId(vaultProperties, appRole);
SecretId secretId = getSecretId(vaultProperties, appRole);
builder.roleId(roleId).secretId(secretId);
return builder.build();
}
private static RoleId getRoleId(VaultProperties vaultProperties, AppRoleProperties appRole) {
if (StringUtils.hasText(appRole.getRoleId())) {
return RoleId.provided(appRole.getRoleId());
}
if (StringUtils.hasText(vaultProperties.getToken()) && StringUtils.hasText(appRole.getRole())) {
return RoleId.pull(VaultToken.of(vaultProperties.getToken()));
}
if (StringUtils.hasText(vaultProperties.getToken())) {
return RoleId.wrapped(VaultToken.of(vaultProperties.getToken()));
}
throw new IllegalArgumentException(
"Cannot configure RoleId. Any of role-id, initial token, or initial token and role name must be configured.");
}
private static SecretId getSecretId(VaultProperties vaultProperties, AppRoleProperties appRole) {
if (StringUtils.hasText(appRole.getSecretId())) {
return SecretId.provided(appRole.getSecretId());
}
if (StringUtils.hasText(vaultProperties.getToken()) && StringUtils.hasText(appRole.getRole())) {
return SecretId.pull(VaultToken.of(vaultProperties.getToken()));
}
if (StringUtils.hasText(vaultProperties.getToken())) {
return SecretId.wrapped(VaultToken.of(vaultProperties.getToken()));
}
return SecretId.absent();
}
private ClientAuthentication awsEc2Authentication(VaultProperties vaultProperties) {
VaultProperties.AwsEc2Properties awsEc2 = vaultProperties.getAwsEc2();
Nonce nonce = StringUtils.hasText(awsEc2.getNonce()) ? Nonce.provided(awsEc2.getNonce().toCharArray())
: Nonce.generated();
AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder().role(awsEc2.getRole()) //
.path(awsEc2.getAwsEc2Path()) //
.nonce(nonce) //
.identityDocumentUri(awsEc2.getIdentityDocument()) //
.build();
return new AwsEc2Authentication(authenticationOptions, this.restOperations, this.externalRestOperations);
}
private ClientAuthentication awsIamAuthentication(VaultProperties vaultProperties) {
AwsIamProperties awsIam = vaultProperties.getAwsIam();
AWSCredentialsProvider credentialsProvider = AwsCredentialProvider.getAwsCredentialsProvider();
AwsIamAuthenticationOptionsBuilder builder = AwsIamAuthenticationOptions.builder();
if (StringUtils.hasText(awsIam.getRole())) {
builder.role(awsIam.getRole());
}
if (StringUtils.hasText(awsIam.getServerName())) {
builder.serverName(awsIam.getServerName());
}
if (awsIam.getEndpointUri() != null) {
builder.endpointUri(awsIam.getEndpointUri());
}
builder.path(awsIam.getAwsPath()) //
.credentialsProvider(credentialsProvider);
AwsIamAuthenticationOptions options = builder.credentialsProvider(credentialsProvider).build();
return new AwsIamAuthentication(options, this.restOperations);
}
private ClientAuthentication azureMsiAuthentication(VaultProperties vaultProperties) {
AzureMsiProperties azureMsi = vaultProperties.getAzureMsi();
Assert.hasText(azureMsi.getRole(), "Azure role (spring.cloud.vault.azure-msi.role) must not be empty");
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() //
.role(azureMsi.getRole()).path(azureMsi.getAzurePath()) //
.instanceMetadataUri(azureMsi.getMetadataService()) //
.identityTokenServiceUri(azureMsi.getIdentityTokenService()) //
.build();
return new AzureMsiAuthentication(options, this.restOperations, this.externalRestOperations);
}
private ClientAuthentication cubbyholeAuthentication() {
Assert.hasText(this.vaultProperties.getToken(),
"Initial Token (spring.cloud.vault.token) for Cubbyhole authentication must not be empty");
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() //
.wrapped() //
.initialToken(VaultToken.of(this.vaultProperties.getToken())) //
.build();
return new CubbyholeAuthentication(options, this.restOperations);
}
private ClientAuthentication gcpGceAuthentication(VaultProperties vaultProperties) {
VaultProperties.GcpGceProperties gcp = vaultProperties.getGcpGce();
Assert.hasText(gcp.getRole(), "Role (spring.cloud.vault.gcp-gce.role) must not be empty");
GcpComputeAuthenticationOptionsBuilder builder = GcpComputeAuthenticationOptions.builder()
.path(gcp.getGcpPath()).role(gcp.getRole());
if (StringUtils.hasText(gcp.getServiceAccount())) {
builder.serviceAccount(gcp.getServiceAccount());
}
return new GcpComputeAuthentication(builder.build(), this.restOperations, this.externalRestOperations);
}
private ClientAuthentication gcpIamAuthentication(VaultProperties vaultProperties) {
if (GOOGLE_CREDENTIAL_AVAILABLE) {
return GcpIamAuthenticationFactory.create(vaultProperties, this.restOperations);
}
if (GOOGLE_CREDENTIALS_AVAILABLE) {
return GcpIamCredentialsAuthenticationFactory.create(vaultProperties, this.restOperations);
}
throw new IllegalStateException(
"Cannot create authentication mechanism for GCP IAM. This method requires one of the following dependencies: google-auth-library-oauth2-http or google-api-client (deprecated).");
}
private ClientAuthentication kubernetesAuthentication(VaultProperties vaultProperties) {
VaultProperties.KubernetesProperties kubernetes = vaultProperties.getKubernetes();
Assert.hasText(kubernetes.getRole(), "Role (spring.cloud.vault.kubernetes.role) must not be empty");
Assert.hasText(kubernetes.getServiceAccountTokenFile(),
"Service account token file (spring.cloud.vault.kubernetes.service-account-token-file) must not be empty");
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
.path(kubernetes.getKubernetesPath()).role(kubernetes.getRole())
.jwtSupplier(new KubernetesServiceAccountTokenFile(kubernetes.getServiceAccountTokenFile())).build();
return new KubernetesAuthentication(options, this.restOperations);
}
private ClientAuthentication pcfAuthentication(VaultProperties vaultProperties) {
VaultProperties.PcfProperties pcfProperties = vaultProperties.getPcf();
Assert.isTrue(ClassUtils.isPresent("org.bouncycastle.crypto.signers.PSSSigner", getClass().getClassLoader()),
"BouncyCastle (bcpkix-jdk15on) must be on the classpath");
Assert.hasText(pcfProperties.getRole(), "Role (spring.cloud.vault.pcf.role) must not be empty");
PcfAuthenticationOptions.PcfAuthenticationOptionsBuilder builder = PcfAuthenticationOptions.builder()
.role(pcfProperties.getRole()).path(pcfProperties.getPcfPath());
if (pcfProperties.getInstanceCertificate() != null) {
builder.instanceCertificate(new ResourceCredentialSupplier(pcfProperties.getInstanceCertificate()));
}
if (pcfProperties.getInstanceKey() != null) {
builder.instanceKey(new ResourceCredentialSupplier(pcfProperties.getInstanceKey()));
}
return new PcfAuthentication(builder.build(), this.restOperations);
}
private static class AwsCredentialProvider {
private static AWSCredentialsProvider getAwsCredentialsProvider() {
DefaultAWSCredentialsProviderChain backingCredentialsProvider = DefaultAWSCredentialsProviderChain
.getInstance();
// Eagerly fetch credentials preventing lag during the first, actual login.
AWSCredentials firstAccess = backingCredentialsProvider.getCredentials();
AtomicReference<AWSCredentials> once = new AtomicReference<>(firstAccess);
return new AWSCredentialsProvider() {
@Override
public AWSCredentials getCredentials() {
if (once.compareAndSet(firstAccess, null)) {
return firstAccess;
}
return backingCredentialsProvider.getCredentials();
}
@Override
public void refresh() {
backingCredentialsProvider.refresh();
}
};
}
}
}
| 38.084706 | 182 | 0.803596 |
31ffb835c301558c4539d5d3cfa9c92707594890 | 7,718 | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.messaging.simp.user;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
/**
* Unit tests for {@link MultiServerUserRegistry}.
*
* @author Rossen Stoyanchev
*/
public class MultiServerUserRegistryTests {
private SimpUserRegistry localRegistry;
private MultiServerUserRegistry registry;
private MessageConverter converter;
@Before
public void setup() throws Exception {
this.localRegistry = Mockito.mock(SimpUserRegistry.class);
this.registry = new MultiServerUserRegistry(this.localRegistry);
this.converter = new MappingJackson2MessageConverter();
}
@Test
public void getUserFromLocalRegistry() throws Exception {
SimpUser user = Mockito.mock(SimpUser.class);
Set<SimpUser> users = Collections.singleton(user);
when(this.localRegistry.getUsers()).thenReturn(users);
when(this.localRegistry.getUserCount()).thenReturn(1);
when(this.localRegistry.getUser("joe")).thenReturn(user);
assertEquals(1, this.registry.getUserCount());
assertSame(user, this.registry.getUser("joe"));
}
@Test
public void getUserFromRemoteRegistry() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser testUser = new TestSimpUser("joe");
TestSimpSession testSession = new TestSimpSession("remote-sess");
testSession.addSubscriptions(new TestSimpSubscription("remote-sub", "/remote-dest"));
testUser.addSessions(testSession);
SimpUserRegistry testRegistry = mock(SimpUserRegistry.class);
when(testRegistry.getUsers()).thenReturn(Collections.singleton(testUser));
Object registryDto = new MultiServerUserRegistry(testRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, 20000);
assertEquals(1, this.registry.getUserCount());
SimpUser user = this.registry.getUser("joe");
assertNotNull(user);
assertTrue(user.hasSessions());
assertEquals(1, user.getSessions().size());
SimpSession session = user.getSession("remote-sess");
assertNotNull(session);
assertEquals("remote-sess", session.getId());
assertSame(user, session.getUser());
assertEquals(1, session.getSubscriptions().size());
SimpSubscription subscription = session.getSubscriptions().iterator().next();
assertEquals("remote-sub", subscription.getId());
assertSame(session, subscription.getSession());
assertEquals("/remote-dest", subscription.getDestination());
}
@Test
public void findSubscriptionsFromRemoteRegistry() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser user1 = new TestSimpUser("joe");
TestSimpUser user2 = new TestSimpUser("jane");
TestSimpUser user3 = new TestSimpUser("jack");
TestSimpSession session1 = new TestSimpSession("sess1");
TestSimpSession session2 = new TestSimpSession("sess2");
TestSimpSession session3 = new TestSimpSession("sess3");
session1.addSubscriptions(new TestSimpSubscription("sub1", "/match"));
session2.addSubscriptions(new TestSimpSubscription("sub1", "/match"));
session3.addSubscriptions(new TestSimpSubscription("sub1", "/not-a-match"));
user1.addSessions(session1);
user2.addSessions(session2);
user3.addSessions(session3);
SimpUserRegistry userRegistry = mock(SimpUserRegistry.class);
when(userRegistry.getUsers()).thenReturn(new HashSet<>(Arrays.asList(user1, user2, user3)));
Object registryDto = new MultiServerUserRegistry(userRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, 20000);
assertEquals(3, this.registry.getUserCount());
Set<SimpSubscription> matches = this.registry.findSubscriptions(s -> s.getDestination().equals("/match"));
assertEquals(2, matches.size());
Iterator<SimpSubscription> iterator = matches.iterator();
Set<String> sessionIds = new HashSet<>(2);
sessionIds.add(iterator.next().getSession().getId());
sessionIds.add(iterator.next().getSession().getId());
assertEquals(new HashSet<>(Arrays.asList("sess1", "sess2")), sessionIds);
}
@Test // SPR-13800
public void getSessionsWhenUserIsConnectedToMultipleServers() throws Exception {
// Add user to local registry
TestSimpUser localUser = new TestSimpUser("joe");
TestSimpSession localSession = new TestSimpSession("sess123");
localUser.addSessions(localSession);
when(this.localRegistry.getUser("joe")).thenReturn(localUser);
// Prepare broadcast message from remote server
TestSimpUser remoteUser = new TestSimpUser("joe");
TestSimpSession remoteSession = new TestSimpSession("sess456");
remoteUser.addSessions(remoteSession);
SimpUserRegistry remoteRegistry = mock(SimpUserRegistry.class);
when(remoteRegistry.getUsers()).thenReturn(Collections.singleton(remoteUser));
Object remoteRegistryDto = new MultiServerUserRegistry(remoteRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(remoteRegistryDto, null);
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, 20000);
assertEquals(1, this.registry.getUserCount());
SimpUser user = this.registry.getUsers().iterator().next();
assertTrue(user.hasSessions());
assertEquals(2, user.getSessions().size());
assertThat(user.getSessions(), containsInAnyOrder(localSession, remoteSession));
assertSame(localSession, user.getSession("sess123"));
assertEquals(remoteSession, user.getSession("sess456"));
user = this.registry.getUser("joe");
assertEquals(2, user.getSessions().size());
assertThat(user.getSessions(), containsInAnyOrder(localSession, remoteSession));
assertSame(localSession, user.getSession("sess123"));
assertEquals(remoteSession, user.getSession("sess456"));
}
@Test
public void purgeExpiredRegistries() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser testUser = new TestSimpUser("joe");
testUser.addSessions(new TestSimpSession("remote-sub"));
SimpUserRegistry testRegistry = mock(SimpUserRegistry.class);
when(testRegistry.getUsers()).thenReturn(Collections.singleton(testUser));
Object registryDto = new MultiServerUserRegistry(testRegistry).getLocalRegistryDto();
Message<?> message = this.converter.toMessage(registryDto, null);
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, -1);
assertEquals(1, this.registry.getUserCount());
this.registry.purgeExpiredRegistries();
assertEquals(0, this.registry.getUserCount());
}
}
| 40.197917 | 108 | 0.77248 |
d9524056d577841bb849c89148eb3551c028d73f | 1,566 | /************************************************************************
* A Comparator for sorting MusicItem objects by title.
* Queens University, Kingston, Ontario
*
* author: Margaret Lamb
***********************************************************************/
import java.util.*; // for Vector and Comparator
public class TitleComparator implements Comparator {
/***********************************************************************
* This is a comparison method that may be used by a sorting method.
* It defines how pairs of objects are compared; in effect, it gives a
* meaning for "greater than", "less than", or "equal to". This class
* will be used for sorting objects by title, so we compare titles
* only, ignoring the other contents of the objects.
*
* Parameters:
* obj1, obj2: the objects to compare. These must both be MusicItems
* (CDs or Tracks). They are declared as
* Objects to agree with the Comparator interface.
* Return value:
* negative if obj1 < obj2 (if obj1's title should sort before obj2's title)
* equal if obj1 == obj2 (if their titles are equal)
* positive if obj1 > obj2 (if obj1's title should sort after obj2's title)
***********************************************************************/
public int compare(Object obj1, Object obj2) {
MusicItem music1 = (MusicItem) obj1;
MusicItem music2 = (MusicItem) obj2;
return music1.getTitle().compareTo(music2.getTitle());
} // end compare
} // end class TitleComparator
| 47.454545 | 80 | 0.55811 |
7888291329dda32595b8dad710c319732b7185c5 | 2,547 | package com.youhaoxi.livelink.gateway.im.handler;
import com.youhaoxi.livelink.gateway.im.enums.EventType;
import com.youhaoxi.livelink.gateway.im.event.IMsgEvent;
import com.youhaoxi.livelink.gateway.im.msg.IMsg;
import com.youhaoxi.livelink.gateway.im.msg.Msg;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by pan
*/
public class HandlerManager {
private static final Logger logger = LoggerFactory.getLogger(HandlerManager.class);
private static final Map<Integer, Constructor<? extends IMEventHandler>> _handlers = new HashMap<>();
public static void register(int eventType, Class<? extends IMEventHandler> handler) {
try {
Constructor<? extends IMEventHandler> constructor = handler.getConstructor(ChannelHandlerContext.class, IMsgEvent.class);
_handlers.put(eventType, constructor);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static IMEventHandler getHandler(ChannelHandlerContext ctx,IMsgEvent msg)
throws IllegalAccessException, InvocationTargetException, InstantiationException {
int eventType=msg.getEventType();
Constructor<? extends IMEventHandler> constructor = _handlers.get(eventType);
if(constructor == null) {
logger.error("IMEventHandler not exist, eventType: {} msg:{}", eventType,msg.toString());
return null;
}
return constructor.newInstance(ctx,msg);
}
public static void initHandlers() {
HandlerManager.register(EventType.TEST.getValue(), TestEventHandler.class);
HandlerManager.register(EventType.CREATEROOM.getValue(), CreateRoomEventHandler.class);
HandlerManager.register(EventType.LOGIN.getValue(), LoginEventHandler.class);
HandlerManager.register(EventType.LOGOUT.getValue(), LogoutEventHandler.class);
HandlerManager.register(EventType.JOINROOM.getValue(), JoinRoomEventHandler.class);
HandlerManager.register(EventType.QUITROOM.getValue(), QuitRoomEventHandler.class);
HandlerManager.register(EventType.PLAINMSG.getValue(), PlainMsgEventHandler.class);
HandlerManager.register(EventType.RICHMSG.getValue(), RichMsgEventHandler.class);
HandlerManager.register(EventType.STATS.getValue(), StatsEventHandler.class);
}
}
| 41.754098 | 133 | 0.741264 |
51e3d57db60e732366970047bf83c53248a0c874 | 2,774 | package pl.piotron.animals.model.mapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import pl.piotron.animals.model.User;
import pl.piotron.animals.model.UserDetails;
import pl.piotron.animals.model.UserRole;
import pl.piotron.animals.model.dto.UserDto;
import pl.piotron.animals.repositories.UserRoleRepository;
@Service
public class UserMapper {
private final UserRoleRepository userRoleRepository;
private final PasswordEncoder encoder;
private static final String DEFAULT_ROLE= "USER";
public UserMapper( UserRoleRepository userRoleRepository, PasswordEncoder encoder) {
this.encoder = encoder;
this.userRoleRepository = userRoleRepository;
}
public UserDto userDto(User user) {
UserDto dto = new UserDto();
dto.setId(user.getId());
UserDetails userDetails = user.getUserDetails();
dto.setFirstName(userDetails.getFirstName());
dto.setLastName(userDetails.getLastName());
dto.setEmail(user.getEmail());
dto.setPhoneNumber(userDetails.getPhoneNumber());
String password = encoder.encode(user.getPassword());
dto.setPassword(password);
dto.setEnabled(user.isEnabled());
dto.setRoles(user.getRoles());
return dto;
}
public User toEntity(UserDto user) {
User entity = new User();
entity.setId(user.getId());
UserDetails userDetails = detailsMapper(user);
entity.setUserDetails(userDetails);
entity.setEmail(user.getEmail());
try {
String password = encoder.encode(user.getPassword());
entity.setPassword(password);
}catch (IllegalArgumentException e)
{
e.getMessage();
}
UserRole defaultRole = userRoleRepository.findByRole(DEFAULT_ROLE);
user.getRoles().add(defaultRole);
entity.setRoles(user.getRoles());
entity.setEnabled(false);
return entity;
}
public UserDetails updateUser(UserDto user) {
return detailsMapper(user);
}
public UserDto updatedToDto (UserDetails user)
{
UserDto dto = new UserDto();
dto.setId(user.getId());
dto.setFirstName(user.getFirstName());
dto.setLastName(user.getLastName());
dto.setPhoneNumber(user.getPhoneNumber());
return dto;
}
private UserDetails detailsMapper(UserDto user)
{
UserDetails userDetails = new UserDetails();
userDetails.setId(user.getId());
userDetails.setFirstName(user.getFirstName());
userDetails.setLastName(user.getLastName());
userDetails.setPhoneNumber(user.getPhoneNumber());
return userDetails;
}
}
| 34.675 | 88 | 0.675919 |
f3c236580f60589b64816a5eec115c8376541ce1 | 7,579 | /*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.spi.MixerProvider;
import com.sun.media.sound.JDK13Services;
/**
* @test
* @bug 4776511
* @summary RFE: Setting the default MixerProvider. Test the retrieving of lines
* with defaut mixer properties.
* @modules java.desktop/com.sun.media.sound
*/
public class DefaultMixers {
private static final String ERROR_PROVIDER_CLASS_NAME = "abc";
private static final String ERROR_INSTANCE_NAME = "def";
private static final Class[] lineClasses = {
SourceDataLine.class,
TargetDataLine.class,
Clip.class,
Port.class,
};
public static void main(String[] args) throws Exception {
boolean allOk = true;
Mixer.Info[] infos;
out("Testing Mixers retrieved via AudioSystem");
infos = AudioSystem.getMixerInfo();
allOk &= testMixers(infos, null);
out("Testing MixerProviders");
List providers = JDK13Services.getProviders(MixerProvider.class);
for (int i = 0; i < providers.size(); i++) {
MixerProvider provider = (MixerProvider) providers.get(i);
infos = provider.getMixerInfo();
allOk &= testMixers(infos, provider.getClass().getName());
}
if (! allOk) {
throw new Exception("Test failed");
} else {
out("Test passed");
}
}
private static boolean testMixers(Mixer.Info[] infos,
String providerClassName) {
boolean allOk = true;
for (int i = 0; i < infos.length; i++) {
Mixer mixer = null;
try {
mixer = AudioSystem.getMixer(infos[i]);
} catch (NullPointerException e) {
out("Exception thrown; Test NOT failed.");
e.printStackTrace();
}
for (int j = 0; j < lineClasses.length; j++) {
if (mixer.isLineSupported(new Line.Info(lineClasses[j]))) {
allOk &= testMixer(mixer, lineClasses[j],
providerClassName);
}
}
}
return allOk;
}
private static boolean testMixer(Mixer mixer, Class lineType,
String providerClassName) {
boolean allOk = true;
String instanceName = mixer.getMixerInfo().getName();
// no error
allOk &= testMixer(mixer, lineType,
providerClassName, instanceName);
// erroneous provider class name, correct instance name
allOk &= testMixer(mixer, lineType,
ERROR_PROVIDER_CLASS_NAME, instanceName);
// erroneous provider class name, no instance name
allOk &= testMixer(mixer, lineType,
ERROR_PROVIDER_CLASS_NAME, "");
// erroneous provider class name, erroneous instance name
allOk &= testMixer(mixer, lineType,
ERROR_PROVIDER_CLASS_NAME, ERROR_INSTANCE_NAME);
return allOk;
}
private static boolean testMixer(Mixer mixer, Class lineType,
String providerClassName,
String instanceName) {
boolean allOk = true;
try {
String propertyValue = (providerClassName != null) ? providerClassName: "" ;
propertyValue += "#" + instanceName;
out("property value: " + propertyValue);
System.setProperty(lineType.getName(), propertyValue);
Line line = null;
Line.Info info = null;
Line.Info[] infos;
AudioFormat format = null;
if (lineType == SourceDataLine.class || lineType == Clip.class) {
infos = mixer.getSourceLineInfo();
format = getFirstLinearFormat(infos);
info = new DataLine.Info(lineType, format);
} else if (lineType == TargetDataLine.class) {
infos = mixer.getTargetLineInfo();
format = getFirstLinearFormat(infos);
info = new DataLine.Info(lineType, format);
} else if (lineType == Port.class) {
/* Actually, a Ports Mixer commonly has source infos
as well as target infos. We ignore this here, since we
just need a random one. */
infos = mixer.getSourceLineInfo();
for (int i = 0; i < infos.length; i++) {
if (infos[i] instanceof Port.Info) {
info = infos[i];
break;
}
}
}
out("Line.Info: " + info);
line = AudioSystem.getLine(info);
out("line: " + line);
if (! lineType.isInstance(line)) {
out("type " + lineType + " failed: class should be '" +
lineType + "' but is '" + line.getClass() + "'!");
allOk = false;
}
} catch (Exception e) {
out("Exception thrown; Test NOT failed.");
e.printStackTrace();
}
return allOk;
}
private static AudioFormat getFirstLinearFormat(Line.Info[] infos) {
for (int i = 0; i < infos.length; i++) {
if (infos[i] instanceof DataLine.Info) {
AudioFormat[] formats = ((DataLine.Info) infos[i]).getFormats();
for (int j = 0; j < formats.length; j++) {
AudioFormat.Encoding encoding = formats[j].getEncoding();
int sampleSizeInBits = formats[j].getSampleSizeInBits();
if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED) &&
sampleSizeInBits == 16 ||
encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED) &&
sampleSizeInBits == 16) {
return formats[j];
}
}
}
}
return null;
}
private static void out(String message) {
System.out.println(message);
}
}
| 38.085427 | 88 | 0.57092 |
653190932baaaa238131761e098aa7bf82fa285b | 659 | package mx.ipn.escom.matefacil;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class WelcomeActivity extends AppCompatActivity {
Button btnContinue;
public void btnContinueOnClick(View v) {
startActivity(new Intent(this, MainActivity.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
btnContinue = (Button) findViewById(R.id.btnContinue);
}
} | 25.346154 | 62 | 0.746586 |
519c222cfe9244bc7061d246ef608d8fb431d338 | 144 | package cn.dankefu.service;
import cn.dankefu.bean.Customer_tags;
public interface CustomerTagsService extends BaseService<Customer_tags> {
}
| 20.571429 | 73 | 0.833333 |
c649d4d1ce454d495edea6e0b7b58bd58329ba0e | 15,856 | package appviews;
import android.content.Intent;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CalendarView;
import android.widget.ImageButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.medicalapp.Event;
import com.example.medicalapp.Prescription;
import com.example.medicalapp.R;
import com.example.medicalapp.UserManager;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
/*
CalendarFragment class
*/
public class CalendarFragment extends Fragment {
// UI element attributes
private RecyclerView recyclerView;
private EventAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
private CalendarView calendarView;
private ImageButton btn_syncCalendar;
// Current date
private LocalDate today = LocalDate.now();
// List of events to display on the calendar view UI object
ArrayList<com.example.medicalapp.Event> events = new ArrayList<>();
// UI method called when the Calendar Page is loaded
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar_view, container, false);
// Initialises UI elements
calendarView = (CalendarView) view.findViewById(R.id.calendarView);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
btn_syncCalendar = (ImageButton) view.findViewById(R.id.btn_syncCalendar);
layoutManager = new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false);
//--> Function listens to button press for sync calendar
btn_syncCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Iterates through each prescription and creates separate reccurent events
for(int i = 0; i< UserManager.PRESCRIPTIONS.size(); i++){
Calendar beginTime = Calendar.getInstance();
beginTime.set(UserManager.PRESCRIPTIONS.get(i).getStartDate().getYear(),
UserManager.PRESCRIPTIONS.get(i).getStartDate().getMonthValue()-1,
UserManager.PRESCRIPTIONS.get(i).getStartDate().getDayOfMonth(), UserManager.PRESCRIPTIONS.get(i).getSetTime().getHours(),
UserManager.PRESCRIPTIONS.get(i).getSetTime().getMinutes());
Calendar endTime = Calendar.getInstance();
endTime.set(UserManager.PRESCRIPTIONS.get(i).getStartDate().getYear(), UserManager.PRESCRIPTIONS.get(i).getStartDate().getMonthValue()-1,
UserManager.PRESCRIPTIONS.get(i).getStartDate().getDayOfMonth(), UserManager.PRESCRIPTIONS.get(i).getSetTime().getHours(),
UserManager.PRESCRIPTIONS.get(i).getSetTime().getMinutes()+15);
// Creates an RRULE string for recurrent events
String recurDateUntil ="FREQ=WEEKLY;UNTIL=";
String dateUntil = Integer.toString(UserManager.PRESCRIPTIONS.get(i).getEndDate().getYear());
// Converts DayOfWeek objects to RRULE string
if (UserManager.PRESCRIPTIONS.get(i).getEndDate().getMonthValue()<9){
dateUntil+="0"+Integer.toString(UserManager.PRESCRIPTIONS.get(i).getEndDate().getMonthValue());
} else {
dateUntil+=Integer.toString(UserManager.PRESCRIPTIONS.get(i).getEndDate().getMonthValue());
}
if(UserManager.PRESCRIPTIONS.get(i).getEndDate().getDayOfMonth()<9){
dateUntil+="0"+Integer.toString(UserManager.PRESCRIPTIONS.get(i).getEndDate().getDayOfMonth());
} else {
dateUntil+=Integer.toString(UserManager.PRESCRIPTIONS.get(i).getEndDate().getDayOfMonth());
}
String recurRepeat ="T000000Z;WKST=SU;BYDAY=";
String recurDays = "";
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.MONDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.MONDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="MO;";
} else {
recurDays+="MO,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.TUESDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.TUESDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="TU;";
} else {
recurDays+="TU,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.WEDNESDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.WEDNESDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="WE;";
} else {
recurDays+="WE,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.THURSDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.THURSDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="TH;";
} else {
recurDays+="TH,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.FRIDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.FRIDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="FR;";
} else {
recurDays+="FR,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.SATURDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.SATURDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="SA;";
} else {
recurDays+="SA,";
}
}
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().contains(DayOfWeek.SUNDAY)){
if(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().indexOf(DayOfWeek.SUNDAY)==UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size()-1){
recurDays+="SU;";
} else {
recurDays+="SU,";
}
}
// Android Calendar Intent is created for the user to bring the events from Medify to an external calendar app
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
.putExtra(CalendarContract.Events.TITLE, "Medify - "+UserManager.PRESCRIPTIONS.get(i).getMedicineName()+ " | " + UserManager.PRESCRIPTIONS.get(i).getPrescribedDosage()+"mg") // Title
.putExtra(CalendarContract.Events.RRULE, recurDateUntil+dateUntil+recurRepeat+recurDays);
startActivity(intent);
}
}
});
// Try to get events from UserManager class first if its populated
if(!UserManager.EVENTS.isEmpty()){
// Check if some events are passed
for(int i = 0; i<UserManager.EVENTS.size(); i++){
// If events are passed remove it from the array
if(UserManager.EVENTS.get(i).date.isBefore(today)){
UserManager.EVENTS.remove(i); // Remove events that are passed in order to reduce the memory allocation
}
}
events = UserManager.EVENTS; // get a private list of events from the static reference
}
//--> Generate Events
// Go through each prescription and create a hashmap of possible events
HashMap<LocalDate, ArrayList<Prescription>> possibleEvents = new HashMap<LocalDate, ArrayList<Prescription>>();
for(int i = 0; i<UserManager.PRESCRIPTIONS.size(); i++){
LocalDate startDate;
// If the start date is passed
if(UserManager.PRESCRIPTIONS.get(i).getStartDate().isBefore(today)){
startDate = today; // Make the start date into today
} else {
startDate = UserManager.PRESCRIPTIONS.get(i).getStartDate(); // Keep the original start date
}
// Go through each day of the between today or start date and end date
for(int j = 0; j<ChronoUnit.DAYS
.between(startDate, UserManager.PRESCRIPTIONS.get(i).getEndDate().plusDays(1)); j++){
// Go through the repeating days of the week
for(int k = 0; k<UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().size(); k++){
// If the day matches the repeating days, add to possible events
if(startDate.plusDays(j).getDayOfWeek()
.compareTo(UserManager.PRESCRIPTIONS.get(i).getRepeatingDaysOfWeek().get(k))==0){
// Check if map key already exists
if(possibleEvents.size()>0){
for(int g = 0; g<possibleEvents.size(); g++){
ArrayList<Prescription> tempPrescriptions = new ArrayList<>();
// If the same key is found
if(possibleEvents.containsKey(startDate.plusDays(j))){
tempPrescriptions = possibleEvents.get(startDate.plusDays(j));
tempPrescriptions.add(UserManager.PRESCRIPTIONS.get(i)); // Add the prescription
} else { // If its a new key
tempPrescriptions.add(UserManager.PRESCRIPTIONS.get(i));
}
possibleEvents.put(startDate.plusDays(j), tempPrescriptions);
}
} else { // If map key does not exist
ArrayList<Prescription> tempPrescriptions = new ArrayList<>();
tempPrescriptions.add(UserManager.PRESCRIPTIONS.get(i));
possibleEvents.put(startDate.plusDays(j), tempPrescriptions);
}
}
}
}
}
//--> Hashmap conversion to Events
// Go through the events hashmap and generate event objects
events.clear();
for (Map.Entry<LocalDate, ArrayList<Prescription>> entry : possibleEvents.entrySet()) {
for(int i = 0; i<entry.getValue().size(); i++){
int count = 0; // Keeps track of same dates
for(int j = 0; j<entry.getValue().size(); j++){
if(entry.getValue().get(i).equals(entry.getValue().get(j))){
count++;
}
if(count>1){
entry.getValue().remove(j); // Removes duplicate event entries
}
}
}
// Create a new event objects from hashmap
com.example.medicalapp.Event newEvent = new Event(entry.getKey(), entry.getValue());
events.add(newEvent); // add to the private list of events
}
// Set the UserManager's events to the newly created events
UserManager.EVENTS = events;
//--> Updates event shown based on the selected date from Calendar View
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
ArrayList<Prescription> selectedPrescriptions = new ArrayList<>();
LocalDate selectedDate = LocalDate.of(year, month+1, dayOfMonth);
// Remove any potential duplicate prescriptions in events
for(int i = 0; i<UserManager.EVENTS.size(); i++){
for(int j = 0; j<UserManager.EVENTS.get(i).datePrescriptions.size(); j++){
for(int k = j+1; k<UserManager.EVENTS.get(i).datePrescriptions.size(); k++){
if(UserManager.EVENTS.get(i).datePrescriptions.get(j).equals(UserManager.EVENTS.get(i).datePrescriptions.get(k))){
UserManager.EVENTS.get(i).datePrescriptions.remove(k); // Remove duplicate
}
}
}
}
// Count up the total number of intakes for each prescription
for(int i = 0; i<UserManager.PRESCRIPTIONS.size(); i++){
int count = 0;
for(int j = 0; j<UserManager.EVENTS.size(); j++){
for(int k = 0; k<UserManager.EVENTS.get(j).getDatePrescriptions().size(); k++){
if(UserManager.EVENTS.get(j).datePrescriptions.get(k).equals(UserManager.PRESCRIPTIONS.get(i))){
count++;
}
}
}
UserManager.PRESCRIPTIONS.get(i).setTotalNumIntakes(count); // Update prescription total required number of intakes
}
// Go through the list of event
for(int i = 0; i<events.size(); i++){
// If the selected date exists as an event of the user
if(selectedDate.compareTo(events.get(i).getDate())==0){
selectedPrescriptions = events.get(i).getDatePrescriptions(); // Stores prescription list for individual events
}
}
// Update recycle view adapter setting
adapter = new EventAdapter(selectedPrescriptions);
recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(),1));
recyclerView.setAdapter(adapter);
}
});
return view;
}
}
| 54.487973 | 210 | 0.569816 |
ff065f0d765407b2f9df7324d9dfc18b23fe1b46 | 297 | package ml.bigbrains.fsspapiclient.model;
public enum TaskType {
UNDEFINED, //0 - не определен
PHYSICAL, // 1 - запрос на поиск физического лица;
LEGAL, // 2 - запрос на поиск юридического лица;
IP // 3 - запрос на поиск по номеру исполнительного производства;
}
| 33 | 78 | 0.666667 |
a3afb5cce4f8c008414dea2ff07f77f7a643c8c3 | 8,415 | /**
* vertigo - application development platform
*
* Copyright (C) 2013-2022, Vertigo.io, [email protected]
*
* 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 io.vertigo.datastore.plugins.filestore.db;
import java.time.Instant;
import java.util.Optional;
import javax.inject.Inject;
import io.vertigo.core.lang.Assertion;
import io.vertigo.core.lang.DataStream;
import io.vertigo.core.node.Node;
import io.vertigo.core.param.ParamValue;
import io.vertigo.core.util.ClassUtil;
import io.vertigo.datamodel.structure.definitions.DtDefinition;
import io.vertigo.datamodel.structure.definitions.DtField;
import io.vertigo.datamodel.structure.definitions.DtFieldName;
import io.vertigo.datamodel.structure.model.DtObject;
import io.vertigo.datamodel.structure.model.Entity;
import io.vertigo.datamodel.structure.model.UID;
import io.vertigo.datamodel.structure.util.DtObjectUtil;
import io.vertigo.datastore.filestore.definitions.FileInfoDefinition;
import io.vertigo.datastore.filestore.model.FileInfo;
import io.vertigo.datastore.filestore.model.FileInfoURI;
import io.vertigo.datastore.filestore.model.InputStreamBuilder;
import io.vertigo.datastore.filestore.model.VFile;
import io.vertigo.datastore.impl.filestore.FileStorePlugin;
import io.vertigo.datastore.impl.filestore.model.StreamFile;
/**
* Permet de gérer le CRUD sur un fichier stocké sur deux tables (Méta données / Données).
*
* @author sezratty
*/
public final class TwoTablesDbFileStorePlugin extends AbstractDbFileStorePlugin implements FileStorePlugin {
/**
* Liste des champs du Dto de stockage.
* Ces champs sont obligatoire sur les Dt associés aux fileInfoDefinitions
*/
private enum DtoFields implements DtFieldName {
fileName, mimeType, lastModified, length, fileData, fmdId, fdtId
}
private final DtDefinition storeMetaDataDtDefinition;
private final DtField storeMetaDataIdField;
private final DtDefinition storeFileDtDefinition;
/**
* Constructor.
* @param name This store name
* @param storeMetaDataDtDefinitionName MetaData storing dtDefinition
* @param storeFileDtDefinitionName File storing dtDefinition
*/
@Inject
public TwoTablesDbFileStorePlugin(
@ParamValue("name") final Optional<String> name,
@ParamValue("storeMetaDataDtName") final String storeMetaDataDtDefinitionName,
@ParamValue("storeFileDtName") final String storeFileDtDefinitionName,
@ParamValue("fileInfoClass") final String fileInfoClassName) {
super(name, fileInfoClassName);
//-----
storeMetaDataDtDefinition = Node.getNode().getDefinitionSpace().resolve(storeMetaDataDtDefinitionName, DtDefinition.class);
storeFileDtDefinition = Node.getNode().getDefinitionSpace().resolve(storeFileDtDefinitionName, DtDefinition.class);
storeMetaDataIdField = storeMetaDataDtDefinition.getIdField().get();
}
/** {@inheritDoc} */
@Override
public FileInfo read(final FileInfoURI fileInfoUri) {
checkDefinitionStoreBinding(fileInfoUri.getDefinition());
// Ramène FileMetada
final UID<Entity> dtoMetaDataUri = UID.of(storeMetaDataDtDefinition, fileInfoUri.getKeyAs(storeMetaDataIdField.getSmartTypeDefinition().getJavaClass()));
final DtObject fileMetadataDto = getEntityStoreManager().readOne(dtoMetaDataUri);
final Object fdtId = getValue(fileMetadataDto, DtoFields.fdtId, Object.class);
// Ramène FileData
final UID<Entity> dtoDataUri = UID.of(storeFileDtDefinition, fdtId);
final DtObject fileDataDto = getEntityStoreManager().readOne(dtoDataUri);
// Construction du vFile.
final InputStreamBuilder inputStreamBuilder = new DataStreamInputStreamBuilder(getValue(fileDataDto, DtoFields.fileData, DataStream.class));
final String fileName = getValue(fileMetadataDto, DtoFields.fileName, String.class);
final String mimeType = getValue(fileMetadataDto, DtoFields.mimeType, String.class);
final Instant lastModified = getValue(fileMetadataDto, DtoFields.lastModified, Instant.class);
final Long length = getValue(fileMetadataDto, DtoFields.length, Long.class);
final VFile vFile = StreamFile.of(fileName, mimeType, lastModified, length, inputStreamBuilder);
//TODO passer par une factory de FileInfo à partir de la FileInfoDefinition (comme DomainFactory)
final FileInfo fileInfo = new DatabaseFileInfo(fileInfoUri.getDefinition(), vFile);
fileInfo.setURIStored(fileInfoUri);
return fileInfo;
}
/** {@inheritDoc} */
@Override
public FileInfo create(final FileInfo fileInfo) {
checkReadonly();
checkDefinitionStoreBinding(fileInfo.getDefinition());
Assertion.check().isNull(fileInfo.getURI(), "Only file without any id can be created");
//-----
final Entity fileMetadataDto = createMetaDataEntity(fileInfo);
final Entity fileEntity = createFileEntity(fileInfo);
//-----
getEntityStoreManager().create(fileEntity);
setValue(fileMetadataDto, DtoFields.fdtId, DtObjectUtil.getId(fileEntity));
getEntityStoreManager().create(fileMetadataDto);
final FileInfoURI fileInfoUri = createURI(fileInfo.getDefinition(), DtObjectUtil.getId(fileMetadataDto));
fileInfo.setURIStored(fileInfoUri);
return fileInfo;
}
/** {@inheritDoc} */
@Override
public void update(final FileInfo fileInfo) {
checkReadonly();
checkDefinitionStoreBinding(fileInfo.getDefinition());
Assertion.check().isTrue(fileInfo.getURI() != null, "Only file with id can be updated");
//-----
final Entity fileMetadataDto = createMetaDataEntity(fileInfo);
final Entity fileDataDto = createFileEntity(fileInfo);
//-----
setIdValue(fileMetadataDto, fileInfo.getURI());
// Chargement du FDT_ID
final UID<Entity> dtoMetaDataUri = UID.of(storeMetaDataDtDefinition, fileInfo.getURI().getKeyAs(storeMetaDataIdField.getSmartTypeDefinition().getJavaClass()));
final DtObject fileMetadataDtoOld = getEntityStoreManager().readOne(dtoMetaDataUri);
final Object fdtId = getValue(fileMetadataDtoOld, DtoFields.fdtId, Object.class);
setValue(fileMetadataDto, DtoFields.fdtId, fdtId);
setValue(fileDataDto, DtoFields.fdtId, fdtId);
getEntityStoreManager().update(fileDataDto);
getEntityStoreManager().update(fileMetadataDto);
}
private static FileInfoURI createURI(final FileInfoDefinition fileInfoDefinition, final Object key) {
return new FileInfoURI(fileInfoDefinition, key);
}
/** {@inheritDoc} */
@Override
public void delete(final FileInfoURI fileInfoUri) {
checkReadonly();
checkDefinitionStoreBinding(fileInfoUri.getDefinition());
//-----
final UID<Entity> dtoMetaDataUri = UID.of(storeMetaDataDtDefinition, fileInfoUri.getKeyAs(storeMetaDataIdField.getSmartTypeDefinition().getJavaClass()));
final DtObject fileMetadataDtoOld = getEntityStoreManager().readOne(dtoMetaDataUri);
final Object fdtId = getValue(fileMetadataDtoOld, DtoFields.fdtId, Object.class);
final UID<Entity> dtoDataUri = UID.of(storeFileDtDefinition, fdtId);
getEntityStoreManager().delete(dtoMetaDataUri);
getEntityStoreManager().delete(dtoDataUri);
}
@Override
public Class<? extends FileInfo> getFileInfoClass() {
return ClassUtil.classForName(getFileInfoClassName(), FileInfo.class);
}
private Entity createMetaDataEntity(final FileInfo fileInfo) {
final Entity fileMetadataDto = DtObjectUtil.createEntity(storeMetaDataDtDefinition);
final VFile vFile = fileInfo.getVFile();
setValue(fileMetadataDto, DtoFields.fileName, vFile.getFileName());
setValue(fileMetadataDto, DtoFields.mimeType, vFile.getMimeType());
setValue(fileMetadataDto, DtoFields.lastModified, vFile.getLastModified());
setValue(fileMetadataDto, DtoFields.length, vFile.getLength());
return fileMetadataDto;
}
private Entity createFileEntity(final FileInfo fileInfo) {
final Entity fileDataDto = DtObjectUtil.createEntity(storeFileDtDefinition);
final VFile vFile = fileInfo.getVFile();
setValue(fileDataDto, DtoFields.fileName, vFile.getFileName());
setValue(fileDataDto, DtoFields.fileData, new VFileDataStream(vFile));
return fileDataDto;
}
}
| 44.057592 | 161 | 0.791682 |
e942f09f2bd0bd54269053824d91159c75b8faae | 971 | /*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.intel.iot.ams.repository;
import com.intel.iot.ams.entity.ClientDeviceMapping;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ClientDeviceMappingDao extends JpaRepository<ClientDeviceMapping, Integer> {
public ClientDeviceMapping findByClientUuidAndProductName(
String amsClientUuid, String productName);
public List<ClientDeviceMapping> findByProductName(String name);
public ClientDeviceMapping findByProductDeviceId(String deviceId);
public void removeByProductName(String name);
public void removeByClientUuid(String clientUuid);
public ClientDeviceMapping findByClientUuidAndProductNameAndProjectId(
String amsClientUuid, String productName, String projectId);
public List<ClientDeviceMapping> findByProductNameAndProjectId(String name, String projectId);
}
| 33.482759 | 97 | 0.821833 |
65c6b3b8c166ad2faec5a03ec79c8fc53022d233 | 5,862 | /**
* Copyright (c) 2003-2013 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.sakaiproject.tool.messageforums.entityproviders.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager;
import org.sakaiproject.tool.messageforums.entityproviders.sparsepojos.SparseMessage;
import org.sakaiproject.tool.messageforums.entityproviders.sparsepojos.SparseThread;
/**
* A helper class for arranging messages into their proper parent child relationships.
*
* @author Adrian Fish <[email protected]>
*/
public class MessageUtils {
/**
* Extracts the threads (messages with no parent) from the supplied messages and sets
* the message totals up on each of them.
*
* @param sparseForum The SparseForum to extract the threads from
* @param forumManager We need this to the get the read stati for the accumulated message ids.
* @param userId We need this to the get the read stati for the accumulated message ids.
*/
public List<SparseThread> getThreadsWithCounts(List<SparseMessage> messages,DiscussionForumManager forumManager, String userId) {
List<Long> messageIds = new ArrayList<Long>();
// Find the top level threads, the messages with no parent, basically.
List<SparseThread> threads = new ArrayList<SparseThread>();
for (SparseMessage message : messages) {
if(message.isDraft() || message.isDeleted()) {
continue;
}
messageIds.add(message.getMessageId());
if(message.getReplyTo() == null) {
threads.add(new SparseThread(message));
}
}
Map<Long,Boolean> readStati = forumManager.getReadStatusForMessagesWithId(messageIds, userId);
for(SparseMessage thread : threads) {
boolean read = readStati.get(thread.getMessageId());
Counts counts = new Counts(1,(read) ? 1 : 0);
thread.setRead(read);
// We don't want to add the messages and bulk up the resulting JSON feed. We
// still want the total and unread messages counts for this thread though.
setupCounts(thread,messages,readStati,counts);
thread.setTotalMessages(counts.total);
thread.setReadMessages(counts.read);
}
return threads;
}
/**
* Sets up the message hierarchy for topMessage.
*
* @param topMessage The topmost message that we want to setup the message graph for
* @param messages The flat list of messages that we want to insert into the hierarchy
* @param forumManager We need this to the get the read stati for the accumulated message ids.
* @param userId We need this to the get the read stati for the accumulated message ids.
*/
public void attachReplies(SparseMessage topMessage, List<SparseMessage> messages,DiscussionForumManager forumManager, String userId) {
List<Long> messageIds = new ArrayList<Long>();
for (SparseMessage message : messages) {
messageIds.add(message.getMessageId());
}
Map<Long,Boolean> readStati = forumManager.getReadStatusForMessagesWithId(messageIds, userId);
boolean read = readStati.get(topMessage.getMessageId());
topMessage.setRead(read);
Counts counts = new Counts(1,(read) ? 1 : 0);
addReplies(topMessage,messages,readStati,counts);
topMessage.setTotalMessages(counts.total);
topMessage.setReadMessages(counts.read);
}
/**
* Does a depth first recursion into the messages list, looking for replies
* to the specified parent.
*
* @param parent
* @param messages
*/
private void addReplies(SparseMessage parent,List<SparseMessage> messages, Map<Long,Boolean> readStati,Counts counts) {
for (SparseMessage message : messages) {
if(message.isDraft() || message.isDeleted()) {
continue;
}
if(message.getReplyTo() != null
&& message.getReplyTo().equals(parent.getMessageId())) {
counts.total = counts.total + 1;
boolean read = readStati.get(message.getMessageId());
message.setRead(read);
if(read) {
counts.read = counts.read + 1;
}
parent.addReply(message);
// Recurse
addReplies(message,messages, readStati,counts);
}
}
}
/**
* Recursively iterates over the messages and increments the counts accumulator if any of them
* are a reply to the parent. The idea is to finally exit with a set of totals for an ancestor.
*
* @param parent The message for which to look for replies.
* @param messages The flatted list of messages to search.
* @param readStati The pre-retrieved list of read stati for the messsage list.
* @param counts An accumulator of message counts
*/
private void setupCounts(SparseMessage parent,List<SparseMessage> messages, Map<Long,Boolean> readStati,Counts counts) {
for (SparseMessage message : messages) {
if(message.isDraft() || message.isDeleted()) {
continue;
}
if(message.getReplyTo() != null
&& message.getReplyTo().equals(parent.getMessageId())) {
counts.total = counts.total + 1;
if(readStati.get(message.getMessageId())) {
counts.read = counts.read + 1;
}
// Recurse
setupCounts(message,messages, readStati,counts);
}
}
}
public class Counts {
public int total = 0;
public int read = 0;
public Counts(int total,int read) {
this.total = total;
this.read = read;
}
}
}
| 32.566667 | 135 | 0.714773 |
40918a7fe2f87e1735530b6a30bd4a4325508993 | 1,036 | package pl.srw.todos.presenter;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import pl.srw.todos.model.Todo;
import pl.srw.todos.presenter.task.PushTask;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
public class AddViewPresenterTest {
@InjectMocks private AddViewPresenter sut;
@Mock private PushTask pushTask;
@Mock private AddViewPresenter.AddView view;
@Before
public void setUp() throws Exception {
sut = new AddViewPresenter(pushTask);
MockitoAnnotations.initMocks(this);
}
@Test
public void addClicked_executePushTask() throws Exception {
// WHEN
sut.addClicked(false, "");
// THEN
verify(pushTask).execute(any(Todo.class));
}
@Test
public void addClicked_closeView() throws Exception {
// WHEN
sut.addClicked(false, "");
// THEN
verify(view).close();
}
} | 23.022222 | 63 | 0.684363 |
ecf561e054f9d3d88f81aea70e0206f6cc40602c | 1,967 | package userinterface;
import javafx.scene.chart.XYChart;
/**
* This class stores the Series of one tool. These are needed
* to display tracking data in XYCharts.
*/
@SuppressWarnings("rawtypes")
public class TrackingDataDisplay {
private final String toolName;
private final XYChart.Series<Double, Double> dataSeries1;
private final XYChart.Series<Double, Double> dataSeries2;
private final XYChart.Series<Double, Double> dataSeries3;
public TrackingDataDisplay(String toolName) {
this.toolName = toolName;
dataSeries1 = new XYChart.Series<>();
dataSeries2 = new XYChart.Series<>();
dataSeries3 = new XYChart.Series<>();
// set names, so labels display tool name
dataSeries1.setName(toolName);
dataSeries2.setName(toolName);
dataSeries3.setName(toolName);
// Series need to have a data set so name and symbol are set correctly
dataSeries1.getData().add(new XYChart.Data<>(0.0, 0.0));
dataSeries2.getData().add(new XYChart.Data<>(0.0, 0.0));
dataSeries3.getData().add(new XYChart.Data<>(0.0, 0.0));
}
public String getToolName() {
return this.toolName;
}
public XYChart.Series getDataSeries1() {
return dataSeries1;
}
public XYChart.Series getDataSeries2() {
return dataSeries2;
}
public XYChart.Series getDataSeries3() {
return dataSeries3;
}
public void addDataToSeries1(XYChart.Data<Double, Double> dataset) {
dataSeries1.getData().add(dataset);
}
public void addDataToSeries2(XYChart.Data<Double, Double> dataset) {
dataSeries2.getData().add(dataset);
}
public void addDataToSeries3(XYChart.Data<Double, Double> dataset) {
dataSeries3.getData().add(dataset);
}
public void clearData() {
dataSeries1.getData().clear();
dataSeries2.getData().clear();
dataSeries3.getData().clear();
}
}
| 29.80303 | 78 | 0.661922 |
42e81ba002f7204f813ffb53e899776386ff5389 | 839 | package ss.week3.test;
import org.junit.Before;
import org.junit.Test;
import ss.week3.hotel.Bill;
import ss.week3.hotel.PricedRoom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PricedRoomTest {
private Bill.Item item;
private static final double PRICE = 6.36;
private static final String PRICE_PATTERN = ".*6[.,]36.*";
@Before
public void setUp() throws Exception {
item = new PricedRoom(0, PRICE, 0);
}
@Test
public void testGetAmount() throws Exception {
assertEquals("GetAmount should return the price of the room.", PRICE, item.getAmount(), 0);
}
@Test
public void testToString() throws Exception {
assertTrue("The price per night should be included.", item.toString().matches(PRICE_PATTERN));
}
}
| 25.424242 | 102 | 0.693683 |
1c5006bbeac6ff6ebb87c530323894f0829b26be | 957 | package controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
public class ManageItemFormController {
public AnchorPane root;
public void btnAddItemOnAction(ActionEvent actionEvent) {
}
public void btnSaveOnAction(ActionEvent actionEvent) {
}
public void btnDeleteOnAction(ActionEvent actionEvent) {
}
public void navigate(MouseEvent mouseEvent) throws IOException {
URL resource = this.getClass().getResource("/view/MainForm.fxml");
Parent root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) (this.root.getScene().getWindow());
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
}
}
| 27.342857 | 74 | 0.731452 |
48a7316c62de6a102ff533d27efa64c50b1adeda | 3,110 | package com.edwise.completespring.controllers;
import com.edwise.completespring.exceptions.InvalidRequestException;
import com.edwise.completespring.exceptions.NotFoundException;
import com.edwise.completespring.exceptions.helpers.ErrorInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RestExceptionProcessorTest {
private static final int ONE_ITEM = 1;
private static final int TWO_ITEMS = 2;
private static final String FIELD_ERROR_OBJECT_TEST1 = "Book";
private static final String FIELD_ERROR_FIELD_TEST1 = "title";
private static final String FIELD_ERROR_FIELD_TEST2 = "isbn";
private static final String FIELD_ERROR_MESSAGE_TEST1 = "No puede ser nulo";
private static final String FIELD_ERROR_MESSAGE_TEST2 = "No puede ser vacio";
private static final String EXCEPTION_MESSAGE_TEST1 = "No existe la entidad";
private RestExceptionProcessor restExceptionProcessor;
private MockHttpServletRequest request;
@Mock
private BindingResult errors;
@Before
public void setUp() {
this.request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request));
this.restExceptionProcessor = new RestExceptionProcessor();
}
@Test
public void testEntityNotFound() {
NotFoundException exception = new NotFoundException(EXCEPTION_MESSAGE_TEST1);
ErrorInfo errorInfo = restExceptionProcessor.entityNotFound(request, exception);
assertThat(errorInfo).isNotNull();
assertThat(errorInfo.getUrl()).isEqualTo(request.getRequestURL().toString());
assertThat(errorInfo.getErrors()).hasSize(ONE_ITEM);
}
@Test
public void testInvalidPostData() {
when(errors.getFieldErrors()).thenReturn(createMockListFieldErrors());
InvalidRequestException exception = new InvalidRequestException(errors);
ErrorInfo errorInfo = restExceptionProcessor.invalidPostData(request, exception);
assertThat(errorInfo).isNotNull();
assertThat(errorInfo.getUrl()).isEqualTo(request.getRequestURL().toString());
assertThat(errorInfo.getErrors()).hasSize(TWO_ITEMS);
}
private List<FieldError> createMockListFieldErrors() {
return Arrays.asList(
new FieldError(FIELD_ERROR_OBJECT_TEST1, FIELD_ERROR_FIELD_TEST1, FIELD_ERROR_MESSAGE_TEST1),
new FieldError(FIELD_ERROR_OBJECT_TEST1, FIELD_ERROR_FIELD_TEST2, FIELD_ERROR_MESSAGE_TEST2));
}
} | 40.38961 | 110 | 0.77299 |
55dea572af047d9bf5b8c5c3becd242ac296c7fb | 1,511 | package $PACKAGE$.init;
import $PACKAGE$.$MOD_CLASS$;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.ItemTags;
import net.minecraft.tags.Tag;
import net.minecraft.util.ResourceLocation;
public class ModTags {
public static final class Blocks {
// This will be "forge:ores/example"
public static final Tag<Block> EXAMPLE = tag("forge", "ores/example");
// Default namespace is mod ID, so this one will be "$MOD_ID$:example_block"
public static final Tag<Block> EXAMPLE2 = tag("example_block");
private Blocks() {}
private static Tag<Block> tag(String name) {
return new BlockTags.Wrapper(new ResourceLocation($MOD_CLASS$.MOD_ID, name));
}
private static Tag<Block> tag(String namespace, String name) {
return new BlockTags.Wrapper(new ResourceLocation(namespace, name));
}
}
public static final class Items {
// Item tags work the same way as block tags, so this is "$MOD_ID$:example_item"
public static final Tag<Item> EXAMPLE = tag("example_item");
private Items() {}
private static Tag<Item> tag(String name) {
return new ItemTags.Wrapper(new ResourceLocation($MOD_CLASS$.MOD_ID, name));
}
private static Tag<Item> tag(String namespace, String name) {
return new ItemTags.Wrapper(new ResourceLocation(namespace, name));
}
}
}
| 34.340909 | 89 | 0.665784 |
f2272fd5d5f0c7a94e10d51a1e5ea0982bafc266 | 366 | package ninja.harmless.tethys.aop.logging;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author [email protected] - 10/13/16.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EnableExceptionLogging {
}
| 24.4 | 44 | 0.800546 |
6c3cd29ee04c59cfa9d62ce2fce0c0add9de31ec | 1,963 | package org.infinispan.stream.impl.interceptor;
import org.infinispan.Cache;
import org.infinispan.CacheSet;
import org.infinispan.CacheStream;
import org.infinispan.commons.util.CloseableSpliterator;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.stream.impl.AbstractDelegatingCacheSet;
import org.infinispan.stream.impl.local.LocalEntryCacheStream;
import java.util.stream.StreamSupport;
/**
* Abstract cache entry set that delegates to the underlying cache for stream usage
* @param <K> key type of the cache
* @param <V> value type of the cache
*/
public abstract class AbstractDelegatingEntryCacheSet<K, V> extends AbstractDelegatingCacheSet<CacheEntry<K, V>> {
private final Cache<K, V> cache;
private final CacheSet<CacheEntry<K, V>> set;
protected AbstractDelegatingEntryCacheSet(Cache<K, V> cache, CacheSet<CacheEntry<K, V>> set) {
this.cache = cache;
this.set = set;
}
@Override
protected final CacheSet<CacheEntry<K, V>> delegate() {
return set;
}
@Override
public CacheStream<CacheEntry<K, V>> stream() {
return getStream(false);
}
@Override
public CacheStream<CacheEntry<K, V>> parallelStream() {
return getStream(true);
}
private CacheStream<CacheEntry<K, V>> getStream(boolean parallel) {
DistributionManager dm = cache.getAdvancedCache().getDistributionManager();
CloseableSpliterator<CacheEntry<K, V>> closeableSpliterator = spliterator();
CacheStream<CacheEntry<K, V>> stream = new LocalEntryCacheStream<>(cache, parallel, dm != null ?
dm.getConsistentHash() : null, () -> StreamSupport.stream(closeableSpliterator, parallel),
cache.getAdvancedCache().getComponentRegistry());
// We rely on the fact that on close returns the same instance
stream.onClose(() -> closeableSpliterator.close());
return stream;
}
}
| 36.351852 | 114 | 0.731024 |
ef0e1abd2bedceb665c0016c01712aa478b4468b | 947 | package com.Project2;
import javax.persistence.*;
import java.util.*;
@Entity// This tells Hibernate to make a table out of this
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//.IDENTITY needed to produce independent ids to new users and movies
private int userId;
private String password;
private String email;
@OneToMany
Set<Bookmark> bookmarks= new HashSet<Bookmark>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return userId;
}
public void setId(int id) {
this.userId = id;
}
public void addBookmarks(Bookmark bookmark) {
this.bookmarks.add(bookmark);
}
}
| 17.537037 | 122 | 0.637804 |
c5fbcab6ea5f386fcb0a4f673244bad5dbb3538d | 1,379 | package audio.rabid.dev.roe;
import android.os.Handler;
import android.os.Looper;
/**
* Created by charles on 10/28/15.
*/
public class BackgroundThread extends Thread {
private Handler handler;
private Handler mainHandler = new Handler(Looper.getMainLooper());
private final Object semaphore = new Object();
private BackgroundThread() {
// super("SourceBackgroundLooperTask");
// try {
// start();
// synchronized (semaphore) {
// semaphore.wait();
// }
// } catch (InterruptedException e) {
// throw new RuntimeException("Problem creating background thread", e);
// }
}
public void run() {
Looper.prepare();
handler = new Handler(Looper.myLooper());
synchronized (semaphore) {
semaphore.notify();
}
Looper.loop();
}
private static final BackgroundThread instance = new BackgroundThread();
// public static Handler getBackgroundHandler() {
// return instance.handler;
// }
public static Handler getMainHandler() {
return instance.mainHandler;
}
public static void postMain(Runnable r) {
getMainHandler().post(r);
}
public static void postBackground(Runnable r) {
// getBackgroundHandler().post(r);
new Thread(r).start();
}
}
| 24.192982 | 82 | 0.603336 |
18f5fb53a36f98b445d28042595e93b9e5e15fd5 | 1,527 | package com.njust.test.kemu2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import lombok.ToString;
@ToString
public class SerializableDemo implements Serializable
{
//都可以
public String name = "BBB";
//private可以被序列化,反序列化
private int age = 90;
//final不可以被反序列化,即不能被修改
final String hobby = "yyy";
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
SerializableDemo demo = new SerializableDemo();
//SerializableDemo(name=AAA, age=10, hobby=xxx)
//writeObject(demo);
SerializableDemo demo222 = (SerializableDemo)readObject();
//SerializableDemo(name=AAA, age=10, hobby=yyy)
System.out.println(demo222);
}
private static Object readObject()
throws IOException, ClassNotFoundException
{
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("./111.txt")))
{
return objectInputStream.readObject();
}
}
private static void writeObject(Serializable serializable)
throws IOException
{
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("./111.txt")))
{
objectOutputStream.writeObject(serializable);
objectOutputStream.flush();
}
}
}
| 27.267857 | 111 | 0.668631 |
2b1c974c2676fdfdb457ec8a74d58f55c43acaea | 833 | import java.util.Scanner;
public class ScannerTest01 {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.println("next方式接收:");
if (a.hasNext()){//判断是否还有下一个输入项
String cai = a.next();
/*
* a.next()与a.nextLine的区别
* next():作为字符串输入的方法,自动屏蔽掉输入的分隔符,如空格、Tab键、回车键,直到遇到有效地字符输入后,则将这些分隔符作为结束标志;
nextLine();
* 则是将从开始运行所输入的所有的字符,包括分隔符,均作为控制台输入,只有在遇到enter回车键时,才结束输入,并将所有的内容作为输入内容传给Scanner;
也就是说,next()方法并不能返回带空格、Tab键、回车符的字符串,而nextLine可以;
————————————————
版权声明:本文为CSDN博主「qauchangqingwei」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qauchangqingwei/article/details/80803627
* */
System.out.print("输入的内容: "+cai);
}
a.close();
}
}
| 33.32 | 91 | 0.606242 |
3909fdac7e20b8b95b34759208e6f88d6d56046e | 4,859 | package org.softuni.resident_evil.web.controllers;
import org.modelmapper.ModelMapper;
import org.softuni.resident_evil.domain.models.binding.VirusAddBindingModel;
import org.softuni.resident_evil.domain.models.binding.VirusDeleteBindingModel;
import org.softuni.resident_evil.domain.models.binding.VirusEditBindingModel;
import org.softuni.resident_evil.domain.models.service.VirusServiceModel;
import org.softuni.resident_evil.domain.models.view.VirusTableViewModel;
import org.softuni.resident_evil.service.CapitalService;
import org.softuni.resident_evil.service.VirusService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.List;
@Controller
@RequestMapping("/viruses")
public class VirusController extends BaseController {
private final VirusService virusService;
private final CapitalService capitalService;
private final ModelMapper mapper;
public VirusController(ModelMapper mapper, VirusService virusService, CapitalService capitalService) {
this.mapper = mapper;
this.virusService = virusService;
this.capitalService = capitalService;
}
@GetMapping("/show")
public ModelAndView allVirusesView() {
List<VirusTableViewModel> allViruses = this.virusService.getAllViruses();
return view("/all-viruses")
.addObject("allViruses", allViruses);
}
@GetMapping("/add")
public ModelAndView addView(@ModelAttribute("model") VirusAddBindingModel model) {
return prepareVirusModel("add-form", true);
}
@PostMapping("/add")
public ModelAndView addAction(@Valid @ModelAttribute("model") VirusAddBindingModel model,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return prepareVirusModel("add-form", true);
}
VirusServiceModel serviceModel = this.mapper.map(model, VirusServiceModel.class);
if (this.virusService.createVirus(serviceModel)) {
return redirect("/");
}
return super.view("/add-form");
}
@GetMapping("/edit/{virusId}")
public ModelAndView editView(@PathVariable String virusId) {
VirusServiceModel serviceModel = this.virusService.getOneById(virusId);
VirusEditBindingModel editBindingModel =
this.mapper.map(serviceModel, VirusEditBindingModel.class);
if (editBindingModel == null) {
return super.redirect("/viruses/show");
}
return this.prepareVirusModel("edit-form",false)
.addObject("model", editBindingModel);
}
@PostMapping("/edit")
@PreAuthorize("hasRole('ROLE_MODERATOR')")
public ModelAndView editAction(@Valid @ModelAttribute("model") VirusEditBindingModel editBindingModel,
final BindingResult bindingResult) {
if (editBindingModel == null) {
return super.redirect("/viruses/show");
}
if (bindingResult.hasErrors() || !this.virusService.editVirus(editBindingModel)) {
return this.prepareVirusModel("edit-form", false)
.addObject("model", editBindingModel);
}
return super.redirect("/viruses/show");
}
@GetMapping("/delete/{virusId}")
public ModelAndView deleteView(@PathVariable String virusId) {
VirusServiceModel serviceModel = this.virusService.getOneById(virusId);
VirusDeleteBindingModel deleteBindingModel =
this.mapper.map(serviceModel, VirusDeleteBindingModel.class);
if (deleteBindingModel == null) {
return super.redirect("/viruses/show");
}
return this.prepareVirusModel("delete-form",true)
.addObject("model", deleteBindingModel);
}
@PreAuthorize("hasRole('ROLE_MODERATOR')")
@PostMapping("/delete/{id}")
public ModelAndView deleteAction(@PathVariable String id) {
if (this.virusService.deleteVirus(id)){
return this.redirect("/viruses/show");
}
return this.redirect("/viruses/show");
}
private ModelAndView prepareVirusModel(String formName, boolean showDate){
return view(formName)
.addObject("allCapitals",
this.capitalService.capitalsNamesList())
.addObject("showDate", showDate);
}
@GetMapping(value = "/all_viruses", produces = "application/json")
@ResponseBody
public Object fetchData() {
List<VirusTableViewModel> allViruses = this.virusService
.getAllViruses();
return allViruses;
}
}
| 36.810606 | 106 | 0.685944 |
c57a75073ef88fc16b97ba7be11bfe8808986458 | 10,011 | package com.mazmaz.sharedhouse;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ImageButton btn_create_new_house, btn_existing_houses;
private FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference mDatabase;
String userId;
private ImageButton btnLogout;
String key_token;
boolean doubleBackToExitPressedOnce = false;
private static final int TIME_INTERVAL = 3000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mDatabase = FirebaseDatabase.getInstance().getReference();
btnLogout = findViewById(R.id.btnLogout);
firebaseAuth = FirebaseAuth.getInstance();
btn_existing_houses = findViewById(R.id.btn_existing_houses);
// Log.d("Test",user.getEmail());
// Log.d("Test","in main ");
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(MainActivity.this,LoginActivity.class));
}
});
btn_create_new_house = findViewById(R.id.btn_create_new_house);
final FirebaseUser user = firebaseAuth.getInstance().getCurrentUser() ;
firebaseDatabase = FirebaseDatabase.getInstance();
mDatabase = firebaseDatabase.getReference("SharedHouseUsers");
btn_create_new_house.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
writeNewSharedHouse(user.getEmail());
Intent i = new Intent(MainActivity.this, CreateNewSharedHouse.class);
i.putExtra("UserToken", userId);
i.putExtra("show_only_houses_list",1);
i.putExtra("token_key",key_token);
// Log.d("Test","111111 "+key_token);
// finish();
startActivity(i);
}
});
if(key_token==null){
btn_existing_houses.setEnabled(false);
}else{
btn_existing_houses.setEnabled(true);
}
btn_existing_houses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Log.d("Test", "hiiiiiiiii");
Runnable runnable = new Runnable() {
@Override
public void run() {
setToken();
}
};
// if(key_token==null){
runnable.run();
Intent i = new Intent(MainActivity.this, CreateNewSharedHouse.class);
i.putExtra("UserToken", userId);
i.putExtra("token_key",key_token);
i.putExtra("show_only_houses_list",0);
// Log.d("Test", "sending token : "+ key_token);
// finish();
startActivity(i);
}
});
// query.addListenerForSingleValueEvent();
// Log.d("Test", "Query: "+ query.getRef());
// query.getRef();
}
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("admin mail", username);
// result.put("shared houses", "");
//// result.put("title", title);
//// result.put("body", body);
//// result.put("starCount", starCount);
//// result.put("stars", stars);
//
// return result;
// }
@Override
protected void onResume() {
super.onResume();
final FirebaseUser user = firebaseAuth.getInstance().getCurrentUser() ;
if(user==null){
firebaseAuth.signOut();
finish();
startActivity(new Intent(MainActivity.this,LoginActivity.class));
}
userId = user.getUid();
Runnable runnable = new Runnable() {
@Override
public void run() {
setToken();
}
};
// if(key_token==null){
runnable.run();
//// setToken();;
// Log.d("Test", "1 -- key_token is null in onResume" + key_token);
// if(key_token == null){
// btn_existing_houses.setEnabled(false);
// Log.d("Test", "2 -- key_token is null in onResume" + key_token);
//
// }
// else{
// btn_existing_houses.setEnabled(true);
//
// }
// }
}
private void setToken(){
final FirebaseUser user = firebaseAuth.getInstance().getCurrentUser() ;
mDatabase = FirebaseDatabase.getInstance().getReference();
firebaseDatabase = FirebaseDatabase.getInstance();
mDatabase = firebaseDatabase.getReference("SharedHouseUsers");
mDatabase.child("houses").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
boolean fl = false;
for (DataSnapshot children: dataSnapshot.getChildren()){
if(fl==true){
break;
}
for (DataSnapshot child : children.getChildren()) {
if(child.getKey().equals("admin mail")){
if(child.getValue().equals(user.getEmail())){
// Log.d("Test", "setToken token: "+ child.getValue());
key_token=children.getKey();
break;
}
continue;
}
}
}
if(fl){
btn_existing_houses.setEnabled(false);
}else{
btn_existing_houses.setEnabled(true);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void writeNewSharedHouse(String userMail) throws IllegalArgumentException{
if(userMail==null || userMail.isEmpty()) throw new IllegalArgumentException();
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("houses").push().getKey();
// Post post = new Post(userId, username, title, body);
SharedHome sharedHome = new SharedHome(userMail);
Map<String, Object> sharedHomeValues = sharedHome.toMap();
Map<String, Object> childUpdates = new HashMap<>();
if(key_token==null){
// key_token=key;
// Log.d("Test","NULL in key");
childUpdates.put("/houses/" + key, sharedHomeValues);
childUpdates.put("/user-houses/" + userId + "/" + key, sharedHomeValues);
key_token=key;
}else{
Runnable runnable = new Runnable() {
@Override
public void run() {
setToken();
}
};
// if(key_token==null){
runnable.run();
}
mDatabase.updateChildren(childUpdates);
// SharedHome sharedHome = new SharedHome(userMail);
// mDatabase.updateChildrenAsync(sharedHome+"/gracehop");
}
@Override
protected void onDestroy() {
super.onDestroy();
// firebaseAuth.signOut();
// Auth.GoogleSignInApi.signOut(new GoogleApiClient.Builder(getApplicationContext()) //Use app context to prevent leaks using activity
// //.enableAutoManage(this /* FragmentActivity */, connectionFailedListener)
// .addApi(Auth.GOOGLE_SIGN_IN_API)
// .build());
}
@Override
protected void onStart() {
super.onStart();
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
};
});
}
@Override
public void onBackPressed() {
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{
super.onBackPressed();
return;
}
else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
// private class searchinDBTssk extends AsyncTask<Void, Void, Void>{
//
//
//
//
// @Override
// protected Void doInBackground(Void... voids) {
//// setToken();
//
// return null;
// }
//
// @Override
// protected void onPostExecute(Void result) {
// }
// }
}
| 31.780952 | 141 | 0.564879 |
c8c8dabe708368e7dad01443d58509fee7a88f39 | 702 | package com.corey.springbootquartzdemo.jobs;
import com.corey.springbootquartzdemo.info.TimerInfo;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class HelloWorldJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
TimerInfo info = (TimerInfo) jobDataMap.get(HelloWorldJob.class.getSimpleName());
log.info(info.getCallBackData());
}
}
| 27 | 89 | 0.773504 |
585f854e0f625aab26a0cb2b09d4c38d4e1fe762 | 662 | package com.calistasakralya.response;
import com.calistasakralya.model.InboxModel;
import com.calistasakralya.model.InboxbalasModel;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GetBalas {
@SerializedName("result")
List<InboxbalasModel> listInbox;
@SerializedName("message")
final private String message;
public GetBalas(List<InboxbalasModel> listInbox, String message) {
this.listInbox = listInbox;
this.message = message;
}
public List<InboxbalasModel> getListInbox() {
return listInbox;
}
public String getMessage() {
return message;
}
}
| 22.827586 | 70 | 0.714502 |
1499ccc5b4bf4c508d30a75948c30062377b5580 | 520 | package com.mafour.api.dao.dao;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
import lombok.Data;
@Data
@TableName("update_record")
public class BookUpdateRecordDO {
@TableId(type = IdType.AUTO)
private Long id;
private String bookName;
private String bookSlug;
private String activeType;
private String slug;
private String slugName;
private Date updatedAt;
}
| 18.571429 | 53 | 0.782692 |
7d900831db5ec787e0469b45aca7f0e8df8c50c9 | 473 | // Test incorrect conditional expression assignment.
// .result=COMPILE_FAIL
interface Ownable { }
interface Thing { }
abstract class Entity implements Thing { }
abstract class NotEntity { }
class Unit extends Entity implements Ownable { }
class Resource extends NotEntity implements Ownable { }
class Test {
void foo(Resource resource, Unit unit) {
// Thing is not a common supertype of Resource and Unit.
Thing l = (resource != null) ? resource : unit;
}
}
| 27.823529 | 60 | 0.731501 |
34946941cb30a0791b8fb28bda8a54ecc97207a2 | 12,591 | package com.tools.plugin.utils.ftp;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import com.tools.plugin.utils.Exceptions;
import com.tools.plugin.utils.NewMapUtil;
import com.tools.plugin.utils.NumberUtils;
import com.tools.plugin.utils.StringUtil;
public class FtpHelper implements Closeable {
private final static Logger logger = LoggerFactory.getLogger(FtpHelper.class);
private static Map<String,Object> ftpMap = new HashMap<>();
private FTPClient ftp = null;
boolean _isLogin = false;
public static FtpHelper getInstance() {
return new FtpHelper();
}
/**
*
* ftp 匿名登录;如果没有设置ftp用户可将username设为anonymous,密码为任意字符串
*
* @param ip ftp服务地址
* @param port 端口号
* @param uname 用户名
* @param pass 密码
*/
public boolean login(String ip, int port) {
ftpMap.clear();
ftpMap.putAll(new NewMapUtil().set("ip", ip)
.set("port", port)
.set("uname", "anonymous")
.set("pass", "")
.get());
return login(ip, port, "anonymous", "");
}
/**
*
* ftp登录
*
* @param ip ftp服务地址
* @param port 端口号
* @param uname 用户名
* @param pass 密码
* @param workingDir ftp 根目目录
*/
public boolean login(String ip, int port, String uname, String pass) {
ftp = new FTPClient();
try {
// 设置传输超时时间为60秒
ftp.setDataTimeout(60*1000*60);
// 连接超时为60秒
ftp.setConnectTimeout(60*1000*10);
// 连接
ftp.connect(ip, port);
_isLogin = ftp.login(uname, pass);
logger.info("ftp:"+(_isLogin ? "登录成功" : "登录失败"));
// 检测连接是否成功
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.err.println("FTP服务器拒绝连接 ");
return false;
}
ftpMap.clear();
ftpMap.putAll(new NewMapUtil().set("ip", ip)
.set("port", port)
.set("uname", uname)
.set("pass", pass)
.get());
return true;
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
return false;
}
}
/**
* Ftp 服务掉线重连
* @param ftpMap
* @return
*/
private boolean reLogin(Map<String, Object> ftpMap) {
if (null == ftpMap || ftpMap.isEmpty()) {
logger.info("ftp:登录失败 ; ftp map is null or Empty");
return false;
}
if (StringUtil.isNullOrEmpty(ftpMap.get("ip"))) {
logger.info("ftp:登录失败 ; ftp ip is null or Empty");
return false;
}
if (StringUtil.isNullOrEmpty(ftpMap.get("port"))) {
logger.info("ftp:登录失败 ; ftp port is null or Empty");
return false;
}
if (StringUtil.isNullOrEmpty(ftpMap.get("uname"))) {
logger.info("ftp:登录失败 ; ftp user name is null or Empty");
return false;
}
//关闭上传连接
this.close();
String ip = String.valueOf(ftpMap.get("ip"));
int port = NumberUtils.intValue(ftpMap.get("port"), 21);
String uname = String.valueOf(ftpMap.get("uname"));
String pass = String.valueOf(ftpMap.get("pass"));
if (uname.equalsIgnoreCase("anonymous")) {
return this.login(ip, port);
} else {
return this.login(ip, port, uname, pass);
}
}
/**
* 上传后触发
*/
public Function<FtpFileInfo, Boolean> onUploadFileAfter;
/**
*
* ftp上传文件
*
* @param localFileName 待上传文件
* @param ftpDirName ftp 目录名
* @param ftpFileName ftp目标文件
* @return true||false
*/
public boolean uploadFile(String localFileName, String ftpDirName, String ftpFileName) {
return uploadFile(localFileName, ftpDirName, ftpFileName, false);
}
/**
*
* ftp上传文件
*
* @param localFileName 待上传文件
* @param ftpDirName ftp 目录名
* @param ftpFileName ftp 目标文件
* @param deleteLocalFile 是否删除本地文件
* @return true||false
*/
public boolean uploadFile(String localFileName, String ftpDirName, String ftpFileName, boolean deleteLocalFile) {
logger.debug("准备上传 [" + localFileName + "] 到 ftp://" + ftpDirName + "/" + ftpFileName);
if (!this.isConnected()) {
boolean _login = this.reLogin(ftpMap);
if (!_login) {
throw new RuntimeException("Ftp 服务重连失败!");
}
}
File srcFile = new File(localFileName);
if (!srcFile.exists()) {
throw new RuntimeException("文件不存在:" + localFileName);
}
try (FileInputStream fis = new FileInputStream(srcFile)) {
// 上传文件
boolean flag = uploadFile(fis, ftpDirName, ftpFileName, 0);
// 上传前事件
if (onUploadFileAfter != null) {
onUploadFileAfter.apply(new FtpFileInfo(localFileName, ftpDirName, ftpFileName));
}
// 删除文件
if (deleteLocalFile) {
srcFile.delete();
logger.debug("ftp删除源文件:" + srcFile);
}
fis.close();
return flag;
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
return false;
}
}
/**
*
* ftp上传文件 (使用inputstream)
*
* @param localFileName 待上传文件
* @param ftpDirName ftp 目录名
* @param ftpFileName ftp目标文件
* @return true||false
*/
public boolean uploadFile(FileInputStream uploadInputStream, String ftpDirName, String ftpFileName, int cycle) {
logger.debug("准备上传 [流] 到 ftp://"+ftpDirName+"/"+ftpFileName );
try {
if (!this.isConnected()) {
boolean _login = this.reLogin(ftpMap);
if (!_login) {
throw new RuntimeException("Ftp 服务重连失败!");
}
}
if (StringUtil.isNullOrEmpty(ftpFileName)){
throw new RuntimeException("上传文件必须填写文件名!");
}
if (!createDir(ftpDirName)) {
throw new RuntimeException("切入FTP目录失败:" + ftpDirName);
}
ftp.setBufferSize(1024);
// 解决上传中文 txt 文件乱码
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
// 设置文件类型(二进制)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// 上传
String fileName = new String(ftpFileName.getBytes("GBK"), "iso-8859-1");
// 每次数据连接之前,ftp client 通知ftp server开通一个端口来传输数据。
ftp.enterLocalPassiveMode();
if (ftp.storeFile(fileName, uploadInputStream)) {
uploadInputStream.close();
logger.debug("文件上传成功:"+ftpDirName+"/"+ftpFileName);
return true;
}
return false;
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
cycle++;
if (cycle < 3) {
this.reLogin(ftpMap);
return this.uploadFile(uploadInputStream, ftpDirName, ftpFileName, cycle);
}
return false;
}
}
/**
* 下载文件(使用HttpServletResponse)
*
* @param remoteremoteAdr 远程路径
* @param localAdr 文件名称
* @return
*/
public void downloadFile(String remoteremoteAdr, String localAdr, HttpServletResponse response) {
try {
if (StringUtil.isNullOrEmpty(remoteremoteAdr)) {
remoteremoteAdr = "/";
}
String dir = new String(remoteremoteAdr.getBytes("GBK"), "iso-8859-1");
if (!ftp.changeWorkingDirectory(dir)) {
System.out.println("切换目录失败:" + remoteremoteAdr);
return;
}
ftp.enterLocalPassiveMode();
// 由于apache不支持中文语言环境,通过定制类解析中文日期类型
ftp.configure(new FTPClientConfig("com.zznode.tnms.ra.c11n.nj.resource.ftp.UnixFTPEntryParser"));
FTPFile[] fs = ftp.listFiles();
String fileName = new String(localAdr.getBytes("GBK"), "iso-8859-1");
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
// 这个就就是弹出下载对话框的关键代码
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(ff.getName().getBytes("gb2312"), "ISO8859-1"));
response.setContentType("application/octet-stream; charset=utf-8");
// 将文件保存到输出流outputStream中
OutputStream os = response.getOutputStream();
ftp.retrieveFile(new String(ff.getName().getBytes("UTF-8"), "ISO8859-1"), os);
os.flush();
os.close();
break;
}
}
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
}
}
/**
* 下载文件
*
* @param ftpDirName ftp目录名
* @param ftpFileName ftp文件名
* @param localFileFullName 本地文件名
* @return
*/
public boolean downloadFile(String ftpDirName, String ftpFileName, String localFileFullName) {
try {
if (StringUtil.isNullOrEmpty(ftpDirName)){
ftpDirName = "/";
}
String dir = new String(ftpDirName.getBytes("GBK"), "iso-8859-1");
if (!ftp.changeWorkingDirectory(dir)) {
System.out.println("切换目录失败:" + ftpDirName);
return false;
}
FTPFile[] fs = ftp.listFiles();
String fileName = new String(ftpFileName.getBytes("GBK"), "iso-8859-1");
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
FileOutputStream is = new FileOutputStream(new File(localFileFullName));
ftp.retrieveFile(ff.getName(), is);
is.close();
System.out.println("下载ftp文件已下载:" + localFileFullName);
return true;
}
}
System.out.println("下载ftp文件失败:" + ftpFileName + ";目录:" + ftpDirName);
return false;
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
return false;
}
}
/**
*
* 删除ftp上的文件
*
* @param ftpFileName
* @return true || false
*/
public boolean removeFile(String ftpFileName) {
boolean flag = false;
logger.debug("待删除文件:"+ ftpFileName);
try {
ftpFileName = new String(ftpFileName.getBytes("GBK"), "iso-8859-1");
flag = ftp.deleteFile(ftpFileName);
logger.debug("删除文件:["+(flag ? "成功" : "失败")+"]");
return flag;
} catch (IOException ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
return false;
}
}
/**
* 删除空目录
*
* @param dir
* @return
*/
public boolean removeDir(String dir) {
if (dir.startsWith("/"))
dir = "/" + dir;
try {
String d = new String(dir.toString().getBytes("GBK"), "iso-8859-1");
return ftp.removeDirectory(d);
} catch (Exception ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
return false;
}
}
/**
* 创建目录(有则切换目录,没有则创建目录)
*
* @param dir
* @return
*/
public boolean createDir(String dir) throws Exception {
if (StringUtil.isNullOrEmpty(dir)) {
return true;
}
// 目录编码,解决中文路径问题
String d = new String(dir.toString().getBytes("GBK"), "iso-8859-1");
// 尝试切入目录
if (ftp.changeWorkingDirectory(d)) {
return true;
}
dir = StringExtend.trimStart(dir, "/");
dir = StringExtend.trimEnd(dir, "/");
String[] arr = dir.split("/");
StringBuffer sbfDir = new StringBuffer();
// 循环生成子目录
for (String s : arr) {
sbfDir.append("/");
sbfDir.append(s);
// 目录编码,解决中文路径问题
d = new String(sbfDir.toString().getBytes("GBK"), "iso-8859-1");
// 尝试切入目录
if (ftp.changeWorkingDirectory(d)) {
continue;
}
if (!ftp.makeDirectory(d)) {
System.out.println("[失败]ftp创建目录:" + sbfDir.toString());
return false;
}
System.out.println("[成功]创建ftp目录:" + sbfDir.toString());
}
// 将目录切换至指定路径
return ftp.changeWorkingDirectory(d);
}
/**
*
* 销毁ftp连接
*
*/
private void closeFtpConnection() {
_isLogin = false;
if (ftp != null) {
if (ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
logger.info("关闭 ftp 客户端 连接成功!");
} catch (IOException ex) {
logger.error(Exceptions.getStackTraceAsString(ex));
}
}
}
}
/**
*
* 销毁ftp连接
*
*/
@Override
public void close() {
this.closeFtpConnection();
}
/**
*
* 销毁ftp连接
*
*/
public boolean isConnected() {
if (ftp != null) {
if (ftp.isConnected()) {
return true;
}
}
return false;
}
public static class FtpFileInfo {
public FtpFileInfo(String srcFile, String ftpDirName, String ftpFileName) {
this.ftpDirName = ftpDirName;
this.ftpFileName = ftpFileName;
this.srcFile = srcFile;
}
String srcFile;
String ftpDirName;
String ftpFileName;
String ftpFileFullName;
public String getSrcFile() {
return srcFile;
}
public void setSrcFile(String srcFile) {
this.srcFile = srcFile;
}
public String getFtpDirName() {
return ftpDirName;
}
public void setFtpDirName(String ftpDirName) {
this.ftpDirName = ftpDirName;
}
public String getFtpFileName() {
return ftpFileName;
}
public void setFtpFileName(String ftpFileName) {
this.ftpFileName = ftpFileName;
}
/**
* 获取ftp上传文件的完整路径名
*
* @return
*/
public String getFtpFileFullName() {
return PathExtend.Combine("/", ftpDirName, ftpFileName);
}
}
} | 25.283133 | 130 | 0.651656 |
3d067e43e78907355cfb34de7928f08fb4deb0c6 | 1,242 | package com.example.coolweather.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.coolweather.util.LogUtil;
/**
* Created by chenbing on 2018/4/26.
*/
public class BaseBusiness {
private static final String TAG = "BaseBusiness";
//对象锁
public static final Object lock = new Object();
//数据库名称
private final String dbName = "cool_weather.db";
protected static SQLiteDatabase db;
private DbHelper dbHelper;
/**数据库版本
* 1 2018.4.26 初始创建
*/
private final int db_version = 1;
public BaseBusiness(Context context){
dbHelper = new DbHelper(context,dbName,null,db_version);
synchronized (lock){
openDataBase(context);
}
}
/**
* 获取数据库对象
* @param context
* @return
*/
private SQLiteDatabase openDataBase(Context context){
if (context == null){
return null;
}
if (db == null || !db.isOpen()){
try {
db = dbHelper.getWritableDatabase();
}catch (Exception e){
LogUtil.e(TAG, "openDataBase: " + e.getMessage());
}
}
return db;
}
}
| 23.433962 | 66 | 0.592593 |
dd67c3849fd869906be9521595626bea20f01cf1 | 2,236 | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.pds.client.models;
import com.aliyun.tea.*;
/**
*
*/
public class SignatureInfo extends TeaModel {
@NameInMap("bucket")
public String bucket;
@NameInMap("canonicalized_resource")
public String canonicalizedResource;
@NameInMap("endpoint")
public String endpoint;
@NameInMap("headers")
public java.util.Map<String, ?> headers;
@NameInMap("object_key")
public String objectKey;
@NameInMap("signature")
public String signature;
@NameInMap("str_to_sign")
public String strToSign;
public static SignatureInfo build(java.util.Map<String, ?> map) throws Exception {
SignatureInfo self = new SignatureInfo();
return TeaModel.build(map, self);
}
public SignatureInfo setBucket(String bucket) {
this.bucket = bucket;
return this;
}
public String getBucket() {
return this.bucket;
}
public SignatureInfo setCanonicalizedResource(String canonicalizedResource) {
this.canonicalizedResource = canonicalizedResource;
return this;
}
public String getCanonicalizedResource() {
return this.canonicalizedResource;
}
public SignatureInfo setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public String getEndpoint() {
return this.endpoint;
}
public SignatureInfo setHeaders(java.util.Map<String, ?> headers) {
this.headers = headers;
return this;
}
public java.util.Map<String, ?> getHeaders() {
return this.headers;
}
public SignatureInfo setObjectKey(String objectKey) {
this.objectKey = objectKey;
return this;
}
public String getObjectKey() {
return this.objectKey;
}
public SignatureInfo setSignature(String signature) {
this.signature = signature;
return this;
}
public String getSignature() {
return this.signature;
}
public SignatureInfo setStrToSign(String strToSign) {
this.strToSign = strToSign;
return this;
}
public String getStrToSign() {
return this.strToSign;
}
}
| 24.043011 | 86 | 0.651163 |
e4705ac314a5a8975f64f3a6d2dfee55dd2385ef | 228,180 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: dstore/engine/procedures/mi_GetStorageAllocInfo_Ad.proto
package io.dstore.engine.procedures;
public final class MiGetStorageAllocInfoAd {
private MiGetStorageAllocInfoAd() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface ParametersOrBuilder extends
// @@protoc_insertion_point(interface_extends:dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
boolean hasGetInfoForADatabase();
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
io.dstore.values.BooleanValue getGetInfoForADatabase();
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
io.dstore.values.BooleanValueOrBuilder getGetInfoForADatabaseOrBuilder();
/**
* <code>bool get_info_for_a_database_null = 1001;</code>
*/
boolean getGetInfoForADatabaseNull();
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
boolean hasGetStorageAllocInfoFor();
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
io.dstore.values.StringValue getGetStorageAllocInfoFor();
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
io.dstore.values.StringValueOrBuilder getGetStorageAllocInfoForOrBuilder();
/**
* <code>bool get_storage_alloc_info_for_null = 1002;</code>
*/
boolean getGetStorageAllocInfoForNull();
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters}
*/
public static final class Parameters extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters)
ParametersOrBuilder {
// Use Parameters.newBuilder() to construct.
private Parameters(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Parameters() {
getInfoForADatabaseNull_ = false;
getStorageAllocInfoForNull_ = false;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Parameters(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
io.dstore.values.BooleanValue.Builder subBuilder = null;
if (getInfoForADatabase_ != null) {
subBuilder = getInfoForADatabase_.toBuilder();
}
getInfoForADatabase_ = input.readMessage(io.dstore.values.BooleanValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(getInfoForADatabase_);
getInfoForADatabase_ = subBuilder.buildPartial();
}
break;
}
case 18: {
io.dstore.values.StringValue.Builder subBuilder = null;
if (getStorageAllocInfoFor_ != null) {
subBuilder = getStorageAllocInfoFor_.toBuilder();
}
getStorageAllocInfoFor_ = input.readMessage(io.dstore.values.StringValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(getStorageAllocInfoFor_);
getStorageAllocInfoFor_ = subBuilder.buildPartial();
}
break;
}
case 8008: {
getInfoForADatabaseNull_ = input.readBool();
break;
}
case 8016: {
getStorageAllocInfoForNull_ = input.readBool();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.Builder.class);
}
public static final int GET_INFO_FOR_A_DATABASE_FIELD_NUMBER = 1;
private io.dstore.values.BooleanValue getInfoForADatabase_;
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public boolean hasGetInfoForADatabase() {
return getInfoForADatabase_ != null;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public io.dstore.values.BooleanValue getGetInfoForADatabase() {
return getInfoForADatabase_ == null ? io.dstore.values.BooleanValue.getDefaultInstance() : getInfoForADatabase_;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public io.dstore.values.BooleanValueOrBuilder getGetInfoForADatabaseOrBuilder() {
return getGetInfoForADatabase();
}
public static final int GET_INFO_FOR_A_DATABASE_NULL_FIELD_NUMBER = 1001;
private boolean getInfoForADatabaseNull_;
/**
* <code>bool get_info_for_a_database_null = 1001;</code>
*/
public boolean getGetInfoForADatabaseNull() {
return getInfoForADatabaseNull_;
}
public static final int GET_STORAGE_ALLOC_INFO_FOR_FIELD_NUMBER = 2;
private io.dstore.values.StringValue getStorageAllocInfoFor_;
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public boolean hasGetStorageAllocInfoFor() {
return getStorageAllocInfoFor_ != null;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public io.dstore.values.StringValue getGetStorageAllocInfoFor() {
return getStorageAllocInfoFor_ == null ? io.dstore.values.StringValue.getDefaultInstance() : getStorageAllocInfoFor_;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public io.dstore.values.StringValueOrBuilder getGetStorageAllocInfoForOrBuilder() {
return getGetStorageAllocInfoFor();
}
public static final int GET_STORAGE_ALLOC_INFO_FOR_NULL_FIELD_NUMBER = 1002;
private boolean getStorageAllocInfoForNull_;
/**
* <code>bool get_storage_alloc_info_for_null = 1002;</code>
*/
public boolean getGetStorageAllocInfoForNull() {
return getStorageAllocInfoForNull_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (getInfoForADatabase_ != null) {
output.writeMessage(1, getGetInfoForADatabase());
}
if (getStorageAllocInfoFor_ != null) {
output.writeMessage(2, getGetStorageAllocInfoFor());
}
if (getInfoForADatabaseNull_ != false) {
output.writeBool(1001, getInfoForADatabaseNull_);
}
if (getStorageAllocInfoForNull_ != false) {
output.writeBool(1002, getStorageAllocInfoForNull_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (getInfoForADatabase_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getGetInfoForADatabase());
}
if (getStorageAllocInfoFor_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getGetStorageAllocInfoFor());
}
if (getInfoForADatabaseNull_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(1001, getInfoForADatabaseNull_);
}
if (getStorageAllocInfoForNull_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(1002, getStorageAllocInfoForNull_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters)) {
return super.equals(obj);
}
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters other = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters) obj;
boolean result = true;
result = result && (hasGetInfoForADatabase() == other.hasGetInfoForADatabase());
if (hasGetInfoForADatabase()) {
result = result && getGetInfoForADatabase()
.equals(other.getGetInfoForADatabase());
}
result = result && (getGetInfoForADatabaseNull()
== other.getGetInfoForADatabaseNull());
result = result && (hasGetStorageAllocInfoFor() == other.hasGetStorageAllocInfoFor());
if (hasGetStorageAllocInfoFor()) {
result = result && getGetStorageAllocInfoFor()
.equals(other.getGetStorageAllocInfoFor());
}
result = result && (getGetStorageAllocInfoForNull()
== other.getGetStorageAllocInfoForNull());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasGetInfoForADatabase()) {
hash = (37 * hash) + GET_INFO_FOR_A_DATABASE_FIELD_NUMBER;
hash = (53 * hash) + getGetInfoForADatabase().hashCode();
}
hash = (37 * hash) + GET_INFO_FOR_A_DATABASE_NULL_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getGetInfoForADatabaseNull());
if (hasGetStorageAllocInfoFor()) {
hash = (37 * hash) + GET_STORAGE_ALLOC_INFO_FOR_FIELD_NUMBER;
hash = (53 * hash) + getGetStorageAllocInfoFor().hashCode();
}
hash = (37 * hash) + GET_STORAGE_ALLOC_INFO_FOR_NULL_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getGetStorageAllocInfoForNull());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters)
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.ParametersOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.Builder.class);
}
// Construct using io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
if (getInfoForADatabaseBuilder_ == null) {
getInfoForADatabase_ = null;
} else {
getInfoForADatabase_ = null;
getInfoForADatabaseBuilder_ = null;
}
getInfoForADatabaseNull_ = false;
if (getStorageAllocInfoForBuilder_ == null) {
getStorageAllocInfoFor_ = null;
} else {
getStorageAllocInfoFor_ = null;
getStorageAllocInfoForBuilder_ = null;
}
getStorageAllocInfoForNull_ = false;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters getDefaultInstanceForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.getDefaultInstance();
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters build() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters buildPartial() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters result = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters(this);
if (getInfoForADatabaseBuilder_ == null) {
result.getInfoForADatabase_ = getInfoForADatabase_;
} else {
result.getInfoForADatabase_ = getInfoForADatabaseBuilder_.build();
}
result.getInfoForADatabaseNull_ = getInfoForADatabaseNull_;
if (getStorageAllocInfoForBuilder_ == null) {
result.getStorageAllocInfoFor_ = getStorageAllocInfoFor_;
} else {
result.getStorageAllocInfoFor_ = getStorageAllocInfoForBuilder_.build();
}
result.getStorageAllocInfoForNull_ = getStorageAllocInfoForNull_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters) {
return mergeFrom((io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters other) {
if (other == io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters.getDefaultInstance()) return this;
if (other.hasGetInfoForADatabase()) {
mergeGetInfoForADatabase(other.getGetInfoForADatabase());
}
if (other.getGetInfoForADatabaseNull() != false) {
setGetInfoForADatabaseNull(other.getGetInfoForADatabaseNull());
}
if (other.hasGetStorageAllocInfoFor()) {
mergeGetStorageAllocInfoFor(other.getGetStorageAllocInfoFor());
}
if (other.getGetStorageAllocInfoForNull() != false) {
setGetStorageAllocInfoForNull(other.getGetStorageAllocInfoForNull());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private io.dstore.values.BooleanValue getInfoForADatabase_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.BooleanValue, io.dstore.values.BooleanValue.Builder, io.dstore.values.BooleanValueOrBuilder> getInfoForADatabaseBuilder_;
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public boolean hasGetInfoForADatabase() {
return getInfoForADatabaseBuilder_ != null || getInfoForADatabase_ != null;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public io.dstore.values.BooleanValue getGetInfoForADatabase() {
if (getInfoForADatabaseBuilder_ == null) {
return getInfoForADatabase_ == null ? io.dstore.values.BooleanValue.getDefaultInstance() : getInfoForADatabase_;
} else {
return getInfoForADatabaseBuilder_.getMessage();
}
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public Builder setGetInfoForADatabase(io.dstore.values.BooleanValue value) {
if (getInfoForADatabaseBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
getInfoForADatabase_ = value;
onChanged();
} else {
getInfoForADatabaseBuilder_.setMessage(value);
}
return this;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public Builder setGetInfoForADatabase(
io.dstore.values.BooleanValue.Builder builderForValue) {
if (getInfoForADatabaseBuilder_ == null) {
getInfoForADatabase_ = builderForValue.build();
onChanged();
} else {
getInfoForADatabaseBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public Builder mergeGetInfoForADatabase(io.dstore.values.BooleanValue value) {
if (getInfoForADatabaseBuilder_ == null) {
if (getInfoForADatabase_ != null) {
getInfoForADatabase_ =
io.dstore.values.BooleanValue.newBuilder(getInfoForADatabase_).mergeFrom(value).buildPartial();
} else {
getInfoForADatabase_ = value;
}
onChanged();
} else {
getInfoForADatabaseBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public Builder clearGetInfoForADatabase() {
if (getInfoForADatabaseBuilder_ == null) {
getInfoForADatabase_ = null;
onChanged();
} else {
getInfoForADatabase_ = null;
getInfoForADatabaseBuilder_ = null;
}
return this;
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public io.dstore.values.BooleanValue.Builder getGetInfoForADatabaseBuilder() {
onChanged();
return getGetInfoForADatabaseFieldBuilder().getBuilder();
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
public io.dstore.values.BooleanValueOrBuilder getGetInfoForADatabaseOrBuilder() {
if (getInfoForADatabaseBuilder_ != null) {
return getInfoForADatabaseBuilder_.getMessageOrBuilder();
} else {
return getInfoForADatabase_ == null ?
io.dstore.values.BooleanValue.getDefaultInstance() : getInfoForADatabase_;
}
}
/**
* <code>.dstore.values.BooleanValue get_info_for_a_database = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.BooleanValue, io.dstore.values.BooleanValue.Builder, io.dstore.values.BooleanValueOrBuilder>
getGetInfoForADatabaseFieldBuilder() {
if (getInfoForADatabaseBuilder_ == null) {
getInfoForADatabaseBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.BooleanValue, io.dstore.values.BooleanValue.Builder, io.dstore.values.BooleanValueOrBuilder>(
getGetInfoForADatabase(),
getParentForChildren(),
isClean());
getInfoForADatabase_ = null;
}
return getInfoForADatabaseBuilder_;
}
private boolean getInfoForADatabaseNull_ ;
/**
* <code>bool get_info_for_a_database_null = 1001;</code>
*/
public boolean getGetInfoForADatabaseNull() {
return getInfoForADatabaseNull_;
}
/**
* <code>bool get_info_for_a_database_null = 1001;</code>
*/
public Builder setGetInfoForADatabaseNull(boolean value) {
getInfoForADatabaseNull_ = value;
onChanged();
return this;
}
/**
* <code>bool get_info_for_a_database_null = 1001;</code>
*/
public Builder clearGetInfoForADatabaseNull() {
getInfoForADatabaseNull_ = false;
onChanged();
return this;
}
private io.dstore.values.StringValue getStorageAllocInfoFor_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder> getStorageAllocInfoForBuilder_;
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public boolean hasGetStorageAllocInfoFor() {
return getStorageAllocInfoForBuilder_ != null || getStorageAllocInfoFor_ != null;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public io.dstore.values.StringValue getGetStorageAllocInfoFor() {
if (getStorageAllocInfoForBuilder_ == null) {
return getStorageAllocInfoFor_ == null ? io.dstore.values.StringValue.getDefaultInstance() : getStorageAllocInfoFor_;
} else {
return getStorageAllocInfoForBuilder_.getMessage();
}
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public Builder setGetStorageAllocInfoFor(io.dstore.values.StringValue value) {
if (getStorageAllocInfoForBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
getStorageAllocInfoFor_ = value;
onChanged();
} else {
getStorageAllocInfoForBuilder_.setMessage(value);
}
return this;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public Builder setGetStorageAllocInfoFor(
io.dstore.values.StringValue.Builder builderForValue) {
if (getStorageAllocInfoForBuilder_ == null) {
getStorageAllocInfoFor_ = builderForValue.build();
onChanged();
} else {
getStorageAllocInfoForBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public Builder mergeGetStorageAllocInfoFor(io.dstore.values.StringValue value) {
if (getStorageAllocInfoForBuilder_ == null) {
if (getStorageAllocInfoFor_ != null) {
getStorageAllocInfoFor_ =
io.dstore.values.StringValue.newBuilder(getStorageAllocInfoFor_).mergeFrom(value).buildPartial();
} else {
getStorageAllocInfoFor_ = value;
}
onChanged();
} else {
getStorageAllocInfoForBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public Builder clearGetStorageAllocInfoFor() {
if (getStorageAllocInfoForBuilder_ == null) {
getStorageAllocInfoFor_ = null;
onChanged();
} else {
getStorageAllocInfoFor_ = null;
getStorageAllocInfoForBuilder_ = null;
}
return this;
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public io.dstore.values.StringValue.Builder getGetStorageAllocInfoForBuilder() {
onChanged();
return getGetStorageAllocInfoForFieldBuilder().getBuilder();
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
public io.dstore.values.StringValueOrBuilder getGetStorageAllocInfoForOrBuilder() {
if (getStorageAllocInfoForBuilder_ != null) {
return getStorageAllocInfoForBuilder_.getMessageOrBuilder();
} else {
return getStorageAllocInfoFor_ == null ?
io.dstore.values.StringValue.getDefaultInstance() : getStorageAllocInfoFor_;
}
}
/**
* <code>.dstore.values.StringValue get_storage_alloc_info_for = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>
getGetStorageAllocInfoForFieldBuilder() {
if (getStorageAllocInfoForBuilder_ == null) {
getStorageAllocInfoForBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>(
getGetStorageAllocInfoFor(),
getParentForChildren(),
isClean());
getStorageAllocInfoFor_ = null;
}
return getStorageAllocInfoForBuilder_;
}
private boolean getStorageAllocInfoForNull_ ;
/**
* <code>bool get_storage_alloc_info_for_null = 1002;</code>
*/
public boolean getGetStorageAllocInfoForNull() {
return getStorageAllocInfoForNull_;
}
/**
* <code>bool get_storage_alloc_info_for_null = 1002;</code>
*/
public Builder setGetStorageAllocInfoForNull(boolean value) {
getStorageAllocInfoForNull_ = value;
onChanged();
return this;
}
/**
* <code>bool get_storage_alloc_info_for_null = 1002;</code>
*/
public Builder clearGetStorageAllocInfoForNull() {
getStorageAllocInfoForNull_ = false;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters)
}
// @@protoc_insertion_point(class_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Parameters)
private static final io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters();
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Parameters>
PARSER = new com.google.protobuf.AbstractParser<Parameters>() {
public Parameters parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Parameters(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Parameters> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Parameters> getParserForType() {
return PARSER;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Parameters getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface ResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:dstore.engine.mi_GetStorageAllocInfo_Ad.Response)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
java.util.List<io.dstore.engine.MetaInformation>
getMetaInformationList();
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
io.dstore.engine.MetaInformation getMetaInformation(int index);
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
int getMetaInformationCount();
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
java.util.List<? extends io.dstore.engine.MetaInformationOrBuilder>
getMetaInformationOrBuilderList();
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
io.dstore.engine.MetaInformationOrBuilder getMetaInformationOrBuilder(
int index);
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
java.util.List<io.dstore.engine.Message>
getMessageList();
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
io.dstore.engine.Message getMessage(int index);
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
int getMessageCount();
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
java.util.List<? extends io.dstore.engine.MessageOrBuilder>
getMessageOrBuilderList();
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
io.dstore.engine.MessageOrBuilder getMessageOrBuilder(
int index);
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row>
getRowList();
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getRow(int index);
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
int getRowCount();
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
java.util.List<? extends io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder>
getRowOrBuilderList();
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder getRowOrBuilder(
int index);
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Response}
*/
public static final class Response extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Response)
ResponseOrBuilder {
// Use Response.newBuilder() to construct.
private Response(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Response() {
metaInformation_ = java.util.Collections.emptyList();
message_ = java.util.Collections.emptyList();
row_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Response(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
metaInformation_ = new java.util.ArrayList<io.dstore.engine.MetaInformation>();
mutable_bitField0_ |= 0x00000001;
}
metaInformation_.add(
input.readMessage(io.dstore.engine.MetaInformation.parser(), extensionRegistry));
break;
}
case 26: {
if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
message_ = new java.util.ArrayList<io.dstore.engine.Message>();
mutable_bitField0_ |= 0x00000002;
}
message_.add(
input.readMessage(io.dstore.engine.Message.parser(), extensionRegistry));
break;
}
case 34: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
row_ = new java.util.ArrayList<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row>();
mutable_bitField0_ |= 0x00000004;
}
row_.add(
input.readMessage(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.parser(), extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
metaInformation_ = java.util.Collections.unmodifiableList(metaInformation_);
}
if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
message_ = java.util.Collections.unmodifiableList(message_);
}
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
row_ = java.util.Collections.unmodifiableList(row_);
}
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Builder.class);
}
public interface RowOrBuilder extends
// @@protoc_insertion_point(interface_extends:dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row)
com.google.protobuf.MessageOrBuilder {
/**
* <code>int32 row_id = 10000;</code>
*/
int getRowId();
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
boolean hasTableName();
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
io.dstore.values.StringValue getTableName();
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
io.dstore.values.StringValueOrBuilder getTableNameOrBuilder();
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
boolean hasIndexSizeMb();
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
io.dstore.values.DecimalValue getIndexSizeMb();
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
io.dstore.values.DecimalValueOrBuilder getIndexSizeMbOrBuilder();
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
boolean hasNumberOfIndexes();
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
io.dstore.values.IntegerValue getNumberOfIndexes();
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
io.dstore.values.IntegerValueOrBuilder getNumberOfIndexesOrBuilder();
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
boolean hasNumberOfRows();
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
io.dstore.values.IntegerValue getNumberOfRows();
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
io.dstore.values.IntegerValueOrBuilder getNumberOfRowsOrBuilder();
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
boolean hasTableSizeMb();
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
io.dstore.values.DecimalValue getTableSizeMb();
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
io.dstore.values.DecimalValueOrBuilder getTableSizeMbOrBuilder();
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
boolean hasDataSizeMb();
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
io.dstore.values.DecimalValue getDataSizeMb();
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
io.dstore.values.DecimalValueOrBuilder getDataSizeMbOrBuilder();
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
boolean hasMballocated();
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
io.dstore.values.DecimalValue getMballocated();
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
io.dstore.values.DecimalValueOrBuilder getMballocatedOrBuilder();
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
boolean hasSegmentName();
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
io.dstore.values.StringValue getSegmentName();
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
io.dstore.values.StringValueOrBuilder getSegmentNameOrBuilder();
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
boolean hasMbused();
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
io.dstore.values.DecimalValue getMbused();
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
io.dstore.values.DecimalValueOrBuilder getMbusedOrBuilder();
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
boolean hasFreeSpaceInPercent();
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
io.dstore.values.DecimalValue getFreeSpaceInPercent();
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
io.dstore.values.DecimalValueOrBuilder getFreeSpaceInPercentOrBuilder();
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
boolean hasDBName();
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
io.dstore.values.StringValue getDBName();
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
io.dstore.values.StringValueOrBuilder getDBNameOrBuilder();
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
boolean hasMbfree();
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
io.dstore.values.DecimalValue getMbfree();
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
io.dstore.values.DecimalValueOrBuilder getMbfreeOrBuilder();
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row}
*/
public static final class Row extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row)
RowOrBuilder {
// Use Row.newBuilder() to construct.
private Row(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Row() {
rowId_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private Row(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 80000: {
rowId_ = input.readInt32();
break;
}
case 80010: {
io.dstore.values.StringValue.Builder subBuilder = null;
if (tableName_ != null) {
subBuilder = tableName_.toBuilder();
}
tableName_ = input.readMessage(io.dstore.values.StringValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(tableName_);
tableName_ = subBuilder.buildPartial();
}
break;
}
case 80018: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (indexSizeMb_ != null) {
subBuilder = indexSizeMb_.toBuilder();
}
indexSizeMb_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(indexSizeMb_);
indexSizeMb_ = subBuilder.buildPartial();
}
break;
}
case 80026: {
io.dstore.values.IntegerValue.Builder subBuilder = null;
if (numberOfIndexes_ != null) {
subBuilder = numberOfIndexes_.toBuilder();
}
numberOfIndexes_ = input.readMessage(io.dstore.values.IntegerValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(numberOfIndexes_);
numberOfIndexes_ = subBuilder.buildPartial();
}
break;
}
case 80034: {
io.dstore.values.IntegerValue.Builder subBuilder = null;
if (numberOfRows_ != null) {
subBuilder = numberOfRows_.toBuilder();
}
numberOfRows_ = input.readMessage(io.dstore.values.IntegerValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(numberOfRows_);
numberOfRows_ = subBuilder.buildPartial();
}
break;
}
case 80042: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (tableSizeMb_ != null) {
subBuilder = tableSizeMb_.toBuilder();
}
tableSizeMb_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(tableSizeMb_);
tableSizeMb_ = subBuilder.buildPartial();
}
break;
}
case 80050: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (dataSizeMb_ != null) {
subBuilder = dataSizeMb_.toBuilder();
}
dataSizeMb_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(dataSizeMb_);
dataSizeMb_ = subBuilder.buildPartial();
}
break;
}
case 160010: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (mballocated_ != null) {
subBuilder = mballocated_.toBuilder();
}
mballocated_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(mballocated_);
mballocated_ = subBuilder.buildPartial();
}
break;
}
case 160018: {
io.dstore.values.StringValue.Builder subBuilder = null;
if (segmentName_ != null) {
subBuilder = segmentName_.toBuilder();
}
segmentName_ = input.readMessage(io.dstore.values.StringValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(segmentName_);
segmentName_ = subBuilder.buildPartial();
}
break;
}
case 160026: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (mbused_ != null) {
subBuilder = mbused_.toBuilder();
}
mbused_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(mbused_);
mbused_ = subBuilder.buildPartial();
}
break;
}
case 160034: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (freeSpaceInPercent_ != null) {
subBuilder = freeSpaceInPercent_.toBuilder();
}
freeSpaceInPercent_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(freeSpaceInPercent_);
freeSpaceInPercent_ = subBuilder.buildPartial();
}
break;
}
case 160042: {
io.dstore.values.StringValue.Builder subBuilder = null;
if (dBName_ != null) {
subBuilder = dBName_.toBuilder();
}
dBName_ = input.readMessage(io.dstore.values.StringValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(dBName_);
dBName_ = subBuilder.buildPartial();
}
break;
}
case 160050: {
io.dstore.values.DecimalValue.Builder subBuilder = null;
if (mbfree_ != null) {
subBuilder = mbfree_.toBuilder();
}
mbfree_ = input.readMessage(io.dstore.values.DecimalValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(mbfree_);
mbfree_ = subBuilder.buildPartial();
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder.class);
}
public static final int ROW_ID_FIELD_NUMBER = 10000;
private int rowId_;
/**
* <code>int32 row_id = 10000;</code>
*/
public int getRowId() {
return rowId_;
}
public static final int TABLE_NAME_FIELD_NUMBER = 10001;
private io.dstore.values.StringValue tableName_;
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public boolean hasTableName() {
return tableName_ != null;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public io.dstore.values.StringValue getTableName() {
return tableName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : tableName_;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public io.dstore.values.StringValueOrBuilder getTableNameOrBuilder() {
return getTableName();
}
public static final int INDEX_SIZE_MB_FIELD_NUMBER = 10002;
private io.dstore.values.DecimalValue indexSizeMb_;
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public boolean hasIndexSizeMb() {
return indexSizeMb_ != null;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public io.dstore.values.DecimalValue getIndexSizeMb() {
return indexSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : indexSizeMb_;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getIndexSizeMbOrBuilder() {
return getIndexSizeMb();
}
public static final int NUMBER_OF_INDEXES_FIELD_NUMBER = 10003;
private io.dstore.values.IntegerValue numberOfIndexes_;
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public boolean hasNumberOfIndexes() {
return numberOfIndexes_ != null;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public io.dstore.values.IntegerValue getNumberOfIndexes() {
return numberOfIndexes_ == null ? io.dstore.values.IntegerValue.getDefaultInstance() : numberOfIndexes_;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public io.dstore.values.IntegerValueOrBuilder getNumberOfIndexesOrBuilder() {
return getNumberOfIndexes();
}
public static final int NUMBER_OF_ROWS_FIELD_NUMBER = 10004;
private io.dstore.values.IntegerValue numberOfRows_;
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public boolean hasNumberOfRows() {
return numberOfRows_ != null;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public io.dstore.values.IntegerValue getNumberOfRows() {
return numberOfRows_ == null ? io.dstore.values.IntegerValue.getDefaultInstance() : numberOfRows_;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public io.dstore.values.IntegerValueOrBuilder getNumberOfRowsOrBuilder() {
return getNumberOfRows();
}
public static final int TABLE_SIZE_MB_FIELD_NUMBER = 10005;
private io.dstore.values.DecimalValue tableSizeMb_;
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public boolean hasTableSizeMb() {
return tableSizeMb_ != null;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public io.dstore.values.DecimalValue getTableSizeMb() {
return tableSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : tableSizeMb_;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getTableSizeMbOrBuilder() {
return getTableSizeMb();
}
public static final int DATA_SIZE_MB_FIELD_NUMBER = 10006;
private io.dstore.values.DecimalValue dataSizeMb_;
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public boolean hasDataSizeMb() {
return dataSizeMb_ != null;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public io.dstore.values.DecimalValue getDataSizeMb() {
return dataSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : dataSizeMb_;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getDataSizeMbOrBuilder() {
return getDataSizeMb();
}
public static final int MBALLOCATED_FIELD_NUMBER = 20001;
private io.dstore.values.DecimalValue mballocated_;
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public boolean hasMballocated() {
return mballocated_ != null;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public io.dstore.values.DecimalValue getMballocated() {
return mballocated_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mballocated_;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMballocatedOrBuilder() {
return getMballocated();
}
public static final int SEGMENT_NAME_FIELD_NUMBER = 20002;
private io.dstore.values.StringValue segmentName_;
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public boolean hasSegmentName() {
return segmentName_ != null;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public io.dstore.values.StringValue getSegmentName() {
return segmentName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : segmentName_;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public io.dstore.values.StringValueOrBuilder getSegmentNameOrBuilder() {
return getSegmentName();
}
public static final int MBUSED_FIELD_NUMBER = 20003;
private io.dstore.values.DecimalValue mbused_;
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public boolean hasMbused() {
return mbused_ != null;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public io.dstore.values.DecimalValue getMbused() {
return mbused_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mbused_;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMbusedOrBuilder() {
return getMbused();
}
public static final int FREE_SPACE_IN_PERCENT_FIELD_NUMBER = 20004;
private io.dstore.values.DecimalValue freeSpaceInPercent_;
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public boolean hasFreeSpaceInPercent() {
return freeSpaceInPercent_ != null;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public io.dstore.values.DecimalValue getFreeSpaceInPercent() {
return freeSpaceInPercent_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : freeSpaceInPercent_;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getFreeSpaceInPercentOrBuilder() {
return getFreeSpaceInPercent();
}
public static final int D_B_NAME_FIELD_NUMBER = 20005;
private io.dstore.values.StringValue dBName_;
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public boolean hasDBName() {
return dBName_ != null;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public io.dstore.values.StringValue getDBName() {
return dBName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : dBName_;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public io.dstore.values.StringValueOrBuilder getDBNameOrBuilder() {
return getDBName();
}
public static final int MBFREE_FIELD_NUMBER = 20006;
private io.dstore.values.DecimalValue mbfree_;
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public boolean hasMbfree() {
return mbfree_ != null;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public io.dstore.values.DecimalValue getMbfree() {
return mbfree_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mbfree_;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMbfreeOrBuilder() {
return getMbfree();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (rowId_ != 0) {
output.writeInt32(10000, rowId_);
}
if (tableName_ != null) {
output.writeMessage(10001, getTableName());
}
if (indexSizeMb_ != null) {
output.writeMessage(10002, getIndexSizeMb());
}
if (numberOfIndexes_ != null) {
output.writeMessage(10003, getNumberOfIndexes());
}
if (numberOfRows_ != null) {
output.writeMessage(10004, getNumberOfRows());
}
if (tableSizeMb_ != null) {
output.writeMessage(10005, getTableSizeMb());
}
if (dataSizeMb_ != null) {
output.writeMessage(10006, getDataSizeMb());
}
if (mballocated_ != null) {
output.writeMessage(20001, getMballocated());
}
if (segmentName_ != null) {
output.writeMessage(20002, getSegmentName());
}
if (mbused_ != null) {
output.writeMessage(20003, getMbused());
}
if (freeSpaceInPercent_ != null) {
output.writeMessage(20004, getFreeSpaceInPercent());
}
if (dBName_ != null) {
output.writeMessage(20005, getDBName());
}
if (mbfree_ != null) {
output.writeMessage(20006, getMbfree());
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (rowId_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(10000, rowId_);
}
if (tableName_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10001, getTableName());
}
if (indexSizeMb_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10002, getIndexSizeMb());
}
if (numberOfIndexes_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10003, getNumberOfIndexes());
}
if (numberOfRows_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10004, getNumberOfRows());
}
if (tableSizeMb_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10005, getTableSizeMb());
}
if (dataSizeMb_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(10006, getDataSizeMb());
}
if (mballocated_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20001, getMballocated());
}
if (segmentName_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20002, getSegmentName());
}
if (mbused_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20003, getMbused());
}
if (freeSpaceInPercent_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20004, getFreeSpaceInPercent());
}
if (dBName_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20005, getDBName());
}
if (mbfree_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(20006, getMbfree());
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row)) {
return super.equals(obj);
}
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row other = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row) obj;
boolean result = true;
result = result && (getRowId()
== other.getRowId());
result = result && (hasTableName() == other.hasTableName());
if (hasTableName()) {
result = result && getTableName()
.equals(other.getTableName());
}
result = result && (hasIndexSizeMb() == other.hasIndexSizeMb());
if (hasIndexSizeMb()) {
result = result && getIndexSizeMb()
.equals(other.getIndexSizeMb());
}
result = result && (hasNumberOfIndexes() == other.hasNumberOfIndexes());
if (hasNumberOfIndexes()) {
result = result && getNumberOfIndexes()
.equals(other.getNumberOfIndexes());
}
result = result && (hasNumberOfRows() == other.hasNumberOfRows());
if (hasNumberOfRows()) {
result = result && getNumberOfRows()
.equals(other.getNumberOfRows());
}
result = result && (hasTableSizeMb() == other.hasTableSizeMb());
if (hasTableSizeMb()) {
result = result && getTableSizeMb()
.equals(other.getTableSizeMb());
}
result = result && (hasDataSizeMb() == other.hasDataSizeMb());
if (hasDataSizeMb()) {
result = result && getDataSizeMb()
.equals(other.getDataSizeMb());
}
result = result && (hasMballocated() == other.hasMballocated());
if (hasMballocated()) {
result = result && getMballocated()
.equals(other.getMballocated());
}
result = result && (hasSegmentName() == other.hasSegmentName());
if (hasSegmentName()) {
result = result && getSegmentName()
.equals(other.getSegmentName());
}
result = result && (hasMbused() == other.hasMbused());
if (hasMbused()) {
result = result && getMbused()
.equals(other.getMbused());
}
result = result && (hasFreeSpaceInPercent() == other.hasFreeSpaceInPercent());
if (hasFreeSpaceInPercent()) {
result = result && getFreeSpaceInPercent()
.equals(other.getFreeSpaceInPercent());
}
result = result && (hasDBName() == other.hasDBName());
if (hasDBName()) {
result = result && getDBName()
.equals(other.getDBName());
}
result = result && (hasMbfree() == other.hasMbfree());
if (hasMbfree()) {
result = result && getMbfree()
.equals(other.getMbfree());
}
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ROW_ID_FIELD_NUMBER;
hash = (53 * hash) + getRowId();
if (hasTableName()) {
hash = (37 * hash) + TABLE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getTableName().hashCode();
}
if (hasIndexSizeMb()) {
hash = (37 * hash) + INDEX_SIZE_MB_FIELD_NUMBER;
hash = (53 * hash) + getIndexSizeMb().hashCode();
}
if (hasNumberOfIndexes()) {
hash = (37 * hash) + NUMBER_OF_INDEXES_FIELD_NUMBER;
hash = (53 * hash) + getNumberOfIndexes().hashCode();
}
if (hasNumberOfRows()) {
hash = (37 * hash) + NUMBER_OF_ROWS_FIELD_NUMBER;
hash = (53 * hash) + getNumberOfRows().hashCode();
}
if (hasTableSizeMb()) {
hash = (37 * hash) + TABLE_SIZE_MB_FIELD_NUMBER;
hash = (53 * hash) + getTableSizeMb().hashCode();
}
if (hasDataSizeMb()) {
hash = (37 * hash) + DATA_SIZE_MB_FIELD_NUMBER;
hash = (53 * hash) + getDataSizeMb().hashCode();
}
if (hasMballocated()) {
hash = (37 * hash) + MBALLOCATED_FIELD_NUMBER;
hash = (53 * hash) + getMballocated().hashCode();
}
if (hasSegmentName()) {
hash = (37 * hash) + SEGMENT_NAME_FIELD_NUMBER;
hash = (53 * hash) + getSegmentName().hashCode();
}
if (hasMbused()) {
hash = (37 * hash) + MBUSED_FIELD_NUMBER;
hash = (53 * hash) + getMbused().hashCode();
}
if (hasFreeSpaceInPercent()) {
hash = (37 * hash) + FREE_SPACE_IN_PERCENT_FIELD_NUMBER;
hash = (53 * hash) + getFreeSpaceInPercent().hashCode();
}
if (hasDBName()) {
hash = (37 * hash) + D_B_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDBName().hashCode();
}
if (hasMbfree()) {
hash = (37 * hash) + MBFREE_FIELD_NUMBER;
hash = (53 * hash) + getMbfree().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row)
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder.class);
}
// Construct using io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
rowId_ = 0;
if (tableNameBuilder_ == null) {
tableName_ = null;
} else {
tableName_ = null;
tableNameBuilder_ = null;
}
if (indexSizeMbBuilder_ == null) {
indexSizeMb_ = null;
} else {
indexSizeMb_ = null;
indexSizeMbBuilder_ = null;
}
if (numberOfIndexesBuilder_ == null) {
numberOfIndexes_ = null;
} else {
numberOfIndexes_ = null;
numberOfIndexesBuilder_ = null;
}
if (numberOfRowsBuilder_ == null) {
numberOfRows_ = null;
} else {
numberOfRows_ = null;
numberOfRowsBuilder_ = null;
}
if (tableSizeMbBuilder_ == null) {
tableSizeMb_ = null;
} else {
tableSizeMb_ = null;
tableSizeMbBuilder_ = null;
}
if (dataSizeMbBuilder_ == null) {
dataSizeMb_ = null;
} else {
dataSizeMb_ = null;
dataSizeMbBuilder_ = null;
}
if (mballocatedBuilder_ == null) {
mballocated_ = null;
} else {
mballocated_ = null;
mballocatedBuilder_ = null;
}
if (segmentNameBuilder_ == null) {
segmentName_ = null;
} else {
segmentName_ = null;
segmentNameBuilder_ = null;
}
if (mbusedBuilder_ == null) {
mbused_ = null;
} else {
mbused_ = null;
mbusedBuilder_ = null;
}
if (freeSpaceInPercentBuilder_ == null) {
freeSpaceInPercent_ = null;
} else {
freeSpaceInPercent_ = null;
freeSpaceInPercentBuilder_ = null;
}
if (dBNameBuilder_ == null) {
dBName_ = null;
} else {
dBName_ = null;
dBNameBuilder_ = null;
}
if (mbfreeBuilder_ == null) {
mbfree_ = null;
} else {
mbfree_ = null;
mbfreeBuilder_ = null;
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getDefaultInstanceForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.getDefaultInstance();
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row build() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row buildPartial() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row result = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row(this);
result.rowId_ = rowId_;
if (tableNameBuilder_ == null) {
result.tableName_ = tableName_;
} else {
result.tableName_ = tableNameBuilder_.build();
}
if (indexSizeMbBuilder_ == null) {
result.indexSizeMb_ = indexSizeMb_;
} else {
result.indexSizeMb_ = indexSizeMbBuilder_.build();
}
if (numberOfIndexesBuilder_ == null) {
result.numberOfIndexes_ = numberOfIndexes_;
} else {
result.numberOfIndexes_ = numberOfIndexesBuilder_.build();
}
if (numberOfRowsBuilder_ == null) {
result.numberOfRows_ = numberOfRows_;
} else {
result.numberOfRows_ = numberOfRowsBuilder_.build();
}
if (tableSizeMbBuilder_ == null) {
result.tableSizeMb_ = tableSizeMb_;
} else {
result.tableSizeMb_ = tableSizeMbBuilder_.build();
}
if (dataSizeMbBuilder_ == null) {
result.dataSizeMb_ = dataSizeMb_;
} else {
result.dataSizeMb_ = dataSizeMbBuilder_.build();
}
if (mballocatedBuilder_ == null) {
result.mballocated_ = mballocated_;
} else {
result.mballocated_ = mballocatedBuilder_.build();
}
if (segmentNameBuilder_ == null) {
result.segmentName_ = segmentName_;
} else {
result.segmentName_ = segmentNameBuilder_.build();
}
if (mbusedBuilder_ == null) {
result.mbused_ = mbused_;
} else {
result.mbused_ = mbusedBuilder_.build();
}
if (freeSpaceInPercentBuilder_ == null) {
result.freeSpaceInPercent_ = freeSpaceInPercent_;
} else {
result.freeSpaceInPercent_ = freeSpaceInPercentBuilder_.build();
}
if (dBNameBuilder_ == null) {
result.dBName_ = dBName_;
} else {
result.dBName_ = dBNameBuilder_.build();
}
if (mbfreeBuilder_ == null) {
result.mbfree_ = mbfree_;
} else {
result.mbfree_ = mbfreeBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row) {
return mergeFrom((io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row other) {
if (other == io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.getDefaultInstance()) return this;
if (other.getRowId() != 0) {
setRowId(other.getRowId());
}
if (other.hasTableName()) {
mergeTableName(other.getTableName());
}
if (other.hasIndexSizeMb()) {
mergeIndexSizeMb(other.getIndexSizeMb());
}
if (other.hasNumberOfIndexes()) {
mergeNumberOfIndexes(other.getNumberOfIndexes());
}
if (other.hasNumberOfRows()) {
mergeNumberOfRows(other.getNumberOfRows());
}
if (other.hasTableSizeMb()) {
mergeTableSizeMb(other.getTableSizeMb());
}
if (other.hasDataSizeMb()) {
mergeDataSizeMb(other.getDataSizeMb());
}
if (other.hasMballocated()) {
mergeMballocated(other.getMballocated());
}
if (other.hasSegmentName()) {
mergeSegmentName(other.getSegmentName());
}
if (other.hasMbused()) {
mergeMbused(other.getMbused());
}
if (other.hasFreeSpaceInPercent()) {
mergeFreeSpaceInPercent(other.getFreeSpaceInPercent());
}
if (other.hasDBName()) {
mergeDBName(other.getDBName());
}
if (other.hasMbfree()) {
mergeMbfree(other.getMbfree());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int rowId_ ;
/**
* <code>int32 row_id = 10000;</code>
*/
public int getRowId() {
return rowId_;
}
/**
* <code>int32 row_id = 10000;</code>
*/
public Builder setRowId(int value) {
rowId_ = value;
onChanged();
return this;
}
/**
* <code>int32 row_id = 10000;</code>
*/
public Builder clearRowId() {
rowId_ = 0;
onChanged();
return this;
}
private io.dstore.values.StringValue tableName_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder> tableNameBuilder_;
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public boolean hasTableName() {
return tableNameBuilder_ != null || tableName_ != null;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public io.dstore.values.StringValue getTableName() {
if (tableNameBuilder_ == null) {
return tableName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : tableName_;
} else {
return tableNameBuilder_.getMessage();
}
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public Builder setTableName(io.dstore.values.StringValue value) {
if (tableNameBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
tableName_ = value;
onChanged();
} else {
tableNameBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public Builder setTableName(
io.dstore.values.StringValue.Builder builderForValue) {
if (tableNameBuilder_ == null) {
tableName_ = builderForValue.build();
onChanged();
} else {
tableNameBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public Builder mergeTableName(io.dstore.values.StringValue value) {
if (tableNameBuilder_ == null) {
if (tableName_ != null) {
tableName_ =
io.dstore.values.StringValue.newBuilder(tableName_).mergeFrom(value).buildPartial();
} else {
tableName_ = value;
}
onChanged();
} else {
tableNameBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public Builder clearTableName() {
if (tableNameBuilder_ == null) {
tableName_ = null;
onChanged();
} else {
tableName_ = null;
tableNameBuilder_ = null;
}
return this;
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public io.dstore.values.StringValue.Builder getTableNameBuilder() {
onChanged();
return getTableNameFieldBuilder().getBuilder();
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
public io.dstore.values.StringValueOrBuilder getTableNameOrBuilder() {
if (tableNameBuilder_ != null) {
return tableNameBuilder_.getMessageOrBuilder();
} else {
return tableName_ == null ?
io.dstore.values.StringValue.getDefaultInstance() : tableName_;
}
}
/**
* <pre>
* Name einer Tabelle, auf die sich die weiteren Spalten beziehen (für die also der Speicher-Verbrauch bestimmt wurde)
* </pre>
*
* <code>.dstore.values.StringValue table_name = 10001;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>
getTableNameFieldBuilder() {
if (tableNameBuilder_ == null) {
tableNameBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>(
getTableName(),
getParentForChildren(),
isClean());
tableName_ = null;
}
return tableNameBuilder_;
}
private io.dstore.values.DecimalValue indexSizeMb_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> indexSizeMbBuilder_;
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public boolean hasIndexSizeMb() {
return indexSizeMbBuilder_ != null || indexSizeMb_ != null;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public io.dstore.values.DecimalValue getIndexSizeMb() {
if (indexSizeMbBuilder_ == null) {
return indexSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : indexSizeMb_;
} else {
return indexSizeMbBuilder_.getMessage();
}
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public Builder setIndexSizeMb(io.dstore.values.DecimalValue value) {
if (indexSizeMbBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
indexSizeMb_ = value;
onChanged();
} else {
indexSizeMbBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public Builder setIndexSizeMb(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (indexSizeMbBuilder_ == null) {
indexSizeMb_ = builderForValue.build();
onChanged();
} else {
indexSizeMbBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public Builder mergeIndexSizeMb(io.dstore.values.DecimalValue value) {
if (indexSizeMbBuilder_ == null) {
if (indexSizeMb_ != null) {
indexSizeMb_ =
io.dstore.values.DecimalValue.newBuilder(indexSizeMb_).mergeFrom(value).buildPartial();
} else {
indexSizeMb_ = value;
}
onChanged();
} else {
indexSizeMbBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public Builder clearIndexSizeMb() {
if (indexSizeMbBuilder_ == null) {
indexSizeMb_ = null;
onChanged();
} else {
indexSizeMb_ = null;
indexSizeMbBuilder_ = null;
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public io.dstore.values.DecimalValue.Builder getIndexSizeMbBuilder() {
onChanged();
return getIndexSizeMbFieldBuilder().getBuilder();
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getIndexSizeMbOrBuilder() {
if (indexSizeMbBuilder_ != null) {
return indexSizeMbBuilder_.getMessageOrBuilder();
} else {
return indexSizeMb_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : indexSizeMb_;
}
}
/**
* <pre>
* Speicherverbrauch für die Indizes der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue index_size_mb = 10002;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getIndexSizeMbFieldBuilder() {
if (indexSizeMbBuilder_ == null) {
indexSizeMbBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getIndexSizeMb(),
getParentForChildren(),
isClean());
indexSizeMb_ = null;
}
return indexSizeMbBuilder_;
}
private io.dstore.values.IntegerValue numberOfIndexes_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder> numberOfIndexesBuilder_;
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public boolean hasNumberOfIndexes() {
return numberOfIndexesBuilder_ != null || numberOfIndexes_ != null;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public io.dstore.values.IntegerValue getNumberOfIndexes() {
if (numberOfIndexesBuilder_ == null) {
return numberOfIndexes_ == null ? io.dstore.values.IntegerValue.getDefaultInstance() : numberOfIndexes_;
} else {
return numberOfIndexesBuilder_.getMessage();
}
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public Builder setNumberOfIndexes(io.dstore.values.IntegerValue value) {
if (numberOfIndexesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
numberOfIndexes_ = value;
onChanged();
} else {
numberOfIndexesBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public Builder setNumberOfIndexes(
io.dstore.values.IntegerValue.Builder builderForValue) {
if (numberOfIndexesBuilder_ == null) {
numberOfIndexes_ = builderForValue.build();
onChanged();
} else {
numberOfIndexesBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public Builder mergeNumberOfIndexes(io.dstore.values.IntegerValue value) {
if (numberOfIndexesBuilder_ == null) {
if (numberOfIndexes_ != null) {
numberOfIndexes_ =
io.dstore.values.IntegerValue.newBuilder(numberOfIndexes_).mergeFrom(value).buildPartial();
} else {
numberOfIndexes_ = value;
}
onChanged();
} else {
numberOfIndexesBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public Builder clearNumberOfIndexes() {
if (numberOfIndexesBuilder_ == null) {
numberOfIndexes_ = null;
onChanged();
} else {
numberOfIndexes_ = null;
numberOfIndexesBuilder_ = null;
}
return this;
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public io.dstore.values.IntegerValue.Builder getNumberOfIndexesBuilder() {
onChanged();
return getNumberOfIndexesFieldBuilder().getBuilder();
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
public io.dstore.values.IntegerValueOrBuilder getNumberOfIndexesOrBuilder() {
if (numberOfIndexesBuilder_ != null) {
return numberOfIndexesBuilder_.getMessageOrBuilder();
} else {
return numberOfIndexes_ == null ?
io.dstore.values.IntegerValue.getDefaultInstance() : numberOfIndexes_;
}
}
/**
* <pre>
* Anzahl Indizes der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_indexes = 10003;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder>
getNumberOfIndexesFieldBuilder() {
if (numberOfIndexesBuilder_ == null) {
numberOfIndexesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder>(
getNumberOfIndexes(),
getParentForChildren(),
isClean());
numberOfIndexes_ = null;
}
return numberOfIndexesBuilder_;
}
private io.dstore.values.IntegerValue numberOfRows_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder> numberOfRowsBuilder_;
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public boolean hasNumberOfRows() {
return numberOfRowsBuilder_ != null || numberOfRows_ != null;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public io.dstore.values.IntegerValue getNumberOfRows() {
if (numberOfRowsBuilder_ == null) {
return numberOfRows_ == null ? io.dstore.values.IntegerValue.getDefaultInstance() : numberOfRows_;
} else {
return numberOfRowsBuilder_.getMessage();
}
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public Builder setNumberOfRows(io.dstore.values.IntegerValue value) {
if (numberOfRowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
numberOfRows_ = value;
onChanged();
} else {
numberOfRowsBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public Builder setNumberOfRows(
io.dstore.values.IntegerValue.Builder builderForValue) {
if (numberOfRowsBuilder_ == null) {
numberOfRows_ = builderForValue.build();
onChanged();
} else {
numberOfRowsBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public Builder mergeNumberOfRows(io.dstore.values.IntegerValue value) {
if (numberOfRowsBuilder_ == null) {
if (numberOfRows_ != null) {
numberOfRows_ =
io.dstore.values.IntegerValue.newBuilder(numberOfRows_).mergeFrom(value).buildPartial();
} else {
numberOfRows_ = value;
}
onChanged();
} else {
numberOfRowsBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public Builder clearNumberOfRows() {
if (numberOfRowsBuilder_ == null) {
numberOfRows_ = null;
onChanged();
} else {
numberOfRows_ = null;
numberOfRowsBuilder_ = null;
}
return this;
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public io.dstore.values.IntegerValue.Builder getNumberOfRowsBuilder() {
onChanged();
return getNumberOfRowsFieldBuilder().getBuilder();
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
public io.dstore.values.IntegerValueOrBuilder getNumberOfRowsOrBuilder() {
if (numberOfRowsBuilder_ != null) {
return numberOfRowsBuilder_.getMessageOrBuilder();
} else {
return numberOfRows_ == null ?
io.dstore.values.IntegerValue.getDefaultInstance() : numberOfRows_;
}
}
/**
* <pre>
* Anzahl Datensätze in der Tabelle "TableName"
* </pre>
*
* <code>.dstore.values.IntegerValue number_of_rows = 10004;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder>
getNumberOfRowsFieldBuilder() {
if (numberOfRowsBuilder_ == null) {
numberOfRowsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.IntegerValue, io.dstore.values.IntegerValue.Builder, io.dstore.values.IntegerValueOrBuilder>(
getNumberOfRows(),
getParentForChildren(),
isClean());
numberOfRows_ = null;
}
return numberOfRowsBuilder_;
}
private io.dstore.values.DecimalValue tableSizeMb_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> tableSizeMbBuilder_;
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public boolean hasTableSizeMb() {
return tableSizeMbBuilder_ != null || tableSizeMb_ != null;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public io.dstore.values.DecimalValue getTableSizeMb() {
if (tableSizeMbBuilder_ == null) {
return tableSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : tableSizeMb_;
} else {
return tableSizeMbBuilder_.getMessage();
}
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public Builder setTableSizeMb(io.dstore.values.DecimalValue value) {
if (tableSizeMbBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
tableSizeMb_ = value;
onChanged();
} else {
tableSizeMbBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public Builder setTableSizeMb(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (tableSizeMbBuilder_ == null) {
tableSizeMb_ = builderForValue.build();
onChanged();
} else {
tableSizeMbBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public Builder mergeTableSizeMb(io.dstore.values.DecimalValue value) {
if (tableSizeMbBuilder_ == null) {
if (tableSizeMb_ != null) {
tableSizeMb_ =
io.dstore.values.DecimalValue.newBuilder(tableSizeMb_).mergeFrom(value).buildPartial();
} else {
tableSizeMb_ = value;
}
onChanged();
} else {
tableSizeMbBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public Builder clearTableSizeMb() {
if (tableSizeMbBuilder_ == null) {
tableSizeMb_ = null;
onChanged();
} else {
tableSizeMb_ = null;
tableSizeMbBuilder_ = null;
}
return this;
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public io.dstore.values.DecimalValue.Builder getTableSizeMbBuilder() {
onChanged();
return getTableSizeMbFieldBuilder().getBuilder();
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getTableSizeMbOrBuilder() {
if (tableSizeMbBuilder_ != null) {
return tableSizeMbBuilder_.getMessageOrBuilder();
} else {
return tableSizeMb_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : tableSizeMb_;
}
}
/**
* <pre>
* Gesamte Größe der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue table_size_mb = 10005;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getTableSizeMbFieldBuilder() {
if (tableSizeMbBuilder_ == null) {
tableSizeMbBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getTableSizeMb(),
getParentForChildren(),
isClean());
tableSizeMb_ = null;
}
return tableSizeMbBuilder_;
}
private io.dstore.values.DecimalValue dataSizeMb_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> dataSizeMbBuilder_;
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public boolean hasDataSizeMb() {
return dataSizeMbBuilder_ != null || dataSizeMb_ != null;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public io.dstore.values.DecimalValue getDataSizeMb() {
if (dataSizeMbBuilder_ == null) {
return dataSizeMb_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : dataSizeMb_;
} else {
return dataSizeMbBuilder_.getMessage();
}
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public Builder setDataSizeMb(io.dstore.values.DecimalValue value) {
if (dataSizeMbBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
dataSizeMb_ = value;
onChanged();
} else {
dataSizeMbBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public Builder setDataSizeMb(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (dataSizeMbBuilder_ == null) {
dataSizeMb_ = builderForValue.build();
onChanged();
} else {
dataSizeMbBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public Builder mergeDataSizeMb(io.dstore.values.DecimalValue value) {
if (dataSizeMbBuilder_ == null) {
if (dataSizeMb_ != null) {
dataSizeMb_ =
io.dstore.values.DecimalValue.newBuilder(dataSizeMb_).mergeFrom(value).buildPartial();
} else {
dataSizeMb_ = value;
}
onChanged();
} else {
dataSizeMbBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public Builder clearDataSizeMb() {
if (dataSizeMbBuilder_ == null) {
dataSizeMb_ = null;
onChanged();
} else {
dataSizeMb_ = null;
dataSizeMbBuilder_ = null;
}
return this;
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public io.dstore.values.DecimalValue.Builder getDataSizeMbBuilder() {
onChanged();
return getDataSizeMbFieldBuilder().getBuilder();
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getDataSizeMbOrBuilder() {
if (dataSizeMbBuilder_ != null) {
return dataSizeMbBuilder_.getMessageOrBuilder();
} else {
return dataSizeMb_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : dataSizeMb_;
}
}
/**
* <pre>
* Speicherverbrauch für die Daten der Tabelle "TableName" in MB
* </pre>
*
* <code>.dstore.values.DecimalValue data_size_mb = 10006;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getDataSizeMbFieldBuilder() {
if (dataSizeMbBuilder_ == null) {
dataSizeMbBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getDataSizeMb(),
getParentForChildren(),
isClean());
dataSizeMb_ = null;
}
return dataSizeMbBuilder_;
}
private io.dstore.values.DecimalValue mballocated_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> mballocatedBuilder_;
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public boolean hasMballocated() {
return mballocatedBuilder_ != null || mballocated_ != null;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public io.dstore.values.DecimalValue getMballocated() {
if (mballocatedBuilder_ == null) {
return mballocated_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mballocated_;
} else {
return mballocatedBuilder_.getMessage();
}
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public Builder setMballocated(io.dstore.values.DecimalValue value) {
if (mballocatedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
mballocated_ = value;
onChanged();
} else {
mballocatedBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public Builder setMballocated(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (mballocatedBuilder_ == null) {
mballocated_ = builderForValue.build();
onChanged();
} else {
mballocatedBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public Builder mergeMballocated(io.dstore.values.DecimalValue value) {
if (mballocatedBuilder_ == null) {
if (mballocated_ != null) {
mballocated_ =
io.dstore.values.DecimalValue.newBuilder(mballocated_).mergeFrom(value).buildPartial();
} else {
mballocated_ = value;
}
onChanged();
} else {
mballocatedBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public Builder clearMballocated() {
if (mballocatedBuilder_ == null) {
mballocated_ = null;
onChanged();
} else {
mballocated_ = null;
mballocatedBuilder_ = null;
}
return this;
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public io.dstore.values.DecimalValue.Builder getMballocatedBuilder() {
onChanged();
return getMballocatedFieldBuilder().getBuilder();
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMballocatedOrBuilder() {
if (mballocatedBuilder_ != null) {
return mballocatedBuilder_.getMessageOrBuilder();
} else {
return mballocated_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : mballocated_;
}
}
/**
* <pre>
* Wieviel MB für "SegmentName" alloziert sind, sprich die Größe des Segments
* </pre>
*
* <code>.dstore.values.DecimalValue mballocated = 20001;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getMballocatedFieldBuilder() {
if (mballocatedBuilder_ == null) {
mballocatedBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getMballocated(),
getParentForChildren(),
isClean());
mballocated_ = null;
}
return mballocatedBuilder_;
}
private io.dstore.values.StringValue segmentName_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder> segmentNameBuilder_;
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public boolean hasSegmentName() {
return segmentNameBuilder_ != null || segmentName_ != null;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public io.dstore.values.StringValue getSegmentName() {
if (segmentNameBuilder_ == null) {
return segmentName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : segmentName_;
} else {
return segmentNameBuilder_.getMessage();
}
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public Builder setSegmentName(io.dstore.values.StringValue value) {
if (segmentNameBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
segmentName_ = value;
onChanged();
} else {
segmentNameBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public Builder setSegmentName(
io.dstore.values.StringValue.Builder builderForValue) {
if (segmentNameBuilder_ == null) {
segmentName_ = builderForValue.build();
onChanged();
} else {
segmentNameBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public Builder mergeSegmentName(io.dstore.values.StringValue value) {
if (segmentNameBuilder_ == null) {
if (segmentName_ != null) {
segmentName_ =
io.dstore.values.StringValue.newBuilder(segmentName_).mergeFrom(value).buildPartial();
} else {
segmentName_ = value;
}
onChanged();
} else {
segmentNameBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public Builder clearSegmentName() {
if (segmentNameBuilder_ == null) {
segmentName_ = null;
onChanged();
} else {
segmentName_ = null;
segmentNameBuilder_ = null;
}
return this;
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public io.dstore.values.StringValue.Builder getSegmentNameBuilder() {
onChanged();
return getSegmentNameFieldBuilder().getBuilder();
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
public io.dstore.values.StringValueOrBuilder getSegmentNameOrBuilder() {
if (segmentNameBuilder_ != null) {
return segmentNameBuilder_.getMessageOrBuilder();
} else {
return segmentName_ == null ?
io.dstore.values.StringValue.getDefaultInstance() : segmentName_;
}
}
/**
* <pre>
* Name eines Segments in der Datenbank "DBName"
* </pre>
*
* <code>.dstore.values.StringValue segment_name = 20002;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>
getSegmentNameFieldBuilder() {
if (segmentNameBuilder_ == null) {
segmentNameBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>(
getSegmentName(),
getParentForChildren(),
isClean());
segmentName_ = null;
}
return segmentNameBuilder_;
}
private io.dstore.values.DecimalValue mbused_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> mbusedBuilder_;
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public boolean hasMbused() {
return mbusedBuilder_ != null || mbused_ != null;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public io.dstore.values.DecimalValue getMbused() {
if (mbusedBuilder_ == null) {
return mbused_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mbused_;
} else {
return mbusedBuilder_.getMessage();
}
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public Builder setMbused(io.dstore.values.DecimalValue value) {
if (mbusedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
mbused_ = value;
onChanged();
} else {
mbusedBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public Builder setMbused(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (mbusedBuilder_ == null) {
mbused_ = builderForValue.build();
onChanged();
} else {
mbusedBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public Builder mergeMbused(io.dstore.values.DecimalValue value) {
if (mbusedBuilder_ == null) {
if (mbused_ != null) {
mbused_ =
io.dstore.values.DecimalValue.newBuilder(mbused_).mergeFrom(value).buildPartial();
} else {
mbused_ = value;
}
onChanged();
} else {
mbusedBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public Builder clearMbused() {
if (mbusedBuilder_ == null) {
mbused_ = null;
onChanged();
} else {
mbused_ = null;
mbusedBuilder_ = null;
}
return this;
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public io.dstore.values.DecimalValue.Builder getMbusedBuilder() {
onChanged();
return getMbusedFieldBuilder().getBuilder();
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMbusedOrBuilder() {
if (mbusedBuilder_ != null) {
return mbusedBuilder_.getMessageOrBuilder();
} else {
return mbused_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : mbused_;
}
}
/**
* <pre>
* Wieviel MB "SegmentName" derzeit tatsächlich belegt.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies "MB_allocated" ABZÜGLICH für "rollbacks" reserviertem Speicher und Anzahl freier Pages im Log-Segment.
* </pre>
*
* <code>.dstore.values.DecimalValue mbused = 20003;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getMbusedFieldBuilder() {
if (mbusedBuilder_ == null) {
mbusedBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getMbused(),
getParentForChildren(),
isClean());
mbused_ = null;
}
return mbusedBuilder_;
}
private io.dstore.values.DecimalValue freeSpaceInPercent_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> freeSpaceInPercentBuilder_;
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public boolean hasFreeSpaceInPercent() {
return freeSpaceInPercentBuilder_ != null || freeSpaceInPercent_ != null;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public io.dstore.values.DecimalValue getFreeSpaceInPercent() {
if (freeSpaceInPercentBuilder_ == null) {
return freeSpaceInPercent_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : freeSpaceInPercent_;
} else {
return freeSpaceInPercentBuilder_.getMessage();
}
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public Builder setFreeSpaceInPercent(io.dstore.values.DecimalValue value) {
if (freeSpaceInPercentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
freeSpaceInPercent_ = value;
onChanged();
} else {
freeSpaceInPercentBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public Builder setFreeSpaceInPercent(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (freeSpaceInPercentBuilder_ == null) {
freeSpaceInPercent_ = builderForValue.build();
onChanged();
} else {
freeSpaceInPercentBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public Builder mergeFreeSpaceInPercent(io.dstore.values.DecimalValue value) {
if (freeSpaceInPercentBuilder_ == null) {
if (freeSpaceInPercent_ != null) {
freeSpaceInPercent_ =
io.dstore.values.DecimalValue.newBuilder(freeSpaceInPercent_).mergeFrom(value).buildPartial();
} else {
freeSpaceInPercent_ = value;
}
onChanged();
} else {
freeSpaceInPercentBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public Builder clearFreeSpaceInPercent() {
if (freeSpaceInPercentBuilder_ == null) {
freeSpaceInPercent_ = null;
onChanged();
} else {
freeSpaceInPercent_ = null;
freeSpaceInPercentBuilder_ = null;
}
return this;
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public io.dstore.values.DecimalValue.Builder getFreeSpaceInPercentBuilder() {
onChanged();
return getFreeSpaceInPercentFieldBuilder().getBuilder();
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getFreeSpaceInPercentOrBuilder() {
if (freeSpaceInPercentBuilder_ != null) {
return freeSpaceInPercentBuilder_.getMessageOrBuilder();
} else {
return freeSpaceInPercent_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : freeSpaceInPercent_;
}
}
/**
* <pre>
* Wieviel Prozent von "SegmentName" noch frei sind (also das Verhältnis von "MB_free" zu "MB_allocated" in Prozent)
* </pre>
*
* <code>.dstore.values.DecimalValue free_space_in_percent = 20004;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getFreeSpaceInPercentFieldBuilder() {
if (freeSpaceInPercentBuilder_ == null) {
freeSpaceInPercentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getFreeSpaceInPercent(),
getParentForChildren(),
isClean());
freeSpaceInPercent_ = null;
}
return freeSpaceInPercentBuilder_;
}
private io.dstore.values.StringValue dBName_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder> dBNameBuilder_;
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public boolean hasDBName() {
return dBNameBuilder_ != null || dBName_ != null;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public io.dstore.values.StringValue getDBName() {
if (dBNameBuilder_ == null) {
return dBName_ == null ? io.dstore.values.StringValue.getDefaultInstance() : dBName_;
} else {
return dBNameBuilder_.getMessage();
}
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public Builder setDBName(io.dstore.values.StringValue value) {
if (dBNameBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
dBName_ = value;
onChanged();
} else {
dBNameBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public Builder setDBName(
io.dstore.values.StringValue.Builder builderForValue) {
if (dBNameBuilder_ == null) {
dBName_ = builderForValue.build();
onChanged();
} else {
dBNameBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public Builder mergeDBName(io.dstore.values.StringValue value) {
if (dBNameBuilder_ == null) {
if (dBName_ != null) {
dBName_ =
io.dstore.values.StringValue.newBuilder(dBName_).mergeFrom(value).buildPartial();
} else {
dBName_ = value;
}
onChanged();
} else {
dBNameBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public Builder clearDBName() {
if (dBNameBuilder_ == null) {
dBName_ = null;
onChanged();
} else {
dBName_ = null;
dBNameBuilder_ = null;
}
return this;
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public io.dstore.values.StringValue.Builder getDBNameBuilder() {
onChanged();
return getDBNameFieldBuilder().getBuilder();
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
public io.dstore.values.StringValueOrBuilder getDBNameOrBuilder() {
if (dBNameBuilder_ != null) {
return dBNameBuilder_.getMessageOrBuilder();
} else {
return dBName_ == null ?
io.dstore.values.StringValue.getDefaultInstance() : dBName_;
}
}
/**
* <pre>
* Name der in "@GetStorageAllocInfoFor" angegebenen Datenbank
* </pre>
*
* <code>.dstore.values.StringValue d_b_name = 20005;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>
getDBNameFieldBuilder() {
if (dBNameBuilder_ == null) {
dBNameBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.StringValue, io.dstore.values.StringValue.Builder, io.dstore.values.StringValueOrBuilder>(
getDBName(),
getParentForChildren(),
isClean());
dBName_ = null;
}
return dBNameBuilder_;
}
private io.dstore.values.DecimalValue mbfree_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder> mbfreeBuilder_;
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public boolean hasMbfree() {
return mbfreeBuilder_ != null || mbfree_ != null;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public io.dstore.values.DecimalValue getMbfree() {
if (mbfreeBuilder_ == null) {
return mbfree_ == null ? io.dstore.values.DecimalValue.getDefaultInstance() : mbfree_;
} else {
return mbfreeBuilder_.getMessage();
}
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public Builder setMbfree(io.dstore.values.DecimalValue value) {
if (mbfreeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
mbfree_ = value;
onChanged();
} else {
mbfreeBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public Builder setMbfree(
io.dstore.values.DecimalValue.Builder builderForValue) {
if (mbfreeBuilder_ == null) {
mbfree_ = builderForValue.build();
onChanged();
} else {
mbfreeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public Builder mergeMbfree(io.dstore.values.DecimalValue value) {
if (mbfreeBuilder_ == null) {
if (mbfree_ != null) {
mbfree_ =
io.dstore.values.DecimalValue.newBuilder(mbfree_).mergeFrom(value).buildPartial();
} else {
mbfree_ = value;
}
onChanged();
} else {
mbfreeBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public Builder clearMbfree() {
if (mbfreeBuilder_ == null) {
mbfree_ = null;
onChanged();
} else {
mbfree_ = null;
mbfreeBuilder_ = null;
}
return this;
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public io.dstore.values.DecimalValue.Builder getMbfreeBuilder() {
onChanged();
return getMbfreeFieldBuilder().getBuilder();
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
public io.dstore.values.DecimalValueOrBuilder getMbfreeOrBuilder() {
if (mbfreeBuilder_ != null) {
return mbfreeBuilder_.getMessageOrBuilder();
} else {
return mbfree_ == null ?
io.dstore.values.DecimalValue.getDefaultInstance() : mbfree_;
}
}
/**
* <pre>
* Wieviel MB von "SegmentName" noch belegt werden können.Anmerkung : Im Falle des Log-Segments ("SegmentName = 'log only'") ist dies die Anzahl freier Pages im Log-Segment ABZÜGLICH für "rollbacks" reserviertem Speicher.
* </pre>
*
* <code>.dstore.values.DecimalValue mbfree = 20006;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>
getMbfreeFieldBuilder() {
if (mbfreeBuilder_ == null) {
mbfreeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
io.dstore.values.DecimalValue, io.dstore.values.DecimalValue.Builder, io.dstore.values.DecimalValueOrBuilder>(
getMbfree(),
getParentForChildren(),
isClean());
mbfree_ = null;
}
return mbfreeBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row)
}
// @@protoc_insertion_point(class_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row)
private static final io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row();
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Row>
PARSER = new com.google.protobuf.AbstractParser<Row>() {
public Row parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Row(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Row> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Row> getParserForType() {
return PARSER;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public static final int META_INFORMATION_FIELD_NUMBER = 2;
private java.util.List<io.dstore.engine.MetaInformation> metaInformation_;
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public java.util.List<io.dstore.engine.MetaInformation> getMetaInformationList() {
return metaInformation_;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public java.util.List<? extends io.dstore.engine.MetaInformationOrBuilder>
getMetaInformationOrBuilderList() {
return metaInformation_;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public int getMetaInformationCount() {
return metaInformation_.size();
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformation getMetaInformation(int index) {
return metaInformation_.get(index);
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformationOrBuilder getMetaInformationOrBuilder(
int index) {
return metaInformation_.get(index);
}
public static final int MESSAGE_FIELD_NUMBER = 3;
private java.util.List<io.dstore.engine.Message> message_;
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public java.util.List<io.dstore.engine.Message> getMessageList() {
return message_;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public java.util.List<? extends io.dstore.engine.MessageOrBuilder>
getMessageOrBuilderList() {
return message_;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public int getMessageCount() {
return message_.size();
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.Message getMessage(int index) {
return message_.get(index);
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.MessageOrBuilder getMessageOrBuilder(
int index) {
return message_.get(index);
}
public static final int ROW_FIELD_NUMBER = 4;
private java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row> row_;
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row> getRowList() {
return row_;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public java.util.List<? extends io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder>
getRowOrBuilderList() {
return row_;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public int getRowCount() {
return row_.size();
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getRow(int index) {
return row_.get(index);
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder getRowOrBuilder(
int index) {
return row_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < metaInformation_.size(); i++) {
output.writeMessage(2, metaInformation_.get(i));
}
for (int i = 0; i < message_.size(); i++) {
output.writeMessage(3, message_.get(i));
}
for (int i = 0; i < row_.size(); i++) {
output.writeMessage(4, row_.get(i));
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < metaInformation_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, metaInformation_.get(i));
}
for (int i = 0; i < message_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, message_.get(i));
}
for (int i = 0; i < row_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, row_.get(i));
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response)) {
return super.equals(obj);
}
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response other = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response) obj;
boolean result = true;
result = result && getMetaInformationList()
.equals(other.getMetaInformationList());
result = result && getMessageList()
.equals(other.getMessageList());
result = result && getRowList()
.equals(other.getRowList());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getMetaInformationCount() > 0) {
hash = (37 * hash) + META_INFORMATION_FIELD_NUMBER;
hash = (53 * hash) + getMetaInformationList().hashCode();
}
if (getMessageCount() > 0) {
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessageList().hashCode();
}
if (getRowCount() > 0) {
hash = (37 * hash) + ROW_FIELD_NUMBER;
hash = (53 * hash) + getRowList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code dstore.engine.mi_GetStorageAllocInfo_Ad.Response}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:dstore.engine.mi_GetStorageAllocInfo_Ad.Response)
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.ResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.class, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Builder.class);
}
// Construct using io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getMetaInformationFieldBuilder();
getMessageFieldBuilder();
getRowFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (metaInformationBuilder_ == null) {
metaInformation_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
metaInformationBuilder_.clear();
}
if (messageBuilder_ == null) {
message_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
} else {
messageBuilder_.clear();
}
if (rowBuilder_ == null) {
row_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
} else {
rowBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response getDefaultInstanceForType() {
return io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.getDefaultInstance();
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response build() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response buildPartial() {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response result = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response(this);
int from_bitField0_ = bitField0_;
if (metaInformationBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
metaInformation_ = java.util.Collections.unmodifiableList(metaInformation_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.metaInformation_ = metaInformation_;
} else {
result.metaInformation_ = metaInformationBuilder_.build();
}
if (messageBuilder_ == null) {
if (((bitField0_ & 0x00000002) == 0x00000002)) {
message_ = java.util.Collections.unmodifiableList(message_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.message_ = message_;
} else {
result.message_ = messageBuilder_.build();
}
if (rowBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
row_ = java.util.Collections.unmodifiableList(row_);
bitField0_ = (bitField0_ & ~0x00000004);
}
result.row_ = row_;
} else {
result.row_ = rowBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response) {
return mergeFrom((io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response other) {
if (other == io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.getDefaultInstance()) return this;
if (metaInformationBuilder_ == null) {
if (!other.metaInformation_.isEmpty()) {
if (metaInformation_.isEmpty()) {
metaInformation_ = other.metaInformation_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMetaInformationIsMutable();
metaInformation_.addAll(other.metaInformation_);
}
onChanged();
}
} else {
if (!other.metaInformation_.isEmpty()) {
if (metaInformationBuilder_.isEmpty()) {
metaInformationBuilder_.dispose();
metaInformationBuilder_ = null;
metaInformation_ = other.metaInformation_;
bitField0_ = (bitField0_ & ~0x00000001);
metaInformationBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getMetaInformationFieldBuilder() : null;
} else {
metaInformationBuilder_.addAllMessages(other.metaInformation_);
}
}
}
if (messageBuilder_ == null) {
if (!other.message_.isEmpty()) {
if (message_.isEmpty()) {
message_ = other.message_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureMessageIsMutable();
message_.addAll(other.message_);
}
onChanged();
}
} else {
if (!other.message_.isEmpty()) {
if (messageBuilder_.isEmpty()) {
messageBuilder_.dispose();
messageBuilder_ = null;
message_ = other.message_;
bitField0_ = (bitField0_ & ~0x00000002);
messageBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getMessageFieldBuilder() : null;
} else {
messageBuilder_.addAllMessages(other.message_);
}
}
}
if (rowBuilder_ == null) {
if (!other.row_.isEmpty()) {
if (row_.isEmpty()) {
row_ = other.row_;
bitField0_ = (bitField0_ & ~0x00000004);
} else {
ensureRowIsMutable();
row_.addAll(other.row_);
}
onChanged();
}
} else {
if (!other.row_.isEmpty()) {
if (rowBuilder_.isEmpty()) {
rowBuilder_.dispose();
rowBuilder_ = null;
row_ = other.row_;
bitField0_ = (bitField0_ & ~0x00000004);
rowBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getRowFieldBuilder() : null;
} else {
rowBuilder_.addAllMessages(other.row_);
}
}
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<io.dstore.engine.MetaInformation> metaInformation_ =
java.util.Collections.emptyList();
private void ensureMetaInformationIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
metaInformation_ = new java.util.ArrayList<io.dstore.engine.MetaInformation>(metaInformation_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.MetaInformation, io.dstore.engine.MetaInformation.Builder, io.dstore.engine.MetaInformationOrBuilder> metaInformationBuilder_;
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public java.util.List<io.dstore.engine.MetaInformation> getMetaInformationList() {
if (metaInformationBuilder_ == null) {
return java.util.Collections.unmodifiableList(metaInformation_);
} else {
return metaInformationBuilder_.getMessageList();
}
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public int getMetaInformationCount() {
if (metaInformationBuilder_ == null) {
return metaInformation_.size();
} else {
return metaInformationBuilder_.getCount();
}
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformation getMetaInformation(int index) {
if (metaInformationBuilder_ == null) {
return metaInformation_.get(index);
} else {
return metaInformationBuilder_.getMessage(index);
}
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder setMetaInformation(
int index, io.dstore.engine.MetaInformation value) {
if (metaInformationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetaInformationIsMutable();
metaInformation_.set(index, value);
onChanged();
} else {
metaInformationBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder setMetaInformation(
int index, io.dstore.engine.MetaInformation.Builder builderForValue) {
if (metaInformationBuilder_ == null) {
ensureMetaInformationIsMutable();
metaInformation_.set(index, builderForValue.build());
onChanged();
} else {
metaInformationBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder addMetaInformation(io.dstore.engine.MetaInformation value) {
if (metaInformationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetaInformationIsMutable();
metaInformation_.add(value);
onChanged();
} else {
metaInformationBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder addMetaInformation(
int index, io.dstore.engine.MetaInformation value) {
if (metaInformationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetaInformationIsMutable();
metaInformation_.add(index, value);
onChanged();
} else {
metaInformationBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder addMetaInformation(
io.dstore.engine.MetaInformation.Builder builderForValue) {
if (metaInformationBuilder_ == null) {
ensureMetaInformationIsMutable();
metaInformation_.add(builderForValue.build());
onChanged();
} else {
metaInformationBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder addMetaInformation(
int index, io.dstore.engine.MetaInformation.Builder builderForValue) {
if (metaInformationBuilder_ == null) {
ensureMetaInformationIsMutable();
metaInformation_.add(index, builderForValue.build());
onChanged();
} else {
metaInformationBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder addAllMetaInformation(
java.lang.Iterable<? extends io.dstore.engine.MetaInformation> values) {
if (metaInformationBuilder_ == null) {
ensureMetaInformationIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, metaInformation_);
onChanged();
} else {
metaInformationBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder clearMetaInformation() {
if (metaInformationBuilder_ == null) {
metaInformation_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
metaInformationBuilder_.clear();
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public Builder removeMetaInformation(int index) {
if (metaInformationBuilder_ == null) {
ensureMetaInformationIsMutable();
metaInformation_.remove(index);
onChanged();
} else {
metaInformationBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformation.Builder getMetaInformationBuilder(
int index) {
return getMetaInformationFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformationOrBuilder getMetaInformationOrBuilder(
int index) {
if (metaInformationBuilder_ == null) {
return metaInformation_.get(index); } else {
return metaInformationBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public java.util.List<? extends io.dstore.engine.MetaInformationOrBuilder>
getMetaInformationOrBuilderList() {
if (metaInformationBuilder_ != null) {
return metaInformationBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(metaInformation_);
}
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformation.Builder addMetaInformationBuilder() {
return getMetaInformationFieldBuilder().addBuilder(
io.dstore.engine.MetaInformation.getDefaultInstance());
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public io.dstore.engine.MetaInformation.Builder addMetaInformationBuilder(
int index) {
return getMetaInformationFieldBuilder().addBuilder(
index, io.dstore.engine.MetaInformation.getDefaultInstance());
}
/**
* <code>repeated .dstore.engine.MetaInformation meta_information = 2;</code>
*/
public java.util.List<io.dstore.engine.MetaInformation.Builder>
getMetaInformationBuilderList() {
return getMetaInformationFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.MetaInformation, io.dstore.engine.MetaInformation.Builder, io.dstore.engine.MetaInformationOrBuilder>
getMetaInformationFieldBuilder() {
if (metaInformationBuilder_ == null) {
metaInformationBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.MetaInformation, io.dstore.engine.MetaInformation.Builder, io.dstore.engine.MetaInformationOrBuilder>(
metaInformation_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
metaInformation_ = null;
}
return metaInformationBuilder_;
}
private java.util.List<io.dstore.engine.Message> message_ =
java.util.Collections.emptyList();
private void ensureMessageIsMutable() {
if (!((bitField0_ & 0x00000002) == 0x00000002)) {
message_ = new java.util.ArrayList<io.dstore.engine.Message>(message_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.Message, io.dstore.engine.Message.Builder, io.dstore.engine.MessageOrBuilder> messageBuilder_;
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public java.util.List<io.dstore.engine.Message> getMessageList() {
if (messageBuilder_ == null) {
return java.util.Collections.unmodifiableList(message_);
} else {
return messageBuilder_.getMessageList();
}
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public int getMessageCount() {
if (messageBuilder_ == null) {
return message_.size();
} else {
return messageBuilder_.getCount();
}
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.Message getMessage(int index) {
if (messageBuilder_ == null) {
return message_.get(index);
} else {
return messageBuilder_.getMessage(index);
}
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder setMessage(
int index, io.dstore.engine.Message value) {
if (messageBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMessageIsMutable();
message_.set(index, value);
onChanged();
} else {
messageBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder setMessage(
int index, io.dstore.engine.Message.Builder builderForValue) {
if (messageBuilder_ == null) {
ensureMessageIsMutable();
message_.set(index, builderForValue.build());
onChanged();
} else {
messageBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder addMessage(io.dstore.engine.Message value) {
if (messageBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMessageIsMutable();
message_.add(value);
onChanged();
} else {
messageBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder addMessage(
int index, io.dstore.engine.Message value) {
if (messageBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMessageIsMutable();
message_.add(index, value);
onChanged();
} else {
messageBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder addMessage(
io.dstore.engine.Message.Builder builderForValue) {
if (messageBuilder_ == null) {
ensureMessageIsMutable();
message_.add(builderForValue.build());
onChanged();
} else {
messageBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder addMessage(
int index, io.dstore.engine.Message.Builder builderForValue) {
if (messageBuilder_ == null) {
ensureMessageIsMutable();
message_.add(index, builderForValue.build());
onChanged();
} else {
messageBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder addAllMessage(
java.lang.Iterable<? extends io.dstore.engine.Message> values) {
if (messageBuilder_ == null) {
ensureMessageIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, message_);
onChanged();
} else {
messageBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder clearMessage() {
if (messageBuilder_ == null) {
message_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
messageBuilder_.clear();
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public Builder removeMessage(int index) {
if (messageBuilder_ == null) {
ensureMessageIsMutable();
message_.remove(index);
onChanged();
} else {
messageBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.Message.Builder getMessageBuilder(
int index) {
return getMessageFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.MessageOrBuilder getMessageOrBuilder(
int index) {
if (messageBuilder_ == null) {
return message_.get(index); } else {
return messageBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public java.util.List<? extends io.dstore.engine.MessageOrBuilder>
getMessageOrBuilderList() {
if (messageBuilder_ != null) {
return messageBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(message_);
}
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.Message.Builder addMessageBuilder() {
return getMessageFieldBuilder().addBuilder(
io.dstore.engine.Message.getDefaultInstance());
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public io.dstore.engine.Message.Builder addMessageBuilder(
int index) {
return getMessageFieldBuilder().addBuilder(
index, io.dstore.engine.Message.getDefaultInstance());
}
/**
* <code>repeated .dstore.engine.Message message = 3;</code>
*/
public java.util.List<io.dstore.engine.Message.Builder>
getMessageBuilderList() {
return getMessageFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.Message, io.dstore.engine.Message.Builder, io.dstore.engine.MessageOrBuilder>
getMessageFieldBuilder() {
if (messageBuilder_ == null) {
messageBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.Message, io.dstore.engine.Message.Builder, io.dstore.engine.MessageOrBuilder>(
message_,
((bitField0_ & 0x00000002) == 0x00000002),
getParentForChildren(),
isClean());
message_ = null;
}
return messageBuilder_;
}
private java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row> row_ =
java.util.Collections.emptyList();
private void ensureRowIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) {
row_ = new java.util.ArrayList<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row>(row_);
bitField0_ |= 0x00000004;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder> rowBuilder_;
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row> getRowList() {
if (rowBuilder_ == null) {
return java.util.Collections.unmodifiableList(row_);
} else {
return rowBuilder_.getMessageList();
}
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public int getRowCount() {
if (rowBuilder_ == null) {
return row_.size();
} else {
return rowBuilder_.getCount();
}
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row getRow(int index) {
if (rowBuilder_ == null) {
return row_.get(index);
} else {
return rowBuilder_.getMessage(index);
}
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder setRow(
int index, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row value) {
if (rowBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowIsMutable();
row_.set(index, value);
onChanged();
} else {
rowBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder setRow(
int index, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder builderForValue) {
if (rowBuilder_ == null) {
ensureRowIsMutable();
row_.set(index, builderForValue.build());
onChanged();
} else {
rowBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder addRow(io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row value) {
if (rowBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowIsMutable();
row_.add(value);
onChanged();
} else {
rowBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder addRow(
int index, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row value) {
if (rowBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRowIsMutable();
row_.add(index, value);
onChanged();
} else {
rowBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder addRow(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder builderForValue) {
if (rowBuilder_ == null) {
ensureRowIsMutable();
row_.add(builderForValue.build());
onChanged();
} else {
rowBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder addRow(
int index, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder builderForValue) {
if (rowBuilder_ == null) {
ensureRowIsMutable();
row_.add(index, builderForValue.build());
onChanged();
} else {
rowBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder addAllRow(
java.lang.Iterable<? extends io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row> values) {
if (rowBuilder_ == null) {
ensureRowIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, row_);
onChanged();
} else {
rowBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder clearRow() {
if (rowBuilder_ == null) {
row_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
} else {
rowBuilder_.clear();
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public Builder removeRow(int index) {
if (rowBuilder_ == null) {
ensureRowIsMutable();
row_.remove(index);
onChanged();
} else {
rowBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder getRowBuilder(
int index) {
return getRowFieldBuilder().getBuilder(index);
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder getRowOrBuilder(
int index) {
if (rowBuilder_ == null) {
return row_.get(index); } else {
return rowBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public java.util.List<? extends io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder>
getRowOrBuilderList() {
if (rowBuilder_ != null) {
return rowBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(row_);
}
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder addRowBuilder() {
return getRowFieldBuilder().addBuilder(
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.getDefaultInstance());
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder addRowBuilder(
int index) {
return getRowFieldBuilder().addBuilder(
index, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.getDefaultInstance());
}
/**
* <pre>
* no output parameters
* </pre>
*
* <code>repeated .dstore.engine.mi_GetStorageAllocInfo_Ad.Response.Row row = 4;</code>
*/
public java.util.List<io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder>
getRowBuilderList() {
return getRowFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder>
getRowFieldBuilder() {
if (rowBuilder_ == null) {
rowBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.Row.Builder, io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response.RowOrBuilder>(
row_,
((bitField0_ & 0x00000004) == 0x00000004),
getParentForChildren(),
isClean());
row_ = null;
}
return rowBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Response)
}
// @@protoc_insertion_point(class_scope:dstore.engine.mi_GetStorageAllocInfo_Ad.Response)
private static final io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response();
}
public static io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Response>
PARSER = new com.google.protobuf.AbstractParser<Response>() {
public Response parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Response(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Response> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Response> getParserForType() {
return PARSER;
}
public io.dstore.engine.procedures.MiGetStorageAllocInfoAd.Response getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n8dstore/engine/procedures/mi_GetStorage" +
"AllocInfo_Ad.proto\022\'dstore.engine.mi_Get" +
"StorageAllocInfo_Ad\032\023dstore/values.proto" +
"\032\032dstore/engine/engine.proto\"\333\001\n\nParamet" +
"ers\022<\n\027get_info_for_a_database\030\001 \001(\0132\033.d" +
"store.values.BooleanValue\022%\n\034get_info_fo" +
"r_a_database_null\030\351\007 \001(\010\022>\n\032get_storage_" +
"alloc_info_for\030\002 \001(\0132\032.dstore.values.Str" +
"ingValue\022(\n\037get_storage_alloc_info_for_n" +
"ull\030\352\007 \001(\010\"\274\006\n\010Response\0228\n\020meta_informat",
"ion\030\002 \003(\0132\036.dstore.engine.MetaInformatio" +
"n\022\'\n\007message\030\003 \003(\0132\026.dstore.engine.Messa" +
"ge\022B\n\003row\030\004 \003(\01325.dstore.engine.mi_GetSt" +
"orageAllocInfo_Ad.Response.Row\032\210\005\n\003Row\022\017" +
"\n\006row_id\030\220N \001(\005\022/\n\ntable_name\030\221N \001(\0132\032.d" +
"store.values.StringValue\0223\n\rindex_size_m" +
"b\030\222N \001(\0132\033.dstore.values.DecimalValue\0227\n" +
"\021number_of_indexes\030\223N \001(\0132\033.dstore.value" +
"s.IntegerValue\0224\n\016number_of_rows\030\224N \001(\0132" +
"\033.dstore.values.IntegerValue\0223\n\rtable_si",
"ze_mb\030\225N \001(\0132\033.dstore.values.DecimalValu" +
"e\0222\n\014data_size_mb\030\226N \001(\0132\033.dstore.values" +
".DecimalValue\0222\n\013mballocated\030\241\234\001 \001(\0132\033.d" +
"store.values.DecimalValue\0222\n\014segment_nam" +
"e\030\242\234\001 \001(\0132\032.dstore.values.StringValue\022-\n" +
"\006mbused\030\243\234\001 \001(\0132\033.dstore.values.DecimalV" +
"alue\022<\n\025free_space_in_percent\030\244\234\001 \001(\0132\033." +
"dstore.values.DecimalValue\022.\n\010d_b_name\030\245" +
"\234\001 \001(\0132\032.dstore.values.StringValue\022-\n\006mb" +
"free\030\246\234\001 \001(\0132\033.dstore.values.DecimalValu",
"eBZ\n\033io.dstore.engine.proceduresZ;gosdk." +
"dstore.de/engine/procedures/mi_GetStorag" +
"eAllocInfo_Adb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
io.dstore.values.ValuesOuterClass.getDescriptor(),
io.dstore.engine.EngineOuterClass.getDescriptor(),
}, assigner);
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Parameters_descriptor,
new java.lang.String[] { "GetInfoForADatabase", "GetInfoForADatabaseNull", "GetStorageAllocInfoFor", "GetStorageAllocInfoForNull", });
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor,
new java.lang.String[] { "MetaInformation", "Message", "Row", });
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor =
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_descriptor.getNestedTypes().get(0);
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_dstore_engine_mi_GetStorageAllocInfo_Ad_Response_Row_descriptor,
new java.lang.String[] { "RowId", "TableName", "IndexSizeMb", "NumberOfIndexes", "NumberOfRows", "TableSizeMb", "DataSizeMb", "Mballocated", "SegmentName", "Mbused", "FreeSpaceInPercent", "DBName", "Mbfree", });
io.dstore.values.ValuesOuterClass.getDescriptor();
io.dstore.engine.EngineOuterClass.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 37.69701 | 241 | 0.602735 |
3e759194e66bfe97cdae170a4cf373145f2425b1 | 6,802 | package com.covid.repository;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.covid.dto.PatientLocationDto;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.covid.dto.PatientDto;
@Repository
public class PatientDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public PatientLocationDto searchPatients(Long locationId, Long userId, String phoneNumber, int size, int from,
String firstName, String lastName, String covid19Status, String quarantineStatus, String isolationStatus,
String quarantineRequestStatus, String medicalRequestStatus, String suppliesRequestStatus,
String geofenceCompliant, String geofenceStatus, String heartbeatStatus, String healthAlert) {
List<Object> queryParam = new ArrayList<>();
String sql = "select distinct p.\"PatientId\", pu.\"FirstName\", pu.\"LastName\", ps.\"COVID19Status\", ps.\"QuarantineStatus\", ps.\"IsolationStatus\", "
+ "ps.\"HealthAlert\", ps.\"MedicalRequestStatus\", ps.\"QuarantineRequestStatus\", ps.\"SuppliesRequestStatus\", ps.\"GeofenceStatus\", ps.\"HeartbeatStatus\", ps.\"Latitude\", ps.\"Longitude\" "
+ "from \"Patient\" p "
+ "LEFT JOIN \"PatientProviderRelationship\" ppr on ppr.\"PatientId\"=p.\"PatientId\" "
+ "LEFT JOIN \"User\" pu on p.\"UserId\"=pu.\"UserId\" "
+ "LEFT JOIN \"PatientStatus\" ps on p.\"PatientId\"=ps.\"PatientId\" "
+ "LEFT JOIN \"PhoneNumber\" pn on p.\"UserId\"=pn.\"UserId\" where 1=1 ";
if (locationId != null && userId != null) {
sql += " and ppr.\"RelationshipFacilityLocation\"=? and ppr.\"ProviderId\"=? ";
queryParam.add(locationId);
queryParam.add(userId);
}
if (StringUtils.isNotBlank(phoneNumber)) {
sql += " and pn.\"PhoneNumber\"=?";
queryParam.add(phoneNumber);
}
if (StringUtils.isNotBlank(firstName)) {
sql += " and lower(pu.\"FirstName\")= lower(?)";
queryParam.add(firstName);
}
if (StringUtils.isNotBlank(lastName)) {
sql += " and lower(pu.\"LastName\")= lower(?)";
queryParam.add(lastName);
}
if (StringUtils.isNotBlank(covid19Status)) {
sql += " and ps.\"COVID19Status\"=?";
queryParam.add(covid19Status);
}
if (StringUtils.isNotBlank(quarantineStatus)) {
sql += " and ps.\"QuarantineStatus\"=?";
queryParam.add(quarantineStatus);
}
if (StringUtils.isNotBlank(isolationStatus)) {
sql += " and ps.\"IsolationStatus\"=?";
queryParam.add(isolationStatus);
}
if (StringUtils.isNotBlank(quarantineRequestStatus)) {
sql += " and ps.\"QuarantineRequestStatus\"=?";
queryParam.add(quarantineRequestStatus);
}
if (StringUtils.isNotBlank(medicalRequestStatus)) {
sql += " and ps.\"MedicalRequestStatus\"=?";
queryParam.add(medicalRequestStatus);
}
if (StringUtils.isNotBlank(suppliesRequestStatus)) {
sql += " and ps.\"SuppliesRequestStatus\"=?";
queryParam.add(suppliesRequestStatus);
}
if (StringUtils.isNotBlank(geofenceStatus)) {
sql += " and ps.\"GeofenceStatus\"=?";
queryParam.add(geofenceStatus);
}
if (StringUtils.isNotBlank(geofenceCompliant)) {
if (geofenceCompliant.equals("true")) {
sql += " and ps.\"GeofenceStatus\"='Inside'";
//queryParam.add(geofenceStatus);
}
if (geofenceCompliant.equals("false")) {
//sql += " and ps.\"GeofenceStatus\" IN ('Outside - near', 'Outside - far')";
sql += " and ps.\"GeofenceStatus\"='Outside - near'";
sql += " or ps.\"GeofenceStatus\"='Outside - far'";
//queryParam.add(geofenceStatus);
}
}
if (StringUtils.isNotBlank(heartbeatStatus)) {
sql += " and ps.\"HeartbeatStatus\"=?";
queryParam.add(heartbeatStatus);
}
if (StringUtils.isNotBlank(healthAlert)) {
sql += " and ps.\"HealthAlert\"=?";
queryParam.add(healthAlert);
}
sql += " order by p.\"PatientId\" ";
List<PatientDto> list = jdbcTemplate.query(sql, queryParam.toArray(), (rs, rowNum) -> {
PatientDto dto = new PatientDto();
dto.setPatientID(rs.getLong("PatientId"));
dto.setFirstName(rs.getString("FirstName"));
dto.setLastName(rs.getString("LastName"));
dto.setCovid19Status(rs.getString("COVID19Status"));
dto.setMedicalRequestStatus(rs.getString("MedicalRequestStatus"));
dto.setQuarantineStatus(rs.getString("QuarantineStatus"));
dto.setIsolationStatus(rs.getString("IsolationStatus"));
dto.setHealthAlert(rs.getString("HealthAlert"));
dto.setQuarantineRequestStatus(rs.getString("QuarantineRequestStatus"));
dto.setSuppliesRequestStatus(rs.getString("SuppliesRequestStatus"));
dto.setGeofenceStatus(rs.getString("GeofenceStatus"));
if (rs.getString("GeofenceStatus") != null && rs.getString("GeofenceStatus").equals("Outside - near")) {
dto.setGeofenceCompliant(false);
} else if (rs.getString("GeofenceStatus") != null
&& rs.getString("GeofenceStatus").equals("Outside - far")) {
dto.setGeofenceCompliant(false);
} else if (rs.getString("GeofenceStatus") == null) {
dto.setGeofenceCompliant(null);
} else {
dto.setGeofenceCompliant(true);
}
dto.setHeartbeatStatus(rs.getString("HeartbeatStatus"));
dto.setLatitude(rs.getDouble("Latitude"));
dto.setLongitude(rs.getDouble("Longitude"));
return dto;
});
int totalCount = list.size();
List<PatientDto> subList = Collections.emptyList();
if (totalCount > from) {
int to = Math.min(totalCount, from + size);
subList = list.subList(from, to);
}
PatientLocationDto patients = new PatientLocationDto();
patients.setTotal(list.size());
patients.setSize(size);
patients.setFrom(from);
patients.setPatients(subList);
return patients;
}
}
| 41.224242 | 212 | 0.597177 |
b086fd19a40f73397b0c96fc870d53dbba4d078e | 14,057 | /*
* Jigasi, the JItsi GAteway to SIP.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.jitsi.jigasi.stats;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jitsi.jigasi.*;
import org.jitsi.jigasi.util.*;
import org.jitsi.stats.media.*;
import org.jitsi.utils.concurrent.*;
import org.osgi.framework.*;
import java.util.*;
import java.util.concurrent.*;
/**
* The entry point for stats logging.
* Listens for start of calls to start reporting and end of calls
* to stop reporting.
*
* @author Damian Minkov
*/
public class StatsHandler
extends CallChangeAdapter
{
/**
* The logger.
*/
private final static Logger logger = Logger.getLogger(StatsHandler.class);
/**
* CallStats account property: appId
* The account id from callstats.io settings.
*/
private static final String CS_ACC_PROP_APP_ID = "CallStats.appId";
/**
* CallStats account property: keyId
* The key id from callstats.io settings.
*/
private static final String CS_ACC_PROP_KEY_ID = "CallStats.keyId";
/**
* CallStats account property: keyPath
* The path to the key file on the file system.
*/
private static final String CS_ACC_PROP_KEY_PATH = "CallStats.keyPath";
/**
* CallStats account property: conferenceIDPrefix
* The domain that this stats account is handling.
*/
private static final String CS_ACC_PROP_CONFERENCE_PREFIX
= "CallStats.conferenceIDPrefix";
/**
* CallStats account property: STATISTICS_INTERVAL
* The interval on which to publish statistics.
*/
private static final String CS_ACC_PROP_STATISTICS_INTERVAL
= "CallStats.STATISTICS_INTERVAL";
/**
* The default value for statistics interval.
*/
public static final int DEFAULT_STAT_INTERVAL = 5000;
/**
* CallStats account property: jigasiId
* The jigasi id to report to callstats.io.
*/
private static final String CS_ACC_PROP_JIGASI_ID
= "CallStats.jigasiId";
/**
* The default jigasi id to use if setting is missing.
*/
public static final String DEFAULT_JIGASI_ID = "jigasi";
/**
* The {@link RecurringRunnableExecutor} which periodically invokes
* generating and pushing statistics per call for every statistic from the
* MediaStream.
*/
private static final RecurringRunnableExecutor statisticsExecutor
= new RecurringRunnableExecutor(
StatsHandler.class.getSimpleName() + "-statisticsExecutor");
/**
* List of the processor per call. Kept in order to stop and
* deRegister them from the executor.
*/
private final Map<Call,CallPeriodicRunnable>
statisticsProcessors = new ConcurrentHashMap<>();
/**
* The remote endpoint jvb or sip.
*/
private final String remoteEndpointID;
/**
* The origin ID. From jigasi we always report jigasi-NUMBER as
* the origin ID.
*/
private final String originID;
/**
* Constructs StatsHandler.
* @param remoteEndpointID the remote endpoint.
*/
public StatsHandler(String originID, String remoteEndpointID)
{
this.remoteEndpointID = remoteEndpointID;
this.originID = originID;
}
@Override
public synchronized void callStateChanged(CallChangeEvent evt)
{
Call call = evt.getSourceCall();
if (call.getCallState() == CallState.CALL_IN_PROGRESS)
{
startConferencePeriodicRunnable(call);
}
else if(call.getCallState() == CallState.CALL_ENDED)
{
CallPeriodicRunnable cpr
= statisticsProcessors.remove(call);
if (cpr == null)
{
return;
}
cpr.stop();
statisticsExecutor.deRegisterRecurringRunnable(cpr);
}
}
/**
* Starts <tt>CallPeriodicRunnable</tt> for a call.
* @param call the call.
*/
private void startConferencePeriodicRunnable(Call call)
{
CallContext callContext = (CallContext) call.getData(CallContext.class);
BundleContext bundleContext = JigasiBundleActivator.osgiContext;
Object source = callContext.getSource();
if (source == null)
{
logger.warn(
"No source of callContext found, will not init stats");
return;
}
AccountID targetAccountID = null;
if (source instanceof ProtocolProviderService
&& ((ProtocolProviderService) source).getProtocolName()
.equals(ProtocolNames.JABBER))
{
targetAccountID = ((ProtocolProviderService) source).getAccountID();
}
else
{
// if call is not created by a jabber provider
// try to match conferenceIDPrefix of jabber accounts
// to callContext.getDomain
Collection<ServiceReference<ProtocolProviderService>> providers
= ServiceUtils.getServiceReferences(
bundleContext,
ProtocolProviderService.class);
for (ServiceReference<ProtocolProviderService> serviceRef
: providers)
{
ProtocolProviderService candidate
= bundleContext.getService(serviceRef);
if (ProtocolNames.JABBER.equals(candidate.getProtocolName()))
{
AccountID acc = candidate.getAccountID();
String confPrefix = acc.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
if (callContext.getDomain().equals(confPrefix))
{
targetAccountID = acc;
break;
}
}
}
}
if (targetAccountID == null)
{
// No account found with enabled stats
// we are maybe in the case where there are no xmpp control accounts
// this is when outgoing calls are disabled
// and we have only the xmpp client account, which may have the
// callstats settings
for (Call confCall : call.getConference().getCalls())
{
if (confCall.getProtocolProvider().getProtocolName()
.equals(ProtocolNames.JABBER))
{
AccountID acc = confCall.getProtocolProvider()
.getAccountID();
if (acc.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0) != 0)
{
// there are callstats settings then use it
targetAccountID = acc;
}
}
}
if (targetAccountID == null)
{
logger.debug("No account found with enabled stats");
return;
}
}
int appId
= targetAccountID.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0);
String keyId
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_ID);
String keyPath
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_PATH);
String jigasiId = targetAccountID.getAccountPropertyString(
CS_ACC_PROP_JIGASI_ID, DEFAULT_JIGASI_ID);
String roomName = callContext.getRoomName();
if (roomName.contains("@"))
{
roomName = Util.extractCallIdFromResource(roomName);
}
StatsService statsService
= StatsServiceFactory.getInstance()
.getStatsService(appId, bundleContext);
if (statsService == null)
{
// no service will create it, and listen for its registration
// in OSGi
StatsServiceListener serviceListener = new StatsServiceListener(
bundleContext, roomName, call, targetAccountID);
bundleContext.addServiceListener(serviceListener);
final String targetAccountIDDescription
= targetAccountID.toString();
StatsServiceFactory.getInstance()
.createStatsService(
bundleContext,
appId,
null,
keyId,
keyPath,
jigasiId,
true,
((reason, errorMessage) -> {
logger.error("Jitsi-stats library failed to initialize "
+ "with reason: " + reason
+ " and error message: " + errorMessage
+ " for account: " + targetAccountIDDescription);
bundleContext.removeServiceListener(serviceListener);
// callstats holds this lambda and listener instance
// and we clean instances to make sure we do not leave
// anything behind, as much as possible
serviceListener.clean();
}));
return;
}
createAndStartCallPeriodicRunnable(
statsService, roomName, call, targetAccountID);
}
/**
* Creates and starts <tt>CallPeriodicRunnable</tt>.
* @param statsService the <tt>StatsService</tt> to use for reporting.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the account.
*/
private void createAndStartCallPeriodicRunnable(
StatsService statsService,
String conferenceName,
Call call,
AccountID accountID)
{
String conferenceIDPrefix = accountID.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
int interval = accountID.getAccountPropertyInt(
CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL);
CallPeriodicRunnable cpr
= new CallPeriodicRunnable(
call,
interval,
statsService,
conferenceName,
conferenceIDPrefix,
DEFAULT_JIGASI_ID + "-" + originID,
this.remoteEndpointID);
cpr.start();
// register for periodic execution.
statisticsProcessors.put(call, cpr);
statisticsExecutor.registerRecurringRunnable(cpr);
}
/**
* Disposes this stats handler and any left processors are cleared.
*/
public void dispose()
{
statisticsProcessors.values().stream()
.forEach(cpr ->
{
cpr.stop();
statisticsExecutor.deRegisterRecurringRunnable(cpr);
});
}
/**
* Waits for <tt>StatsService</tt> to registered to OSGi.
*/
private class StatsServiceListener
implements ServiceListener
{
/**
* The context.
*/
private BundleContext context;
/**
* The conference name.
*/
private String conferenceName;
/**
* The call.
*/
private Call call;
/**
* The accountID.
*/
private AccountID accountID;
/**
* Constructs <tt>StatsServiceListener</tt>.
* @param context the OSGi context.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the accountID.
*/
StatsServiceListener(
BundleContext context,
String conferenceName,
Call call,
AccountID accountID)
{
this.context = context;
this.conferenceName = conferenceName;
this.call = call;
this.accountID = accountID;
}
/**
* Cleans instances the listener holds.
*/
private void clean()
{
this.context = null;
this.conferenceName = null;
this.call = null;
this.accountID = null;
}
@Override
public void serviceChanged(ServiceEvent ev)
{
if (this.context == null
|| this.conferenceName == null
|| this.call == null
|| this.accountID == null)
{
logger.warn(
"Received serviceChanged after listener was maybe cleaned");
return;
}
Object service;
try
{
service = context.getService(ev.getServiceReference());
}
catch (IllegalArgumentException
| IllegalStateException
| SecurityException ex)
{
service = null;
}
if (service == null || !(service instanceof StatsService))
return;
switch (ev.getType())
{
case ServiceEvent.REGISTERED:
context.removeServiceListener(this);
createAndStartCallPeriodicRunnable(
(StatsService) service,
this.conferenceName,
call,
accountID);
break;
}
}
}
}
| 31.30735 | 80 | 0.569823 |
686cf0b90b1fe698f6be5eef76310978874700fc | 275 | package com.algaworks.algafood.api.model.mixin;
import java.util.List;
import com.algaworks.algafood.domain.model.Restaurant;
import com.fasterxml.jackson.annotation.JsonIgnore;
public abstract class KitchenMixin {
@JsonIgnore
private List<Restaurant> restaurants;
}
| 19.642857 | 54 | 0.810909 |
90fca7afdb48fdc30a259f0ce68675dda64e8164 | 6,251 | package cat.udl.cig.structures.ecc;
import cat.udl.cig.structures.ExtensionField;
import cat.udl.cig.structures.ExtensionFieldElement;
import cat.udl.cig.structures.PrimeField;
import cat.udl.cig.structures.RingElement;
import cat.udl.cig.utils.Polynomial;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class LittleExtensionFieldECTest {
private BigInteger p;
private PrimeField primeField;
private ExtensionField field;
private EllipticCurve curve;
private EllipticCurve ec;
private ExtensionFieldElement A;
private ExtensionFieldElement B;
@BeforeEach
void setUp() {
p = BigInteger.valueOf(3);
primeField = new PrimeField(p);
field = ExtensionField.ExtensionFieldP2(p);
A = field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.addTerm(0, primeField.getMultiplicativeIdentity())
.build()).build().orElseThrow();
B = field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow();
ec = new EllipticCurve(field, A, B);
}
@Test
void testAllLiftX() {
HashMap<ExtensionFieldElement, Set<ExtensionFieldElement>> points = new HashMap<>();
points.put(field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder().addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow()).build()).build().orElseThrow(),
new HashSet<>(List.of(
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder().addTerm(0, primeField.buildElement().setValue(0).build().orElseThrow()).build()).build().orElseThrow()
)));
points.put(field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder().addTerm(1, primeField.getMultiplicativeIdentity()).build()).build().orElseThrow(),
new HashSet<>(List.of(
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.getMultiplicativeIdentity())
.addTerm(0, primeField.getMultiplicativeIdentity())
.build())
.build().orElseThrow(),
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow()).build()).build().orElseThrow()
)));
points.put(field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.getMultiplicativeIdentity())
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow(),
new HashSet<>(List.of(
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(0, primeField.getMultiplicativeIdentity())
.build()).build().orElseThrow(),
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow()
)));
points.put(field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow(),
new HashSet<>(List.of(
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(1).build().orElseThrow())
.build()).build().orElseThrow(),
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow()
)));
points.put(field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder().addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow()).build()).build().orElseThrow(),
new HashSet<>(List.of(
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.getMultiplicativeIdentity())
.addTerm(0, primeField.buildElement().setValue(2).build().orElseThrow())
.build()).build().orElseThrow(),
field.buildElement().setPolynomial(new Polynomial.PolynomialBuilder()
.addTerm(1, primeField.buildElement().setValue(2).build().orElseThrow())
.addTerm(0, primeField.getMultiplicativeIdentity())
.build()).build().orElseThrow()
)));
points.forEach((a, b) -> {
System.out.println(a);
ArrayList<? extends EllipticCurvePoint> actualPoints = ec.liftX(a);
for (EllipticCurvePoint actualPoint : actualPoints) {
RingElement y = actualPoint.getY();
assertTrue(y instanceof ExtensionFieldElement);
assertTrue(b.contains((ExtensionFieldElement) actualPoint.getY()));
}
});
}
}
| 57.348624 | 196 | 0.590306 |
b8c1565b506d3ec1c0cfe4b14a58baccbd180d00 | 1,849 | package com.watcher;
import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 刷新bat执行时的控制台输出流.
* Created by Zhao Jinyan on 2017-1-1.
*/
class ProcessWatch extends ThreadAdapter {
private static String NAME = "Process Watch";
private Process process = null;
private boolean over;
private Lock lock;
private Condition condition;
ProcessWatch(){
super(NAME);
over = false;
lock = new ReentrantLock();
condition = lock.newCondition();
}
@Override
protected void execute() throws InterruptedException{
lock.lockInterruptibly();
try{
if(process == null)
condition.await();
Scanner scanner = new Scanner(process.getInputStream());
while(true){
if(over)
break;
String before = null;
while(scanner.hasNext()){
String temp = scanner.nextLine();
if(before == null || !temp.equals(before)){
for(int i = 0; i < temp.length() * 2; i++)
System.out.print('\b');
System.out.print(temp.trim());
before = temp;
}
}
}
} finally {
lock.unlock();
}
}
void setOver(boolean over) {
this.over = over;
this.process = null;
}
void setProcess(Process process) throws InterruptedException {
lock.lockInterruptibly();
try {
this.process = process;
this.over = false;
condition.signal();
} finally {
lock.unlock();
}
}
}
| 25.328767 | 68 | 0.517036 |
8108ea71343d039f73c8631ba3e1ea5c622ff18a | 570 | package io.github.cd871127.hodgepodge.mybatis.multidatasource;
public class MultiDataSourceManager {
private static ThreadLocal<String> currentDataSource = new ThreadLocal<>();
public static void setCurrentDataSource(String dataSourceName) {
currentDataSource.set(dataSourceName);
}
public static String getCurrentDataSource() {
return currentDataSource.get();
}
public static String clear() {
String dataSourceName = getCurrentDataSource();
currentDataSource.remove();
return dataSourceName;
}
}
| 27.142857 | 79 | 0.717544 |
c9d577befd893078cca357db38a571be8347b996 | 413 | /*
* Copyright (C) 2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.rfid.api.sensor;
public class SensorSoftwareVersions {
public String app_version;
public String module_version;
public String platform_id;
public String platform_support_version;
public String pkg_manifest_version;
public String uboot_version;
public String linux_version;
}
| 21.736842 | 43 | 0.755448 |
673a990a9d39a3e6c87db45362cd388be0b50c3e | 5,301 | package pl.sternik.jk.weekend.web.controlers.th;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
//import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.sternik.jk.weekend.entities.Ksiazka;
import pl.sternik.jk.weekend.entities.Stan;
import pl.sternik.jk.weekend.repositories.KsiazkaUtils;
import pl.sternik.jk.weekend.services.KlaserService;
import pl.sternik.jk.weekend.services.NotificationService;
import pl.sternik.jk.weekend.services.NotificationService.NotificationMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class KsiazkaController {
@Autowired
private Logger logger;
@Autowired
// @Qualifier("spring-data")
@Qualifier("lista")
// @Qualifier("lista")
private KlaserService klaserService;
@Autowired
private NotificationService notifyService;
@ModelAttribute("statusyAll")
public List<Stan> populateStatusy() {
return Arrays.asList(Stan.ALL);
}
@ModelAttribute("MyMessages")
public List<NotificationMessage> populateMessages() {
logger.info("Messagesy dej");
return notifyService.getNotificationMessages();
}
@GetMapping(value = "/ksiazki/{id}")
public String view(@PathVariable("id") Long id, final ModelMap model) {
Optional<Ksiazka> result;
result = klaserService.findById(id);
if (result.isPresent()) {
Ksiazka ksiazka = result.get();
model.addAttribute("ksiazka", ksiazka);
return "th/ksiazka";
} else {
notifyService.addErrorMessage("Cannot find ksiazka #" + id);
model.clear();
return "redirect:/ksiazki";
}
}
@RequestMapping(value = "/ksiazki/{id}/json", produces = "application/json", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Ksiazka> viewAsJson(@PathVariable("id") Long id, final ModelMap model) {
Optional<Ksiazka> result;
result = klaserService.findById(id);
if (result.isPresent()) {
Ksiazka ksiazka = result.get();
return new ResponseEntity<Ksiazka>(ksiazka, HttpStatus.OK);
} else {
notifyService.addErrorMessage("Cannot find ksiazka #" + id);
model.clear();
return new ResponseEntity<Ksiazka>(HttpStatus.NOT_FOUND);
}
}
@RequestMapping(value = "/ksiazki", params = { "save" }, method = RequestMethod.POST)
public String saveKsiazka(Ksiazka ksiazka, BindingResult bindingResult, ModelMap model) {
// @Valid
if (bindingResult.hasErrors()) {
notifyService.addErrorMessage("Wypełnij pola poprawnie");
model.addAttribute("MyMessages", notifyService.getNotificationMessages());
return "th/ksiazka";
}
if (ksiazka.getStatus() == Stan.NOWA) {
ksiazka.setStatus(Stan.UZYWANA);
}
Optional<Ksiazka> result = klaserService.edit(ksiazka);
if (result.isPresent())
notifyService.addInfoMessage("Zapis udany");
else
notifyService.addErrorMessage("Zapis NIE udany");
model.clear();
return "redirect:/ksiazki";
}
@RequestMapping(value = "/ksiazki", params = { "create" }, method = RequestMethod.POST)
public String createKsiazka(Ksiazka ksiazka, BindingResult bindingResult, ModelMap model) {
if (bindingResult.hasErrors()) {
logger.info("Create książka errors");
notifyService.addErrorMessage("Wypełnij pola poprawnie");
model.addAttribute("MyMessages", notifyService.getNotificationMessages());
return "th/ksiazka";
}
klaserService.create(ksiazka);
model.clear();
notifyService.addInfoMessage("Zapis książki udany");
return "redirect:/ksiazki";
}
@RequestMapping(value = "/ksiazki", params = { "remove" }, method = RequestMethod.POST)
public String removeRow(final Ksiazka ksiazka, final BindingResult bindingResult, final HttpServletRequest req) {
final Integer rowId = Integer.valueOf(req.getParameter("remove"));
Optional<Boolean> result = klaserService.deleteById(rowId.longValue());
return "redirect:/ksiazki";
}
@RequestMapping(value = "/ksiazki/create", method = RequestMethod.GET)
public String showMainPages(final Ksiazka ksiazka) {
// Ustawiamy date nowej ksiazki, na dole strony do dodania
ksiazka.setDataWydania(Calendar.getInstance().getTime());
return "th/ksiazka";
}
} | 38.977941 | 117 | 0.688361 |
8131cd231f3863fae1142bf6ceefd3b86ac0a7be | 2,250 | package br.unicamp.ic.lsd.mercurius.datatype;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public interface Promotion extends Serializable {
/**
* Returns the {@link Promotion} id.
*
* @return
*/
Integer getId();
/**
* Returns the date that the promotion was created.
*
* @return
*/
Date getDateAdded();
/**
* Sets the date that the promotion was created.
*
* @param date
*/
void setDateAdded(Date date);
/**
* Returns the date that the promotion will start to be available.
*
* @return
*/
Date getStartDate();
/**
* Sets the date that the promotion will start to be available.
*
* @param date
*/
void setStartDate(Date date);
/**
* Returns the that the promotion will end.
*
* @return
*/
Date getEndDate();
/**
* Sets the that the promotion will end.
*
* @param date
*/
void setEndDate(Date date);
/**
* Returns the date that the promotion was last modified.
*
* @return
*/
Date getDateModified();
/**
* Sets the date that the promotion was last modified.
*
* @param date
*/
void setDateModified(Date date);
/**
* Returns the promotion's name.
*
* @return
*/
String getName();
/**
* Sets the promotion's name.
*
* @param name
*/
void setName(String name);
/**
* Returns the promotion's description.
*
* @return
*/
String getDescription();
/**
* Sets the promotion's description.
*
* @param description
*/
void setDescription(String description);
/**
* Returns <code>true</code> if this promotion can be given with other
* promotions.
*
* @return
*/
boolean isCumulative();
/**
* Sets if this promotion can be given with other promotions.
*
* @param cumulative
*/
void setCumulative(boolean cumulative);
/**
* Returns <code>true</code> if this promotion is percent.
*/
boolean isPercent();
/**
* Sets if this promotion is percent.
*
* @param cumulative
*/
void setPercent(boolean percent);
/**
* Returns the discount given by this promotion.
*
* @return
*/
BigDecimal getDiscountValue();
/**
* Sets the discount given by this promotion.
*/
void setDiscountValue(BigDecimal discountValue);
}
| 16.071429 | 71 | 0.636889 |
83c1a870f80cc3284d419e1992ee399cb79932b5 | 23,417 | package org.apache.servicemix.examples.cxf.send;
import java.util.ArrayList;
import java.util.List;
import org.apache.servicemix.examples.cxf.info.GatewayInfo;
import org.apache.servicemix.examples.cxf.info.ServiceInfo;
import org.apache.servicemix.examples.cxf.model.Bundler;
import org.apache.servicemix.examples.cxf.model.Gateway;
import org.apache.servicemix.examples.cxf.model.Service;
import org.apache.servicemix.examples.cxf.service.ServiceService;
import org.apache.servicemix.examples.cxf.util.ConstantsUtil;
/**
* Class responsible for verifying changes to the service information at the
* gateway and requesting submission of changes.
*
* @author Nilson Rodrigues Sousa
*/
public class ControlSendServiceInformation {
/* Local list of all gateway services */
private static List<Service> listServices;
/* Responsible for sending the information to the server */
private ServiceService serviceService;
/* Responsible for capturing gateway service information */
private ServiceInfo serviceInfo = new ServiceInfo();
/**
* Method to create instances of serviceService and listService.
*
* @author Nilson Rodrigues Sousa
*/
public ControlSendServiceInformation() {
serviceService = new ServiceService();
listServices = new ArrayList<Service>();
}
/**
* Method used by blueprint to instantiate serviceInfo.
*
* @author Nilson Rodrigues Sousa
*/
public void setServiceInfo(ServiceInfo serviceInfo) {
this.serviceInfo = serviceInfo;
}
/**
* A method that compares service information and requests the submission of
* the modified information to the server.
*
* @author Nilson Rodrigues Sousa
*/
public void compareInfoService() {
/*
* conditional that verifies that the gateway has already been properly
* registered on the server
*/
if (ControlSendGatewayInformation.storaged) {
/* Conditional to avoid entering the loop in the first iteration */
if (ConstantsUtil.constantControlSendInfomation) {
System.out.println("Entred in compareInfoService.<<<<<<<<<<<<<<<<<");
/*
* list to be worked from the system to be used for comparisons
*/
List<Service> listCapt = new ArrayList<Service>();
/* completion of the list for comparisons */
for (Service tr : serviceInfo.getListService()) {
Service s = new Service();
s.setId(tr.getId()); //--------------add id
s.setNameService(tr.getNameService());
s.setBundlerProvide(tr.getBundlerProvide());
s.setListUsesBundles(tr.getListUsesBundles());
listCapt.add(s);
}
/*
* conditional for evaluation of first iteration or restart of
* listing
*/
if (listServices.isEmpty() || listServices == null) {
/* update local list */
for (Service tr : listCapt) {
Service s = new Service();
s.setId(tr.getId()); //--------------add id
s.setNameService(tr.getNameService());
s.setBundlerProvide(tr.getBundlerProvide());
s.getListUsesBundles().addAll(tr.getListUsesBundles());
listServices.add(s);
}
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
gatewaySend.getListService().addAll(listServices);
/* sending information for the first time */
serviceService.sendServiceConnected(gatewaySend);
} else {
/*
* List to be worked from the system to be used for
* comparisons
*/
List<Service> listServicesIntance = new ArrayList<Service>();
/* Completion of the list for comparisons */
for (Service tr : listCapt) {
Service s = new Service();
s.setId(tr.getId()); //--------------add id
s.setNameService(tr.getNameService());
s.setBundlerProvide(tr.getBundlerProvide());
s.getListUsesBundles().addAll(tr.getListUsesBundles());
listServicesIntance.add(s);
}
/*
* --------------------COMPARISON OF
* SERVICES-------------------
*/
List<Service> listServicesDisconnected = this.compareToServices(listServices, listServicesIntance);
List<Service> listServicesConnected = this.compareToServices(listServicesIntance, listServices);
/*
* ----COMPARE INFORMATION FROM BUNDLES USERS OF THE
* SERVICE----
*/
List<Service> listServicesInformationConnectedBundlerUse = new ArrayList<Service>();
List<Service> listServicesInformationDisconnectedBundlerUse = new ArrayList<Service>();
listServicesInformationConnectedBundlerUse = this
.compareToServiceInformationBundlerConnected(listServicesIntance, listServices);
listServicesInformationDisconnectedBundlerUse = this
.compareToServiceInformationBundlerDisconnected(listServices, listServicesIntance);
/*
* ---CONDITIONAL OF EVALUATION OF THE INFORMATION TO BE
* SENT---
*/
/* Evaluates the existence of disconnected services */
if (listServicesDisconnected != null && !(listServicesDisconnected.isEmpty())) {
System.out.println(
"\n###########################Existe elementos em listServicesDisconnected.\n");
this.infoServiceDisconnected(listServicesDisconnected);
}
/* Evaluates the existence of connected services */
if (listServicesConnected != null && !(listServicesConnected.isEmpty())) {
System.out.println("\n###########################Existe elementos em listServicesConnected.\n");
this.infoServiceConnected(listServicesConnected);
}
/* Evaluates the existence of new service users bundles */
if (listServicesInformationConnectedBundlerUse != null
&& !(listServicesInformationConnectedBundlerUse.isEmpty())) {
System.out.println(
"###########################Existe elementos em infoServiceAlteredConnectedBundlerUse.");
this.infoServiceAlteredConnectedBundlerUse(listServicesInformationConnectedBundlerUse);
}
/* Evaluates the existence of disconnected users bundles */
if (listServicesInformationDisconnectedBundlerUse != null
&& !(listServicesInformationDisconnectedBundlerUse.isEmpty())) {
System.out.println(
"###########################Existe elementos em infoServiceAlteredDisconnectedBundlerUse.");
this.infoServiceAlteredDisconnectedBundlerUse(listServicesInformationDisconnectedBundlerUse);
}
}
} else {
ConstantsUtil.constantControlSendInfomation = true;
}
}
}
// ------------------------------------------------------------------------------------------------------------------
/**
* Method that receives a list of disconnected services, removes these
* elements from the local list, and sends the list of disconnected services
* to the server to update the database.
*
* @author Nilson Rodrigues Sousa
* @param serviceDisconnected
* List<Service> - list disconnected services
*/
public void infoServiceDisconnected(List<Service> serviceDisconnected) {
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* removing bundles from the local information list */
for (Service serviceDisc : serviceDisconnected) {
for (Service service : listServices) {
if (serviceDisc.getId() == service.getId() && serviceDisc.getNameService().equals(service.getNameService())
&& serviceDisc.getBundlerProvide().equals(service.getBundlerProvide())) { //--------------add id
listServices.remove(service);
break;
}
}
}
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
for (Service sv : serviceDisconnected) {
sv.getListUsesBundles().clear();
}
gatewaySend.getListService().addAll(serviceDisconnected);
/* sending information */
serviceService.sendServiceDisconnected(gatewaySend);
}
/**
* Method that receives a list of connected services, adds these elements to
* the local list, and sends the list of connected services to the server to
* update the database.
*
* @author Nilson Rodrigues Sousa
* @param serviceConnected
* List<Service>
*/
public void infoServiceConnected(List<Service> serviceConnected) {
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* update information locale */
listServices.addAll(serviceConnected);
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
gatewaySend.getListService().addAll(serviceConnected);
/* sending information */
serviceService.sendServiceConnected(gatewaySend);
}
/**
* A method that receives a list of services that have new bundles, adds
* those bundles to the appropriate services in the local list, and sends
* the list of services with new bundles to the server to update the
* database.
*
* @author Nilson Rodrigues Sousa
* @param listServiceBundlesConnected
* List<Service>
*/
public void infoServiceAlteredConnectedBundlerUse(List<Service> listServiceBundlesConnected) {
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* update information locale */
for (Service serviceAlter : listServiceBundlesConnected) {
for (Service service : listServices) {
if (serviceAlter.getId() == service.getId() && serviceAlter.getNameService().equals(service.getNameService())
&& serviceAlter.getBundlerProvide().equals(service.getBundlerProvide())) { //--------------add id
// --service.setNameService(serviceAlter.getNameService());
Bundler newBundler = new Bundler();
// --newBundler.setName(serviceAlter.getBundlerProvide().getName());
// --newBundler.setVersion(serviceAlter.getBundlerProvide().getVersion());
// --newBundler.setLocation(serviceAlter.getBundlerProvide().getLocation());
// --newBundler.setState(serviceAlter.getBundlerProvide().getState());
// --service.setBundlerProvide(newBundler);
List<Bundler> listBundlerTemp = new ArrayList<Bundler>();
for (Bundler bg : serviceAlter.getListUsesBundles()) {
newBundler = new Bundler();
newBundler.setName(bg.getName());
newBundler.setVersion(bg.getVersion());
newBundler.setLocation(bg.getLocation());
newBundler.setStatus(bg.getStatus());
listBundlerTemp.add(newBundler);
service.getListUsesBundles().add(newBundler);
}
/* update */
//service.getListUsesBundles().addAll(listBundlerTemp);
//trocar essa linha e armazenar dentro do for
break;
}
}
}
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
gatewaySend.getListService().addAll(listServiceBundlesConnected);
/* sending information */
serviceService.sendServiceAlteredConnectedBundlerUse(gatewaySend);
}
/**
* Method that receives a list of services that have bundles removed,
* removes these bundles from the appropriate services in the local list,
* and sends the list of services with removed bundles to the server to
* update the database.
*
* @author Nilson Rodrigues Sousa
* @param listServiceBundlesDisconnected
* List<Service>
*/
public void infoServiceAlteredDisconnectedBundlerUse(List<Service> listServiceBundlesDisconnected) {
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* update information locale */
for (Service serviceAlter : listServiceBundlesDisconnected) {
for (Service service : listServices) {
if (serviceAlter.getId() == service.getId() && serviceAlter.getNameService().equals(service.getNameService())
&& serviceAlter.getBundlerProvide().equals(service.getBundlerProvide())) { //--------------add id
List<Bundler> listBundlerAux1 = new ArrayList<Bundler>();
listBundlerAux1.addAll(serviceAlter.getListUsesBundles());
List<Bundler> listBundlerAux2 = new ArrayList<Bundler>();
listBundlerAux2.addAll(service.getListUsesBundles());
for (Bundler bundlerDisconnected : listBundlerAux1) {
for (Bundler bundlerToRemove : listBundlerAux2) {
if (bundlerDisconnected.getName().equals(bundlerToRemove.getName())
&& bundlerDisconnected.getVersion().equals(bundlerToRemove.getVersion())) {
service.getListUsesBundles().remove(bundlerToRemove);
break;
}
}
}
}
}
}
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
gatewaySend.getListService().addAll(listServiceBundlesDisconnected);
/* sending information */
serviceService.sendServiceAlteredDisconnectedBundlerUse(gatewaySend);
}
/**
* A method that receives a list of services that have bundles changed,
* updates the bundle information in the appropriate services in the local
* list, and sends the list of services with edited bundles to the server to
* update the database.
*
* @author Nilson Rodrigues Sousa
* @param listServiceBundlesAltered
* List<Service>
*/
/* Not used */
public void infoServiceAlteredInformationAlteredBundlerUse(List<Service> listServiceBundlesAltered) {
GatewayInfo gatewayInfo = new GatewayInfo();
Gateway gatewaySend = new Gateway();
/* update information locale */
for (Service serviceAlter : listServiceBundlesAltered) {
for (Service service : listServices) {
if (serviceAlter.getId() == service.getId() && serviceAlter.getNameService().equals(service.getNameService())
&& serviceAlter.getBundlerProvide().equals(service.getBundlerProvide())) { //--------------add id
for (Bundler bundlerModified : serviceAlter.getListUsesBundles()) {
for (Bundler bundlerToUpdate : service.getListUsesBundles()) {
if (bundlerModified.getName().equals(bundlerToUpdate.getName())
&& bundlerModified.getVersion().equals(bundlerToUpdate.getVersion())) {
bundlerToUpdate.setLocation(bundlerModified.getLocation());
bundlerToUpdate.setStatus(bundlerModified.getStatus());
break;
}
}
}
}
}
}
/* mounting information to be sent */
gatewaySend.setMac(gatewayInfo.getMac());
gatewaySend.setLastUpdate(gatewayInfo.getLastUpdate());
gatewaySend.getListService().addAll(listServiceBundlesAltered);
/* sending information */
serviceService.sendServiceAlteredInformationAlteredBundlerUse(gatewaySend);
}
/* ----------------------AUXILIARY METHODS---------------------- */
/**
* Method responsible for returning services that exist in list1 and does
* not exist in list2
*
* @author Nilson Rodrigues Sousa
* @param s1
* List<Service>, s2 List<Service>
* @return List<Service> -Returns the services that exist in l1 and do not
* exist in l2
*/
public List<Service> compareToServices(List<Service> s1, List<Service> s2) {
List<Service> result = new ArrayList<Service>();
boolean exist;
for (Service service1 : s1) {
exist = false;
for (Service service2 : s2) {
if (service1.getId() == service2.getId() && (service1.getNameService().equals(service2.getNameService()))
&& (service1.getBundlerProvide().equals(service2.getBundlerProvide()))) { //--------------add id
exist = true;
break;
}
}
if (exist == false) {
result.add(service1);
}
}
return result;
}
/**
* Returns services that have new bundles. Receiving as input a system list
* and the local list that has the persistent information from the last
* update.
*
* @author Nilson Rodrigues Sousa
* @param s1
* List<Service>, s2 List<Service>
* @return List<Service> - Returns services that have new bundles
*/
public List<Service> compareToServiceInformationBundlerConnected(List<Service> s1, List<Service> s2) {
List<Service> result = new ArrayList<Service>();
for (Service service1 : s1) {
for (Service service2 : s2) {
if (service1.getId() == service2.getId() && (service1.getNameService().equals(service2.getNameService()))
&& (service2.getBundlerProvide().equals(service2.getBundlerProvide()))) { //--------------add id
List<Bundler> listTempService1 = new ArrayList<Bundler>();
listTempService1.addAll(service1.getListUsesBundles());
List<Bundler> listTempService2 = new ArrayList<Bundler>();
listTempService2.addAll(service2.getListUsesBundles());
/* Returns elements of the first list that does not exist in the second */
List<Bundler> listBundlerConnected = compareToServiceInformationCompareBundlers(listTempService1,
listTempService2);
if (listBundlerConnected != null && !listBundlerConnected.isEmpty()) {
Service newService = new Service();
newService.setNameService(service1.getNameService());
Bundler newBundler = new Bundler();
newBundler.setName(service1.getBundlerProvide().getName());
newBundler.setVersion(service1.getBundlerProvide().getVersion());
newBundler.setLocation(service1.getBundlerProvide().getLocation());
newBundler.setStatus(service1.getBundlerProvide().getStatus());
newService.setBundlerProvide(newBundler);
newService.getListUsesBundles().addAll(listBundlerConnected);
result.add(newService);
}
}
}
}
return result;
}
/**
* The method that receives the list as persistent with the last update and
* the list with the system information at that time.
*
* @author Nilson Rodrigues Sousa
* @param s1
* List<Service>, s2 List<Service>
* @return List<Service> - Returns services that have excluded bundles
*/
public List<Service> compareToServiceInformationBundlerDisconnected(List<Service> s1, List<Service> s2) {
List<Service> result = new ArrayList<Service>();
for (Service service1 : s1) {
for (Service service2 : s2) {
if (service1.getId() == service2.getId() && (service1.getNameService().equals(service2.getNameService()))
&& (service2.getBundlerProvide().equals(service2.getBundlerProvide()))) { //--------------add id
List<Bundler> listTempService1 = new ArrayList<Bundler>();
listTempService1.addAll(service1.getListUsesBundles());
List<Bundler> listTempService2 = new ArrayList<Bundler>();
listTempService2.addAll(service2.getListUsesBundles());
List<Bundler> listBundlerConnected = compareToServiceInformationCompareBundlers(listTempService1,
listTempService2);
if (!(listBundlerConnected.isEmpty() || listBundlerConnected == null)) {
Service serviceTemp = new Service();
serviceTemp.setId(service1.getId()); //--------------add id
serviceTemp.setNameService(service1.getNameService());
serviceTemp.setBundlerProvide(service1.getBundlerProvide());
serviceTemp.getListUsesBundles().addAll(listBundlerConnected);
result.add(serviceTemp);
}
}
}
}
return result;
}
/**
* Method that compares two lists of bundles and returns the bundles that
* exist in the first list and do not exist in the second.
*
* @author Nilson Rodrigues Sousa
* @param l1
* List<Bundler>, l2 List<Bundler>
* @return List<Bundler> - Returns elements of the first list that does not
* exist in the second
*/
public List<Bundler> compareToServiceInformationCompareBundlers(List<Bundler> l1, List<Bundler> l2) {
List<Bundler> result = new ArrayList<Bundler>();
boolean exist;
for (Bundler b1 : l1) {
exist = false;
for (Bundler b2 : l2) {
if ((b1.getName().equals(b2.getName())) && (b1.getVersion().equals(b2.getVersion()))) {
exist = true;
break;
}
}
if (exist == false) {
result.add(b1);
}
}
return result;
}
/**
* Method receives the list of persistent services and the list of system
* services then calls the bundle comparison method to check if there is
* different information in the existing bundles. If it does, it assembles a
* class with the gateway, service, and bundle information with changed
* information.
*
* @author Nilson Rodrigues Sousa
* @param s1
* List<Service>, s2 List<Service>
* @return List<Service> - Returns a list of information about services and
* bundles with changed information
*/
/* Not used */
public List<Service> compareToServiceInformationBundlerAltered(List<Service> s1, List<Service> s2) {
List<Service> result = new ArrayList<Service>();
for (Service service1 : s1) {
for (Service service2 : s2) {
if (service1.getId() == service2.getId() && (service1.getNameService().equals(service2.getNameService()))
&& (service2.getBundlerProvide().equals(service2.getBundlerProvide()))) { //--------------add id
List<Bundler> listBundlerAltered = this.compareToServiceInformationCompareInformationBundler(
service1.getListUsesBundles(), service2.getListUsesBundles());
if (!(listBundlerAltered.isEmpty() || listBundlerAltered == null)) {
Service temp = new Service();
// modificar para capturar somente o que está alterado.
// (MELHORIA)
temp.setNameService(service2.getNameService());
Bundler newBundler = new Bundler();
newBundler.setName(service2.getBundlerProvide().getName());
newBundler.setVersion(service2.getBundlerProvide().getVersion());
newBundler.setLocation(service2.getBundlerProvide().getLocation());
newBundler.setStatus(service2.getBundlerProvide().getStatus());
temp.setBundlerProvide(newBundler);
List<Bundler> listTemp = new ArrayList<Bundler>();
for (Bundler bd : listBundlerAltered) {
for (Bundler bd2 : service2.getListUsesBundles()) {
if (bd.getName().equals(bd2.getName()) && bd.getVersion().equals(bd2.getVersion())) {
newBundler = new Bundler();
newBundler.setName(bd2.getName());
newBundler.setStatus(bd2.getStatus());
newBundler.setLocation(bd2.getLocation());
newBundler.setVersion(bd2.getVersion());
listTemp.add(newBundler);
}
}
}
temp.getListUsesBundles().addAll(listTemp);
result.add(temp);
}
}
}
}
return result;
}
/**
* Method that receives the persistent list and a system list and returns
* the list of bundles that have changed information
*
* @author Nilson Rodrigues Sousa
* @param l1
* List<Bundler>, l2 List<Bundler>
* @return List<Bundler> - Returns the list of bundles that have changed
* information
*/
/* Not used */
public List<Bundler> compareToServiceInformationCompareInformationBundler(List<Bundler> l1, List<Bundler> l2) {
// input - listPersistent - listSystem(Karaf)
List<Bundler> result = new ArrayList<Bundler>();
boolean exist;
for (Bundler b1 : l1) {
exist = false;
for (Bundler b2 : l2) {
if ((b1.getName().equals(b2.getName())) && (b1.getVersion().equals(b2.getVersion()))) {
if (!(b1.getLocation().equals(b2.getLocation())) || !(b1.getStatus().equals(b2.getStatus()))) {
exist = true;
}
break;
}
}
if (exist == true) {
result.add(b1);
}
}
return result;
}
} | 33.500715 | 118 | 0.687407 |
5d161aa10d8968f76a61b8232c3ad3bc0eb00470 | 778 | package com.zygon.htm.core.io.channel.Input;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Random;
/**
*
* @author zygon
*/
public class RandomInputChannel extends InputChannel<BooleanInputSet> {
private final Random random = new Random();
public RandomInputChannel() {
super(Settings.create(2));
}
@Override
public BooleanInputSet getValue() {
List<BooleanInput> inputs = Lists.newArrayList();
for (int i = 0; i < 9; i++) {
BooleanInput bi = new BooleanInput(String.valueOf(i));
bi.setValue(this.random.nextBoolean());
inputs.add(bi);
}
BooleanInputSet boolInputSet = new BooleanInputSet(inputs);
return boolInputSet;
}
}
| 21.611111 | 71 | 0.641388 |
e33f1aafe225514cf039b51b660fe2de535ea827 | 8,854 | /****************************************************************************
* Copyright AGAT-Team (2014)
*
* Contributors:
* J.F. Randrianasoa
* K. Kurtz
* E. Desjardin
* N. Passat
*
* This software is a computer program whose purpose is to [describe
* functionalities and technical features of your software].
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*
* The full license is in the file LICENSE, distributed with this software.
*****************************************************************************/
package datastructure.set;
import java.awt.image.BufferedImage;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import datastructure.Adjacency;
import datastructure.ListW;
import datastructure.Adjacency.State;
import metric.bricks.Metric;
import metric.bricks.MetricFactory;
import multi.strategy.consensus.bricks.Consensus;
import metric.bricks.Metric.TypeOfMetric;
import utils.ImTool;
import utils.Log;
/**
* A @link {@link TreeSet} based structure containing all the adjacency links of the region adjacency graph (RAG).
*
* <p> The structure is maintained ordered and allows each adjacency to know its rank (~position) among all.
* It also associates and links an image and a similarity metric to each other.
* The similarity distances computed with the metric allow the management of the order although a chaining structure helps to keep the ranks updated.
*
*/
public class SetW implements ListW{
/**
* knowing the strategy used when creating the structure of hierarchy will help to minimize the instructions for some methods (e.g.: reduction by not updating the chaining links between consecutive adjacency links as the ranks are not used.
*/
public Consensus strategy;
/**
* Identification of the setW (or listW by language abuse)
*/
public int index;
/**
* Similarity metric to consider while computing the distance scores
*/
public Metric metric;
/**
* Core structure containing the ordered adjacency links
*/
public TreeSet<Adjacency> set;
/**
* Determines where to start the rank update
*/
public Adjacency updateStart;
/**
* Creates a setW that will be ready to contain and order adjacency links
*
* @param listIndex identification
* @param image of interest; should not be null
* @param metricType defining the similarity metric to consider; should not be null
* @param consensus {@link SetW#strategy strategy} helping the choice of the couple of nodes to merge when creating a structure of hierarchy
*
* @throws NullPointerException if adjacency or metricTye is null
*/
public SetW(int listIndex, BufferedImage image, TypeOfMetric metricType, Consensus consensus) {
this.index = listIndex;
this.metric = MetricFactory.initMetric(metricType, image);
this.strategy = consensus;
AdjaComparator adjaComparator = new AdjaComparator(this.index, this.strategy.needRanks());
this.set = new TreeSet<Adjacency>(adjaComparator);
Log.println(String.valueOf(CONTEXT), "ListW linking <Image-"+ ImTool.getNameOf(this.metric.img) +", "+ this.metric.type +"> prepared!");
}
@Override
public void add(Adjacency adjacency) {
boolean succed = this.set.add(adjacency);
if(succed) {
adjacency.updateChains[this.index] = false;
adjacency.state[this.index] = State.ADDED;
if(this.strategy.needRanks()) {
this.setUpdateStart(adjacency);
}
}
}
@Override
public Set<Adjacency> elements() {
return this.set;
}
@Override
public int getIndex() {
return this.index;
}
@Override
public Metric getMetric() {
return this.metric;
}
@Override
public int getRankOf(Adjacency adjacency) {
return adjacency.ranks[this.index];
}
@Override
public void initRanks() {
if(this.strategy.needRanks()) {
int r = 1;
Adjacency prevTmp = null;
for(Adjacency a: this.elements()){
a.ranks[this.getIndex()] = r++;
a.previous[this.getIndex()] = prevTmp;
if(prevTmp != null) prevTmp.next[this.getIndex()] = a;
prevTmp = a;
}
}
}
@Override
public boolean isEmpty() {
return set.isEmpty();
}
@Override
public Iterator<Adjacency> iterator() {
return this.set.iterator();
}
@Override
public Adjacency optimalElement() {
return this.set.first();
}
@Override
public void print() {
System.out.println("size of the listW: "+ this.size());
for(Adjacency adjacency: this.elements()){
System.out.print("\n["+ CONTEXT+this.index +"] adja: "+ adjacency.getIndex() +" rank: ("+ this.getRankOf(adjacency) +") score: "+ adjacency.scores[this.index]);
if(adjacency.previous[this.index] != null) {
System.out.print(" previous: "+ adjacency.previous[this.index].getIndex());
}else System.out.print(" previous: null");
if(adjacency.next[this.index] != null) {
System.out.println(" next: "+ adjacency.next[this.index].getIndex());
}else System.out.println(" next: null");
}
}
@Override
public void remove(Adjacency adjacency) {
adjacency.updateChains[this.index] = false;
boolean succed = this.set.remove(adjacency);
if(succed){
adjacency.updateChains[this.index] = false;
adjacency.state[this.index] = State.REMOVED;
if(this.strategy.needRanks()) {
if(adjacency.next[this.index] != null) {
adjacency.next[this.index].previous[this.index] = adjacency.previous[this.index];
}
if(adjacency.previous[this.index] != null) {
adjacency.previous[this.index].next[this.index] = adjacency.next[this.index];
}
this.setUpdateStart(adjacency);
}
}else {
System.err.println(this.index+ ") Cannot remove: "+ adjacency.getIndex());
}
}
/**
*
* @param adjacency potentially used as a starting point when updating the ranks; should not be null
*
* @throws NullPointerException if adjacency is null
*/
public void setUpdateStart(Adjacency adjacency){
if(updateStart != null){
if(updateStart.compareTo(adjacency) > 0) {
updateStart = adjacency;
}
}else this.updateStart = adjacency;
}
@Override
public int size() {
return this.set.size();
}
@Override
public void updateRanks() {
if(this.updateStart != null){
Adjacency current = this.updateStart;
Adjacency next = this.updateStart.next[this.index];
switch(this.updateStart.state[this.index]){
case ADDED:
while(next != null){
next.ranks[this.index] = next.previous[this.index].ranks[this.index] + 1;
current = next;
next = next.next[this.index];
}
break;
case REMOVED:
while(next != null && current.state[this.index]==State.REMOVED){
if(next.previous[this.index] == null) next.ranks[this.index] = 1;
else next.ranks[this.index] = next.previous[this.index].ranks[this.index] + 1;
current = next;
next = current.next[this.index];
}
while(next != null){
next.ranks[this.index] = next.previous[this.index].ranks[this.index] + 1;
next = next.next[this.index];
}
break;
default:
break;
}
this.updateStart = null;
}
}
}
| 28.469453 | 241 | 0.66422 |
4ea585cf21a5c54670e7f8c9fb081ba9547d266d | 2,139 | /* */ package psdi.webclient.beans.common;
/* */
/* */ import java.rmi.RemoteException;
/* */ import psdi.mbo.MboSetRemote;
/* */ import psdi.util.MXException;
/* */ import psdi.webclient.components.RecordImage;
/* */ import psdi.webclient.system.beans.DataBean;
/* */ import psdi.webclient.system.controller.AppInstance;
/* */ import psdi.webclient.system.controller.BoundComponentInstance;
/* */ import psdi.webclient.system.controller.ComponentInstance;
/* */ import psdi.webclient.system.controller.WebClientEvent;
/* */ import psdi.webclient.system.session.WebClientSession;
/* */
/* */ public class ViewImageBean extends DataBean
/* */ {
/* 33 */ DataBean images = null;
/* */
/* */ protected MboSetRemote getMboSetRemote()
/* */ throws MXException, RemoteException
/* */ {
/* 38 */ ComponentInstance compInstance = this.creatingEvent.getSourceComponentInstance();
/* */
/* 40 */ MboSetRemote mboset = null;
/* 41 */ if ((compInstance instanceof RecordImage))
/* */ {
/* 43 */ String dataSrc = compInstance.getProperty("datasrc");
/* 44 */ this.images = this.app.getDataBean(dataSrc);
/* 45 */ mboset = this.images.getMboSet();
/* */ }
/* 47 */ else if ((compInstance instanceof BoundComponentInstance))
/* */ {
/* 49 */ String dataattr = compInstance.getProperty("dataattribute");
/* 50 */ WebClientEvent event = this.clientSession.getCurrentEvent();
/* 51 */ this.images = ((BoundComponentInstance)compInstance).getDataBean();
/* 52 */ mboset = this.images.getMboSetFromSmartFind(event.getValueString(), dataattr);
/* */ }
/* 54 */ return mboset;
/* */ }
/* */
/* */ public synchronized void close()
/* */ {
/* 60 */ if (this.dialogReferences > 0)
/* */ {
/* 62 */ this.dialogReferences -= 1;
/* */ }
/* 64 */ cleanup();
/* */ }
/* */ }
/* Location: D:\maxapp\MAXIMO.ear\maximouiweb.war\WEB-INF\classes\
* Qualified Name: psdi.webclient.beans.common.ViewImageBean
* JD-Core Version: 0.6.0
*/ | 40.358491 | 94 | 0.610566 |
57ae9f1aabf680e6f7e1885634c0ab26f2ea3490 | 934 | package cn.nwinfo.exhibition.config;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
/**
* @描叙: 错误页面配置
*/
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
/*1、按错误的类型显示错误的网页*/
/*错误类型为404,找不到网页的,默认显示404.html网页*/
ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404.html");
/*错误类型为500,表示服务器响应错误,默认显示500.html网页*/
ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/404.html");
ErrorPage e400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/404.html");
registry.addErrorPages(e400 ,e404, e500);
}
} | 37.36 | 92 | 0.749465 |
bc6537fcf8e6d64ee5e2ee2351f105b0f483e5df | 2,780 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.tags;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.unitime.timetable.webutil.BackTracker;
/**
* @author Tomas Muller
*/
public class BackButton extends BodyTagSupport {
private static final long serialVersionUID = 8565058511853635478L;
String iTitle = "Return to %%";
String iName = "Back";
String iAccessKey = null;
String iStyle = null;
String iClass = null;
String iType = null;
String iId = null;
int iBack = 2;
public String getTitle() { return iTitle; }
public void setTitle(String title) { iTitle = title; }
public String getName() { return iName; }
public void setName(String name) { iName = name; }
public String getAccesskey() { return iAccessKey; }
public void setAccesskey(String accessKey) { iAccessKey = accessKey; }
public String getStyle() { return iStyle; }
public void setStyle(String style) { iStyle = style; }
public String getStyleClass() { return iClass; }
public void setStyleClass(String styleClass) { iClass = styleClass; }
public int getBack() { return iBack; }
public void setBack(int back) { iBack = back; }
public String getType() { return iType; }
public void setType(String type) { iType = type; }
public String getId() { return iId; }
public void setId(String id) { iId = id; }
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
try {
String id = (getBodyContent()==null?null:getBodyContent().getString());
pageContext.getOut().print(
BackTracker.getBackButton((HttpServletRequest)pageContext.getRequest(),getBack(),getName(),getTitle(),getAccesskey(),getStyle(),getStyleClass(),getType(),(id==null || id.trim().length()==0?null:id.trim()))
);
} catch (Exception e) {
throw new JspTagException(e.getMessage());
}
return EVAL_PAGE;
}
}
| 36.103896 | 210 | 0.734892 |
368e5c8297f50a52ad252c23b437c5340c93aa53 | 1,298 | package victor.testing.mocks.time;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static java.time.LocalDate.parse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class TimeBasedLogicTest {
@Mock
OrderRepo orderRepo;
@InjectMocks
TimeBasedLogic target;
@Test
@Disabled("flaky, time-based")
void isFrequentBuyer() {
when(orderRepo.findByCustomerIdAndCreatedOnBetween(
13, parse("2021-09-01"), parse("2021-09-08"))).thenReturn(List.of(new Order().setTotalAmount(130d)));
assertThat(target.isFrequentBuyer(13)).isTrue();
// 1: inject a Clock; Hint: you'll need ZoneId.systemDefault()
// 2: interface for Clock retrival [general solution] -> **indirection without abstraction**
// 3: inject a Supplier<LocalDate>
// 4: pass time as method arg
// 5: package-protected variant for testing
// 6: mock now() - mocks all methods (try to add another LD.parse in the prod code) >> mockStatic(, CALLS_REAL_METHODS)
}
} | 34.157895 | 125 | 0.728814 |
f284772e39fb5d5d632a47c0f543874f451cee23 | 6,783 | package io.opensaber.registry.middleware.util;
import io.opensaber.converters.JenaRDF4J;
import org.apache.jena.ext.com.google.common.io.ByteStreams;
import org.apache.jena.query.DatasetFactory;
import org.apache.jena.rdf.model.*;
import org.apache.jena.riot.JsonLDWriteContext;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.WriterDatasetRIOT;
import org.apache.jena.riot.system.PrefixMap;
import org.apache.jena.riot.system.RiotLib;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class RDFUtil {
private static Logger logger = LoggerFactory.getLogger(RDFUtil.class);
public static Model getRdfModelBasedOnFormat(String jsonldData, String format){
Model m = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(jsonldData);
return m.read(reader, null, format);
}
public static Statement updateSubjectLabel(Statement statement, String label) {
Resource subject = statement.getSubject();
Property predicate = statement.getPredicate();
RDFNode object = statement.getObject();
Resource subjectCopy = ResourceFactory.createResource(label);
BeanWrapper bw = new BeanWrapperImpl(subject);
BeanUtils.copyProperties(bw.getWrappedInstance(), subjectCopy);
return ResourceFactory.createStatement(subjectCopy, predicate, object);
}
public static Statement updateResource(Statement statement, String label) {
Resource subject = statement.getSubject();
Property predicate = statement.getPredicate();
RDFNode object = statement.getObject();
Resource res = object.asResource();
Resource objectCopy = ResourceFactory.createResource(label);
BeanWrapper bw = new BeanWrapperImpl(object);
BeanUtils.copyProperties(bw.getWrappedInstance(), objectCopy);
return ResourceFactory.createStatement(subject, predicate, objectCopy);
}
public static String frameEntity(org.eclipse.rdf4j.model.Model entityModel) throws IOException {
Model jenaEntityModel = JenaRDF4J.asJenaModel(entityModel);
DatasetGraph g = DatasetFactory.create(jenaEntityModel).asDatasetGraph();
JsonLDWriteContext ctx = new JsonLDWriteContext();
InputStream is = RDFUtil.class.getClassLoader().getResourceAsStream("frame.json");
String fileString = new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8);
ctx.setFrame(fileString);
WriterDatasetRIOT w = RDFDataMgr.createDatasetWriter(org.apache.jena.riot.RDFFormat.JSONLD_FRAME_FLAT) ;
PrefixMap pm = RiotLib.prefixMap(g);
String base = null;
StringWriter sWriterJena = new StringWriter();
w.write(sWriterJena, g, pm, base, ctx) ;
String jenaJSON = sWriterJena.toString();
return jenaJSON;
}
public static void updateRdfModelNodeId(Model rdfModel, RDFNode object, String label) {
StmtIterator stmtIterator = rdfModel.listStatements();
ArrayList<Statement> updatedStatements = new ArrayList<>();
while(stmtIterator.hasNext()) {
Statement node = stmtIterator.next();
if(!node.getObject().isLiteral() && node.getObject().asResource().equals(object)) {
StmtIterator parentItr = rdfModel.listStatements(null, null, node.getSubject());
StmtIterator nodeProperties = node.getSubject().listProperties();
int updatePropertyCount =0;
while (nodeProperties.hasNext()) {
Statement childNode = nodeProperties.next();
Statement updated = RDFUtil.updateSubjectLabel(childNode, label);
nodeProperties.remove();
updatedStatements.add(updated);
logger.debug("Updated Rdf statement %s : %s", updatePropertyCount++, updated.toString());
}
while (parentItr.hasNext()) {
Statement parent = parentItr.next();
Statement updatedParent = RDFUtil.updateResource(parent, label);
parentItr.remove();
updatedStatements.add(updatedParent);
logger.debug("Updated corresponding parent statement(s) for RdfModel(s) : "+ updatedParent.toString());
}
}
}
rdfModel.add(updatedStatements.toArray(new Statement[0]));
}
public static List<Resource> getRootLabels(Model rdfModel){
List<Resource> rootLabelList = new ArrayList<Resource>();
ResIterator resIter = rdfModel.listSubjects();
while(resIter.hasNext()){
Resource resource = resIter.next();
StmtIterator stmtIter = rdfModel.listStatements(null, null, resource);
if(!stmtIter.hasNext()){
rootLabelList.add(resource);
}
}
return rootLabelList;
}
public static List<String> getTypeForSubject(Model rdfModel, Resource root){
List<String> typeIRIs = new ArrayList<String>();
NodeIterator nodeIter = rdfModel.listObjectsOfProperty(root, RDF.type);
while(nodeIter.hasNext()){
RDFNode rdfNode = nodeIter.next();
typeIRIs.add(rdfNode.toString());
}
return typeIRIs;
}
public static StmtIterator filterStatement(String subject, Property predicate, String object, Model resultModel){
Resource subjectResource = subject!=null? ResourceFactory.createResource(subject) : null;
RDFNode objectResource = object!=null? ResourceFactory.createResource(object) : null;
StmtIterator iter = resultModel.listStatements(subjectResource, predicate, objectResource);
return iter;
}
public static List<Resource> getListOfSubjects(Property predicate, String object, Model resultModel){
RDFNode objectResource = object!=null? ResourceFactory.createResource(object) : null;
ResIterator iter = resultModel.listSubjectsWithProperty(predicate, objectResource);
return iter.toList();
}
public static List<RDFNode> getListOfObjectNodes(Resource resource, Property predicate, Model resultModel){
NodeIterator iter = resultModel.listObjectsOfProperty(resource, predicate);
return iter.toList();
}
public static String printRDF(Model validationRdf) {
StringWriter sw = new StringWriter();
RDFDataMgr.write(sw, validationRdf, Lang.TTL);
return sw.toString();
}
}
| 41.87037 | 123 | 0.708389 |
a77c218c0ec8ed485277e38240896107c45da133 | 2,056 | package org.kunze.diansh.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.kunze.diansh.controller.vo.SkuVo;
import org.kunze.diansh.entity.HotelSku;
import org.kunze.diansh.entity.Sku;
import java.util.List;
import java.util.Map;
public interface ISkuService extends IService<Sku> {
/**
* 根据spuId查询相关联的sku
* @param spuId
* @return
*/
List<Sku> querySkuBySpuId(String spuId);
/**
* 查询商品展示的详细信息 通过spuId
* @param spuId
* @return
*/
List<Map<String,Object>> selectSkuInfoBySpuId(String spuId);
/***
* 查询不是特卖商品的规格
* @param spuId
* @return
*/
PageInfo<Sku> queryNotFeatSku(@Param("spuId") String spuId,Integer pageNo,Integer pageSize);
/**
* 添加规格
* @param skuVo
* @return
*/
Boolean saveSku(SkuVo skuVo);
/**
* 通过id删除sku
* @param id
* @return
*/
boolean delSkuById(String id);
/**
* 添加sku 类型为餐饮
* @param hotelSku
* @return
*/
Boolean addHotelSku(HotelSku hotelSku);
/**
* 修改sku 类型为餐饮
* @param hotelSku
* @return
*/
Boolean updateHotelSku(HotelSku hotelSku);
/**
* 删除sku 通过id 类型为餐饮
* @param id
* @return
*/
Boolean delHotelSkuById(String id);
/**
* 查询sku 通过店铺id 类型为餐饮
* @return
*/
PageInfo<Map<String,Object>> queryHotelSku(HotelSku hotelSku,Integer pageNo,Integer pageSize);
/**
* 查询sku 通过分类id 类型为餐饮
* @param shopId
* @param cid
* @return
*/
List<Map<String,Object>> queryHotelSkuByCid(String shopId,String cid,String saleable);
/**
* 检索hotelSku 类型为餐饮
* @param shopId
* @param title
* @return
*/
PageInfo<Map<String,Object>> searchHotelSku(String shopId,String title,Integer pageNo,Integer pageSize);
/**
* 通过id查询hotelSku 类型为餐饮
* @param id
* @return
*/
HotelSku queryHotelById(String id);
}
| 20.56 | 108 | 0.614786 |
19c830dad48883f905f529fbd5fb91051b71af14 | 1,058 | package com.webank.ai.fatecloud.system.dao.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EqualsAndHashCode
@ApiModel(value = "group info of site")
public class FederatedGroupInfoDo implements Serializable {
private static final long serialVersionUID = -1L;
@ApiModelProperty(value = "primary key")
@TableId(value = "group_id", type = IdType.AUTO)
private Long groupId;
@ApiModelProperty(value = "group name")
@TableField(value = "group_name")
private String groupName;
@ApiModelProperty(value = "role, 1:guest, 2:host")
@TableField(value = "role")
private Integer role;
@ApiModelProperty(value = "group status, 1:valid, 2:delete")
@TableField(value = "status")
private Integer status;
}
| 27.128205 | 64 | 0.751418 |
1b1ea189591b97d88008ac1eaddb3abbaccc4cb2 | 155 | package org.ddd4j.value.versioned;
//TODO needed?
@FunctionalInterface
public interface EventProcessor<K, V, T> {
T applyEvent(Committed<K, V> event);
} | 19.375 | 42 | 0.754839 |
410be5422aecbbf67ddbc308cde117c08558f3b5 | 834 | package Nov2020Leetcode;
import java.util.Arrays;
public class _1317ConvertIntegerToTheSumOfTwoNoZeroIntegers {
public static void main(String[] args) {
System.out.println(Arrays.toString(getNoZeroIntegers(2)));
System.out.println(Arrays.toString(getNoZeroIntegers(11)));
System.out.println(Arrays.toString(getNoZeroIntegers(10000)));
System.out.println(Arrays.toString(getNoZeroIntegers(1010)));
}
public static int[] getNoZeroIntegers(int n) {
int leftIndex = 1;
int rightIndex = n - 1;
while (leftIndex < rightIndex) {
if (leftIndex % 10 != 0 && rightIndex % 10 != 0 && String.valueOf(leftIndex).indexOf('0') == -1 && String.valueOf(rightIndex).indexOf('0') == -1) {
return new int[] { leftIndex, rightIndex };
}
leftIndex++;
rightIndex--;
}
return new int[] { leftIndex, rightIndex };
}
}
| 32.076923 | 150 | 0.705036 |
41844b92edc78664d470402d1048e8b69e6e87f0 | 951 | package ru.job4j.map;
import org.junit.Test;
import ru.job4j.map.User2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author Денис Мироненко
* @version $Id$
* @since 04.10.2018
*/
public class ConvertListInMapTest {
private User2 user1 = new User2(0, "Denis", "Piter");
private User2 user2 = new User2(1, "Vasiliy", "Moscow");
@Test
public void convertListMap() {
ConvertListInMap convert = new ConvertListInMap();
List<User2> list = new ArrayList<>();
list.add(this.user1);
list.add(this.user2);
HashMap<Integer, User2> result = convert.convert(list);
HashMap<Integer, User2> expect = new HashMap<>();
expect.put(this.user1.getId(), this.user1);
expect.put(this.user2.getId(), this.user2);
assertThat(result, is(expect));
}
}
| 25.026316 | 63 | 0.658254 |
c20a05158ba8f1e52d2bc519141aee45103d0150 | 4,429 | /*
* Copyright (c) OSGi Alliance (2002, 2010). 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.
* 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.osgi.service.url;
import java.net.*;
/**
* Abstract implementation of the {@code URLStreamHandlerService}
* interface. All the methods simply invoke the corresponding methods on
* {@code java.net.URLStreamHandler} except for {@code parseURL}
* and {@code setURL}, which use the {@code URLStreamHandlerSetter}
* parameter. Subclasses of this abstract class should not need to override the
* {@code setURL} and {@code parseURL(URLStreamHandlerSetter,...)}
* methods.
*
* @ThreadSafe
* @version $Id: 465a0ed86f5d49b338ffc6a13bb68f60f04e54d6 $
*/
public abstract class AbstractURLStreamHandlerService extends URLStreamHandler
implements URLStreamHandlerService {
/**
* @see "java.net.URLStreamHandler.openConnection"
*/
public abstract URLConnection openConnection(URL u)
throws java.io.IOException;
/**
* The {@code URLStreamHandlerSetter} object passed to the parseURL
* method.
*/
protected volatile URLStreamHandlerSetter realHandler;
/**
* Parse a URL using the {@code URLStreamHandlerSetter} object. This
* method sets the {@code realHandler} field with the specified
* {@code URLStreamHandlerSetter} object and then calls
* {@code parseURL(URL,String,int,int)}.
*
* @param realHandler The object on which the {@code setURL} method
* must be invoked for the specified URL.
* @see "java.net.URLStreamHandler.parseURL"
*/
public void parseURL(URLStreamHandlerSetter realHandler, URL u,
String spec, int start, int limit) {
this.realHandler = realHandler;
parseURL(u, spec, start, limit);
}
/**
* This method calls {@code super.toExternalForm}.
*
* @see "java.net.URLStreamHandler.toExternalForm"
*/
public String toExternalForm(URL u) {
return super.toExternalForm(u);
}
/**
* This method calls {@code super.equals(URL,URL)}.
*
* @see "java.net.URLStreamHandler.equals(URL,URL)"
*/
public boolean equals(URL u1, URL u2) {
return super.equals(u1, u2);
}
/**
* This method calls {@code super.getDefaultPort}.
*
* @see "java.net.URLStreamHandler.getDefaultPort"
*/
public int getDefaultPort() {
return super.getDefaultPort();
}
/**
* This method calls {@code super.getHostAddress}.
*
* @see "java.net.URLStreamHandler.getHostAddress"
*/
public InetAddress getHostAddress(URL u) {
return super.getHostAddress(u);
}
/**
* This method calls {@code super.hashCode(URL)}.
*
* @see "java.net.URLStreamHandler.hashCode(URL)"
*/
public int hashCode(URL u) {
return super.hashCode(u);
}
/**
* This method calls {@code super.hostsEqual}.
*
* @see "java.net.URLStreamHandler.hostsEqual"
*/
public boolean hostsEqual(URL u1, URL u2) {
return super.hostsEqual(u1, u2);
}
/**
* This method calls {@code super.sameFile}.
*
* @see "java.net.URLStreamHandler.sameFile"
*/
public boolean sameFile(URL u1, URL u2) {
return super.sameFile(u1, u2);
}
/**
* This method calls
* {@code realHandler.setURL(URL,String,String,int,String,String)}.
*
* @see "java.net.URLStreamHandler.setURL(URL,String,String,int,String,String)"
* @deprecated This method is only for compatibility with handlers written
* for JDK 1.1.
*/
protected void setURL(URL u, String proto, String host, int port,
String file, String ref) {
realHandler.setURL(u, proto, host, port, file, ref);
}
/**
* This method calls
* {@code realHandler.setURL(URL,String,String,int,String,String,String,String)}.
*
* @see "java.net.URLStreamHandler.setURL(URL,String,String,int,String,String,String,String)"
*/
protected void setURL(URL u, String proto, String host, int port,
String auth, String user, String path, String query, String ref) {
realHandler.setURL(u, proto, host, port, auth, user, path, query, ref);
}
}
| 29.526667 | 94 | 0.705351 |
19fff286c50dd25477d1b7023eafb15ce11c9f02 | 1,429 | package api.http.httpResponse.Recruiter.RMP;
/**
* Created by zero on 20/2/17.
*
* Custom employee class
*/
public class EmployeeResponse {
private Long partnerId;
private String firstName;
private String lastName;
private String mobile;
private String emailId;
private String employeeId;
private String locality;
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 getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public Long getPartnerId() {
return partnerId;
}
public void setPartnerId(Long partnerId) {
this.partnerId = partnerId;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
}
| 19.575342 | 50 | 0.627012 |
e5df0043b54f11b0099874704bb083e840c4bf50 | 2,871 | package com.dida.rn.plugin.theme;
import android.util.Log;
import com.dida.rn.MainApplication;
import com.dida.rn.R;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import javax.annotation.Nonnull;
public class ThemeModule extends ReactContextBaseJavaModule {
private static final String TAG = "ThemeModule";
private ReactApplicationContext reactContext;
public ThemeModule(@Nonnull ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Nonnull
@Override
public String getName() {
return "AndroidTheme";
}
@ReactMethod
public void changeTheme(String type) {
Log.d(TAG, "changeTheme: " + type);
if (type == null) {
return;
}
if ("blue".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.BlueTheme;
return;
}
if ("black_night".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.BlackNightTheme;
return;
}
if ("black_black".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.BlackBlackTheme;
return;
}
if ("pink".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.PinkTheme;
return;
}
if ("black_gray".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.BlackGrayTheme;
return;
}
if ("green".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.GreenTheme;
return;
}
if ("gray".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.GrayTheme;
return;
}
if ("yellow".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.YellowTheme;
return;
}
if ("white".equals(type)) {
MainApplication application = (MainApplication) reactContext.getApplicationContext();
application.theme = R.style.WhiteTheme;
return;
}
}
}
| 35.444444 | 97 | 0.635319 |
0d5755477afbe2aed35f2a453631a44198b030c4 | 3,383 | package com.mchapagai.movies.utils;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import com.mchapagai.movies.R;
import com.mchapagai.movies.common.Constants;
public class AnimationUtils {
private static Interpolator fastOutSlowIn;
@SuppressLint("InlinedApi")
public static void setLightStatusBar(@NonNull View view) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
}
public static Interpolator getFastOutSlowInInterpolator(Context context) {
if (fastOutSlowIn == null) {
fastOutSlowIn = android.view.animation.AnimationUtils.loadInterpolator(context,
android.R.interpolator.fast_out_slow_in);
}
return fastOutSlowIn;
}
public static void animateTextColorChange(final TextView tv, int startColor, int endColor) {
ValueAnimator textColorAnimation = ValueAnimator.ofArgb(startColor, endColor);
textColorAnimation.addUpdateListener(
animation -> tv.setTextColor((int) animation.getAnimatedValue()));
textColorAnimation.setDuration(Constants.DURATION);
textColorAnimation.setInterpolator(getFastOutSlowInInterpolator(tv.getContext()));
textColorAnimation.start();
}
public static void resetTextColor(final TextView textView) {
textView.setTextColor(
ContextCompat.getColor(textView.getContext(), R.color.darkThemeSecondaryText));
}
public static void animateBackgroundColorChange(final View view, int startColor, int endColor) {
ValueAnimator infoBackgroundColorAnim = ValueAnimator.ofArgb(startColor, endColor);
infoBackgroundColorAnim.addUpdateListener(
animation -> view.setBackgroundColor((int) animation.getAnimatedValue()));
infoBackgroundColorAnim.setDuration(Constants.DURATION);
infoBackgroundColorAnim.setInterpolator(getFastOutSlowInInterpolator(view.getContext()));
infoBackgroundColorAnim.start();
}
public static int getTargetHeight(View v) {
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(widthSpec, heightSpec);
return v.getMeasuredHeight();
}
public static Animation getExpandHeightAnimation(final View v, final int targetHeight) {
return new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LinearLayout.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
}
}
| 39.337209 | 100 | 0.707065 |
89022a8c3549e3c024c17c706babe8302feac4ca | 1,969 | package org.fuin.cqrs4j.example.spring.query.views.common;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.constraints.NotNull;
import org.fuin.cqrs4j.ProjectionService;
import org.fuin.esc.api.StreamId;
import org.fuin.objects4j.common.Contract;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Service to read and persist the next position of a stream to read.
*/
@Repository
public class QryProjectionService implements ProjectionService {
private static final String ARG_STREAM_ID = "streamId";
@PersistenceContext
private EntityManager em;
@Override
public void resetProjectionPosition(@NotNull final StreamId streamId) {
Contract.requireArgNotNull(ARG_STREAM_ID, streamId);
final QryProjectionPosition pos = em.find(QryProjectionPosition.class, streamId.asString());
if (pos != null) {
pos.setNextPosition(0L);
}
}
@Override
@Transactional(readOnly = true)
public Long readProjectionPosition(@NotNull StreamId streamId) {
Contract.requireArgNotNull(ARG_STREAM_ID, streamId);
final QryProjectionPosition pos = em.find(QryProjectionPosition.class, streamId.asString());
if (pos == null) {
return 0L;
}
return pos.getNextPos();
}
@Override
public void updateProjectionPosition(@NotNull StreamId streamId, @NotNull Long nextEventNumber) {
Contract.requireArgNotNull(ARG_STREAM_ID, streamId);
Contract.requireArgNotNull("nextEventNumber", nextEventNumber);
QryProjectionPosition pos = em.find(QryProjectionPosition.class, streamId.asString());
if (pos == null) {
pos = new QryProjectionPosition(streamId, nextEventNumber);
em.persist(pos);
} else {
pos.setNextPosition(nextEventNumber);
}
}
}
| 34.54386 | 101 | 0.7161 |
4198f7e520986e92c10b38a46799e8df244c5adb | 1,873 | package util;
import java.security.SecureRandom;
public class CommonUtils {
/**
* printListNode 打印单向链表
*
* @param listNode
* @return void
* @author WangZhe
* @since 1.0
*/
public static void printListNode(ListNode listNode) {
if (listNode != null) {
if (listNode.next != null) {
System.out.print(listNode.val + "->");
printListNode(listNode.next);
} else {
System.out.print(listNode.val);
System.out.println();
}
}
}
public static void swap(int[] arr, int i, int j) {
if (arr == null || arr.length == 0) {
return;
}
if (i < 0 || i > arr.length - 1 || j < 0 || j > arr.length - 1) {
return;
}
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static ListNode createListNode(int[] nums) {
if (nums != null && nums.length > 0) {
ListNode rootNode = new ListNode(nums[0]);
ListNode otherNode = rootNode;
for (int i = 1; i < nums.length; i++) {
ListNode tmpNode = new ListNode(nums[i]);
otherNode.next = tmpNode;
otherNode = tmpNode;
}
return rootNode;
}
return null;
}
public static int[] createTestArray(int n) {
SecureRandom random = new SecureRandom((System.currentTimeMillis() + "").getBytes());
int[] array = new int[n];
for (int i = 0; i < n; i++) {
int tmp = random.nextInt(10);
if (1 == tmp || 3 == tmp || 5 == tmp || 7 == tmp) {
array[i] = random.nextInt(n * 50);
} else {
array[i] = -random.nextInt(n * 50);
}
}
return array;
}
}
| 26.380282 | 93 | 0.462894 |
12dfb62e85fa3e36fac4ec7cc05b6942e48e9761 | 834 | package zone.cogni.asquareroot.security;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import zone.cogni.asquare.security.model.AuthenticationToken;
public class WithMockAsquareUserSecurityContextFactory implements WithSecurityContextFactory<WithMockAsquareUser> {
@Override
public SecurityContext createSecurityContext(WithMockAsquareUser asquareUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
AuthenticationToken ivUserAuthToken = new AuthenticationToken(asquareUser.ivUser());
ivUserAuthToken.setFullName(asquareUser.fullName());
context.setAuthentication(ivUserAuthToken);
return context;
}
}
| 41.7 | 115 | 0.845324 |
3b71aae3ea510f216013e53ded6aa6882b0d029c | 1,268 | // https://leetcode.com/problems/next-greater-element-i/
import java.util.Arrays;
public class NextGreatestElement {
public static void main(String[] args) {
int[] nums1 = {1,3,5,2,4};
int[] nums2 = {6,5,4,3,2,1,7};
System.out.println(Arrays.toString(nextGreaterElement(nums1, nums2)));
}
// Bruteforce solution for this problem
static int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
int ind = 0;
boolean added;
for (int value : nums1) {
for (int j = 0; j < nums2.length; j++) {
added = false;
if (value == nums2[j]) {
for (int k = j + 1; k < nums2.length; k++) {
if (nums2[k] > nums2[j] && ind < ans.length) {
ans[ind] = nums2[k];
ind++;
added = true;
break;
}
}
if (!added && ind < ans.length) {
ans[ind] = -1;
ind++;
}
break;
}
}
}
return ans;
}
}
| 30.190476 | 78 | 0.399054 |
be65f8b07f7e7aa9ade979e59139e75c39a986b4 | 4,292 | /**
* This work is protected under copyrights held by the members of the
* TOOP Project Consortium as indicated at
* http://wiki.ds.unipi.gr/display/TOOP/Contributors
* (c) 2018-2021. All rights reserved.
*
* This work is dual licensed under Apache License, Version 2.0
* and the EUPL 1.2.
*
* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
*
* 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.
*
* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
*
* Licensed under the EUPL, Version 1.2 or – as soon they will be approved
* by the European Commission - subsequent versions of the EUPL
* (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*/
package eu.toop.connector.webapi.helper;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Nonnull;
import com.helger.commons.CGlobal;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.error.level.EErrorLevel;
import com.helger.commons.http.CHttp;
import com.helger.commons.http.EHttpMethod;
import com.helger.commons.timing.StopWatch;
import com.helger.json.IJsonObject;
import com.helger.json.serialize.JsonWriterSettings;
import com.helger.photon.api.IAPIDescriptor;
import com.helger.photon.api.IAPIExecutor;
import com.helger.photon.app.PhotonUnifiedResponse;
import com.helger.servlet.response.UnifiedResponse;
import com.helger.web.scope.IRequestWebScopeWithoutResponse;
import eu.toop.kafkaclient.ToopKafkaClient;
/**
* Abstract base invoker for TC REST API
*
* @author Philip Helger
*/
public abstract class AbstractTCAPIInvoker implements IAPIExecutor
{
protected static final String JSON_SUCCESS = "success";
@Nonnull
public abstract IJsonObject invokeAPI (@Nonnull final IAPIDescriptor aAPIDescriptor,
@Nonnull @Nonempty final String sPath,
@Nonnull final Map <String, String> aPathVariables,
@Nonnull final IRequestWebScopeWithoutResponse aRequestScope) throws IOException;
public final void invokeAPI (@Nonnull final IAPIDescriptor aAPIDescriptor,
@Nonnull @Nonempty final String sPath,
@Nonnull final Map <String, String> aPathVariables,
@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
@Nonnull final UnifiedResponse aUnifiedResponse) throws Exception
{
final StopWatch aSW = StopWatch.createdStarted ();
final IJsonObject aJson = invokeAPI (aAPIDescriptor, sPath, aPathVariables, aRequestScope);
final PhotonUnifiedResponse aPUR = (PhotonUnifiedResponse) aUnifiedResponse;
aPUR.setJsonWriterSettings (new JsonWriterSettings ().setIndentEnabled (true));
aPUR.json (aJson);
final boolean bSuccess = aJson.getAsBoolean (JSON_SUCCESS, false);
if (!bSuccess)
aPUR.setAllowContentOnStatusCode (true).setStatus (CHttp.HTTP_BAD_REQUEST);
else
if (aRequestScope.getHttpMethod () == EHttpMethod.GET)
aPUR.enableCaching (3 * CGlobal.SECONDS_PER_HOUR);
else
aPUR.disableCaching ();
aSW.stop ();
ToopKafkaClient.send (bSuccess ? EErrorLevel.INFO : EErrorLevel.ERROR,
() -> "[API] Finished '" +
aAPIDescriptor.getPathDescriptor ().getAsURLString () +
"' after " +
aSW.getMillis () +
" milliseconds with " +
(bSuccess ? "success" : "error"));
}
}
| 40.490566 | 122 | 0.657735 |
14c735e6cb7d46ee1931b303b0045f8f40eedf61 | 108 | package dot.junit.opcodes.invoke_virtual_range.d;
public class Snippet {
public void test() {
}
}
| 13.5 | 49 | 0.694444 |
fe44c68e46234819a0f50d5fba60ebdeb7e00a56 | 17,529 | /*******************************************************************************
* Copyright 2016 Intuit
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.intuit.wasabi.experiment;
import com.intuit.wasabi.assignmentobjects.RuleCache;
import com.intuit.wasabi.authenticationobjects.UserInfo;
import com.intuit.wasabi.eventlog.EventLog;
import com.intuit.wasabi.exceptions.BucketNotFoundException;
import com.intuit.wasabi.exceptions.ConstraintViolationException;
import com.intuit.wasabi.exceptions.ExperimentNotFoundException;
import com.intuit.wasabi.experiment.impl.BucketsImpl;
import com.intuit.wasabi.experimentobjects.Application;
import com.intuit.wasabi.experimentobjects.Bucket;
import com.intuit.wasabi.experimentobjects.BucketList;
import com.intuit.wasabi.experimentobjects.Experiment;
import com.intuit.wasabi.experimentobjects.ExperimentValidator;
import com.intuit.wasabi.experimentobjects.exceptions.InvalidExperimentStateException;
import com.intuit.wasabi.repository.ExperimentRepository;
import com.intuit.wasabi.repository.MutexRepository;
import com.intuit.wasabi.repository.RepositoryException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static com.googlecode.catchexception.CatchException.verifyException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class BucketsImplTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private ExperimentRepository databaseRepository;
@Mock
private ExperimentRepository cassandraRepository;
@Mock
private MutexRepository mutexRepository;
@Mock
private ExperimentValidator validator;
@Mock
private RuleCache ruleCache;
@Mock
private Experiments experiments;
@Mock
private Buckets buckets;
@Mock
private EventLog eventLog;
private final static Application.Name testApp = Application.Name.valueOf("testApp");
private Experiment.ID experimentID;
private Bucket.Label bucketLabel;
private UserInfo changeUser = UserInfo.from(UserInfo.Username.valueOf("userinfo")).build();
@Before
public void setup() {
experimentID = Experiment.ID.newInstance();
bucketLabel = Bucket.Label.valueOf("aLabel");
}
@Test
public void testCreateBucket() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog) {
@Override
public Bucket getBucket(Experiment.ID experimentID, Bucket.Label bucketLabel) {
return Bucket.newInstance(experimentID, bucketLabel).withAllocationPercent(.3).build();
}
};
final Bucket newBucket = Bucket.newInstance(experimentID, bucketLabel).withAllocationPercent(.3).build();
Bucket bucket = Bucket.newInstance(experimentID, bucketLabel).withAllocationPercent(.3).build();
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DELETED)
.build();
when(experiments.getExperiment(experiment.getID())).thenReturn(null);
verifyException(bucketsImpl, ExperimentNotFoundException.class)
.createBucket(experiment.getID(), newBucket, changeUser);
when(experiments.getExperiment(experiment.getID())).thenReturn(experiment);
verifyException(bucketsImpl, InvalidExperimentStateException.class)
.createBucket(experimentID, newBucket, changeUser);
experiment.setState(Experiment.State.DRAFT);
when(cassandraRepository.getBucket(newBucket.getExperimentID(), newBucket.getLabel())).thenReturn(bucket);
verifyException(bucketsImpl, ConstraintViolationException.class)
.createBucket(experimentID, newBucket, changeUser);
when(cassandraRepository.getBucket(newBucket.getExperimentID(), newBucket.getLabel())).thenReturn(null);
Bucket result = bucketsImpl.createBucket(experimentID, newBucket, changeUser);
assert result.getLabel() == newBucket.getLabel();
assert result.getExperimentID() == experimentID;
experiment.setState(Experiment.State.RUNNING);
result = bucketsImpl.createBucket(experimentID, newBucket, changeUser);
assert result.getLabel() == newBucket.getLabel();
assert result.getExperimentID() == experimentID;
doThrow(RepositoryException.class).when(databaseRepository).createBucket(newBucket);
verifyException(bucketsImpl, RepositoryException.class).createBucket(experimentID, newBucket, changeUser);
}
@Test
public void testAdjustAllocationPercentages() {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository, experiments, buckets,
validator, eventLog);
Bucket newBucket = Bucket.newInstance(experimentID, bucketLabel).withAllocationPercent(.3).build();
Bucket bucket = Bucket.newInstance(experimentID, Bucket.Label.valueOf("a")).withAllocationPercent(.4).build();
Bucket bucket2 = Bucket.newInstance(experimentID, Bucket.Label.valueOf("b")).withAllocationPercent(.6).build();
BucketList bucketList = new BucketList();
bucketList.addBucket(bucket);
bucketList.addBucket(bucket2);
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DRAFT)
.build();
when(buckets.getBuckets(experimentID, false)).thenReturn(bucketList);
BucketList newBuckets = bucketsImpl.adjustAllocationPercentages(experiment, newBucket);
bucket.setAllocationPercent(.42);
bucket2.setAllocationPercent(.28);
bucketList = new BucketList();
bucketList.addBucket(bucket);
bucketList.addBucket(bucket2);
for (Bucket b1 : bucketList.getBuckets()) {
for (Bucket b2 : bucketList.getBuckets()) {
if (b1.getLabel().equals(b2.getLabel())) {
assertTrue(b1.equals(b2));
}
}
}
assertTrue(bucketList.getBuckets().size() == newBuckets.getBuckets().size());
}
@Test
public void testValidateBucketChanges() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Bucket bucket = Bucket.newInstance(experimentID, Bucket.Label.valueOf("a")).withAllocationPercent(.3)
.withState(Bucket.State.valueOf("OPEN")).build();
Bucket bucket2 = Bucket.newInstance(Experiment.ID.newInstance(), Bucket.Label.valueOf("a"))
.withAllocationPercent(.3).withState(Bucket.State.valueOf("CLOSED")).build();
try {
bucketsImpl.validateBucketChanges(bucket, bucket2);
fail();
} catch (IllegalArgumentException ignored) {
}
bucket2.setExperimentID(experimentID);
bucket2.setLabel(Bucket.Label.valueOf("b"));
try {
bucketsImpl.validateBucketChanges(bucket, bucket2);
fail();
} catch (IllegalArgumentException ignored) {
}
bucket2.setExperimentID(experimentID);
bucket2.setLabel(Bucket.Label.valueOf("a"));
try {
bucketsImpl.validateBucketChanges(bucket, bucket2);
fail();
} catch (IllegalArgumentException ignored) {
}
bucket2.setState(Bucket.State.valueOf("OPEN"));
bucketsImpl.validateBucketChanges(bucket, bucket2);
}
@Test
public void testGetBucketChangeList() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Bucket bucket = Bucket.newInstance(experimentID, bucketLabel)
.withControl(true).withAllocationPercent(.5).withDescription("one").withPayload("pay1").build();
Bucket bucket2 = Bucket.newInstance(Experiment.ID.newInstance(), bucketLabel)
.withControl(false).withAllocationPercent(.6).withDescription("two").withPayload("pay2").build();
Bucket.Builder builder = Bucket.newInstance(experimentID, bucketLabel);
ArrayList<Bucket.BucketAuditInfo> changes = new ArrayList<>();
Bucket.BucketAuditInfo changeData;
changeData = new Bucket.BucketAuditInfo("is_control", bucket.isControl().toString(),
bucket2.isControl().toString());
changes.add(changeData);
changeData = new Bucket.BucketAuditInfo("allocation", bucket.getAllocationPercent().toString(),
bucket2.getAllocationPercent().toString());
changes.add(changeData);
changeData = new Bucket.BucketAuditInfo("description", bucket.getDescription(), bucket2.getDescription());
changes.add(changeData);
changeData = new Bucket.BucketAuditInfo("payload", bucket.getPayload(), bucket2.getPayload());
changes.add(changeData);
List<Bucket.BucketAuditInfo> returned = bucketsImpl.getBucketChangeList(bucket, bucket2, builder);
assert returned.equals(changes);
}
@Test
public void testUpdateBucket() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DRAFT)
.build();
Bucket bucket = Bucket.newInstance(experimentID, bucketLabel)
.withControl(true).withAllocationPercent(.5).withDescription("one").withState(Bucket.State.OPEN).build();
Bucket updates = Bucket.newInstance(experimentID, bucketLabel)
.withControl(true).withAllocationPercent(.5).withDescription("one").build();
when(experiments.getExperiment(experimentID)).thenReturn(null);
verifyException(bucketsImpl, ExperimentNotFoundException.class)
.updateBucket(experiment.getID(), bucketLabel, updates, changeUser);
when(experiments.getExperiment(experimentID)).thenReturn(experiment);
when(cassandraRepository.getBucket(experimentID, bucketLabel)).thenReturn(null);
verifyException(bucketsImpl, BucketNotFoundException.class)
.updateBucket(experiment.getID(), bucketLabel, updates, changeUser);
updates.setAllocationPercent(0.7);
List<Bucket.BucketAuditInfo> changeList = new ArrayList<>();
Bucket.BucketAuditInfo changeData = new Bucket.BucketAuditInfo("allocation", bucket.getAllocationPercent().toString(),
updates.getAllocationPercent().toString());
changeList.add(changeData);
when(cassandraRepository.getBucket(experimentID, bucketLabel)).thenReturn(bucket);
// The method instantiates an object and sends it as an argument so we have to use matchers
when(buckets.getBucketChangeList(Matchers.<Bucket>any(), Matchers.<Bucket>any(), Matchers.<Bucket.Builder>any())).thenReturn(changeList);
when(cassandraRepository.updateBucket(bucket)).thenReturn(updates);
Bucket result = bucketsImpl.updateBucket(experimentID, bucketLabel, updates, changeUser);
assert result.getLabel().equals(updates.getLabel());
}
@Test
public void testUpdateBucketBatch() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Bucket bucket = Bucket.newInstance(experimentID, bucketLabel)
.withControl(true).withAllocationPercent(.5)
.withDescription("one").build();
bucket.setLabel(Bucket.Label.valueOf("a"));
BucketList bucketList = new BucketList();
bucketList.addBucket(bucket);
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DRAFT)
.build();
when(experiments.getExperiment(experimentID)).thenReturn(null);
try {
bucketsImpl.updateBucketBatch(experimentID, bucketList, changeUser);
fail();
} catch (ExperimentNotFoundException ignored) {
}
when(experiments.getExperiment(experimentID)).thenReturn(experiment);
try {
bucketsImpl.updateBucketBatch(experimentID, bucketList, changeUser);
fail();
} catch (IllegalStateException ignored) {
}
}
@Test
public void testCombineOldAndNewBuckets() throws Exception {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Bucket bucket = Bucket.newInstance(experimentID, Bucket.Label.valueOf("a"))
.withControl(true).withAllocationPercent(.5).withDescription("one").build();
Bucket bucket2 = Bucket.newInstance(experimentID, Bucket.Label.valueOf("b"))
.withControl(false).withAllocationPercent(.5).withDescription("two").build();
Bucket bucketNew = Bucket.newInstance(experimentID, Bucket.Label.valueOf("b"))
.withControl(false).withAllocationPercent(.5).withDescription("three").build();
BucketList oldBucketList = new BucketList();
oldBucketList.addBucket(bucket);
oldBucketList.addBucket(bucket2);
BucketList newBucketList = new BucketList();
newBucketList.addBucket(bucketNew);
BucketList expected = new BucketList();
expected.addBucket(bucket);
expected.addBucket(bucketNew);
BucketList returned = bucketsImpl.combineOldAndNewBuckets(oldBucketList, newBucketList);
assert returned.equals(expected);
}
@Test
public void testDeleteBucket() {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DRAFT)
.build();
Bucket bucket = Bucket.newInstance(experimentID, Bucket.Label.valueOf("awesomeBucket"))
.withControl(true).withAllocationPercent(1.0).withDescription("one").build();
//verify that an not available experiment is not processed
verifyException(bucketsImpl, ExperimentNotFoundException.class)
.deleteBucket(experimentID, bucket.getLabel(), changeUser);
when(experiments.getExperiment(experimentID)).thenReturn(experiment);
when(cassandraRepository.getBucket(experimentID, bucket.getLabel())).thenReturn(bucket);
bucketsImpl.deleteBucket(experimentID, bucket.getLabel(), changeUser);
//verify that Bucket gets deleted in both repositories
verify(cassandraRepository, times(1)).deleteBucket(experimentID, bucket.getLabel());
verify(databaseRepository, times(1)).deleteBucket(experimentID, bucket.getLabel());
verify(cassandraRepository, times(0)).createBucket(bucket);
doThrow(new RepositoryException()).when(databaseRepository).deleteBucket(experimentID, bucket.getLabel());
try {
bucketsImpl.deleteBucket(experimentID, bucket.getLabel(), changeUser);
fail("Delete Bucket should throw RepositoryException!"); //fail in case no exception is thrown!
} catch (RepositoryException e) {
//this exception is expected!
}
//verify that the bucket gets recreated
verify(cassandraRepository, times(1)).createBucket(bucket);
}
@Test
public void testGetBucketBuilder() {
BucketsImpl bucketsImpl = new BucketsImpl(databaseRepository, cassandraRepository,
experiments, buckets, validator, eventLog);
Experiment experiment = Experiment.withID(experimentID)
.withApplicationName(testApp)
.withState(Experiment.State.DRAFT)
.build();
verifyException(bucketsImpl, BucketNotFoundException.class).getBucketBuilder(experiment.getID(), bucketLabel);
}
}
| 44.716837 | 145 | 0.693822 |
814c258c4414e2baed9e9eb23b5238658866e9ce | 231 | package sample;
/**
* Created by freemanliu on 3/19/18.
*/
public class AlienSource {
private final String v;
public AlienSource(String v) {
this.v = v;
}
public Alien getAlien() {
return new Alien(v);
}
}
| 12.157895 | 36 | 0.623377 |
5929c77ee70279dcaac2848e930d99a439442dc7 | 3,631 | package com.roberto.cotaeasy.controllers;
import com.roberto.cotaeasy.domain.base.RetornoBaseModel;
import com.roberto.cotaeasy.domain.entities.Cotacao;
import com.roberto.cotaeasy.domain.entities.CotacaoLance;
import com.roberto.cotaeasy.domain.models.NovaCotacaoModel;
import com.roberto.cotaeasy.service.CotacaoService;
import com.roberto.cotaeasy.utils.DateUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedList;
@RestController
@RequestMapping("/api/cotacoes")
public class CotacaoController {
private final Logger log = LoggerFactory.getLogger(CotacaoController.class);
private RetornoBaseModel objetoRetorno;
private CotacaoService cotacaoService;
@Autowired
public CotacaoController(CotacaoService cotacaoService) {
this.cotacaoService = cotacaoService;
}
@PostMapping(value = "/novaCotacao", consumes = "application/json", produces="application/json")
public RetornoBaseModel novaCotacao(@RequestBody NovaCotacaoModel novaCotacaoModel) throws Exception {
try {
novaCotacaoModel.getCotacao().setDataInicio(DateUtils.removerHorasData(new DateTime(novaCotacaoModel.getCotacao().getDataInicio()).toDate()));
novaCotacaoModel.getCotacao().setDataFinal(DateUtils.removerHorasData(new DateTime(novaCotacaoModel.getCotacao().getDataFinal()).toDate()));
cotacaoService.novaCotacao(novaCotacaoModel);
cotacaoService.EnviarEmailAvisandoFornecedoresNovaCotacao(novaCotacaoModel);
return new RetornoBaseModel<NovaCotacaoModel>(true, "Cotação iniciada.", novaCotacaoModel);
} catch (Exception ex) {
return new RetornoBaseModel<NovaCotacaoModel>(false, ex.getMessage(), null);
}
}
@PostMapping(value = "/getCotacoesDisponiveisFornecedor", consumes = "application/json", produces="application/json")
public RetornoBaseModel getCotacoesDisponiveisFornecedor(@RequestBody long idFornecedor) throws Exception {
try {
LinkedList<Cotacao> cotacoesDisponiveis = cotacaoService.getCotacoesDisponiveisFornecedor(idFornecedor);
return new RetornoBaseModel<LinkedList<Cotacao>>(true, "Cotação disponíveis para o fornecedor.", cotacoesDisponiveis);
} catch (Exception ex) {
return new RetornoBaseModel<LinkedList<Cotacao>>(false, ex.getMessage(), null);
}
}
@PostMapping(value = "/getCotacoesUsuario", consumes = "application/json", produces="application/json")
public RetornoBaseModel getCotacoesUsuario(@RequestBody long idUsuario) throws Exception {
try {
LinkedList<Cotacao> cotacoesWithLances = new LinkedList<>();
LinkedList<CotacaoLance> cotacoes = cotacaoService.getCotacoesDisponiveisUsuario(idUsuario);
for (CotacaoLance cotacaoLance : cotacoes) {
boolean produtoExistente = false;
for (Cotacao cotacao : cotacoesWithLances) {
if (cotacao.getId() == cotacaoLance.getCotacao().getId())
produtoExistente = true;
}
if (!produtoExistente)
cotacoesWithLances.push(cotacaoLance.getCotacao());
}
return new RetornoBaseModel<LinkedList<Cotacao>>(true, "Cotações do usuário.", cotacoesWithLances);
} catch (Exception ex) {
return new RetornoBaseModel<LinkedList<Cotacao>>(false, ex.getMessage(), null);
}
}
}
| 50.430556 | 154 | 0.719361 |
4eb7d6330b1adf7af692d40720e3825e74f930a8 | 1,624 | package io.github.jonestimd.finance.config;
import java.util.Collections;
import java.util.Optional;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class ConfigUtilsTest {
@Test
public void getReturnsOptionalWithValue() throws Exception {
Config config = ConfigFactory.parseString("root { path = value }");
Optional<Config> result = ConfigUtils.get(config, "root");
assertThat(result.isPresent()).isTrue();
assertThat(result.get().root()).containsEntry("path", ConfigValueFactory.fromAnyRef("value"));
}
@Test
public void getReturnsEmptyOptional() throws Exception {
Config config = ConfigFactory.parseString("root { path = value }");
Optional<Config> result = ConfigUtils.get(config, "notroot");
assertThat(result.isPresent()).isFalse();
}
@Test
public void getStringReturnsOptionalWithValue() throws Exception {
Config config = ConfigFactory.parseString("root { path = value }");
Optional<String> result = ConfigUtils.getString(config, "root.path");
assertThat(result.isPresent()).isTrue();
assertThat(result.get()).isEqualTo("value");
}
@Test
public void getStringReturnsEmptyOptional() throws Exception {
Config config = ConfigFactory.parseString("root { path = value }");
Optional<String> result = ConfigUtils.getString(config, "root.path2");
assertThat(result.isPresent()).isFalse();
}
} | 31.843137 | 102 | 0.695197 |
fec7bba6a8cd3c7b9844ceb429d3105d5b011f13 | 295 | package com.designpatternstestautomation.utils.constants;
public class GeneralConstants {
public static final String AUTOMATION_PAGE = "http://automationpractice.com/index.php";
public static final String CLIENT_USER = "Client User";
public static final String CHROME = "chrome";
}
| 36.875 | 91 | 0.776271 |
4fb3e629df478dd3a9530cfa4728f6128ef50243 | 5,998 | package pt.ipc.estgoh.jogoGalo.atividade;
import pt.ipc.estgoh.jogoGalo.baseDados.BaseDados;
import pt.ipc.estgoh.jogoGalo.jogadores.Jogador;
import java.sql.*;
import java.util.ArrayList;
/**
* A classe GereAtividade será útil para realizar a manutenção dos dados contidos na
* tabela atividade da base de dados. Ou seja, esta classe irá fazer a monitorização da
* atividade dos jogadores na aplicação.
*
* @author José Mauricio
* @version 0.3
*/
public class GereAtividade {
private BaseDados bd = new BaseDados();
private PreparedStatement ps = null;
private ResultSet rs = null;
/**
* Construtor por defeito da classe GereAtividade
*/
public GereAtividade() {
}
/**
* Regista todas ações realizados por cada um dos jogadores da aplicação na
* tabela atividade da base de dados. Recebe como parâmetro um objeto da classe
* Atividade com a ação realizada e o jogador que a realizou.
*
* @param aAtividade Recebe um objeto da classe Atividade
*/
public void registarAtividade(Atividade aAtividade) {
try {
if (!aAtividade.getJogador().getNickname().equalsIgnoreCase("Anónimo")) {
ps = bd.conectarBd().prepareStatement("insert into atividade (JG_ID, A_ACAO, A_DATAACAO, A_TEMPOACAO) " +
"VALUES(?,?,?,?);");
int idUtilizador = aAtividade.getJogador().getId();
String acaoRealizada = aAtividade.getAcao();
Date dataAcao = new Date(aAtividade.getData().getTime());
Time hora = new Time(aAtividade.getHora().getTime());
ps.setInt(1, idUtilizador);
ps.setString(2, acaoRealizada);
ps.setDate(3, dataAcao);
ps.setTime(4, hora);
ps.execute();
}
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
} finally {
bd.terminarConeccao();
if (ps != null) {
try {
ps.close();
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
}
}
}
}
/**
* Devolve um ArrayList da classe Atividade com todos os registos da tabela atividade.
* Este método será excutado por qualquer jogador que executar a aplicação.
*
* @return Retorna um ArrayList da classe Atividade
*/
public ArrayList<Atividade> listarTodaAtividade() {
ArrayList<Atividade> listaLog = new ArrayList<>();
try {
ps = bd.conectarBd().prepareStatement("SELECT A_ACAO, A_DATAACAO, A_TEMPOACAO,j.JG_NICKNAME " +
"FROM atividade a, jogador j WHERE a.JG_ID = j.JG_ID ORDER BY JG_NICKNAME;");
rs = ps.executeQuery();
while (rs.next()) {
Jogador jogador = new Jogador();
jogador.setNickname(rs.getString(4));
listaLog.add(new Atividade(rs.getString(1), rs.getDate(2),
rs.getTime(3), jogador));
}
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
} finally {
bd.terminarConeccao();
if (ps != null) {
try {
ps.close();
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
}
}
}
return listaLog;
}
/**
* Retorna um ArrayList com todos os registos referentes ao jogador cujo o nickname seja
* igual ao valor recebido como parâmetro. O utilizador comum sempre que pretender pesquisar registos
* de atividade por jogador deve indicar o nickname do jogador, que será passado por parâmetro
* e devolve os registos referentes a esse jogador.
*
* @param aNome Recebe uma string com o nickname do jogador
* @return Retorna um ArrayList da classe Atividade com os registos do jogador
*/
public ArrayList<Atividade> pesquisarAtividadeUtilizador(String aNome) {
ArrayList<Atividade> listaLog = new ArrayList<>();
try {
ps = bd.conectarBd().prepareStatement("SELECT A_ACAO, A_DATAACAO, A_TEMPOACAO,j.JG_NICKNAME " +
"FROM atividade a, jogador j WHERE a.JG_ID = j.JG_ID " +
"AND j.JG_NICKNAME like ? OR j.JG_NICKNAME like ? OR j.JG_NICKNAME like ? order by A_TEMPOACAO;");
ps.setString(1, "%" + aNome);
ps.setString(2, aNome + "%");
ps.setString(3, aNome);
rs = ps.executeQuery();
while (rs.next()) {
Jogador user = new Jogador();
user.setNickname(rs.getString(4));
listaLog.add(new Atividade(rs.getString(1), rs.getDate(2),
rs.getTime(3), user));
}
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
} finally {
bd.terminarConeccao();
if (ps != null) {
try {
ps.close();
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException sqe) {
System.out.println("Exception: " + sqe);
}
}
}
return listaLog;
}
} | 32.597826 | 122 | 0.522841 |
4aa1149b24391482d771521396b5c2912d91f824 | 5,911 | package com.lifekau.android.lifekau.viewholder;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.lifekau.android.lifekau.DateDisplayer;
import com.lifekau.android.lifekau.R;
import com.lifekau.android.lifekau.manager.LoginManager;
import com.lifekau.android.lifekau.model.Comment;
import java.util.Date;
/**
* Created by sgc109 on 2018-02-12.
*/
public class CommentViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public static final int ITEM_ID_DELETE_COMMENT = 0;
public static final int ITEM_ID_EDIT_COMMENT = 1;
public static final int ITEM_ID_CANCEL_COMMENT = 2;
private TextView mContentTextView;
private TextView mDateTextView;
private TextView mLikeTextView;
private TextView mLikeCountTextView;
private ImageView mLikeImageView;
private TextView mAuthorTextView;
private Context mContext;
private Comment mComment;
private String mCommentKey;
private String mPostAuthor;
public CommentViewHolder(View itemView, Context context, String postAuthor) {
super(itemView);
mPostAuthor = postAuthor;
mContentTextView = itemView.findViewById(R.id.list_item_comment_content_text_view);
mDateTextView = itemView.findViewById(R.id.list_item_comment_date_text_view);
mLikeTextView = itemView.findViewById(R.id.list_item_comment_like_text_view);
mLikeCountTextView = itemView.findViewById(R.id.list_item_comment_like_count_text_view);
mLikeImageView = itemView.findViewById(R.id.list_item_comment_like_image_view);
mAuthorTextView = itemView.findViewById(R.id.list_item_comment_author_text_view);
mContext = context;
itemView.setOnCreateContextMenuListener(this);
}
public void bind(Comment comment, String commentKey, final String postKey) {
mComment = comment;
mCommentKey = commentKey;
updateUI();
if (mPostAuthor.equals(comment.author)) {
mAuthorTextView.setText(mContext.getString(R.string.anonymous_author));
}
mLikeTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String studentId = LoginManager.get(mContext).getStudentId();
DatabaseReference postRef = FirebaseDatabase.getInstance().getReference()
.child(mContext.getString(R.string.firebase_database_post_comments))
.child(postKey)
.child(mCommentKey);
if (mComment.likes.containsKey(studentId)) {
mComment.likes.remove(studentId);
mComment.likeCount--;
} else {
mComment.likes.put(studentId, true);
mComment.likeCount++;
}
onLikeClicked(postRef);
updateUI();
}
});
}
private void updateUI() {
mContentTextView.setText(mComment.text);
mDateTextView.setText(DateDisplayer.dateToStringFormat(new Date(mComment.date)));
mLikeCountTextView.setText("" + mComment.likeCount);
if (mComment.likeCount == 0) {
mLikeImageView.setVisibility(View.GONE);
mLikeCountTextView.setVisibility(View.GONE);
} else {
mLikeImageView.setVisibility(View.VISIBLE);
mLikeCountTextView.setVisibility(View.VISIBLE);
}
if (mComment.likes.get(LoginManager.get(mContext).getStudentId()) != null) {
mLikeTextView.setTextColor(mContext.getResources().getColor(R.color.heart_color));
} else {
mLikeTextView.setTextColor(mContext.getResources().getColor(android.R.color.tab_indicator_text));
}
}
private void onLikeClicked(DatabaseReference postRef) {
final String studentId = LoginManager.get(mContext).getStudentId();
postRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Comment p = mutableData.getValue(Comment.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.likes.containsKey(studentId)) {
p.likeCount--;
p.likes.remove(studentId);
} else {
p.likeCount++;
p.likes.put(studentId, true);
}
mutableData.setValue(p);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d("sgc109_debug", "commentTransaction:onComplete:" + databaseError);
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo MenuInfo) {
if (mComment.author.equals(LoginManager.get(mContext).getStudentId())) {
menu.add(0, ITEM_ID_DELETE_COMMENT, getAdapterPosition(), mContext.getString(R.string.dialog_delete));
menu.add(0, ITEM_ID_CANCEL_COMMENT, getAdapterPosition(), mContext.getString(R.string.dialog_cancel));
}
}
}
| 41.335664 | 114 | 0.66317 |
179a7fbaaf4d7d972ab210fde80e65bf9a381d46 | 14,300 | package us.ihmc.idl;
import org.junit.Test;
import us.ihmc.commons.MutationTestFacilitator;
import us.ihmc.idl.IDLSequence.Byte;
import us.ihmc.idl.IDLSequence.Char;
import us.ihmc.idl.IDLSequence.Double;
import us.ihmc.idl.IDLSequence.Enum;
import us.ihmc.idl.IDLSequence.Float;
import us.ihmc.idl.IDLSequence.Integer;
import us.ihmc.idl.IDLSequence.Long;
import us.ihmc.idl.IDLSequence.Short;
import us.ihmc.idl.IDLSequence.StringBuilderHolder;
import us.ihmc.idl.IDLSequence.Boolean;
import static org.junit.Assert.*;
public class IDLToolsTest
{
@Test(timeout = 30000)
public void testStringBuilderEquals()
{
assertTrue("StringBuilders not equal", IDLTools.equals(new StringBuilder("hi"), new StringBuilder("hi")));
assertTrue("StringBuilders not equal", IDLTools.equals(new StringBuilder("a"), new StringBuilder("a")));
assertFalse("StringBuilders equal", IDLTools.equals(new StringBuilder("hi"), new StringBuilder("bye")));
assertFalse("StringBuilders equal", IDLTools.equals(new StringBuilder("bii"), new StringBuilder("bye")));
assertFalse("StringBuilders equal", IDLTools.equals(new StringBuilder("hii"), new StringBuilder("bye")));
assertFalse("StringBuilders equal", IDLTools.equals(new StringBuilder("a"), new StringBuilder("b")));
}
@Test(timeout = 30000)
public void testStringBuilderEpsilonEquals()
{
assertTrue("StringBuilders not equal", IDLTools.epsilonEqualsStringBuilder(new StringBuilder("hi"), new StringBuilder("hi"), 0.0));
assertFalse("StringBuilders equal", IDLTools.epsilonEqualsStringBuilder(new StringBuilder("hi"), new StringBuilder("bye"), 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsBoolean()
{
assertTrue("Booleans not equal", IDLTools.epsilonEqualsBoolean(true, true, 0.0));
assertTrue("Booleans not equal", IDLTools.epsilonEqualsBoolean(false, false, 0.0));
assertFalse("Booleans equal", IDLTools.epsilonEqualsBoolean(true, false, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEquals()
{
assertTrue("Doubles not equal", IDLTools.epsilonEquals(0.0, 0.0, 0.0));
assertTrue("Doubles not equal", IDLTools.epsilonEquals(0.1, 0.2, 0.1));
assertFalse("Doubles equal", IDLTools.epsilonEquals(0.0, 0.1, 0.05));
assertFalse("Doubles equal", IDLTools.epsilonEquals(0.0, 5.0, 1.0));
assertFalse("Doubles equal", IDLTools.epsilonEquals(0.0, 5.0, 0.0));
assertTrue("Doubles not equal", IDLTools.epsilonEqualsPrimitive(0.0, 0.0, 0.0));
assertTrue("Doubles not equal", IDLTools.epsilonEqualsPrimitive(0.1, 0.2, 0.1));
assertFalse("Doubles equal", IDLTools.epsilonEqualsPrimitive(0.0, 0.1, 0.05));
assertFalse("Doubles equal", IDLTools.epsilonEqualsPrimitive(0.0, 5.0, 1.0));
assertFalse("Doubles equal", IDLTools.epsilonEqualsPrimitive(0.0, 5.0, 0.0));
}
private enum SampleEnum { ONE, TWO }
@Test(timeout = 30000)
public void testEpsilonEqualsEnum()
{
assertTrue("Enums not equal", IDLTools.epsilonEqualsEnum(SampleEnum.ONE, SampleEnum.ONE, 0.0));
assertTrue("Enums not equal", IDLTools.epsilonEqualsEnum(SampleEnum.TWO, SampleEnum.TWO, 0.0));
assertFalse("Enums equal", IDLTools.epsilonEqualsEnum(SampleEnum.ONE, SampleEnum.TWO, 0.0));
}
@Test(timeout = 30000)
public void testStringBuilderEpsilonEqualsSequence()
{
StringBuilderHolder a;
StringBuilderHolder b;
a = new StringBuilderHolder(10, "type_d");
b = new StringBuilderHolder(10, "type_d");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(5, "type_d");
b = new StringBuilderHolder(10, "type_d");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(5, "type_d");
b = new StringBuilderHolder(10, "type_d");
a.add("blah");
assertFalse("Sequences equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(10, "type_d");
b = new StringBuilderHolder(10, "type_d");
a.add("one");
b.add("one");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(5, "type_d");
b = new StringBuilderHolder(10, "type_d");
a.add("one");
b.add("two");
assertFalse("Sequences equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(10, "type_d");
b = new StringBuilderHolder(10, "type_d");
a.add("one");
a.add("two");
a.add("thr");
b.add("one");
b.add("two");
b.add("thr");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
a = new StringBuilderHolder(5, "type_d");
b = new StringBuilderHolder(10, "type_d");
a.add("one");
a.add("one");
b.add("one");
b.add("two");
assertFalse("Sequences equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsEnumSequence()
{
Enum<SampleEnum> a;
Enum<SampleEnum> b;
a = new Enum<>(10, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
assertTrue("Sequences not equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(5, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
assertTrue("Sequences not equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(5, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
a.add(SampleEnum.ONE);
assertFalse("Sequences equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(10, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
a.add(SampleEnum.ONE);
b.add(SampleEnum.ONE);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(5, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
a.add(SampleEnum.ONE);
b.add(SampleEnum.TWO);
assertFalse("Sequences equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(10, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
a.add(SampleEnum.ONE);
a.add(SampleEnum.TWO);
a.add(SampleEnum.TWO);
b.add(SampleEnum.ONE);
b.add(SampleEnum.TWO);
b.add(SampleEnum.TWO);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
a = new Enum<>(5, SampleEnum.class, SampleEnum.values());
b = new Enum<>(10, SampleEnum.class, SampleEnum.values());
a.add(SampleEnum.ONE);
a.add(SampleEnum.ONE);
b.add(SampleEnum.ONE);
b.add(SampleEnum.TWO);
assertFalse("Sequences equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceBoolean()
{
Boolean a;
Boolean b;
a = new Boolean(10, "type_7");
b = new Boolean(10, "type_7");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(5, "type_7");
b = new Boolean(10, "type_7");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(5, "type_7");
b = new Boolean(10, "type_7");
a.add(true);
assertFalse("Sequences equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(10, "type_7");
b = new Boolean(10, "type_7");
a.add(true);
b.add(true);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(5, "type_7");
b = new Boolean(10, "type_7");
a.add(true);
b.add(false);
assertFalse("Sequences equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(10, "type_7");
b = new Boolean(10, "type_7");
a.add(true);
a.add(false);
a.add(true);
b.add(true);
b.add(false);
b.add(true);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
a = new Boolean(5, "type_7");
b = new Boolean(10, "type_7");
a.add(true);
a.add(true);
b.add(true);
b.add(false);
assertFalse("Sequences equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceByte()
{
Byte a;
Byte b;
a = new Byte(10, "type_9");
b = new Byte(10, "type_9");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(5, "type_9");
b = new Byte(10, "type_9");
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(5, "type_9");
b = new Byte(10, "type_9");
a.add((byte) 0);
assertFalse("Sequences equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(10, "type_9");
b = new Byte(10, "type_9");
a.add((byte) 0);
b.add((byte) 0);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(5, "type_9");
b = new Byte(10, "type_9");
a.add((byte) 0);
b.add((byte) 255);
assertFalse("Sequences equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(10, "type_9");
b = new Byte(10, "type_9");
a.add((byte) 0);
a.add((byte) 255);
a.add((byte) 255);
b.add((byte) 0);
b.add((byte) 255);
b.add((byte) -1);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
a = new Byte(5, "type_9");
b = new Byte(10, "type_9");
a.add((byte) 0);
a.add((byte) 0);
b.add((byte) 0);
b.add((byte) 255);
assertFalse("Sequences equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceChar()
{
Char a;
Char b;
a = new Char(10, "type_8");
b = new Char(10, "type_8");
a.add('a');
a.add('b');
a.add('c');
b.add('a');
b.add('b');
b.add('c');
assertTrue("Sequences not equal", IDLTools.epsilonEqualsCharSequence(a, b, 0.0));
a = new Char(5, "type_8");
b = new Char(10, "type_8");
a.add('a');
a.add('a');
b.add('a');
b.add('b');
assertFalse("Sequences equal", IDLTools.epsilonEqualsCharSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceShort()
{
Short a;
Short b;
a = new Short(10, "type_1");
b = new Short(10, "type_1");
a.add((short) 0);
a.add((short) 4);
a.add((short) -1);
b.add((short) 0);
b.add((short) 4);
b.add((short) -1);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsShortSequence(a, b, 0.0));
a = new Short(5, "type_1");
b = new Short(10, "type_1");
a.add((short) 0);
a.add((short) 0);
b.add((short) 0);
b.add((short) 4);
assertFalse("Sequences equal", IDLTools.epsilonEqualsShortSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceInteger()
{
Integer a;
Integer b;
a = new Integer(10, "type_2");
b = new Integer(10, "type_2");
a.add(0);
a.add(4);
a.add(-1);
b.add(0);
b.add(4);
b.add(-1);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsIntegerSequence(a, b, 0.0));
a = new Integer(5, "type_2");
b = new Integer(10, "type_2");
a.add(0);
a.add(0);
b.add(0);
b.add(4);
assertFalse("Sequences equal", IDLTools.epsilonEqualsIntegerSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceLong()
{
Long a;
Long b;
a = new Long(10, "type_11");
b = new Long(10, "type_11");
a.add((long) 0);
a.add((long) 4);
a.add((long) -1);
b.add((long) 0);
b.add((long) 4);
b.add((long) -1);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsLongSequence(a, b, 0.0));
a = new Long(5, "type_11");
b = new Long(10, "type_11");
a.add((long) 0);
a.add((long) 0);
b.add((long) 0);
b.add((long) 4);
assertFalse("Sequences equal", IDLTools.epsilonEqualsLongSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceFloat()
{
Float a;
Float b;
a = new Float(10, "type_5");
b = new Float(10, "type_5");
a.add((float) 0);
a.add((float) 4);
a.add((float) -1);
b.add((float) 0);
b.add((float) 4);
b.add((float) -1);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsFloatSequence(a, b, 0.0));
a = new Float(5, "type_5");
b = new Float(10, "type_5");
a.add((float) 0);
a.add((float) 0);
b.add((float) 0);
b.add((float) 4);
assertFalse("Sequences equal", IDLTools.epsilonEqualsFloatSequence(a, b, 0.0));
}
@Test(timeout = 30000)
public void testEpsilonEqualsSequenceDouble()
{
Double a;
Double b;
a = new Double(10, "type_6");
b = new Double(10, "type_6");
a.add(0.0);
a.add(1.5);
a.add(-3.0);
b.add(0.0);
b.add(1.5);
b.add(-3.0);
assertTrue("Sequences not equal", IDLTools.epsilonEqualsDoubleSequence(a, b, 0.0));
a = new Double(5, "type_6");
b = new Double(10, "type_6");
a.add(0.0);
a.add(0.0);
b.add(0.0);
b.add(1.5);
assertFalse("Sequences equal", IDLTools.epsilonEqualsDoubleSequence(a, b, 0.0));
}
public static void main(String[] args)
{
MutationTestFacilitator.facilitateMutationTestForClass(IDLTools.class, IDLToolsTest.class);
}
}
| 34.047619 | 137 | 0.617762 |
98716318023d92a0c3a415f0b916ca0fc340fdad | 3,617 | package env;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
/**
* Created by tom on 24/02/17.
*/
public class DriverUtil {
public static long DEFAULT_WAIT = 20;
protected static WebDriver driver;
public static WebDriver getDefaultDriver() {
if (driver != null) {
return driver;
}
driver = chooseDriver();
driver.manage().timeouts().setScriptTimeout(DEFAULT_WAIT, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
/**
* By default to web driver will be firefox
*
* Override it by passing -Dbrowser=chrome to the command line arguments
*
* Override it by passing -Dheadless=true to the command line argument
*
* @param capabilities
* @return
*/
@SuppressWarnings("deprecation")
private static WebDriver chooseDriver() {
DesiredCapabilities capabilities = null;
String preferredDriver = System.getProperty("browser", "firefox");
boolean headless = System.getProperty("headless", "false").equals("true");
switch (preferredDriver.toLowerCase()) {
case "chrome":
capabilities = DesiredCapabilities.chrome();
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("takesScreenshot", true);
final ChromeOptions chromeOptions = new ChromeOptions();
if (headless) {
chromeOptions.addArguments("--headless");
}
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
// System.setProperty("webdriver.chrome.driver", "./chromedriver");
WebDriverManager.chromedriver().setup();
System.out.println("********************* loading chrome driver");
driver = new ChromeDriver();
return driver;
// case "phantomjs":
// return new PhantomJSDriver(capabilities);
default:
// capabilities = DesiredCapabilities.firefox();
// capabilities.setJavascriptEnabled(true);
// capabilities.setCapability("takesScreenshot", true);
// FirefoxOptions options = new FirefoxOptions();
// if (headless) {
// options.addArguments("-headless", "-safe-mode");
// }
// capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
// System.setProperty("webdriver.gecko.driver", "./geckodriver");
// WebDriverManager.firefoxdriver().setup();
System.out.println("********************* loading firefox driver");
driver = new FirefoxDriver();
return driver;
}
}
public static WebElement waitAndGetElementByCssSelector(WebDriver driver, String selector, int seconds) {
By selection = By.cssSelector(selector);
return (new WebDriverWait(driver, seconds)).until( // ensure element is visible!
ExpectedConditions.visibilityOfElementLocated(selection));
}
public static void closeDriver() {
if (driver != null) {
try {
driver.close();
driver.quit(); // fails in current geckodriver! TODO: Fixme
} catch (NoSuchMethodError nsme) { // in case quit fails
} catch (NoSuchSessionException nsse) { // in case close fails
} catch (SessionNotCreatedException snce) {
} // in case close fails
driver = null;
}
}
}
| 33.490741 | 106 | 0.732928 |
8dd9e6e9dfd98b0da0acd9d07fff262dde5ec97c | 1,170 | package ggc.app.main;
import pt.tecnico.uilib.menus.Command;
import pt.tecnico.uilib.menus.CommandException;
import java.io.FileNotFoundException;
import java.io.IOException;
import ggc.app.exception.FileOpenFailedException;
import ggc.core.WarehouseManager;
//FIXME import classes
import ggc.core.exception.UnavailableFileException;
/**
* Open existing saved state.
*/
class DoOpenFile extends Command<WarehouseManager> {
/** @param receiver */
DoOpenFile(WarehouseManager receiver) {
super(Label.OPEN, receiver);
// FIXME maybe add command fields
addStringField("filename", Message.openFile());
}
@Override
public final void execute() throws CommandException {
String filename = stringField("filename");
try {
_receiver.load(filename);
} catch (UnavailableFileException ufe) {
throw new FileOpenFailedException(ufe.getFilename());
} catch (ClassNotFoundException e) {
throw new FileOpenFailedException(filename);
} catch (FileNotFoundException e2) {
throw new FileOpenFailedException(filename);
} catch (IOException e3) {
throw new FileOpenFailedException(filename);
}
}
}
| 24.893617 | 59 | 0.734188 |
2149ba7a9eb18e36617cf30cbbb9b49e9ab2eaa9 | 3,196 | /** SJFSchedulingAlgorithm.java
*
* A shortest job first scheduling algorithm.
*
* @author: Kamesh Vedula
* Spring 2018
*
*/
package com.jimweller.cpuscheduler;
import java.util.*;
import com.jimweller.cpuscheduler.Process;
public class SJFSchedulingAlgorithm extends BaseSchedulingAlgorithm implements OptionallyPreemptiveSchedulingAlgorithm {
private boolean preemptive;
private Vector<Process> jobs;
SJFSchedulingAlgorithm(){
// Fill in this method
/*------------------------------------------------------------*/
activeJob = null;
jobs = new Vector<Process>();
/*------------------------------------------------------------*/
}
/** Add the new job to the correct queue.*/
public void addJob(Process p){
// Fill in this method
/*------------------------------------------------------------*/
jobs.add(p);
/*------------------------------------------------------------*/
}
/** Returns true if the job was present and was removed. */
public boolean removeJob(Process p){
// Fill in this method
/*------------------------------------------------------------*/
if (p == activeJob)
activeJob = null;
return jobs.remove(p);
/*------------------------------------------------------------*/
}
/** Transfer all the jobs in the queue of a SchedulingAlgorithm to another, such as
when switching to another algorithm in the GUI */
public void transferJobsTo(SchedulingAlgorithm otherAlg) {
throw new UnsupportedOperationException();
}
/** Returns the next process that should be run by the CPU, null if none available.*/
public Process getNextJob(long currentTime){
// Fill in this method
/*------------------------------------------------------------*/
Process p = null;
Process tempP = null;
long time = 0;
if (isJobFinished() || isPreemptive()){
int i = 0;
long tempTime = 0;
while(i < jobs.size()){
p = jobs.get(i);
time = p.getBurstTime();
if((time < tempTime) || (i == 0)){
tempTime = time;
tempP = p;
}
++i;
}
activeJob = tempP;
}
return activeJob;
/*------------------------------------------------------------*/
}
public String getName(){
return "Shortest Job First";
}
/**
* @return Value of preemptive.
*/
public boolean isPreemptive(){
// Fill in this method
/*------------------------------------------------------------*/
return preemptive;
/*------------------------------------------------------------*/
}
/**
* @param v Value to assign to preemptive.
*/
public void setPreemptive(boolean v){
// Fill in this method
/*------------------------------------------------------------*/
preemptive = v;
/*------------------------------------------------------------*/
}
} | 31.333333 | 120 | 0.411452 |
6e199bfea578575c2f468eeba8b8467bc2e5fc8c | 2,823 | /*
* MFP project, Statement_select.java : Designed and developed by Tony Cui in 2021
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cyzapps.Jmfp;
import com.cyzapps.Jfcalc.DCHelper;
import com.cyzapps.Jmfp.ErrorProcessor.ERRORTYPES;
import com.cyzapps.Jmfp.ErrorProcessor.JMFPCompErrException;
import com.cyzapps.Jmfp.VariableOperator.Variable;
import com.cyzapps.Jsma.AEInvalid;
import com.cyzapps.Jsma.AbstractExpr;
import com.cyzapps.Jsma.ExprAnalyzer;
import java.util.LinkedList;
/**
*
* @author tonyc
*/
public class Statement_select extends StatementType {
private static final long serialVersionUID = 1L;
Statement_select(Statement s) {
mstatement = s;
mstrType = getTypeStr();
}
public static String getTypeStr() {
return "select";
}
public String m_strSelectedExpr;
public AbstractExpr maexprSelectedExpr;
@Override
protected void analyze(String strStatement) throws JMFPCompErrException {
m_strSelectedExpr = strStatement.substring(getTypeStr().length()).trim();
maexprSelectedExpr = new AEInvalid();
if (m_strSelectedExpr.length() == 0) {
ERRORTYPES e = ERRORTYPES.NEED_EXPRESSION;
throw new JMFPCompErrException(mstatement.mstrFilePath, mstatement.mnStartLineNo, mstatement.mnEndLineNo, e);
}
}
@Override
public LinkedList<ModuleInfo> getReferredModules(ProgContext progContext) throws InterruptedException {
return ModuleInfo.getReferredModulesFromString(m_strSelectedExpr, progContext);
}
@Override
protected void analyze2(FunctionEntry fe) {
try {
ProgContext progContext = new ProgContext();
progContext.mstaticProgContext.setCallingFunc(fe.m_sf);
maexprSelectedExpr = ExprAnalyzer.analyseExpression(m_strSelectedExpr, new DCHelper.CurPos(),
new LinkedList<Variable>(), progContext);
} catch (Exception ex) {
// do not throw exception here. Otherwise, the statement may not execute.
maexprSelectedExpr = new AEInvalid();
}
}
@Override
public void analyze2(ProgContext progContext, boolean bForceReanalyse) {
if (bForceReanalyse || maexprSelectedExpr == null || maexprSelectedExpr.menumAEType == AbstractExpr.ABSTRACTEXPRTYPES.ABSTRACTEXPR_INVALID) {
try {
maexprSelectedExpr = ExprAnalyzer.analyseExpression(m_strSelectedExpr, new DCHelper.CurPos(),
new LinkedList<Variable>(), progContext);
} catch (Exception ex) {
// do not throw exception here. Otherwise, the statement may not execute.
maexprSelectedExpr = new AEInvalid();
}
}
}
}
| 37.144737 | 147 | 0.688983 |
c16d291fb99668c53e9b481e1bb74b8c92269354 | 2,537 | package banking.business;
import banking.Card;
import banking.persistence.ICardRepository;
import com.google.common.base.Preconditions;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
public class CardService {
private static final String CARD_BIN = "400000";
private final ICardValidator cardValidator;
private final ICardRepository cardRepository;
private final Random random;
public CardService(ICardValidator cardValidator, ICardRepository cardRepository) {
this.cardValidator = cardValidator;
this.cardRepository = cardRepository;
this.random = new SecureRandom();
}
public Card issueCard() {
String pin = generateRandomPin();
String cardNumber = generateUniqueCardNumber();
Card card = new Card();
card.setPin(pin);
card.setNumber(cardNumber);
return cardRepository.save(card);
}
private String generateRandomPin() {
return String.format("%04d", random.nextInt(10000));
}
private String generateUniqueCardNumber() {
String accountIdentifier = String.format("%09d", random.nextLong(1_000_000_000L));
StringBuilder builder = new StringBuilder().append(CARD_BIN).append(accountIdentifier);
char checkSum = cardValidator.calculateCheckSum(builder.toString());
return builder.append(checkSum).toString();
}
public boolean exists(final String cardNumber) {
Objects.requireNonNull(cardNumber);
return cardRepository.findByCardNumber(cardNumber).isPresent();
}
public Optional<Card> getCard(final String cardNumber, final String cardPin) {
Objects.requireNonNull(cardNumber);
Objects.requireNonNull(cardPin);
return cardRepository.findByCardNumber(cardNumber)
.filter(card -> Objects.equals(card.getPin(), cardPin));
}
public void deleteCard(final String cardNumber) {
Objects.requireNonNull(cardNumber);
cardRepository.deleteByCardNumber(cardNumber);
}
public long addIncome(final String cardNumber, final long income) {
Preconditions.checkArgument(income > 0, "Income: %s", income);
return cardRepository.updateBalance(cardNumber, income);
}
public long transfer(final String fromCardNumber,
final String toCardNumber,
final long delta) {
return cardRepository.transfer(fromCardNumber, toCardNumber, delta);
}
}
| 34.283784 | 95 | 0.698463 |
6e1d60877831311e48971ab8697f14243989ee55 | 2,233 | package moveexecutors;
import chess.Board;
import chess.BoardState;
import chess.PosicionPieza;
import chess.Square;
import layers.ColorBoard;
import layers.KingCacheBoard;
import layers.MoveCacheBoard;
import movecalculators.MoveFilter;
/**
* @author Mauricio Coria
*
*/
class CaptureMove extends AbstractMove {
public CaptureMove(PosicionPieza from, PosicionPieza to) {
super(from, to);
}
@Override
public void executeMove(Board board) {
board.executeMove(this);
}
@Override
public void undoMove(Board board) {
board.undoMove(this);
}
@Override
public boolean filter(MoveFilter filter){
return filter.filterMove(this);
}
@Override
public void executeMove(BoardState boardState) {
super.executeMove(boardState);
if(to.getKey().equals(Square.a1)){
boardState.setEnroqueBlancoReinaPermitido(false);
}
if(to.getKey().equals(Square.h1)){
boardState.setEnroqueBlancoReyPermitido(false);
}
if(to.getKey().equals(Square.a8)){
boardState.setEnroqueNegroReinaPermitido(false);
}
if(to.getKey().equals(Square.h8)){
boardState.setEnroqueNegroReyPermitido(false);
}
}
@Override
public void undoMove(MoveCacheBoard moveCache) {
if (to.getKey().equals(Square.a1) || to.getKey().equals(Square.h1)) {
moveCache.clearPseudoMoves(Square.e1, false);
} else if (to.getKey().equals(Square.a8) || to.getKey().equals(Square.h8)) {
moveCache.clearPseudoMoves(Square.e8, false);
}
super.undoMove(moveCache);
}
@Override
public void executeMove(ColorBoard colorBoard) {
colorBoard.removePositions(to);
colorBoard.swapPositions(from.getValue().getColor(), from.getKey(), to.getKey());
}
@Override
public void undoMove(ColorBoard colorBoard) {
colorBoard.swapPositions(from.getValue().getColor(), to.getKey(), from.getKey());
colorBoard.addPositions(to);
}
@Override
public void executeMove(KingCacheBoard kingCacheBoard) {
throw new RuntimeException("Error !");
}
@Override
public void undoMove(KingCacheBoard kingCacheBoard) {
throw new RuntimeException("Error !");
}
@Override
public boolean equals(Object obj) {
if(super.equals(obj) && obj instanceof CaptureMove){
return true;
}
return false;
}
}
| 21.892157 | 83 | 0.725481 |
21384f008052238719d6ad83b5bb35f828116df7 | 7,028 | /*
* 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 org.matrixlab.indexservice;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.client.CredentialsProvider;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.elasticsearch.client.RestClient;
//import org.matrixlab.dbmdservice.api.Consts;
import org.matrixlab.gmdsdriver.core.Commands;
import org.matrixlab.jsonbuilder.impl.ObjectJson;
/**
*
* @author alexmylnikov
*/
public class DbIndex {
private String repo;
private String esurl = "localhost";
private int esport = 9200;
private static final String OBJECT_ID = "OBJECT_ID";
private static final String OBJECT_JSON = "OBJECT_JSON";
private static final String FILE_MODE_NAME = "FILE_MODE_NAME";
private static final String FILE_TYPE = "FILE_TYPE";
private static final String OBJECT_SIZE = "OBJECT_SIZE";
public DbIndex(){}
public DbIndex(String repo, String esurl, int esport) {
this.repo = repo;
this.esurl = esurl;
this.esport = esport;
}
public static void main(String[] args) {
DbIndex commitIndex = new DbIndex();
try (Repository repository = Commands.getRepo(commitIndex.getRepo())) {
commitIndex.indexCommitTree(repository);
} catch (IOException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static RevTree getRevTree(final Repository repository) {
try (Git git = new Git(repository)) {
Iterable<RevCommit> commits = git.log().all().call();
RevCommit array[] = Iterables.toArray(commits, RevCommit.class);
return array[0].getTree();
} catch (GitAPIException | IOException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public void indexCommitTree(final Repository repository) {
RestClient client = null;
try (TreeWalk treeWalk = new TreeWalk(repository)) {
treeWalk.addTree(getRevTree(repository));
treeWalk.setRecursive(true);
EsRestIndexer esIndexer = new EsRestIndexer();
CredentialsProvider crp = esIndexer.setCredentials("elastic", "changeme");
client = esIndexer.createRestClient(getEsurl(), getEsport(), crp);
Map<String, Object> map = null;
while (treeWalk.next()) {
System.out.println("*****************************************************");
if (treeWalk.isSubtree()) {
System.out.println("\"OBJECT_NODE\": " + treeWalk.getPathString() + "\n\t");
treeWalk.enterSubtree();
// System.out.println(treeWalk.getNameString() + ": " + treeWalk.getPathString());
} else {
FileMode fileMode = treeWalk.getFileMode(0);
ObjectLoader loader = repository.open(treeWalk.getObjectId(0));
ObjectJson objectJson = buildObject(treeWalk, fileMode, loader);
map = objectJson.getObjectAsMap();
// System.out.println(map);
}
if (map != null) {
String objId = (String) map.get(OBJECT_ID);
// String jsonStr = new Gson().toJson(map.get(Consts.OBJECT_JSON), String.class);
String jsonStr = (String) map.get(OBJECT_JSON);
System.out.println("ID: " + objId);
esIndexer.index(client, "mds", "local_derby", objId, jsonStr);
}
}
} catch (IncorrectObjectTypeException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
} catch (CorruptObjectException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (client != null){
try {
client.close();
} catch (IOException ex) {
Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static ObjectJson buildObject(TreeWalk tree, FileMode fileMode, ObjectLoader loader) throws LargeObjectException {
ObjectJson objectJson = new ObjectJson();
objectJson.addDoc(FILE_MODE_NAME, getFileMode(fileMode));
objectJson.addDoc(FILE_MODE_NAME, fileMode);
objectJson.addDoc(FILE_TYPE, fileMode.getObjectType());
objectJson.addDoc(OBJECT_ID, tree.getObjectId(0).getName());
objectJson.addDoc(OBJECT_SIZE, loader.getSize());
objectJson.addDoc(OBJECT_JSON, new String(loader.getBytes()));
return objectJson;
}
private static String getFileMode(FileMode fileMode) {
if (fileMode.equals(FileMode.EXECUTABLE_FILE)) {
return "\"Executable File\"";
} else if (fileMode.equals(FileMode.REGULAR_FILE)) {
return "\"Normal File\"";
} else if (fileMode.equals(FileMode.TREE)) {
return "\"Directory\"";
} else if (fileMode.equals(FileMode.SYMLINK)) {
return "\"Symlink\"";
} else {
// there are a few others, see FileMode javadoc for details
throw new IllegalArgumentException("Unknown type of file encountered: " + fileMode);
}
}
/**
* @return the repo
*/
public String getRepo() {
return repo;
}
/**
* @param repo the repo to set
*/
public void setRepo(String repo) {
this.repo = repo;
}
/**
* @return the esurl
*/
public String getEsurl() {
return esurl;
}
/**
* @param esurl the esurl to set
*/
public void setEsurl(String esurl) {
this.esurl = esurl;
}
/**
* @return the esport
*/
public int getEsport() {
return esport;
}
/**
* @param esport the esport to set
*/
public void setEsport(int esport) {
this.esport = esport;
}
}
| 35.494949 | 125 | 0.604297 |
62b860dac78c40d47c81eaed789c5e030c2dcc1c | 602 | public class Quine1{
public static void main(String ... args){
String str = "public class Quine1{%c%cpublic static void main(String ... args){%c%c%cString str = %c%s%c%c%c%c%cchar quote = 34;%c%c%cchar tab = 9;%c%c%cchar nl = 10;%c%c%cchar semicol = 59;%c%c%cSystem.out.printf(str,nl,tab,nl,tab,tab,quote,str,quote,nl,tab,tab,nl,tab,tab,nl,tab,tab,nl,tab,tab,nl,tab,nl);%c%c}%c}";
char quote = 34;
char tab = 9;
char nl = 10;
char semicol = 59;
System.out.printf(str,nl,tab,nl,tab,tab,quote,str,quote,semicol,nl,tab,tab,nl,tab,tab,nl,tab,tab,nl,tab,tab,nl,tab,tab,nl,tab,nl);
}
} | 60.2 | 320 | 0.664452 |
5756cdf9cd3c1965c627d434b9adc358c7e6e111 | 3,900 | package com.rush.controller;
import com.rush.entity.Comment;
import com.rush.entity.QuestionBank;
import com.rush.service.*;
import com.rush.util.CollectionQuestion;
import com.rush.util.OnlineQuestion;
import com.rush.util.WrongQuestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 刷题和收藏Controller
*/
@Controller
@RequestMapping("brushQuestion")
public class QuestionController {
@Autowired
private WrongTitleSetService wrongTitleSetService;
@Autowired
private RealQuizPaperService realQuizPaperService;
@Autowired
private OnlineTopicService onlineTopicService;
@Autowired
private CollectionTopicService collectionTopicService;
/**
* 获取已做的真题试卷
* @param userId 用户id(从session中获得)
* @param pageCode 当前页码
* @return
*/
@GetMapping("findQuestionPaper4Show/{userId}")
@ResponseBody
public Map<String,Object> findQuestionPaper4Show(@PathVariable Integer userId,Integer pageCode){
return realQuizPaperService.showQuestionPaper(userId,pageCode);
}
/**
* 获取已做过的真题试卷的分页信息
* @param userId 用户id
* @param pageCode 当前页码
* @return
*/
@GetMapping("findQuestionPaper4Show/page/{userId}&{pageCode}")
@ResponseBody
public Map<String, Object> findQuestionPaper4ShowByPage(@PathVariable Integer userId,@PathVariable Integer pageCode){
return findQuestionPaper4Show(userId,pageCode);
}
/**
* 根据用户id获取错题集【修改过后的】
* @param userId
* @return
*/
@GetMapping("showAllWrongQuestions/{userId}")
@ResponseBody
public List<WrongQuestion> showAllWrongQuestions(@PathVariable Integer userId){
return wrongTitleSetService.showAllWrongQuestions(userId);
}
/**
* 显示收藏的题目【修改过后的】
* @param userId
* @return
*/
@GetMapping("showAllCollectionsByUserId/{userId}")
@ResponseBody
public List<CollectionQuestion> showAllCollectionsByUserId(@PathVariable Integer userId){
return collectionTopicService.showCollectionTopicsV2(userId);
}
/**
* 获取在线题目【修改过后的】
*/
@GetMapping("findAllOnlineQuestionsV2")
@ResponseBody
public List<OnlineQuestion> findAllOnlineQuestionsV2(){
return onlineTopicService.showOnlineTopicV2();
}
/**
* 编辑收藏题目的标签名
*/
@PutMapping("collection/editCollectionQuestion/changeTagName")
@ResponseBody
public void changeTagName(Integer userId,Integer questionId,String tagName){
collectionTopicService.modifyQuestionTagName(userId,questionId,tagName);
}
/**
* 删除收藏的题目
*/
@DeleteMapping("collection/editCollectionQuestion/deleteQuestion")
@ResponseBody
public void deleteQuestion(Integer userId,Integer questionId){
collectionTopicService.removeQuestionFromCollectionTopics(userId,questionId);
}
/**
* 查看错题详细信息,并且加载评论
*/
@GetMapping("showWrongQuestion/loadQuestionDetailAndComment/{questionId}")
public ModelAndView loadQuestionDetailAndComment(@PathVariable Integer questionId){
ModelAndView mav=new ModelAndView();
Map<String,Object> detailMap=wrongTitleSetService.showWrongQuestionDetailByQuestionId(questionId);
mav.addObject("detailMap",detailMap);
mav.setViewName("personal/question_details");
return mav;
}
/**
* 发表评论
* @param comment 评论
* @return
*/
@PostMapping("postComment")
@ResponseBody
public Map<String,Object> postComment(Comment comment){
comment.setCommentTime(new Date());
Map<String,Object> map=wrongTitleSetService.postCommentByQuestionIdAndUserId(comment);
return map;
}
}
| 28.888889 | 121 | 0.716923 |
410e029560ddd7f3be3ed5f6504873138008d991 | 3,463 | package net.sourceforge.ondex.rdf.rdf2oxl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.google.common.io.Resources;
import uk.ac.ebi.utils.xml.XPathReader;
/**
* TODO: comment me!
*
* @author brandizi
* <dl><dt>Date:</dt><dd>1 Aug 2018</dd></dl>
*
*/
public class DataConverterTest extends AbstractConverterTest
{
@BeforeClass
public static void initData () throws IOException
{
resultOxl = generateOxl (
"target/data_converter_test.oxl",
"target/data_converter_test_tdb",
Pair.of ( new FileInputStream ( "src/main/assembly/resources/data/bioknet.owl" ), "RDF/XML" ),
Pair.of ( new FileInputStream ( "src/main/assembly/resources/data/bk_ondex.owl" ), "RDF/XML" ),
Pair.of ( Resources.getResource ( "support_test/publications.ttl" ).openStream (), "TURTLE" )
);
}
@Test
public void testPubConcept () throws IOException
{
final String oxlPrefix = "/ondex/ondexdataseq/concepts/concept[pid = '26396590']";
XPathReader xpath = new XPathReader ( resultOxl );
assertEquals ( "Concept PMID:26396590 not found or too many of them!",
1,
xpath.readNodeList ( oxlPrefix ).getLength ()
);
assertEquals ( "Concept PMID:26396590's JOURNAL_REF is wrong!",
"Biotechnology for biofuels",
xpath.readString ( oxlPrefix +
"/cogds/concept_gds[attrname/idRef = 'JOURNAL_REF']/value[@java_class = 'java.lang.String']/literal"
)
);
}
@Test
public void testAnnotation ()
{
final String oxlPrefix = "/ondex/ondexdataseq/concepts/concept[pid = 'testAnnotation']";
XPathReader xpath = new XPathReader ( resultOxl );
assertEquals ( "testAnnotation not found or too many of them!",
1,
xpath.readNodeList ( oxlPrefix ).getLength ()
);
assertEquals ( "testAnnotation's description is wrong!",
"Just a test concept, used to annotate stuff",
xpath.readString ( oxlPrefix + "/description" )
);
assertEquals ( "testAnnotation's evidence is wrong!",
"Manual curation",
xpath.readString ( oxlPrefix + "/evidences/evidence/fullname" )
);
NodeList evs = xpath.readNodeList (
oxlPrefix + "/cogds/concept_gds[attrname/idRef = 'EVIDENCE']" +
"/value[@java_class = 'net.sourceforge.ondex.export.oxl.CollectionHolder']/literal[@clazz = 'java.util.HashSet']" +
"/item/values[@type='xsd:string']/text()"
);
assertNotNull ( "Multi-evidence attribute is null!", evs );
assertEquals ( "Multi-evidence attribute is wrong!", 2, evs.getLength () );
List<String> evStrings = IntStream.range ( 0, 2 )
.mapToObj ( evs::item )
.map ( Node::getNodeValue )
.sorted ()
.collect ( Collectors.toList () );
assertEquals ( "Evidence 1 is wrong!", "Foo Evidence 1", evStrings.get ( 0 ) );
assertEquals ( "Evidence 2 is wrong!", "Foo Evidence 2", evStrings.get ( 1 ) );
}
/**
* TODO: Remove
*
* Just a test to move {@link Rdf2OxlConfiguration} to the XML, which should have a simpler syntax.
*/
// @Test
// public void testBean ()
// {
// ItemConfiguration icfg = springContext.getBean ( "testConfig", ItemConfiguration.class );
// System.out.println ( icfg.getHeader () );
// }
}
| 30.377193 | 118 | 0.698239 |
935d1d856247e6d5f9bab2609c489183972d5a39 | 405 | package com.raven.example.dp.behavioral.command.ex1.tv;
import com.raven.example.dp.behavioral.command.ex1.NoParamCommand;
/**
* TV[关闭]命令
*/
public class CloseCommand implements NoParamCommand {
private final TVReceiver receiver;
public CloseCommand(TVReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.close();
}
}
| 18.409091 | 66 | 0.691358 |
646abffb16289244c350679001bfbf1f1ca81c93 | 1,976 | package com.talanlabs.processmanager.messages.helper;
import com.talanlabs.processmanager.messages.exceptions.SynchronizationException;
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.Calendar;
import java.util.concurrent.Semaphore;
public class IncrementHelper {
private final FastDateFormat dateFormat;
private final Semaphore semaphore = new Semaphore(1);
private volatile Integer increment;
private volatile Calendar calendar;
private IncrementHelper() {
super();
this.calendar = Calendar.getInstance();
this.increment = 0;
dateFormat = FastDateFormat.getInstance("yyyyMMdd_HHmmss");
calendar.set(Calendar.MILLISECOND, 0);
}
public static IncrementHelper getInstance() {
return IncrementHelper.SingletonHolder.instance;
}
private synchronized Integer getIncrement(Calendar now) {
now.set(Calendar.MILLISECOND, 0);
if (now.compareTo(calendar) <= 0) {
increment++;
} else {
calendar = now;
increment = 0;
}
return increment;
}
/**
* Get a date signature with a unique increment associated to that date<br>
* Format: yyyyMMdd_HHmmss_increment
*
* @return the computed string
*/
public String getUniqueDate() {
try {
semaphore.acquire();
Calendar now = Calendar.getInstance();
return dateFormat.format(now.getTime()) + "_" + getIncrement(now);
} catch (InterruptedException e) {
throw new SynchronizationException(e);
} finally {
semaphore.release();
}
}
/**
* Sécurité anti-désérialisation
*/
private Object readResolve() {
return getInstance();
}
/**
* Holder
*/
private static final class SingletonHolder {
private static final IncrementHelper instance = new IncrementHelper();
}
}
| 25.662338 | 81 | 0.63664 |
c5faf0d24fc9877c2ca8317366268883fd4e04d2 | 6,655 | package audioplayer;
import csvFormatter.CSVFormatter;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import utils.CSVUtils;
import utils.DoublyLinkedList;
import utils.PlayListUtils;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class AudioPlayer extends Application {
/**
* Get the runtime arguments (VM arguments)
*/
private static RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
private static List<String> arguments = runtimeMxBean.getInputArguments();
private static String[] args = new String[arguments.size()];
// the playlist directory in the project folder
private static final String FILE_DIRECTORY = "playlist";
// media view
final MediaView view = new MediaView();
// Playlist
public static DoublyLinkedList<String> playlist;
// current song
private static String songPlaying = new String();
// play status
private boolean isPlaying = false;
private static MediaPlayer player = null;
ObservableList observableList = null;
/**
* On player start
*
* @param stage
* @throws MalformedURLException
*/
@Override
public void start(Stage stage) throws Exception {
Iterator<String> iterator = playlist.iterator();
// if playlist has next and nothing is being played
if (iterator.hasNext() && !isPlaying) {
// get song to play
songPlaying = iterator.next();
// play
play(songPlaying, stage);
// toogle play status
isPlaying = true;
}
}
/**
* Play media by filename
*
* @param mediaFile
* @param stage
* @return
* @throws MalformedURLException
*/
public Group play(String mediaFile, Stage stage) throws Exception {
Group group = new Group();
Label label = new Label("Now playing: " + songPlaying);
label.setLayoutX(20);
label.setLayoutY(20);
ListView<String> songs = new ListView<String>();
observableList = FXCollections.observableArrayList();
ListIterator<String> listIterator = PlayListUtils.getFirst(playlist).iterator();
while(listIterator.hasNext()) {
String song = (String) listIterator.next();
if (song.equalsIgnoreCase(songPlaying)) {
song = "Now playing: " + song;
} else {
if(song.contains("Now playing: ")){
song = song.split("Now playing: ")[1];
}
}
observableList.add(song);
}
songs.setItems(observableList);
GridPane gridPane1 = new GridPane();
gridPane1.setHgap(20);
gridPane1.setVgap(20);
gridPane1.addRow(1, label);
gridPane1.addRow(2, songs);
HBox hBox = new HBox(gridPane1);
group.getChildren().add(view);
group.getChildren().add(hBox);
Scene scene = new Scene(group, 360, 460, Color.WHITE);
stage.setScene(scene);
stage.show();
// get playlist directory
File tempDirectory = new File(FILE_DIRECTORY);
// write the current song and time to csv
CSVFormatter csvFormatter = new CSVFormatter();
csvFormatter.setSong(songPlaying);
CSVUtils csvUtils = new CSVUtils();
csvUtils.createAndWriteCSV(csvFormatter, CSVFormatter.class);
File file = null;
// get file to play
file = new File(tempDirectory.getAbsolutePath() + "/" + mediaFile);
// create media
Media media = new Media(file.toURI().toURL().toExternalForm());
// create media player
player = new MediaPlayer(media);
// add media player to UI
view.setMediaPlayer(player);
// play
player.play();
// on end of playing
player.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
player.stop();
isPlaying = false;
// check for next song in the playlist
Iterator<String> iterator = playlist.iterator();
if (iterator.hasNext()) {
songPlaying = iterator.next();
// stage.close();
try {
for(int i = 0; i < observableList.size(); i++){
String song = (String) observableList.get(i);
if(song.equalsIgnoreCase(songPlaying)){
song = "Now playing: " + song;
} else {
if(song.contains("Now playing: ")) {
song = song.split("Now playing: ")[1];
}
}
observableList.remove(i);
observableList.add(i, song);
}
// play next song
play(songPlaying, stage);
// toggle play status
isPlaying = true;
} catch (Exception e) {
e.printStackTrace();
}
}
return;
}
});
// return UI group
return group;
}
public static void stopCurrent() throws Exception {
player.stop();
}
public static void playCustom(String song) throws Exception {
if (player != null) {
player.stop();
}
songPlaying = song;
List<String> playlist = PlayListUtils.getPlaylistFromCSV("playlist.csv");
File tempDirectory = new File(FILE_DIRECTORY);
File file = new File(tempDirectory.getAbsolutePath() + "/" + song);
Media media = new Media(file.toURI().toURL().toExternalForm());
player = new MediaPlayer(media);
player.play();
}
public static void main(String[] args) {
launch(args);
}
} | 35.026316 | 88 | 0.574906 |
c09888984a4a719abb5c009914593bf3be77fb2f | 381 | package br.com.controle.domain.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.controle.domain.model.security.UserSystem;
@Repository
public interface UserRepository extends JpaRepository<UserSystem, Long>{
Optional<UserSystem> findByEmail(String email);
}
| 23.8125 | 72 | 0.832021 |
c5950a001d0ae8d79779ff3f8ad2c8f032f0b76b | 17,104 | package synergynet3.web.apps.numbernet.expressionevaluator;
import java.util.HashMap;
/**
* Java Math Expression Evaluator Freeware V1.01 by The-Son LAI
* [email protected] http://Lts.online.fr
*/
/************************************************************************
* <i>Mathematic expression evaluator.</i> Supports the following functions: +,
* -, *, /, ^, %, cos, sin, tan, acos, asin, atan, sqrt, sqr, log, min, max,
* ceil, floor, abs, neg, rndr.<br>
* When the getValue() is called, a Double object is returned. If it returns
* null, an error occured.
* <p>
*
* <pre>
* Sample:
* MathEvaluator m = new MathEvaluator("-5-6/(-2) + sqr(15+x)");
* m.addVariable("x", 15.1d);
* System.out.println( m.getValue() );
* </pre>
*
* @version 1.1
* @author The-Son LAI, <a href="mailto:[email protected]">[email protected]</a>
* @date April 2001
************************************************************************/
public class MathEvaluator
{
/**
* The Class Node.
*/
protected class Node
{
/** The n left. */
public Node nLeft = null;
/** The n level. */
public int nLevel = 0;
/** The n operator. */
public Operator nOperator = null;
/** The n parent. */
public Node nParent = null;
/** The n right. */
public Node nRight = null;
/** The n string. */
public String nString = null;
/** The n value. */
public Double nValue = null;
/**
* Instantiates a new node.
*
* @param parent
* the parent
* @param s
* the s
* @param level
* the level
* @throws Exception
* the exception
*/
public Node(Node parent, String s, int level) throws Exception
{
init(parent, s, level);
}
/**
* Instantiates a new node.
*
* @param s
* the s
* @throws Exception
* the exception
*/
public Node(String s) throws Exception
{
init(null, s, 0);
}
/***
* Removes spaces, tabs and brackets at the begining
*/
public String removeBrackets(String s)
{
String res = s;
if ((s.length() > 2) && res.startsWith("(") && res.endsWith(")") && (checkBrackets(s.substring(1, s.length() - 1)) == 0))
{
res = res.substring(1, res.length() - 1);
}
if (res != s)
{
return removeBrackets(res);
}
else
{
return res;
}
}
/***
* Removes illegal characters
*/
public String removeIllegalCharacters(String s)
{
char[] illegalCharacters =
{ ' ' };
String res = s;
for (int j = 0; j < illegalCharacters.length; j++)
{
int i = res.lastIndexOf(illegalCharacters[j], res.length());
while (i != -1)
{
String temp = res;
res = temp.substring(0, i);
res += temp.substring(i + 1);
i = res.lastIndexOf(illegalCharacters[j], s.length());
}
}
return res;
}
/***
* displays the tree of the expression
*/
public void trace()
{
String op = getOperator() == null ? " " : getOperator().getOperator();
_D(op + " : " + getString());
if (this.hasChild())
{
if (hasLeft())
{
getLeft().trace();
}
if (hasRight())
{
getRight().trace();
}
}
}
/**
* Gets the next word.
*
* @param s
* the s
* @return the next word
*/
private String getNextWord(String s)
{
int sLength = s.length();
for (int i = 1; i < sLength; i++)
{
char c = s.charAt(i);
if (((c > 'z') || (c < 'a')) && ((c > '9') || (c < '0')))
{
return s.substring(0, i);
}
}
return s;
}
/**
* Gets the operator.
*
* @param s
* the s
* @param start
* the start
* @return the operator
*/
private Operator getOperator(String s, int start)
{
Operator[] operators = getOperators();
String temp = s.substring(start);
temp = getNextWord(temp);
for (int i = 0; i < operators.length; i++)
{
if (temp.startsWith(operators[i].getOperator()))
{
return operators[i];
}
}
return null;
}
/**
* Inits the.
*
* @param parent
* the parent
* @param s
* the s
* @param level
* the level
* @throws Exception
* the exception
*/
private void init(Node parent, String s, int level) throws Exception
{
s = removeIllegalCharacters(s);
s = removeBrackets(s);
s = addZero(s);
if (checkBrackets(s) != 0)
{
throw new Exception("Wrong number of brackets in [" + s + "]");
}
nParent = parent;
nString = s;
nValue = getDouble(s);
nLevel = level;
int sLength = s.length();
int inBrackets = 0;
int startOperator = 0;
for (int i = 0; i < sLength; i++)
{
if (s.charAt(i) == '(')
{
inBrackets++;
}
else if (s.charAt(i) == ')')
{
inBrackets--;
}
else
{
// the expression must be at "root" level
if (inBrackets == 0)
{
Operator o = getOperator(nString, i);
if (o != null)
{
// if first operator or lower priority operator
if ((nOperator == null) || (nOperator.getPriority() >= o.getPriority()))
{
nOperator = o;
startOperator = i;
}
}
}
}
}
if (nOperator != null)
{
// one operand, should always be at the beginning
if ((startOperator == 0) && (nOperator.getType() == 1))
{
// the brackets must be ok
if (checkBrackets(s.substring(nOperator.getOperator().length())) == 0)
{
nLeft = new Node(this, s.substring(nOperator.getOperator().length()), nLevel + 1);
nRight = null;
return;
}
else
{
throw new Exception("Error during parsing... missing brackets in [" + s + "]");
}
}
// two operands
else if ((startOperator > 0) && (nOperator.getType() == 2))
{
// nOperator = nOperator;
nLeft = new Node(this, s.substring(0, startOperator), nLevel + 1);
nRight = new Node(this, s.substring(startOperator + nOperator.getOperator().length()), nLevel + 1);
}
}
}
/**
* d.
*
* @param s
* the s
*/
protected void _D(String s)
{
String nbSpaces = "";
for (int i = 0; i < nLevel; i++)
{
nbSpaces += " ";
}
System.out.println(nbSpaces + "|" + s);
}
/***
* returns a string that doesnt start with a + or a -
*/
protected String addZero(String s)
{
if (s.startsWith("+") || s.startsWith("-"))
{
int sLength = s.length();
for (int i = 0; i < sLength; i++)
{
if (getOperator(s, i) != null)
{
return "0" + s;
}
}
}
return s;
}
/***
* checks if there is any missing brackets
*
* @return true if s is valid
*/
protected int checkBrackets(String s)
{
int sLength = s.length();
int inBracket = 0;
for (int i = 0; i < sLength; i++)
{
if ((s.charAt(i) == '(') && (inBracket >= 0))
{
inBracket++;
}
else if (s.charAt(i) == ')')
{
inBracket--;
}
}
return inBracket;
}
/**
* Gets the left.
*
* @return the left
*/
protected Node getLeft()
{
return nLeft;
}
/**
* Gets the level.
*
* @return the level
*/
protected int getLevel()
{
return nLevel;
}
/**
* Gets the operator.
*
* @return the operator
*/
protected Operator getOperator()
{
return nOperator;
}
/**
* Gets the right.
*
* @return the right
*/
protected Node getRight()
{
return nRight;
}
/**
* Gets the string.
*
* @return the string
*/
protected String getString()
{
return nString;
}
/**
* Gets the value.
*
* @return the value
*/
protected Double getValue()
{
return nValue;
}
/**
* Checks for child.
*
* @return true, if successful
*/
protected boolean hasChild()
{
return ((nLeft != null) || (nRight != null));
}
/**
* Checks for left.
*
* @return true, if successful
*/
protected boolean hasLeft()
{
return (nLeft != null);
}
/**
* Checks for operator.
*
* @return true, if successful
*/
protected boolean hasOperator()
{
return (nOperator != null);
}
/**
* Checks for right.
*
* @return true, if successful
*/
protected boolean hasRight()
{
return (nRight != null);
}
/**
* Sets the value.
*
* @param f
* the new value
*/
protected void setValue(Double f)
{
nValue = f;
}
}
/**
* The Class Operator.
*/
protected class Operator
{
/** The op. */
private String op;
/** The priority. */
private int priority;
/** The type. */
private int type;
/**
* Instantiates a new operator.
*
* @param o
* the o
* @param t
* the t
* @param p
* the p
*/
public Operator(String o, int t, int p)
{
op = o;
type = t;
priority = p;
}
/**
* Gets the operator.
*
* @return the operator
*/
public String getOperator()
{
return op;
}
/**
* Gets the priority.
*
* @return the priority
*/
public int getPriority()
{
return priority;
}
/**
* Gets the type.
*
* @return the type
*/
public int getType()
{
return type;
}
/**
* Sets the operator.
*
* @param o
* the new operator
*/
public void setOperator(String o)
{
op = o;
}
}
/** The operators. */
protected static Operator[] operators = null;
/** The expression. */
private String expression = null;
/** The node. */
private Node node = null;
/** The variables. */
private HashMap<String, Double> variables = new HashMap<String, Double>();
/***
* creates an empty MathEvaluator. You need to use setExpression(String s)
* to assign a math expression string to it.
*/
public MathEvaluator()
{
init();
}
/***
* creates a MathEvaluator and assign the math expression string.
*/
public MathEvaluator(String s)
{
init();
setExpression(s);
}
/***
* Main. To run the program in command line. Usage: java MathEvaluator.main
* [your math expression]
*/
public static void main(String[] args)
{
if ((args == null) || (args.length != 1))
{
System.err.println("Math Expression Evaluator by The-Son LAI [email protected] C(2001):");
System.err.println("Usage: java MathEvaluator.main [your math expression]");
System.exit(0);
}
try
{
MathEvaluator m = new MathEvaluator(args[0]);
System.out.println(m.getValue());
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Evaluate.
*
* @param n
* the n
* @return the double
*/
private static Double evaluate(Node n)
{
if (n.hasOperator() && n.hasChild())
{
if (n.getOperator().getType() == 1)
{
n.setValue(evaluateExpression(n.getOperator(), evaluate(n.getLeft()), null));
}
else if (n.getOperator().getType() == 2)
{
n.setValue(evaluateExpression(n.getOperator(), evaluate(n.getLeft()), evaluate(n.getRight())));
}
}
return n.getValue();
}
/**
* Evaluate expression.
*
* @param o
* the o
* @param f1
* the f1
* @param f2
* the f2
* @return the double
*/
private static Double evaluateExpression(Operator o, Double f1, Double f2)
{
String op = o.getOperator();
Double res = null;
if ("+".equals(op))
{
res = new Double(f1.doubleValue() + f2.doubleValue());
}
else if ("-".equals(op))
{
res = new Double(f1.doubleValue() - f2.doubleValue());
}
else if ("*".equals(op))
{
res = new Double(f1.doubleValue() * f2.doubleValue());
}
else if ("\u00D7".equals(op))
{
res = new Double(f1.doubleValue() * f2.doubleValue());
}
else if ("/".equals(op))
{
res = new Double(f1.doubleValue() / f2.doubleValue());
}
else if ("\u00F7".equals(op))
{
res = new Double(f1.doubleValue() / f2.doubleValue());
}
else if ("^".equals(op))
{
res = new Double(Math.pow(f1.doubleValue(), f2.doubleValue()));
}
else if ("%".equals(op))
{
res = new Double(f1.doubleValue() % f2.doubleValue());
}
else if ("&".equals(op))
{
res = new Double(f1.doubleValue() + f2.doubleValue()); // todo
}
else if ("|".equals(op))
{
res = new Double(f1.doubleValue() + f2.doubleValue()); // todo
}
else if ("cos".equals(op))
{
res = new Double(Math.cos(f1.doubleValue()));
}
else if ("sin".equals(op))
{
res = new Double(Math.sin(f1.doubleValue()));
}
else if ("tan".equals(op))
{
res = new Double(Math.tan(f1.doubleValue()));
}
else if ("acos".equals(op))
{
res = new Double(Math.acos(f1.doubleValue()));
}
else if ("asin".equals(op))
{
res = new Double(Math.asin(f1.doubleValue()));
}
else if ("atan".equals(op))
{
res = new Double(Math.atan(f1.doubleValue()));
}
else if ("sqr".equals(op))
{
res = new Double(f1.doubleValue() * f1.doubleValue());
}
else if ("sqrt".equals(op))
{
res = new Double(Math.sqrt(f1.doubleValue()));
}
else if ("log".equals(op))
{
res = new Double(Math.log(f1.doubleValue()));
}
else if ("min".equals(op))
{
res = new Double(Math.min(f1.doubleValue(), f2.doubleValue()));
}
else if ("max".equals(op))
{
res = new Double(Math.max(f1.doubleValue(), f2.doubleValue()));
}
else if ("exp".equals(op))
{
res = new Double(Math.exp(f1.doubleValue()));
}
else if ("floor".equals(op))
{
res = new Double(Math.floor(f1.doubleValue()));
}
else if ("ceil".equals(op))
{
res = new Double(Math.ceil(f1.doubleValue()));
}
else if ("abs".equals(op))
{
res = new Double(Math.abs(f1.doubleValue()));
}
else if ("neg".equals(op))
{
res = new Double(-f1.doubleValue());
}
else if ("rnd".equals(op))
{
res = new Double(Math.random() * f1.doubleValue());
}
return res;
}
/**
* d.
*
* @param s
* the s
*/
protected static void _D(String s)
{
System.err.println(s);
}
/***
* adds a variable and its value in the MathEvaluator
*/
public void addVariable(String v, double val)
{
addVariable(v, new Double(val));
}
/***
* adds a variable and its value in the MathEvaluator
*/
public void addVariable(String v, Double val)
{
variables.put(v, val);
}
/***
* evaluates and returns the value of the expression
*/
public Double getValue() throws Exception
{
if (expression == null)
{
return null;
}
// try
// {
node = new Node(expression);
return evaluate(node);
// }
// catch (Exception e)
// {
// e.printStackTrace();
// return null;
// }
}
/***
* gets the variable's value that was assigned previously
*/
public Double getVariable(String s)
{
return variables.get(s);
}
/***
* resets the evaluator
*/
public void reset()
{
node = null;
expression = null;
variables = new HashMap<String, Double>();
}
/***
* sets the expression
*/
public void setExpression(String s)
{
expression = s;
}
/***
* trace the binary tree for debug
*/
public void trace()
{
try
{
node = new Node(expression);
node.trace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Gets the double.
*
* @param s
* the s
* @return the double
*/
private Double getDouble(String s)
{
if (s == null)
{
return null;
}
Double res = null;
try
{
res = new Double(Double.parseDouble(s));
}
catch (Exception e)
{
return getVariable(s);
}
return res;
}
/**
* Inits the.
*/
private void init()
{
if (operators == null)
{
initializeOperators();
}
}
/**
* Initialize operators.
*/
private void initializeOperators()
{
operators = new Operator[27];
operators[0] = new Operator("+", 2, 0);
operators[1] = new Operator("-", 2, 0);
operators[2] = new Operator("*", 2, 10);
operators[3] = new Operator("\u00D7", 2, 10);
operators[4] = new Operator("/", 2, 10);
operators[5] = new Operator("\u00F7", 2, 10);
operators[6] = new Operator("^", 2, 10);
operators[7] = new Operator("%", 2, 10);
operators[8] = new Operator("&", 2, 0);
operators[9] = new Operator("|", 2, 0);
operators[10] = new Operator("cos", 1, 20);
operators[11] = new Operator("sin", 1, 20);
operators[12] = new Operator("tan", 1, 20);
operators[13] = new Operator("acos", 1, 20);
operators[14] = new Operator("asin", 1, 20);
operators[15] = new Operator("atan", 1, 20);
operators[16] = new Operator("sqrt", 1, 20);
operators[17] = new Operator("sqr", 1, 20);
operators[18] = new Operator("log", 1, 20);
operators[19] = new Operator("min", 2, 0);
operators[20] = new Operator("max", 2, 0);
operators[21] = new Operator("exp", 1, 20);
operators[22] = new Operator("floor", 1, 20);
operators[23] = new Operator("ceil", 1, 20);
operators[24] = new Operator("abs", 1, 20);
operators[25] = new Operator("neg", 1, 20);
operators[26] = new Operator("rnd", 1, 20);
}
/**
* Gets the operators.
*
* @return the operators
*/
protected Operator[] getOperators()
{
return operators;
}
}
| 18.816282 | 124 | 0.547708 |
050b02be449936f093afe217261c200e975a9c73 | 3,163 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.autoconfigure.http;
import com.google.gson.Gson;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
/**
* Configuration for HTTP Message converters that use Gson.
*
* @author Andy Wilkinson
* @author Eddú Meléndez
*/
@Configuration
@ConditionalOnClass(Gson.class)
class GsonHttpMessageConvertersConfiguration {
@Configuration
@ConditionalOnBean(Gson.class)
@Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
protected static class GsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition {
PreferGsonOrJacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "gson")
static class GsonPreferred {
}
@Conditional(JacksonAndJsonbUnavailableCondition.class)
static class JacksonJsonbUnavailable {
}
}
private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions {
JacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(MappingJackson2HttpMessageConverter.class)
static class JacksonAvailable {
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jsonb")
static class JsonbPreferred {
}
}
}
| 32.608247 | 99 | 0.790389 |
3d63915f6366b5cc4e377f28ee15eda747c90274 | 310 | package org.zeroturnaround.javassist.annotation.processor.test;
public class PrivateInstanceMethod {
public String accessPrivate(String input) {
return method(input);
}
private String method(String input) {
return input.substring(input.length()/2) + input.substring(0, input.length()/2);
}
}
| 25.833333 | 84 | 0.741935 |
5006776f67460e6e953f4fc154d17117e24e0fb3 | 440 | // Java program to check for even or odd
// using Bitwise XOR operator
class GFG
{
// Returns true if n is even, else odd
static boolean isEven(int n)
{
// n^1 is n+1, then even, else odd
if ((n ^ 1) == n + 1)
return true;
else
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 100;
System.out.print(isEven(n) == true ? "Even" : "Odd");
}
}
// This code is contributed by Rajput-Ji
| 16.923077 | 55 | 0.620455 |
c8eec6c3e1d47d0ff45d6f83f4aa5826bd0c2b05 | 904 | package box.star.net.tools;
import box.star.content.MimeTypeMap;
import box.star.content.MimeTypeScanner;
import box.star.net.WebService;
import java.util.HashSet;
/**
* <p>{@link MimeTypeDriver}s create {@link ServerResult}s from {@link ServerContent} using a server environment such as the {@link WebService}.</p>
* <br>
*
*/
public interface MimeTypeDriver {
/**
* <p>Creates a mime-formatted {@link ServerResult} from a {@link ServerContent} source.</p>
*
* @param content the server content
* @return the mime formatted server result
*/
ServerResult createMimeTypeResult(ServerContent content);
interface WithMediaMapControlPort {
void configureMimeTypeController(MimeTypeMap controlPort);
}
interface WithIndexFileListControlPort {
void configureIndexFileList(HashSet<String> indexFiles);
}
interface WithMimeTypeScanner extends MimeTypeScanner {}
}
| 26.588235 | 148 | 0.751106 |
813e371bfa832e09f62328c59444721e620ff9ee | 484 | package cz.mg.language.entities.mg.runtime.components.stamps.buildin;
import cz.mg.collections.text.ReadonlyText;
public class MgInstanceStamp extends MgBuildinStamp {
public static final MgInstanceStamp INSTANCE = new MgInstanceStamp();
public static MgInstanceStamp getInstance() {
return INSTANCE;
}
static {
MgBuildinStamp.ALL.addLast(getInstance());
}
private MgInstanceStamp() {
super(new ReadonlyText("instance"));
}
}
| 23.047619 | 73 | 0.710744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.