repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/WorkbookFunctionsImLog10RequestBuilder.java | 3446 | // Template Source: BaseMethodRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.requests.WorkbookFunctionsImLog10Request;
import com.microsoft.graph.models.WorkbookFunctions;
import com.microsoft.graph.models.WorkbookFunctionResult;
import com.microsoft.graph.http.BaseActionRequestBuilder;
import com.microsoft.graph.models.WorkbookFunctionsImLog10ParameterSet;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workbook Functions Im Log10Request Builder.
*/
public class WorkbookFunctionsImLog10RequestBuilder extends BaseActionRequestBuilder<WorkbookFunctionResult> {
/**
* The request builder for this WorkbookFunctionsImLog10
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public WorkbookFunctionsImLog10RequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
private WorkbookFunctionsImLog10ParameterSet body;
/**
* The request builder for this WorkbookFunctionsImLog10
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
* @param parameters the parameters for the service method
*/
public WorkbookFunctionsImLog10RequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final WorkbookFunctionsImLog10ParameterSet parameters) {
super(requestUrl, client, requestOptions);
this.body = parameters;
}
/**
* Creates the WorkbookFunctionsImLog10Request
*
* @param requestOptions the options for the request
* @return the WorkbookFunctionsImLog10Request instance
*/
@Nonnull
public WorkbookFunctionsImLog10Request buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the WorkbookFunctionsImLog10Request with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for the request
* @return the WorkbookFunctionsImLog10Request instance
*/
@Nonnull
public WorkbookFunctionsImLog10Request buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
final WorkbookFunctionsImLog10Request request = new WorkbookFunctionsImLog10Request(
getRequestUrl(),
getClient(),
requestOptions);
request.body = this.body;
return request;
}
}
| mit |
aikin/java-refactor-training | refactoring-techniques/longer/src/main/java/me/aikin/refactoring/longer/ResidentialSite.java | 3630 | package me.aikin.refactoring.longer;
import java.util.Date;
public class ResidentialSite {
private Zone zone;
private Reading[] readings = new Reading[1000];
private static final double TAX_RATE = 0.05;
public ResidentialSite(Zone zone) {
this.zone = zone;
}
public void addReading(Reading newReading) {
// add reading to end of array
int i = 0;
while (readings[i] != null) i++;
readings[i] = newReading;
}
public Dollars charge() {
// find last reading
int i = 0;
while (readings[i] != null) i++;
int usage = readings[i - 1].getAmount() - readings[i - 2].getAmount();
Date end = readings[i - 1].getDate();
Date start = readings[i - 2].getDate();
start.setDate(start.getDate() + 1); //set to begining of period
return charge(usage, start, end);
}
private Dollars charge(int usage, Date start, Date end) {
Dollars result;
double summerFraction;
// Find out how much of period is in the summer
if (start.after(zone.getSummerEnd()) || end.before(zone.getSummerStart()))
summerFraction = 0;
else if (!start.before(zone.getSummerStart()) && !start.after(zone.getSummerEnd()) && !end.before(zone.getSummerStart()) && !end.after(zone.getSummerEnd())) {
summerFraction = 1;
} else {
// part in summer part in winter
double summerDays;
if (start.before(zone.getSummerStart()) || start.after(zone.getSummerEnd())) {
// end is in the summer
summerDays = DayOfYear(end) - DayOfYear(zone.getSummerStart()) + 1;
} else {
// start is in summer
summerDays = DayOfYear(zone.getSummerEnd()) - DayOfYear(start) + 1;
}
summerFraction = summerDays / (DayOfYear(end) - DayOfYear(start) + 1);
}
result = new Dollars((usage * zone.getSummerRate() * summerFraction) + (usage * zone.getWinterRate() * (1 - summerFraction)));
result = result.plus(new Dollars(result.times(TAX_RATE)));
Dollars fuel = new Dollars(usage * 0.0175);
result = result.plus(fuel);
result = new Dollars(result.plus(fuel.times(TAX_RATE)));
return result;
}
private int DayOfYear(Date arg) {
int result;
switch (arg.getMonth()) {
case 0:
result = 0;
break;
case 1:
result = 31;
break;
case 2:
result = 59;
break;
case 3:
result = 90;
break;
case 4:
result = 120;
break;
case 5:
result = 151;
break;
case 6:
result = 181;
break;
case 7:
result = 212;
break;
case 8:
result = 243;
break;
case 9:
result = 273;
break;
case 10:
result = 304;
break;
case 11:
result = 334;
break;
default:
throw new IllegalArgumentException();
}
result += arg.getDate();
//check leap year
if ((arg.getYear() % 4 == 0) && ((arg.getYear() % 100 != 0) ||
((arg.getYear() + 1900) % 400 == 0))) {
result++;
}
return result;
}
}
| mit |
jurgendl/jhaws | jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/forms/common/FormElementSettings.java | 403 | package org.jhaws.common.web.wicket.forms.common;
@SuppressWarnings("serial")
public class FormElementSettings extends AbstractFormElementSettings<FormElementSettings> {
public FormElementSettings() {
super();
}
public FormElementSettings(boolean required) {
super(required);
}
public FormElementSettings(FormElementSettings other) {
super(other);
}
}
| mit |
nesbarse/sisane-server | src/main/java/net/daw/service/implementation/ImagenService.java | 13009 | /*
* Copyright (c) 2016 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane-server: Helps you to develop easily AJAX web applications
* by copying and modifying this Java Server.
*
* Sources at https://github.com/rafaelaznar/sisane-server
*
* sisane-server is distributed under the MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated imagenation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.daw.service.implementation;
import com.google.gson.Gson;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.daw.bean.implementation.ImagenBean;
import net.daw.bean.implementation.ReplyBean;
import net.daw.bean.implementation.UsuarioBean;
import net.daw.connection.publicinterface.ConnectionInterface;
import net.daw.dao.implementation.ImagenDao;
import net.daw.helper.statics.AppConfigurationHelper;
import static net.daw.helper.statics.AppConfigurationHelper.getSourceConnection;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.JsonMessage;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.ParameterCook;
import net.daw.service.publicinterface.TableServiceInterface;
import net.daw.service.publicinterface.ViewServiceInterface;
public class ImagenService implements TableServiceInterface, ViewServiceInterface {
protected HttpServletRequest oRequest = null;
public ImagenService(HttpServletRequest request) {
oRequest = request;
}
private Boolean checkpermission(String strMethodName) throws Exception {
UsuarioBean oPuserBean = (UsuarioBean) oRequest.getSession().getAttribute("userBean");
if (oPuserBean != null) {
return true;
} else {
return false;
}
}
@Override
public ReplyBean getcount() throws Exception {
if (this.checkpermission("getcount")) {
String data = null;
ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
data = JsonMessage.getJsonExpression(200, Long.toString(oImagenDao.getCount(alFilter)));
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return new ReplyBean(200, data);
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
@Override
public ReplyBean get() throws Exception {
if (this.checkpermission("get")) {
int id = ParameterCook.prepareId(oRequest);
String data = null;
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
ImagenBean oImagenBean = new ImagenBean(id);
oImagenBean = oImagenDao.get(oImagenBean, AppConfigurationHelper.getJsonMsgDepth());
Gson gson = AppConfigurationHelper.getGson();
data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(oImagenBean));
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return new ReplyBean(200, data);
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
@Override
public ReplyBean getall() throws Exception {
if (this.checkpermission("getall")) {
HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest));
ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
String data = null;
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
ArrayList<ImagenBean> arrBeans = oImagenDao.getAll(alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth());
data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans));
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return new ReplyBean(200, data);
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
@Override
public ReplyBean getpage() throws Exception {
if (this.checkpermission("getpage")) {
int intRegsPerPag = ParameterCook.prepareRpp(oRequest);
int intPage = ParameterCook.preparePage(oRequest);
HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest));
ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest));
String data = null;
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
List<ImagenBean> arrBeans = oImagenDao.getPage(intRegsPerPag, intPage, alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth());
data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans));
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return new ReplyBean(200, data);
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
@Override
public ReplyBean remove() throws Exception {
if (this.checkpermission("remove")) {
Integer id = ParameterCook.prepareId(oRequest);
String data = null;
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
oConnection.setAutoCommit(false);
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
data = JsonMessage.getJsonExpression(200, (String) oImagenDao.remove(id).toString());
oConnection.commit();
} catch (Exception ex) {
if (oConnection != null) {
oConnection.rollback();
}
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return new ReplyBean(200, data);
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
@Override
public ReplyBean set() throws Exception {
if (this.checkpermission("set")) {
String jason = ParameterCook.prepareJson(oRequest);
ReplyBean oReplyBean = new ReplyBean();
Connection oConnection = null;
ConnectionInterface oDataConnectionSource = null;
try {
oDataConnectionSource = getSourceConnection();
oConnection = oDataConnectionSource.newConnection();
oConnection.setAutoCommit(false);
ImagenDao oImagenDao = new ImagenDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
ImagenBean oImagenBean = new ImagenBean();
oImagenBean = AppConfigurationHelper.getGson().fromJson(jason, oImagenBean.getClass());
if (oImagenBean != null) {
Integer iResult = oImagenDao.set(oImagenBean);
if (iResult >= 1) {
oReplyBean.setCode(200);
oReplyBean.setJson(JsonMessage.getJsonExpression(200, iResult.toString()));
} else {
oReplyBean.setCode(500);
oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set"));
}
} else {
oReplyBean.setCode(500);
oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set"));
}
oConnection.commit();
} catch (Exception ex) {
if (oConnection != null) {
oConnection.rollback();
}
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oConnection != null) {
oConnection.close();
}
if (oDataConnectionSource != null) {
oDataConnectionSource.disposeConnection();
}
}
return oReplyBean;
} else {
return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
}
}
}
| mit |
DeckerCHAN/ParkingSearcher | src/main/java/com/decker/parkingSearch/entires/CityInfo.java | 1316 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Derek.CHAN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.decker.parkingSearch.entires;
import java.util.List;
public class CityInfo {
public String name;
public String url;
public List<Park> parks;
}
| mit |
controversial/APCS | codingbat/Logic-2/loneSum.java | 217 | public int loneSum(int a, int b, int c) {
int outa = a, outb = b, outc = c;
if (a == b) {outa = 0; outb = 0;}
if (b == c) {outb = 0; outc = 0;}
if (c == a) {outa = 0; outc = 0;}
return outa + outb + outc;
}
| mit |
drissamri/linkshortener | linkshortener-api/src/main/java/be/drissamri/rest/resource/LinkResource.java | 965 | package be.drissamri.rest.resource;
import be.drissamri.entity.LinkEntity;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
public class LinkResource extends Resource {
public LinkResource(UriInfo uri, LinkEntity link) {
super(uri, link.getHash());
put("url", link.getUrl());
put("hash", link.getHash());
put("shortUrl", buildUrl(uri, link.getHash()));
}
private String buildUrl(UriInfo context, String hash) {
final URI uri = context.getAbsolutePath();
final StringBuilder url = new StringBuilder();
url.append(uri.getScheme());
url.append("://");
url.append(uri.getHost());
final int port = uri.getPort();
if (port != -1) {
url.append(":");
url.append(uri.getPort());
}
url.append(uri.getPath().substring(0, uri.getPath().lastIndexOf('/') + 1));
url.append(hash);
return url.toString();
}
}
| mit |
bblue000/AndroidSampleFramework | AndroidFramework_v_2_0/src/org/ixming/android/view/GradientTextView.java | 4706 | package org.ixming.android.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.widget.TextView;
public class GradientTextView extends TextView {
private int[] mTextShaderColors = null;
private float[] mTextShaderPositions = null;
private boolean mIsTextShaderSet = false;
private boolean mForegroundShaderChanged = false;
private int[] mForegroundShaderColors = null;
private float[] mForegroundShaderPositions = null;
private Paint mForegroundPaint = new Paint();
private boolean mIsForegroundShaderSet = false;
public GradientTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initGradientTextView();
}
public GradientTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initGradientTextView();
}
public GradientTextView(Context context) {
super(context);
initGradientTextView();
}
private void initGradientTextView() {
}
private void setTextShader0(Shader shader) {
mIsTextShaderSet = (null != shader);
getPaint().setShader(shader);
}
/**
*
* @param colors The colors to be distributed along the gradient line
* @param positions May be null. The relative positions [0..1] of each corresponding color in the colors array.
* If this is null, the the colors are distributed evenly along the gradient line.
*/
public void setLinearGradientTextShader(int[] colors, float[] positions) {
setLinearGradientTextShader0(colors, positions);
postInvalidate();
}
private void setLinearGradientTextShader0(int[] colors, float[] positions) {
mTextShaderColors = colors;
mTextShaderPositions = positions;
if (null != mTextShaderColors && null != mTextShaderPositions) {
mIsTextShaderSet = true;
} else {
mIsTextShaderSet = false;
}
}
public void setForegroundShader(Shader shader) {
setForegroundShader0(shader);
postInvalidate();
}
private void setForegroundShader0(Shader shader) {
mIsForegroundShaderSet = (null != shader);
mForegroundPaint.setShader(shader);
}
public void setLinearGradientForegroundShader(int[] colors, float[] positions) {
setLinearGradientForegroundShader0(colors, positions);
postInvalidate();
}
private void setLinearGradientForegroundShader0(int[] colors, float[] positions) {
mForegroundShaderColors = colors;
mForegroundShaderPositions = positions;
if (null != mForegroundShaderColors && null != mForegroundShaderColors) {
mIsForegroundShaderSet = true;
} else {
mIsForegroundShaderSet = false;
}
mForegroundShaderChanged = true;
}
/**
* 因为渐变的缘故,会出现边缘处,颜色太纯,导致显示不满足需求;
* <p/>
* 此处预留设置,延伸相对于该View高度一定的比率,使得显示更符合要求。
* @return
*/
protected float getLinearGradientOffsetRatio() {
return 0.0F;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
if (mIsTextShaderSet) {
setTextShader0(new LinearGradient(getPaddingLeft() + getScrollX(),
getTotalPaddingTop() + getScrollY(),
getPaddingLeft() + getScrollX(),
getTotalPaddingTop() + getScrollY() + getHeight() * (1.0F + getLinearGradientOffsetRatio()),
mTextShaderColors, mTextShaderPositions, TileMode.CLAMP));
}
if (mForegroundShaderChanged) {
setForegroundShader0(new LinearGradient(getPaddingLeft(), getPaddingTop(),
getPaddingLeft(), getHeight() - getPaddingBottom(),
mForegroundShaderColors, mForegroundShaderPositions, TileMode.CLAMP));
mForegroundShaderChanged = false;
}
super.onDraw(canvas);
// Rect rect = new Rect(getPaddingLeft(), getPaddingTop(),
// getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
// canvas.drawRect(rect, mForegroundPaint);
if (mIsForegroundShaderSet) {
canvas.drawPaint(mForegroundPaint);
}
// GradientDrawable d = new GradientDrawable(Orientation.TOP_BOTTOM,
// new int[] { Color.TRANSPARENT, 0x88FFFFFF });
// d.setShape(GradientDrawable.RECTANGLE);
// d.setBounds(getPaddingLeft(), getPaddingTop(), getWidth()
// - getPaddingRight(), getHeight() - getPaddingBottom());
// d.setGradientType(GradientDrawable.LINEAR_GRADIENT);
// d.draw(canvas);
}
}
| mit |
talandar/ManaFluidics | src/main/java/derpatiel/manafluidics/compat/jei/castingchamber/CastingRecipeCategory.java | 3520 | package derpatiel.manafluidics.compat.jei.castingchamber;
import derpatiel.manafluidics.ManaFluidics;
import derpatiel.manafluidics.compat.jei.ManaFluidicsPlugin;
import derpatiel.manafluidics.enums.MaterialType;
import derpatiel.manafluidics.item.MFMoldItem;
import derpatiel.manafluidics.util.MaterialItemHelper;
import derpatiel.manafluidics.util.TextHelper;
import mezz.jei.api.gui.IDrawable;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CastingRecipeCategory implements IRecipeCategory {
private static final int MOLD_SLOT=0;
private static final int FLUID_SLOT=1;
private static final int OUTPUT_SLOT=2;
@Nonnull
private final String localizedName = TextHelper.localize("jei.manafluidics.recipe.castingchamber");
@Nonnull
private final IDrawable background = ManaFluidicsPlugin.jeiHelper.getGuiHelper().createDrawable(new ResourceLocation(ManaFluidics.MODID+":textures/gui/jei/drawnozzle.png"),0,80,84,40);
@Override
public String getUid() {
return ManaFluidicsPlugin.CAST_RECIPE_CATEGORY_ID;
}
@Override
public String getTitle() {
return localizedName;
}
@Override
public IDrawable getBackground() {
return background;
}
@Override
public void drawExtras(Minecraft minecraft) {
}
@Nullable
@Override
public IDrawable getIcon() {
return null;
}
@Override
public void drawAnimations(Minecraft minecraft) {
}
@Override
@Deprecated
public void setRecipe(IRecipeLayout recipeLayout, IRecipeWrapper recipeWrapper) {
}
@Override
public void setRecipe(IRecipeLayout recipeLayout, IRecipeWrapper recipeWrapper, IIngredients ingredients) {
recipeLayout.getFluidStacks().init(FLUID_SLOT, true, 9, 4, 16, 16, 4500, true, null);
recipeLayout.getItemStacks().init(MOLD_SLOT,true, 8, 21 );
recipeLayout.getItemStacks().init(OUTPUT_SLOT, false, 58, 11);
if (recipeWrapper instanceof CastingRecipeJEI)
{
FluidStack inputFluidStack = ingredients.getInputs(FluidStack.class).get(0).get(0);
recipeLayout.getFluidStacks().set(FLUID_SLOT, inputFluidStack);
recipeLayout.getItemStacks().set(MOLD_SLOT,ingredients.getInputs(ItemStack.class).get(0));
recipeLayout.getItemStacks().set(OUTPUT_SLOT, ingredients.getOutputs(ItemStack.class).get(0));
}
}
public static List<CastingRecipeJEI> getRecipes() {
ArrayList<CastingRecipeJEI> recipes = new ArrayList<>();
for(MFMoldItem mold : MaterialItemHelper.castingProducts.keySet()){
ItemStack moldStack = new ItemStack(mold);
Map<FluidStack,ItemStack> moldRecipes = MaterialItemHelper.castingProducts.get(mold);
for(FluidStack fluidStack : moldRecipes.keySet()){
ItemStack output = moldRecipes.get(fluidStack);
CastingRecipeJEI recipe = new CastingRecipeJEI(fluidStack,moldStack,output);
recipes.add(recipe);
}
}
return recipes;
}
}
| mit |
alangibson27/plus-f | plus-f/src/main/java/com/socialthingy/plusf/z80/operations/OpAddAIndexed8Reg.java | 1070 | package com.socialthingy.plusf.z80.operations;
import com.socialthingy.plusf.z80.Clock;
import com.socialthingy.plusf.z80.ContentionModel;
import com.socialthingy.plusf.z80.Processor;
import com.socialthingy.plusf.z80.Register;
public class OpAddAIndexed8Reg extends ArithmeticOperation {
private final Register register;
private final String toString;
public OpAddAIndexed8Reg(final Processor processor, final Register register, final boolean useCarryFlag) {
super(processor, useCarryFlag);
this.register = register;
if (useCarryFlag) {
this.toString = "adc a, " + register.name();
} else {
this.toString = "add a, " + register.name();
}
}
@Override
public void execute(ContentionModel contentionModel, int initialPcValue, int irValue) {
contentionModel.applyContention(initialPcValue, 4);
contentionModel.applyContention(initialPcValue + 1, 4);
add(register.get());
}
@Override
public String toString() {
return toString;
}
} | mit |
mnbogner/flickr-api | src/main/java/com/flickr/api/entities/LicensesResponse.java | 1445 | /*
* Copyright (C) 2014 Fabien Barbero
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.flickr.api.entities;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Fabien Barbero
*/
public class LicensesResponse extends ListResponse<License> {
@Override
protected License unmarshall(JSONObject json) throws JSONException {
return new License(json);
}
}
| mit |
fabienvuilleumier/fb | src/main/java/net/collaud/fablab/api/service/impl/SupplyTypeServiceImpl.java | 2211 | package net.collaud.fablab.api.service.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import net.collaud.fablab.api.dao.SupplyTypeRepository;
import net.collaud.fablab.api.data.SupplyTypeEO;
import net.collaud.fablab.api.security.Roles;
import net.collaud.fablab.api.service.SupplyTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* This is the service implementation class for a <tt>SupplyType</tt>.
* @author Fabien Vuilleumier
*/
@Service
@Transactional
@Secured({Roles.SUPPLY_MANAGE})
public class SupplyTypeServiceImpl implements SupplyTypeService {
@Autowired
private SupplyTypeRepository supplyTypeDAO;
@Override
@Secured({Roles.SUPPLY_MANAGE})
public List<SupplyTypeEO> findAll() {
return new ArrayList(new HashSet(supplyTypeDAO.findAll()));
}
@Override
@Secured({Roles.SUPPLY_MANAGE})
public Optional<SupplyTypeEO> getById(Integer id) {
return Optional.ofNullable(supplyTypeDAO.findOne(id));
}
@Override
@Secured({Roles.SUPPLY_MANAGE})
public SupplyTypeEO save(SupplyTypeEO supplyType) {
if (supplyType.getId() == null) {
supplyType.setId(0);
}
if (supplyType.getId() > 0) {
SupplyTypeEO old = supplyTypeDAO.findOne(supplyType.getId());
old.setLabel(supplyType.getLabel());
old.setSupplyList(supplyType.getSupplyList());
old.setActive(supplyType.isActive());
return supplyTypeDAO.saveAndFlush(old);
} else {
return supplyTypeDAO.saveAndFlush(supplyType);
}
}
@Override
@Secured({Roles.SUPPLY_MANAGE})
public void remove(Integer id) {
supplyTypeDAO.delete(id);
}
@Override
@Secured({Roles.SUPPLY_MANAGE})
public void softRemove(Integer id) {
SupplyTypeEO current = supplyTypeDAO.findOne(id);
current.setActive(false);
supplyTypeDAO.saveAndFlush(current);
}
}
| mit |
LUISGA64/ERM_WEB | src/main/java/com/erm/controller/PersonaController.java | 5038 | package com.erm.controller;
import com.erm.ejb.PersonaFacadeLocal;
import com.erm.model.Municipio;
import com.erm.model.NivelEducativo;
import com.erm.model.Ocupacion;
import com.erm.model.Parentesco;
import com.erm.model.Persona;
import com.erm.model.TipoDoc;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.inject.Named;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import org.primefaces.event.SelectEvent;
@ViewScoped
@Named
public class PersonaController implements Serializable {
@EJB
private PersonaFacadeLocal personaEJB;
private List<Persona> lstpersona;
private Persona selpersona;
private List<Persona> listpersona;
private Persona personaseleccionada;
@Inject
private Persona persona;
@Inject
private Municipio municipio;
@Inject
private TipoDoc tipodoc;
@Inject
private Ocupacion ocupacion;
@Inject
private Parentesco parentesco;
@Inject
private NivelEducativo niveleducativo;
@PostConstruct
public void init() {
lstpersona = personaEJB.findAll();
}
//getter y setter
public List<Persona> getListpersona() {
return listpersona;
}
public void setListpersona(List<Persona> listpersona) {
this.listpersona = listpersona;
}
public Persona getSelpersona() {
return selpersona;
}
public void setSelpersona(Persona selpersona) {
this.selpersona = selpersona;
}
public List<Persona> getLstpersona() {
return lstpersona;
}
public void setLstpersona(List<Persona> lstpersona) {
this.lstpersona = lstpersona;
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public Municipio getMunicipio() {
return municipio;
}
public void setMunicipio(Municipio municipio) {
this.municipio = municipio;
}
public Ocupacion getOcupacion() {
return ocupacion;
}
public void setOcupacion(Ocupacion ocupacion) {
this.ocupacion = ocupacion;
}
public Parentesco getParentesco() {
return parentesco;
}
public void setParentesco(Parentesco parentesco) {
this.parentesco = parentesco;
}
public NivelEducativo getNiveleducativo() {
return niveleducativo;
}
public void setNiveleducativo(NivelEducativo niveleducativo) {
this.niveleducativo = niveleducativo;
}
public Persona getPersonaseleccionada() {
return personaseleccionada;
}
public void setPersonaseleccionada(Persona personaseleccionada) {
this.personaseleccionada = personaseleccionada;
}
// Metodos
public void setlistpersona(List<Persona> listpersona) {
this.listpersona = listpersona;
}
public void registrar() {
try {
personaEJB.create(persona);
lstpersona = personaEJB.findAll();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Registro Exitoso."));
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Registro Falló."));
}
}
public void buscar(SelectEvent event){
Persona p1 = (Persona)event.getObject();
}
public static int calcularEdad(String fecha) {
String datetext = fecha;
try {
Calendar birth = new GregorianCalendar();
Calendar today = new GregorianCalendar();
int age = 0;
int factor = 0;
Date birthDate = new SimpleDateFormat("dd-MM-yyyy").parse(datetext);
Date currentDate = new Date(); //current date
birth.setTime(birthDate);
today.setTime(currentDate);
if (today.get(Calendar.MONTH) <= birth.get(Calendar.MONTH)) {
if (today.get(Calendar.MONTH) == birth.get(Calendar.MONTH)) {
if (today.get(Calendar.DATE) > birth.get(Calendar.DATE)) {
factor = -1; //Aun no celebra su cumpleaños
}
} else {
factor = -1; //Aun no celebra su cumpleaños
}
}
age = (today.get(Calendar.YEAR) - birth.get(Calendar.YEAR)) + factor;
return age;
} catch (ParseException e) {
return -1;
}
}
}
| mit |
sathley/AppacitiveQueryAdapterSample | app/src/main/java/com/appacitive/adaptersample/app/MainActivity.java | 2139 | package com.appacitive.adaptersample.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.appacitive.android.AppacitiveContext;
import com.appacitive.core.model.Environment;
import com.appacitive.core.query.AppacitiveQuery;
import com.appacitive.core.query.PropertyFilter;
import java.util.List;
public class MainActivity extends Activity {
ListView mListView;
AppacitiveObjectQueryAdapter mAdapter;
Button mNextButton;
Button mPreviousButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize appacitive context.
AppacitiveContext.initialize("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", Environment.sandbox, this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
mNextButton = (Button) findViewById(R.id.next);
mPreviousButton = (Button) findViewById(R.id.previous);
// In the listview, we will show all objects of schema type 'player' whose team is 'India'.
// Create the query accordingly
AppacitiveQuery query = new AppacitiveQuery();
query.pageNumber = 1;
query.pageSize = 5;
query.filter = new PropertyFilter("team").isEqualTo("India");
List<String> fields = null;
// Tell the adapter to fire this query on the 'player' schema type.
mAdapter = new AppacitiveObjectQueryAdapter(this, "player", fields, query);
mListView.setAdapter(mAdapter);
// attach next page button listener
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAdapter.getNextPage();
}
});
// attach previous page button listener
mPreviousButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAdapter.getPreviousPage();
}
});
}
}
| mit |
cookingfox/lapasse-java | lapasse/src/test/java/fixtures/message/store/FixtureMessageStore.java | 855 | package fixtures.message.store;
import com.cookingfox.lapasse.api.message.Message;
import com.cookingfox.lapasse.api.message.store.OnMessageAdded;
import com.cookingfox.lapasse.impl.message.store.AbstractMessageStore;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Minimal implementation of {@link AbstractMessageStore} that tracks added messages and immediately
* calls listeners.
*/
public class FixtureMessageStore extends AbstractMessageStore {
public final List<Message> addedMessages = new LinkedList<>();
@Override
public void addMessage(Message message) {
addedMessages.add(Objects.requireNonNull(message));
notifyMessageAdded(message);
}
public Set<OnMessageAdded> getMessageAddedListeners() {
return messageAddedListeners;
}
}
| mit |
aleroddepaz/java-samples | ejb-test/src/main/java/org/example/rest/MyEntity.java | 787 | package org.example.rest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 2, max = 20)
private String name;
public MyEntity() {
}
public MyEntity(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mit |
sebastianstock/chimp | src/main/java/htn/guessOrdering/GuessOrderingValOH.java | 333 | package htn.guessOrdering;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.ValueOrderingH;
public class GuessOrderingValOH extends ValueOrderingH {
@Override
public int compare(ConstraintNetwork cn0, ConstraintNetwork cn1) {
return cn1.getConstraints().length - cn0.getConstraints().length;
}
}
| mit |
servicosgoval/editor-de-servicos | src/main/java/br/gov/servicos/editor/conteudo/paginas/Pagina.java | 422 | package br.gov.servicos.editor.conteudo.paginas;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.Wither;
import static lombok.AccessLevel.PRIVATE;
@Data
@Wither
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = PRIVATE)
public class Pagina {
String tipo;
String nome;
String conteudo;
}
| mit |
TVPT/VoxelGunsmith | src/main/java/com/voxelplugineering/voxelsniper/brush/effect/morphological/LinearBlendMaterialOperation.java | 4052 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 The Voxel Plugineering Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.voxelplugineering.voxelsniper.brush.effect.morphological;
import com.voxelplugineering.voxelsniper.util.math.Maths;
import com.voxelplugineering.voxelsniper.world.World;
import com.voxelplugineering.voxelsniper.world.material.MaterialState;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Optional;
/**
* A {@link FilterOperation} for a linear blend effect.
*/
public class LinearBlendMaterialOperation implements FilterOperation
{
private int count;
private double maxDistance;
private Map<MaterialState, Double> mats;
/**
* Creates a new {@link LinearBlendMaterialOperation}.
*/
public LinearBlendMaterialOperation()
{
this.reset();
}
@Override
public String getName()
{
return "blend";
}
@Override
public boolean checkPosition(int x, int y, int z, int dx, int dy, int dz, World w, MaterialState m)
{
if (!(dx == 0 && dy == 0 && dz == 0))
{
// TODO: Use world bounds instead of hardcoded magical values from
// Minecraft.
int clampedY = Maths.clamp(y + dy, 0, 255);
MaterialState mat = w.getBlock(x + dx, clampedY, z + dz).get().getMaterial();
if (this.mats.containsKey(mat))
{
this.mats.put(mat, this.mats.get(mat) + Math.sqrt(dx * dx + dy * dy + dz * dz));
} else
{
this.mats.put(mat, Math.sqrt(dx * dx + dy * dy + dz * dz));
}
this.count++;
this.maxDistance = (Math.sqrt(dx * dx + dy * dy + dz * dz) > this.maxDistance) ? Math.sqrt(dx * dx + dy * dy + dz * dz)
: this.maxDistance;
}
return false;
}
@Override
public Optional<MaterialState> getResult()
{
// Select the material which occurred the most.
double n = 0;
MaterialState winner = null;
for (Map.Entry<MaterialState, Double> e : this.mats.entrySet())
{
if (this.count * this.maxDistance - e.getValue() > n)
{
winner = e.getKey();
n = e.getValue();
}
}
// If multiple materials occurred the most, the tie check will become
// true.
boolean tie = false;
for (Map.Entry<MaterialState, Double> e : this.mats.entrySet())
{
if (e.getValue() == n && !e.getKey().equals(winner))
{
tie = true;
break;
}
}
// If a tie is found, no change is made.
if (!tie)
{
return Optional.of(winner);
}
return Optional.of(null);
}
@Override
public void reset()
{
this.mats = Maps.newHashMapWithExpectedSize(10);
this.count = 0;
this.maxDistance = 0;
}
}
| mit |
hulop/MapService | MapService/src/hulop/hokoukukan/servlet/AdminServlet.java | 5809 | /*******************************************************************************
* Copyright (c) 2014, 2017 IBM Corporation, Carnegie Mellon University and others
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package hulop.hokoukukan.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import hulop.hokoukukan.bean.AuthBean;
import hulop.hokoukukan.bean.DatabaseBean;
/**
* Servlet implementation class ImportServlet
*/
@WebServlet("/api/admin")
@MultipartConfig(fileSizeThreshold = 0, maxFileSize = -1L, maxRequestSize = -1L)
public class AdminServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final AuthBean authBean = new AuthBean();
/**
* @see HttpServlet#HttpServlet()
*/
public AdminServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!authBean.hasRole(request, "admin")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
request.setCharacterEncoding("UTF-8");
String action = request.getParameter("action");
if ("zip-attachments".equals(action)) {
DatabaseBean.zipAttachments(response);
return;
}
response.setContentType("text/plain; charset=UTF-8");
if ("drop-database".equals(action)) {
DatabaseBean.dropDatabase();
response.getWriter().append("dropped database");
} else if ("remove-file".equals(action)) {
String fileName = request.getParameter("file");
if (fileName == null || fileName.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
DatabaseBean.removeFile(new File(fileName));
response.getWriter().append("removed " + fileName);
} else if ("list-files".equals(action)) {
System.out.println(DatabaseBean.listFiles());
PrintWriter writer = response.getWriter();
for (String file : DatabaseBean.listFiles()) {
writer.println(file);
}
} else if ("remove-attachment".equals(action)) {
String fileName = request.getParameter("file");
if (fileName == null || fileName.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
DatabaseBean.deleteAttachment(fileName);
response.getWriter().append("removed " + fileName);
} else if ("list-attachments".equals(action)) {
System.out.println(DatabaseBean.listAttachment());
PrintWriter writer = response.getWriter();
for (String file : DatabaseBean.listAttachment()) {
writer.println(file);
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String dataType = request.getParameter("type");
if (dataType == null) {
return;
}
for (Part part : request.getParts()) {
final String fileName = part.getSubmittedFileName();
if (fileName != null) {
System.out.println(fileName);
InputStream is = null;
try {
final File tempFile = saveTempFile(is = part.getInputStream());
if (tempFile != null && tempFile.exists()) {
new Thread(new Runnable() {
@Override
public void run() {
DatabaseBean.importMapData(tempFile, new File(fileName), dataType);
tempFile.delete();
}
}).start();
}
} finally {
if (is != null) {
is.close();
}
}
response.getWriter().append("importing " + fileName);
break;
}
}
}
private static File saveTempFile(InputStream is) {
File tempFile = null;
try {
tempFile = File.createTempFile("tempfile", ".tmp");
System.out.println(tempFile);
OutputStream os = null;
try {
os = new FileOutputStream(tempFile);
byte data[] = new byte[4096];
int len = 0;
while ((len = is.read(data, 0, data.length)) > 0) {
os.write(data, 0, len);
}
os.flush();
return tempFile;
} finally {
if (os != null) {
os.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
if (tempFile.exists()) {
tempFile.delete();
}
return null;
}
}
| mit |
chorsystem/middleware | messages/src/main/java/org/apache/ode/pmapi/ListAllInstances.java | 781 |
package org.apache.ode.pmapi;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "listAllInstances")
public class ListAllInstances {
}
| mit |
Trojka/AndroidDiagramming | androidDiagramming/src/main/java/be/trojkasoftware/android/data/DataGraphObserver.java | 102 | package be.trojkasoftware.android.data;
public interface DataGraphObserver {
void GraphChanged();
}
| mit |
pomortaz/azure-sdk-for-java | azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/implementation/DeletedSiteInner.java | 19837 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.implementation;
import org.joda.time.DateTime;
import java.util.List;
import com.microsoft.azure.management.appservice.UsageState;
import com.microsoft.azure.management.appservice.SiteAvailabilityState;
import com.microsoft.azure.management.appservice.HostNameSslState;
import com.microsoft.azure.management.appservice.HostingEnvironmentProfile;
import com.microsoft.azure.management.appservice.CloningInfo;
import com.microsoft.azure.management.appservice.SlotSwapStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.Resource;
/**
* A deleted app.
*/
@JsonFlatten
public class DeletedSiteInner extends Resource {
/**
* Time in UTC when the app was deleted.
*/
@JsonProperty(value = "properties.deletedTimestamp", access = JsonProperty.Access.WRITE_ONLY)
private DateTime deletedTimestamp;
/**
* Current state of the app.
*/
@JsonProperty(value = "properties.state", access = JsonProperty.Access.WRITE_ONLY)
private String state;
/**
* Hostnames associated with the app.
*/
@JsonProperty(value = "properties.hostNames", access = JsonProperty.Access.WRITE_ONLY)
private List<String> hostNames;
/**
* Name of the repository site.
*/
@JsonProperty(value = "properties.repositorySiteName", access = JsonProperty.Access.WRITE_ONLY)
private String repositorySiteName;
/**
* State indicating whether the app has exceeded its quota usage.
* Read-only. Possible values include: 'Normal', 'Exceeded'.
*/
@JsonProperty(value = "properties.usageState", access = JsonProperty.Access.WRITE_ONLY)
private UsageState usageState;
/**
* <code>true</code> if the app is enabled; otherwise,
* <code>false</code>. Setting this value to false disables the
* app (takes the app offline).
*/
@JsonProperty(value = "properties.enabled")
private Boolean enabled;
/**
* Enabled hostnames for the app.Hostnames need to be assigned (see
* HostNames) AND enabled. Otherwise,
* the app is not served on those hostnames.
*/
@JsonProperty(value = "properties.enabledHostNames", access = JsonProperty.Access.WRITE_ONLY)
private List<String> enabledHostNames;
/**
* Management information availability state for the app. Possible values
* include: 'Normal', 'Limited', 'DisasterRecoveryMode'.
*/
@JsonProperty(value = "properties.availabilityState", access = JsonProperty.Access.WRITE_ONLY)
private SiteAvailabilityState availabilityState;
/**
* Hostname SSL states are used to manage the SSL bindings for app's
* hostnames.
*/
@JsonProperty(value = "properties.hostNameSslStates")
private List<HostNameSslState> hostNameSslStates;
/**
* Resource ID of the associated App Service plan, formatted as:
* "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms/{appServicePlanName}".
*/
@JsonProperty(value = "properties.serverFarmId")
private String serverFarmId;
/**
* <code>true</code> if reserved; otherwise,
* <code>false</code>.
*/
@JsonProperty(value = "properties.reserved")
private Boolean reserved;
/**
* Last time the app was modified, in UTC. Read-only.
*/
@JsonProperty(value = "properties.lastModifiedTimeUtc", access = JsonProperty.Access.WRITE_ONLY)
private DateTime lastModifiedTimeUtc;
/**
* Configuration of the app.
*/
@JsonProperty(value = "properties.siteConfig")
private SiteConfigInner siteConfig;
/**
* Azure Traffic Manager hostnames associated with the app. Read-only.
*/
@JsonProperty(value = "properties.trafficManagerHostNames", access = JsonProperty.Access.WRITE_ONLY)
private List<String> trafficManagerHostNames;
/**
* Indicates whether app is deployed as a premium app.
*/
@JsonProperty(value = "properties.premiumAppDeployed", access = JsonProperty.Access.WRITE_ONLY)
private Boolean premiumAppDeployed;
/**
* <code>true</code> to stop SCM (KUDU) site when the app is
* stopped; otherwise, <code>false</code>. The default is
* <code>false</code>.
*/
@JsonProperty(value = "properties.scmSiteAlsoStopped")
private Boolean scmSiteAlsoStopped;
/**
* Specifies which deployment slot this app will swap into. Read-only.
*/
@JsonProperty(value = "properties.targetSwapSlot", access = JsonProperty.Access.WRITE_ONLY)
private String targetSwapSlot;
/**
* App Service Environment to use for the app.
*/
@JsonProperty(value = "properties.hostingEnvironmentProfile")
private HostingEnvironmentProfile hostingEnvironmentProfile;
/**
* Micro services like apps, logic apps.
*/
@JsonProperty(value = "properties.microService")
private String microService;
/**
* Name of gateway app associated with the app.
*/
@JsonProperty(value = "properties.gatewaySiteName")
private String gatewaySiteName;
/**
* <code>true</code> to enable client affinity;
* <code>false</code> to stop sending session affinity cookies,
* which route client requests in the same session to the same instance.
* Default is <code>true</code>.
*/
@JsonProperty(value = "properties.clientAffinityEnabled")
private Boolean clientAffinityEnabled;
/**
* <code>true</code> to enable client certificate
* authentication (TLS mutual authentication); otherwise,
* <code>false</code>. Default is
* <code>false</code>.
*/
@JsonProperty(value = "properties.clientCertEnabled")
private Boolean clientCertEnabled;
/**
* <code>true</code> to disable the public hostnames of the
* app; otherwise, <code>false</code>.
* If <code>true</code>, the app is only accessible via API
* management process.
*/
@JsonProperty(value = "properties.hostNamesDisabled")
private Boolean hostNamesDisabled;
/**
* List of IP addresses that the app uses for outbound connections (e.g.
* database access). Read-only.
*/
@JsonProperty(value = "properties.outboundIpAddresses", access = JsonProperty.Access.WRITE_ONLY)
private String outboundIpAddresses;
/**
* Size of the function container.
*/
@JsonProperty(value = "properties.containerSize")
private Integer containerSize;
/**
* Maximum allowed daily memory-time quota (applicable on dynamic apps
* only).
*/
@JsonProperty(value = "properties.dailyMemoryTimeQuota")
private Integer dailyMemoryTimeQuota;
/**
* App suspended till in case memory-time quota is exceeded.
*/
@JsonProperty(value = "properties.suspendedTill", access = JsonProperty.Access.WRITE_ONLY)
private DateTime suspendedTill;
/**
* Maximum number of workers.
* This only applies to Functions container.
*/
@JsonProperty(value = "properties.maxNumberOfWorkers", access = JsonProperty.Access.WRITE_ONLY)
private Integer maxNumberOfWorkers;
/**
* If specified during app creation, the app is cloned from a source app.
*/
@JsonProperty(value = "properties.cloningInfo")
private CloningInfo cloningInfo;
/**
* Name of the resource group the app belongs to. Read-only.
*/
@JsonProperty(value = "properties.resourceGroup", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGroup;
/**
* <code>true</code> if the app is a default container;
* otherwise, <code>false</code>.
*/
@JsonProperty(value = "properties.isDefaultContainer", access = JsonProperty.Access.WRITE_ONLY)
private Boolean isDefaultContainer;
/**
* Default hostname of the app. Read-only.
*/
@JsonProperty(value = "properties.defaultHostName", access = JsonProperty.Access.WRITE_ONLY)
private String defaultHostName;
/**
* Status of the last deployment slot swap operation.
*/
@JsonProperty(value = "properties.slotSwapStatus", access = JsonProperty.Access.WRITE_ONLY)
private SlotSwapStatus slotSwapStatus;
/**
* Get the deletedTimestamp value.
*
* @return the deletedTimestamp value
*/
public DateTime deletedTimestamp() {
return this.deletedTimestamp;
}
/**
* Get the state value.
*
* @return the state value
*/
public String state() {
return this.state;
}
/**
* Get the hostNames value.
*
* @return the hostNames value
*/
public List<String> hostNames() {
return this.hostNames;
}
/**
* Get the repositorySiteName value.
*
* @return the repositorySiteName value
*/
public String repositorySiteName() {
return this.repositorySiteName;
}
/**
* Get the usageState value.
*
* @return the usageState value
*/
public UsageState usageState() {
return this.usageState;
}
/**
* Get the enabled value.
*
* @return the enabled value
*/
public Boolean enabled() {
return this.enabled;
}
/**
* Set the enabled value.
*
* @param enabled the enabled value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withEnabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the enabledHostNames value.
*
* @return the enabledHostNames value
*/
public List<String> enabledHostNames() {
return this.enabledHostNames;
}
/**
* Get the availabilityState value.
*
* @return the availabilityState value
*/
public SiteAvailabilityState availabilityState() {
return this.availabilityState;
}
/**
* Get the hostNameSslStates value.
*
* @return the hostNameSslStates value
*/
public List<HostNameSslState> hostNameSslStates() {
return this.hostNameSslStates;
}
/**
* Set the hostNameSslStates value.
*
* @param hostNameSslStates the hostNameSslStates value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withHostNameSslStates(List<HostNameSslState> hostNameSslStates) {
this.hostNameSslStates = hostNameSslStates;
return this;
}
/**
* Get the serverFarmId value.
*
* @return the serverFarmId value
*/
public String serverFarmId() {
return this.serverFarmId;
}
/**
* Set the serverFarmId value.
*
* @param serverFarmId the serverFarmId value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withServerFarmId(String serverFarmId) {
this.serverFarmId = serverFarmId;
return this;
}
/**
* Get the reserved value.
*
* @return the reserved value
*/
public Boolean reserved() {
return this.reserved;
}
/**
* Set the reserved value.
*
* @param reserved the reserved value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withReserved(Boolean reserved) {
this.reserved = reserved;
return this;
}
/**
* Get the lastModifiedTimeUtc value.
*
* @return the lastModifiedTimeUtc value
*/
public DateTime lastModifiedTimeUtc() {
return this.lastModifiedTimeUtc;
}
/**
* Get the siteConfig value.
*
* @return the siteConfig value
*/
public SiteConfigInner siteConfig() {
return this.siteConfig;
}
/**
* Set the siteConfig value.
*
* @param siteConfig the siteConfig value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withSiteConfig(SiteConfigInner siteConfig) {
this.siteConfig = siteConfig;
return this;
}
/**
* Get the trafficManagerHostNames value.
*
* @return the trafficManagerHostNames value
*/
public List<String> trafficManagerHostNames() {
return this.trafficManagerHostNames;
}
/**
* Get the premiumAppDeployed value.
*
* @return the premiumAppDeployed value
*/
public Boolean premiumAppDeployed() {
return this.premiumAppDeployed;
}
/**
* Get the scmSiteAlsoStopped value.
*
* @return the scmSiteAlsoStopped value
*/
public Boolean scmSiteAlsoStopped() {
return this.scmSiteAlsoStopped;
}
/**
* Set the scmSiteAlsoStopped value.
*
* @param scmSiteAlsoStopped the scmSiteAlsoStopped value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withScmSiteAlsoStopped(Boolean scmSiteAlsoStopped) {
this.scmSiteAlsoStopped = scmSiteAlsoStopped;
return this;
}
/**
* Get the targetSwapSlot value.
*
* @return the targetSwapSlot value
*/
public String targetSwapSlot() {
return this.targetSwapSlot;
}
/**
* Get the hostingEnvironmentProfile value.
*
* @return the hostingEnvironmentProfile value
*/
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return this.hostingEnvironmentProfile;
}
/**
* Set the hostingEnvironmentProfile value.
*
* @param hostingEnvironmentProfile the hostingEnvironmentProfile value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withHostingEnvironmentProfile(HostingEnvironmentProfile hostingEnvironmentProfile) {
this.hostingEnvironmentProfile = hostingEnvironmentProfile;
return this;
}
/**
* Get the microService value.
*
* @return the microService value
*/
public String microService() {
return this.microService;
}
/**
* Set the microService value.
*
* @param microService the microService value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withMicroService(String microService) {
this.microService = microService;
return this;
}
/**
* Get the gatewaySiteName value.
*
* @return the gatewaySiteName value
*/
public String gatewaySiteName() {
return this.gatewaySiteName;
}
/**
* Set the gatewaySiteName value.
*
* @param gatewaySiteName the gatewaySiteName value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withGatewaySiteName(String gatewaySiteName) {
this.gatewaySiteName = gatewaySiteName;
return this;
}
/**
* Get the clientAffinityEnabled value.
*
* @return the clientAffinityEnabled value
*/
public Boolean clientAffinityEnabled() {
return this.clientAffinityEnabled;
}
/**
* Set the clientAffinityEnabled value.
*
* @param clientAffinityEnabled the clientAffinityEnabled value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withClientAffinityEnabled(Boolean clientAffinityEnabled) {
this.clientAffinityEnabled = clientAffinityEnabled;
return this;
}
/**
* Get the clientCertEnabled value.
*
* @return the clientCertEnabled value
*/
public Boolean clientCertEnabled() {
return this.clientCertEnabled;
}
/**
* Set the clientCertEnabled value.
*
* @param clientCertEnabled the clientCertEnabled value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withClientCertEnabled(Boolean clientCertEnabled) {
this.clientCertEnabled = clientCertEnabled;
return this;
}
/**
* Get the hostNamesDisabled value.
*
* @return the hostNamesDisabled value
*/
public Boolean hostNamesDisabled() {
return this.hostNamesDisabled;
}
/**
* Set the hostNamesDisabled value.
*
* @param hostNamesDisabled the hostNamesDisabled value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withHostNamesDisabled(Boolean hostNamesDisabled) {
this.hostNamesDisabled = hostNamesDisabled;
return this;
}
/**
* Get the outboundIpAddresses value.
*
* @return the outboundIpAddresses value
*/
public String outboundIpAddresses() {
return this.outboundIpAddresses;
}
/**
* Get the containerSize value.
*
* @return the containerSize value
*/
public Integer containerSize() {
return this.containerSize;
}
/**
* Set the containerSize value.
*
* @param containerSize the containerSize value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withContainerSize(Integer containerSize) {
this.containerSize = containerSize;
return this;
}
/**
* Get the dailyMemoryTimeQuota value.
*
* @return the dailyMemoryTimeQuota value
*/
public Integer dailyMemoryTimeQuota() {
return this.dailyMemoryTimeQuota;
}
/**
* Set the dailyMemoryTimeQuota value.
*
* @param dailyMemoryTimeQuota the dailyMemoryTimeQuota value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withDailyMemoryTimeQuota(Integer dailyMemoryTimeQuota) {
this.dailyMemoryTimeQuota = dailyMemoryTimeQuota;
return this;
}
/**
* Get the suspendedTill value.
*
* @return the suspendedTill value
*/
public DateTime suspendedTill() {
return this.suspendedTill;
}
/**
* Get the maxNumberOfWorkers value.
*
* @return the maxNumberOfWorkers value
*/
public Integer maxNumberOfWorkers() {
return this.maxNumberOfWorkers;
}
/**
* Get the cloningInfo value.
*
* @return the cloningInfo value
*/
public CloningInfo cloningInfo() {
return this.cloningInfo;
}
/**
* Set the cloningInfo value.
*
* @param cloningInfo the cloningInfo value to set
* @return the DeletedSiteInner object itself.
*/
public DeletedSiteInner withCloningInfo(CloningInfo cloningInfo) {
this.cloningInfo = cloningInfo;
return this;
}
/**
* Get the resourceGroup value.
*
* @return the resourceGroup value
*/
public String resourceGroup() {
return this.resourceGroup;
}
/**
* Get the isDefaultContainer value.
*
* @return the isDefaultContainer value
*/
public Boolean isDefaultContainer() {
return this.isDefaultContainer;
}
/**
* Get the defaultHostName value.
*
* @return the defaultHostName value
*/
public String defaultHostName() {
return this.defaultHostName;
}
/**
* Get the slotSwapStatus value.
*
* @return the slotSwapStatus value
*/
public SlotSwapStatus slotSwapStatus() {
return this.slotSwapStatus;
}
}
| mit |
kalyandechiraju/track-my-order | app/src/main/java/com/challengers/trackmyorder/LoginActivity.java | 1906 | package com.challengers.trackmyorder;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.challengers.trackmyorder.util.Constants;
public class LoginActivity extends AppCompatActivity {
EditText userIdEditText,userPassEditText;
String userName,userPass, loginType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_dboy);
setTitle("Login");
userIdEditText = (EditText) findViewById(R.id.userName);
userPassEditText = (EditText) findViewById(R.id.userPass);
loginType = getIntent().getStringExtra(Constants.LOGINTYPE);
}
public void doLogin(View v){
userName = userIdEditText.getText().toString();
userPass = userPassEditText.getText().toString();
String usernameString = "delboy1";
if(loginType.equals("D")) {
if (userName.equals(usernameString) && userPass.equals("d")) {
Intent intent = new Intent(this, DboyActivity.class);
intent.putExtra(Constants.CURRENT_DELBOY, usernameString);
startActivity(intent);
} else {
Toast.makeText(this, "Wrong Username or Password", Toast.LENGTH_SHORT).show();
}
} else {
String userId = "kalyan123";
if (userName.equals(userId) && userPass.equals("k")) {
Intent intent = new Intent(this, ShowUserOrdersActivity.class);
intent.putExtra(Constants.CURRENT_USER, userId);
startActivity(intent);
} else {
Toast.makeText(this, "Wrong Username or Password", Toast.LENGTH_SHORT).show();
}
}
}
}
| mit |
munificent/magpie-optionally-typed | src/com/stuffwithstuff/magpie/interpreter/builtin/FieldProperty.java | 1355 | package com.stuffwithstuff.magpie.interpreter.builtin;
import java.util.List;
import com.stuffwithstuff.magpie.ast.Expr;
import com.stuffwithstuff.magpie.interpreter.Callable;
import com.stuffwithstuff.magpie.interpreter.Checker;
import com.stuffwithstuff.magpie.interpreter.ClassObj;
import com.stuffwithstuff.magpie.interpreter.Interpreter;
import com.stuffwithstuff.magpie.interpreter.Obj;
import com.stuffwithstuff.magpie.util.Expect;
/**
* Built-in callable that returns the value of a named field.
*/
public abstract class FieldProperty implements Callable {
public FieldProperty(String name, Expr expr, boolean isInitializer) {
Expect.notEmpty(name);
Expect.notNull(expr);
mName = name;
mExpr = expr;
mIsInitializer = isInitializer;
}
public Callable bindTo(ClassObj classObj) {
return this;
}
@Override
public abstract Obj invoke(Interpreter interpreter, Obj thisObj,
List<Obj> typeArgs, Obj arg);
public Obj getType(Interpreter interpreter) {
if (mIsInitializer) {
Checker checker = new Checker(interpreter);
return checker.evaluateExpressionType(mExpr);
} else {
return interpreter.evaluate(mExpr);
}
}
protected String getName() { return mName; }
private final String mName;
private final Expr mExpr;
private final boolean mIsInitializer;
}
| mit |
slagyr/limelight | src/limelight/About.java | 289 | //- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved.
//- Limelight and all included source files are distributed under terms of the MIT License.
package limelight;
import limelight.util.Version;
public class About
{
public static Version version = new Version(0, 6, 19);
}
| mit |
yzhnasa/TASSEL-iRods | src/net/maizegenetics/trait/MarkerPhenotype.java | 5590 | package net.maizegenetics.trait;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.dna.snp.FilterGenotypeTable;
import net.maizegenetics.trait.FilterPhenotype;
import net.maizegenetics.util.TableReport;
import net.maizegenetics.taxa.IdGroupUtils;
import net.maizegenetics.taxa.TaxaList;
/**
* @author terry
*/
public class MarkerPhenotype implements TableReport {
private GenotypeTable myAlignment; //alignment to hold markers
private Phenotype myPhenotype; //alignment to hold characters
/**
* Constructor
*
* @param alignment alignment
* @param phenotype phenotype
*/
private MarkerPhenotype(GenotypeTable alignment, Phenotype phenotype) {
myAlignment = alignment;
myPhenotype = phenotype;
}
public static MarkerPhenotype getInstance(GenotypeTable aa, Phenotype ca, boolean union) {
TaxaList idGroup = getIdGroup(aa.taxa(), ca.getTaxa(), union);
GenotypeTable align = FilterGenotypeTable.getInstance(aa, idGroup);
Phenotype phenotype = FilterPhenotype.getInstance(ca, idGroup, null);
return new MarkerPhenotype(align, phenotype);
}
public static MarkerPhenotype getInstance(MarkerPhenotype aac, TaxaList group) {
GenotypeTable aa = FilterGenotypeTable.getInstance(aac.getAlignment(), group);
Phenotype ca = FilterPhenotype.getInstance(aac.getPhenotype(), group, null);
return new MarkerPhenotype(aa, ca);
}
private static TaxaList getIdGroup(TaxaList group1, TaxaList group2, boolean union) {
if (union) {
return IdGroupUtils.getAllIds(group1, group2);
} else {
return IdGroupUtils.getCommonIds(group1, group2);
}
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(" ");
builder.append(myAlignment.numberOfTaxa());
builder.append(" ");
builder.append(myPhenotype.getNumberOfTraits());
builder.append("Taxa/Trait\t");
for (int j = 0; j < myPhenotype.getNumberOfTraits(); j++) {
builder.append(myPhenotype.getTrait(j).getName());
builder.append("\t");
}
builder.append("\n");
for (int i = 0; i < myAlignment.numberOfTaxa(); i++) {
builder.append(myAlignment.taxaName(i));
builder.append("\t");
for (int j = 0; j < myPhenotype.getNumberOfTraits(); j++) {
builder.append(myPhenotype.getData(i, j));
builder.append("\t");
}
builder.append(myAlignment.genotypeAsStringRow(i));
}
return builder.toString();
}
public GenotypeTable getAlignment() {
return myAlignment;
}
public Phenotype getPhenotype() {
return myPhenotype;
}
public Object[] getTableColumnNames() {
String[] basicLabels = new String[myPhenotype.getNumberOfTraits() + 2];
basicLabels[0] = "Taxa";
for (int c = 0; c < myPhenotype.getNumberOfTraits(); c++) {
basicLabels[c + 1] = myPhenotype.getTrait(c).getName();
}
basicLabels[myPhenotype.getNumberOfTraits() + 1] = "Haplotype";
return basicLabels;
}
public Object[][] getTableData() {
return getTableData(0, getRowCount() - 1);
}
public String getTableTitle() {
return "Phenotypes and Genotypes";
}
public int getColumnCount() {
return myPhenotype.getNumberOfTraits() + 2;
}
public int getRowCount() {
return myAlignment.numberOfTaxa();
}
public int getElementCount() {
return getRowCount() * getColumnCount();
}
public Object[] getRow(int row) {
Object[] data;
data = new String[myPhenotype.getNumberOfTraits() + 2];
data[0] = myAlignment.taxaName(row);
for (int c = 0; c < myPhenotype.getNumberOfTraits(); c++) {
data[c + 1] = "" + myPhenotype.getData(row, c);
}
int siteCount = Math.min(myAlignment.numberOfSites(), 10);
StringBuilder builder = new StringBuilder();
builder.append(myAlignment.genotypeAsStringRange(row, 0, siteCount));
if (myAlignment.numberOfSites() > 10) {
builder.append("...");
}
data[myPhenotype.getNumberOfTraits() + 1] = builder.toString();
return data;
}
public Object[][] getTableData(int start, int end) {
if ((start < 0) || (end >= getRowCount())) {
throw new IndexOutOfBoundsException("getTableData: start: " + start + " end: " + end);
}
if (end < start) {
return null;
}
Object[][] temp = new Object[end - start + 1][];
for (int i = start; i <= end; i++) {
temp[i] = getRow(i);
}
return temp;
}
public Object getValueAt(int row, int col) {
int haplotypeColumn = myPhenotype.getColumnCount();
if (col == haplotypeColumn) {
int siteCount = Math.min(myAlignment.numberOfSites(), 10);
StringBuilder builder = new StringBuilder();
builder.append(myAlignment.genotypeAsStringRange(row, 0, siteCount));
if (myAlignment.numberOfSites() > 10) {
builder.append("...");
}
return builder.toString();
}
return myPhenotype.getValueAt(row, col);
}
}
| mit |
kennylbj/concurrent-java | src/main/java/observer/Observer.java | 125 | package observer;
/**
* Created by kennylbj on 16/8/28.
*/
public interface Observer {
void onNotify(String topic);
}
| mit |
Oruss7/Guilds | src/guilds/GuildsBasic.java | 3655 | package guilds;
import org.bukkit.plugin.java.*;
import org.bukkit.plugin.*;
import guilds.listeners.*;
import org.bukkit.event.*;
import guilds.commands.*;
import org.bukkit.command.*;
import java.util.logging.*;
import com.sk89q.worldguard.bukkit.*;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.Player;
public class GuildsBasic extends JavaPlugin {
private final Plugin wg;
public String chatFormat;
public String v;
private Map<UUID, User> players;
public Map<UUID, Guild> guilds;
private Config config;
public GuildsBasic() {
this.wg = null;
this.v = "0.0.0";
this.players = new HashMap<>();
this.guilds = new HashMap<>();
}
@Override
public void onEnable() {
(this.config = new Config(this)).start();
this.getLogger().info("Loaded configuration!");
this.getServer().getPluginManager().registerEvents((Listener) new PlayerListener(this), (Plugin) this);
this.getCommand("guilds").setExecutor((CommandExecutor) new Commands(this));
this.getCommand("gtp").setExecutor((CommandExecutor) new Commands(this));
this.getCommand("gchat").setExecutor((CommandExecutor) new Commands(this));
this.getLogger().info("Registered commands, listeners!");
this.clearScheduler();
this.v = this.getDescription().getVersion();
this.getLogger().log(Level.INFO, "Guilds v.{0} enabled !", this.v);
}
@Override
public void onDisable() {
this.clearScheduler();
this.getLogger().log(Level.INFO, "Guilds disabled !");
}
public User getUser(final UUID player) {
return this.players.get(player);
}
public Map<UUID, User> getPlayers() {
return this.players;
}
public void addPlayers(final User user) {
this.players.put(user.getOfflinePlayer().getUniqueId(), user);
}
public void removePlayer(final User user) {
if (user == null) {
return;
}
Player player = user.getPlayer();
if (player == null) {
return;
}
this.players.remove(player.getUniqueId());
}
public String getMessage(final String path) {
return this.config.messagesYML.getConfig().getString("Message." + path).replaceAll("&", "§");
}
private WorldGuardPlugin getWorldGuard() throws Exception {
final Plugin plugin = this.getServer().getPluginManager().getPlugin("WorldGuard");
if (plugin == null || !(plugin instanceof WorldGuardPlugin)) {
return null;
}
return (WorldGuardPlugin) plugin;
}
public void addGuild(final Guild g) {
this.guilds.put(g.getId(), g);
}
public Guild getGuild(final String guildName) {
for (final Map.Entry<UUID, Guild> entry : this.guilds.entrySet()) {
final Guild guild = entry.getValue();
if (guild.getName().equalsIgnoreCase(guildName)) {
return guild;
}
}
return null;
}
public List<Guild> getGuilds() {
return new ArrayList<>(this.guilds.values());
}
public Guild getGuild(final UUID guildId) {
return this.guilds.get(guildId);
}
public void removeGuild(final Guild g) {
this.guilds.remove(g.getId());
}
public void clearScheduler() {
Bukkit.getScheduler().cancelTasks((Plugin) this);
}
public Config getConfiguration() {
return this.config;
}
public void sendConsole(final String message) {
this.getLogger().log(Level.INFO, message.replaceAll("&([0-9a-fk-or])", ""));
}
}
| mit |
wdxzs1985/tongrenlu | tongrenlu/src/main/java/info/tongrenlu/domain/AccessBean.java | 615 | package info.tongrenlu.domain;
public class AccessBean extends DtoBean {
/**
*
*/
private static final long serialVersionUID = 1L;
private ArticleBean articleBean;
private UserBean userBean;
public ArticleBean getArticleBean() {
return this.articleBean;
}
public void setArticleBean(final ArticleBean articleBean) {
this.articleBean = articleBean;
}
public UserBean getUserBean() {
return this.userBean;
}
public void setUserBean(final UserBean userBean) {
this.userBean = userBean;
}
}
| mit |
sbearcsiro/functional-test-harness | library/src/main/java/au/org/ala/test/FileResolver.java | 984 | package au.org.ala.test;
import lombok.val;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.nio.file.Paths;
public class FileResolver implements Resolver {
private final File file;
public FileResolver(String path) {
this.file = new File(path);
}
@Override
public Reader getConfigFileReader() throws FileNotFoundException {
return new FileReader(file);
}
@Override
public Reader resolve(String path) throws FileNotFoundException {
val segment = Paths.get(path);
final File file2;
if (segment.isAbsolute()) {
file2 = segment.toFile();
} else {
val parent = file.getAbsoluteFile().getParentFile();
val parentPath = parent.toPath();
val resolvedPath = parentPath.resolve(segment);
file2 = resolvedPath.toFile();
}
return new FileReader(file2);
}
}
| mit |
Seriell/RC24-Bot | src/main/java/xyz/rc24/bot/listeners/DataDogStatsListener.java | 2239 | /*
* MIT License
*
* Copyright (c) 2017-2020 RiiConnect24 and its contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package xyz.rc24.bot.listeners;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.CommandListener;
import com.timgroup.statsd.StatsDClient;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class DataDogStatsListener extends ListenerAdapter implements CommandListener
{
private final StatsDClient statsd;
public DataDogStatsListener(StatsDClient statsd)
{
this.statsd = statsd;
}
@Override
public void onGuildJoin(GuildJoinEvent event)
{
statsd.recordGaugeValue("guilds", event.getJDA().getGuildCache().size());
}
@Override
public void onGuildLeave(GuildLeaveEvent event)
{
statsd.recordGaugeValue("guilds", event.getJDA().getGuildCache().size());
}
@Override
public void onCommand(CommandEvent event, Command command)
{
statsd.incrementCounter("commands");
}
}
| mit |
just-4-fun/Po.Grom | AndroidLib/src/cyua/android/core/location/LocationService.java | 13451 | package cyua.android.core.location;
import java.util.ConcurrentModificationException;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import cyua.android.core.AppCore;
import cyua.android.core.AppCore.AppService;
import cyua.android.core.location.LocationProcessor.ProcessorListener;
import cyua.android.core.location.LocationSource.SrcConf;
import cyua.android.core.log.Wow;
import cyua.android.core.misc.Listeners;
import cyua.android.core.misc.Tiker;
import cyua.android.core.misc.Tool;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import static cyua.android.core.AppCore.D;
public class LocationService extends AppService implements
ProcessorListener, LocationSource.iLocationSourceListener {
private static final String TAG = LocationService.class.getSimpleName();
//
static final String GPS = LocationManager.GPS_PROVIDER;
static final String NET = LocationManager.NETWORK_PROVIDER;
static final String PASSIVE = LocationManager.PASSIVE_PROVIDER;
//
static final long TIK_DELAY = 5000;
//
private static LocationService I;
//FIXME remove
public static StringBuilder textinfo = new StringBuilder();
/** STATIC INIT */
public static AppService instantiate() {
if (I != null) return I;
I = new LocationService();
I.initOrder = AppService.INIT_MID;
I.exitOrder = AppService.EXIT_MID;
return I;
}
public static LocationService getInstance() {
return I;
}
public static boolean isAvailable() {
return I != null && I.isAvailable;
}
public static boolean isGpsAvailable() {
return isAvailable() && I.hasGps;
}
public static boolean isGpsActive() {
return isGpsAvailable() && I.isGpsOn();
}
public static boolean hasGpsSignal() {
return isAvailable() && I.hasGpsSignal;
}
public static void addListener(LocationServiceListener listener, boolean getNow) {
if (!isAvailable()) return;
I.listeners.add(listener);
if (getNow && I.isAvailable)
listener.onSignalStateChanged(I.hasGpsSignal, I.gpsState, I.isGpsEnabled(), I.isNetEnabled());
}
public static void removeListener(LocationServiceListener listener) {
if (!isAvailable()) return;
I.listeners.remove(listener);
}
public static void resumeService() {
if (isAvailable()) I.doPause(false);
}
public static void pauseService() {
if (isAvailable()) I.doPause(true);
}
public static void flushData() {
if (isAvailable()) I.flush();
}
public static Mode getMode() {
return isAvailable() ? I.mode : null;
}
public static void setMode(Mode mode) {
if (!isAvailable()) return;
I.newMode = mode;
}
public static Fix getLastValidFix() {
return I == null ? null : I.validFix;
}
public static Fix getLastAvailableFix() {
return I == null ? null : I.availFix;
}
public static Fix getLastKnownFix() {
LocationManager man = ((LocationManager) AppCore.context().getSystemService(Context.LOCATION_SERVICE));
Location lnl = man.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lnl == null) lnl = man.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (lnl == null) lnl = man.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lnl == null) lnl = new Location("null");
Fix fix = new Fix(lnl);
fix.provider = "";
return fix;
}
public static float getSpeedKmph() {
return isAvailable() ? I.doGetSpeed() : -1;
}
public static String getTailKml() {
return isAvailable() ? I.doGetTailKml() : "";
}
public static String pointOpenTag() {
return "<Point><coordinates>";
}
public static String pointCloseTag() {
return "</coordinates></Point>";
}
public static String lineOpenTag() {
return "<LineString><coordinates>";
}
public static String lineCloseTag() {
return "</coordinates></LineString>";
}
/** INSTATNCE */
private enum Op {
TIC;
}
private Tiker<Op> tiker;
private LocationProcessor processor;
private LocationManager manager;
private Mode mode, newMode;
private LocationSource gpsSource, netSource, pasSource;
//
protected boolean hasGps, hasNet;
protected boolean gpsOn, netOn;
protected boolean isAvailable;
//
SignalState gpsState;
boolean isPaused;
boolean hasGpsSignal;
boolean isMoving;
private Fix validFix, availFix;
//
private Listeners<LocationServiceListener> listeners = new Listeners<LocationServiceListener>();
private final long TAIL_SPAN_5 = 5 * 60 * 1000;
private LinkedList<Fix> tail;
private int lastSpeed = -1;
/** PUBLIC API */
private void doPause(boolean yes) {
isPaused = yes;
}
/** APPSERVICE Methods */
@Override public void onInitStart(AppCore app) throws Throwable {
manager = (LocationManager) AppCore.context().getSystemService(Context.LOCATION_SERVICE);
hasGps = manager.getProvider(GPS) != null;
hasNet = manager.getProvider(NET) != null;
gpsOn = isGpsOn();
netOn = isNetOn();
isAvailable = hasGps || hasNet;
hasGpsSignal = true;
//
if (!isAvailable) {manager = null; return;}
//
if (newMode == null) newMode = Mode.ECONOM;
tiker = new Tiker<Op>(TAG) {
@Override public void handleTik(Op op, Object obj, Bundle data) {
if (op == Op.TIC) tik();
}
};
//
tail = new LinkedList<Fix>();
processor = new LocationProcessor(this);
//FIXME remove
textinfo = new StringBuilder();
}
@Override public String onInitFinish(AppCore app) throws Throwable {
if (!isAvailable) return null;
tik();
return super.onInitFinish(app);
}
@Override public void onExitStart(AppCore app) throws Throwable {
if (!isAvailable) return;
//
if (gpsSource != null) gpsSource.destroy();
if (netSource != null) netSource.destroy();
if (pasSource != null) pasSource.destroy();
tiker.clear();
}
@Override public void onExitFinish(AppCore app) throws Throwable {
listeners.clear();
if (!isAvailable) return;
//
if (tiker != null) tiker.clear();
tiker = null;
gpsSource = netSource = pasSource = null;
tail = null;
processor = null;
manager = null;
newMode = mode = null;
isAvailable = isPaused = hasGpsSignal = isMoving = false;
gpsState = null;
validFix = availFix = null;
}
@Override public String getStateInfo() {
return "Gps (Avail/Enab/On)=(" + hasGps + " / " + isGpsEnabled() + " / " + (gpsSource != null) + "), Net (Avail/Enab/On)=(" + hasNet + " / " + isNetEnabled() + " / " + (netSource != null) + "); sinceLastFix = " + (availFix == null ? "X" : (int) ((Tool.now() - availFix.uptime) / 1000)) + "; sinceValidFix = " + (validFix == null ? "X" : (int) ((Tool.now() - validFix.uptime) / 1000)) + "; mode = " + mode + "; gpsState = " + gpsState;
}
/** OTHER */
public boolean isGpsEnabled() {
return manager != null && manager.isProviderEnabled(GPS);
}
public boolean isNetEnabled() {
return manager != null && manager.isProviderEnabled(NET);
}
public boolean isGpsOn() {
return !hasGps || isGpsEnabled();
}
public boolean isNetOn() {
return !hasNet || isNetEnabled();
}
protected void tik() {
if (AppCore.isExitStarted()) return;
tiker.setTik(Op.TIC, TIK_DELAY);
try {analize(); } catch (Exception ex) { Wow.e(ex); }
}
protected void analize() {
// mode
boolean modeChanged = mode != newMode;
mode = newMode;
// availability check
boolean wasGpsOn = gpsOn, wasNetOn = netOn;
gpsOn = isGpsOn();
netOn = isNetOn();
boolean availabChanged = gpsOn != wasGpsOn || netOn != wasNetOn;
boolean gpsEnabled = isGpsEnabled();
// gps state
gpsState = gpsSource == null ? SignalState.NONE : gpsSource.getState();
// signal
boolean hadSignal = hasGpsSignal;
hasGpsSignal = false;
if (gpsEnabled) hasGpsSignal = (gpsState == SignalState.NONE || gpsState == SignalState.AQUIRING) ? hadSignal : (gpsState == SignalState.ACTIVE || gpsState == SignalState.LINGER);
// action
int action = 0, STOP = -1, START = 1;
if (gpsEnabled && !isPaused) {
if (gpsSource == null) action = START;
else if (modeChanged) action = STOP;
}
else action = STOP;
// GPS manage
if (action == STOP && gpsSource != null) stopGps();
else if (action == START) startGps();
// NET manage
boolean reallyHasSignal = hasGpsSignal && (gpsSource != null || modeChanged);
boolean tooOldFix = availFix == null || !availFix.isActual(300000);// 5 minutes
boolean startNet = !reallyHasSignal || tooOldFix;
if (startNet && netSource == null && isNetEnabled()) startNet();
else if (!startNet && netSource != null) stopNet();
//fire signal event
if (hadSignal != hasGpsSignal || availabChanged) {
while (listeners.hasNext()) {
try { listeners.next().onSignalStateChanged(hasGpsSignal, gpsState, gpsOn, netOn); } catch (Exception ex) {
Wow.e(ex);
}
}
}
if (D)
Wow.i(TAG, "analize", "Mode=" + mode + ", Signal (had/has)=(" + hadSignal + " / " + hasGpsSignal + "), Gps (Enabled/On)=(" + isGpsEnabled() + " / " + (gpsSource != null) + "), Net (Enabled/On)=(" + isNetEnabled() + " / " + (netSource != null) + "), moving=" + isMoving + ", gpsState=" + gpsState + ", action=" + action + ", paused=" + isPaused);
// returns whether gps should be restarted
}
private void startGps() {
gpsSource = mode == Mode.ECONOM ?
new GpsDiscreteSource(this, mode.gps) :
new LocationSource(this, mode.gps);
}
private void stopGps() {
if (gpsSource != null) gpsSource.destroy();
gpsSource = null;
}
private void startNet() {
netSource = new LocationSource(this, mode.net);
}
private void stopNet() {
if (netSource != null) netSource.destroy();
netSource = null;
}
private void flush() {
processor.flush();
}
private String doGetTailKml() {
try {
if (Tool.isEmpty(tail)) return "";// FIXME throws ConcurrentModificationException
StringBuilder str = new StringBuilder();
Fix[] fixes = tail.toArray(new Fix[0]);
for (Fix fix : fixes) {
if (fix.valid > 0) str.append(str.length() > 0 ? " " : "").append(fix.lng + "," + fix.lat);
}
if (str.length() > 0) str.insert(0, lineOpenTag()).append(lineCloseTag());
return str.toString();
} catch (Exception ex) {
if (!(ex instanceof ConcurrentModificationException)) Wow.e(ex);
return "";
}
}
@Override public void onLocationChanged(Location lcn) {
// if (D) Tool.setTimer();
Fix fix = processor.process(lcn, mode, hasGpsSignal);
//
availFix = fix;
// TAIL
long overtime = Tool.now() - TAIL_SPAN_5;
ListIterator<Fix> litr = tail.listIterator();
while (litr.hasNext()) {
if (litr.next().uptime < overtime) litr.remove();
else break;
}
if (fix.isGps && fix.valid >= 0) {
validFix = fix;
if (tail.size() >= 2) lastSpeed = calcSpeed(fix);
tail.add(fix);
}
// fire event
while (listeners.hasNext()) {
try { listeners.next().onNewFix(fix, lcn); } catch (Exception ex) { Wow.e(ex); }
}
// if (D) Wow.i(TAG, "onLocationChanged", "cycle = " + Tool.getTimer(true) + " ms");
}
private int calcSpeed(Fix fix) {
// find fix closest to last within closeTime sec (no less minTime sec, no more maxTime sec) and calc speed in that span
long minTime = fix.uptime - 8000;
long closeTime = fix.uptime - 12000;
long maxTime = fix.uptime - 30000;
ListIterator<Fix> litr = tail.listIterator(tail.size());
Fix newerFix = null, olderFix = null;
while (litr.hasPrevious()) {
olderFix = litr.previous();
if (olderFix.uptime < closeTime) break;
else newerFix = olderFix;
}
long newerDelta = (newerFix == null || newerFix.uptime > minTime) ? -1 : Math.abs(newerFix.uptime - closeTime);
long olderDelta = (olderFix == null || olderFix.uptime < maxTime) ? -1 : Math.abs(olderFix.uptime - closeTime);
Fix baseFix = (newerDelta < olderDelta && newerDelta != -1) ? newerFix : (olderDelta != -1 ? olderFix : null);
if (baseFix == null) return -1;
float baseDrn = (fix.uptime - baseFix.uptime) / 1000f;
float baseDist = LocationProcessor.distanceBetween(baseFix, fix);
float speed = baseDist / baseDrn;
if (D) {
Wow.i(TAG, "doGetSpeed", "DUR=" + baseDrn, "DIST=" + baseDist, ">>>SPEED = " + (int) (speed * 3.6));
textinfo.delete(0, textinfo.length());
textinfo.append("DUR=" + (int) baseDrn + "; DIST=" + (int) baseDist + "; SPEED = " + (int) (speed * 3.6) + "\n");
}
return (int) Math.floor(speed * 3.6f);
}
private int doGetSpeed() {
// todo WARNING should be called from main thread or CuncurrentModification may occure
return !tail.isEmpty() && validFix.isActual(30000) ? lastSpeed : -1;
}
@Override public void onLocationSourceChanged(LocationSource src, int delay) {
tiker.setTik(Op.TIC, delay);
}
@Override public void onMotionChanged(boolean moving) {
isMoving = moving;
}
@Override public void onSave(final List<Fix> fixes) {
// if (D) Tool.setTimer();
// fire event
while (listeners.hasNext()) {
try { listeners.next().onSaveFixes(fixes); } catch (Exception ex) { Wow.e(ex); }
}
// if (D) Wow.i(TAG, "onSave", "cycle = " + Tool.getTimer(true) + " ms");
}
/** MODE */
public static enum Mode {
INTENSIVE(1, 8, 1.02f), NORMAL(8, 2, 1.04f), ECONOM(30, 1, 1.06f);
public int stepTimeSec;
public int commitSteps;
public float distanceMult;
SrcConf gps, net, passive;
private Mode(int _stepTime, int _commitSteps, float _mult) {
stepTimeSec = _stepTime;
commitSteps = _commitSteps;
distanceMult = _mult;
gps = new SrcConf(GPS, stepTimeSec * 1000);
net = new SrcConf(NET, 30 * 1000);
passive = new SrcConf(PASSIVE, 1000);
}
}
//
public static enum SignalState {
NONE, AQUIRING, ACTIVE, LINGER, NOSIGNAL, STUCK
}
/** PUBLIC LISTENER */
public static interface LocationServiceListener {
public void onNewFix(Fix fix, Location lcn);
public void onSaveFixes(List<Fix> fixes);
public void onSignalStateChanged(boolean hasGpsSignal, SignalState gpsState, boolean gpsOn, boolean netOn);
}
}
| mit |
niteshbisht/alg_dynamix | javabase/src/main/java/com/jmx/example/QueueSamplerMXBean.java | 367 | /*
* QueueSamplerMXBean.java - MXBean interface describing the management
* operations and attributes for the QueueSampler MXBean. In this case
* there is a read-only attribute "QueueSample" and an operation "clearQueue".
*/
package com.jmx.example;
public interface QueueSamplerMXBean {
public QueueSample getQueueSample();
public void clearQueue();
}
| mit |
dbooga/MonsterHunter3UDatabase | MonsterHunter3UDatabase/src/com/daviancorp/android/ui/list/HuntingFleetListActivity.java | 2647 | package com.daviancorp.android.ui.list;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.daviancorp.android.mh3udatabase.R;
import com.daviancorp.android.ui.adapter.HuntingFleetListPagerAdapter;
import com.daviancorp.android.ui.general.GenericTabActivity;
public class HuntingFleetListActivity extends GenericTabActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private HuntingFleetListPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = {"Fishing", "Treasure", "Hunting" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.hunting_fleet);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new HuntingFleetListPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.monsterlist, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_03_01/src/main/java/com/microsoft/azure/management/network/v2020_03_01/AzureFirewallApplicationRuleProtocol.java | 2066 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_03_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Properties of the application rule protocol.
*/
public class AzureFirewallApplicationRuleProtocol {
/**
* Protocol type. Possible values include: 'Http', 'Https', 'Mssql'.
*/
@JsonProperty(value = "protocolType")
private AzureFirewallApplicationRuleProtocolType protocolType;
/**
* Port number for the protocol, cannot be greater than 64000. This field
* is optional.
*/
@JsonProperty(value = "port")
private Integer port;
/**
* Get protocol type. Possible values include: 'Http', 'Https', 'Mssql'.
*
* @return the protocolType value
*/
public AzureFirewallApplicationRuleProtocolType protocolType() {
return this.protocolType;
}
/**
* Set protocol type. Possible values include: 'Http', 'Https', 'Mssql'.
*
* @param protocolType the protocolType value to set
* @return the AzureFirewallApplicationRuleProtocol object itself.
*/
public AzureFirewallApplicationRuleProtocol withProtocolType(AzureFirewallApplicationRuleProtocolType protocolType) {
this.protocolType = protocolType;
return this;
}
/**
* Get port number for the protocol, cannot be greater than 64000. This field is optional.
*
* @return the port value
*/
public Integer port() {
return this.port;
}
/**
* Set port number for the protocol, cannot be greater than 64000. This field is optional.
*
* @param port the port value to set
* @return the AzureFirewallApplicationRuleProtocol object itself.
*/
public AzureFirewallApplicationRuleProtocol withPort(Integer port) {
this.port = port;
return this;
}
}
| mit |
yutianfei/FinancingPlan | app/src/main/java/com/wsy/plan/main/presenter/IAccountModelPresenter.java | 437 | package com.wsy.plan.main.presenter;
import com.wsy.plan.main.model.AccountModel;
import java.util.List;
public interface IAccountModelPresenter {
List<AccountModel> getModels(String date);
long saveModel(AccountModel model);
boolean deleteModel(long id);
boolean updateModel(long id, AccountModel model);
String getMonthOut(String type, String month);
String getMonthIncome(String type, String month);
}
| mit |
SquidDev-CC/plethora | src/main/java/org/squiddev/plethora/integration/refinedstorage/MethodExportItem.java | 2915 | package org.squiddev.plethora.integration.refinedstorage;
import com.raoulvdberge.refinedstorage.RS;
import com.raoulvdberge.refinedstorage.api.network.INetwork;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode;
import com.raoulvdberge.refinedstorage.api.util.Action;
import dan200.computercraft.api.lua.LuaException;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import org.squiddev.plethora.api.method.IContext;
import org.squiddev.plethora.api.method.ITransferMethod;
import org.squiddev.plethora.api.method.MarkerInterfaces;
import org.squiddev.plethora.api.method.wrapper.FromContext;
import org.squiddev.plethora.api.method.wrapper.Optional;
import org.squiddev.plethora.api.method.wrapper.PlethoraMethod;
import org.squiddev.plethora.integration.vanilla.NullableItemStack;
import static org.squiddev.plethora.api.method.ArgumentHelper.assertBetween;
import static org.squiddev.plethora.integration.vanilla.method.MethodsInventoryTransfer.extractHandler;
public final class MethodExportItem {
private MethodExportItem() {
}
@PlethoraMethod(modId = RS.ID, doc = "-- Export this item from the RS network to an inventory. Returns the amount transferred.")
@MarkerInterfaces(ITransferMethod.class)
public static int export(
IContext<NullableItemStack> context, @FromContext INetworkNode node,
String toName, @Optional(defInt = Integer.MAX_VALUE) int limit, @Optional int toSlot
) throws LuaException {
if (limit <= 0) throw new LuaException("Limit must be > 0");
// Find location to transfer to
Object location = context.getTransferLocation(toName);
if (location == null) throw new LuaException("Target '" + toName + "' does not exist");
// Validate our location is valid
IItemHandler to = extractHandler(location);
if (to == null) throw new LuaException("Target '" + toName + "' is not an inventory");
if (toSlot != -1) assertBetween(toSlot, 1, to.getSlots(), "To slot out of range (%s)");
NullableItemStack toExtract = context.getTarget();
INetwork network = node.getNetwork();
if (network == null) throw new LuaException("Cannot find network");
// Extract the item from the inventory
int extractLimit = Math.min(limit, toExtract.getFilledStack().getMaxStackSize());
ItemStack toInsert = network.extractItem(toExtract.getFilledStack(), extractLimit, Action.PERFORM);
if (toInsert == null || toInsert.isEmpty()) return 0;
// Attempt to insert into the appropriate inventory
ItemStack remainder = toSlot <= 0
? ItemHandlerHelper.insertItem(to, toInsert, false)
: to.insertItem(toSlot - 1, toInsert, false);
// If not everything could be inserted, replace back in the inventory
if (!remainder.isEmpty()) {
network.insertItem(remainder, remainder.getCount(), Action.PERFORM);
}
return toInsert.getCount() - remainder.getCount();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/models/Agreements.java | 3162 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.billing.models;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
/** Resource collection API of Agreements. */
public interface Agreements {
/**
* Lists the agreements for a billing account.
*
* @param billingAccountName The ID that uniquely identifies a billing account.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return result of listing agreements.
*/
PagedIterable<Agreement> listByBillingAccount(String billingAccountName);
/**
* Lists the agreements for a billing account.
*
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param expand May be used to expand the participants.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return result of listing agreements.
*/
PagedIterable<Agreement> listByBillingAccount(String billingAccountName, String expand, Context context);
/**
* Gets an agreement by ID.
*
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param agreementName The ID that uniquely identifies an agreement.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an agreement by ID.
*/
Agreement get(String billingAccountName, String agreementName);
/**
* Gets an agreement by ID.
*
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param agreementName The ID that uniquely identifies an agreement.
* @param expand May be used to expand the participants.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an agreement by ID.
*/
Response<Agreement> getWithResponse(
String billingAccountName, String agreementName, String expand, Context context);
}
| mit |
rootulp/school | ood/hw/src/hw/hw5/SegmentAnalyst.java | 942 | package hw.hw5;
public class SegmentAnalyst extends AnalystDecorator {
public SegmentAnalyst(StockAnalyst component) {
super(component);
}
public String reasons() {
if (segmentConfidenceLevel() != 0) {
return getComponent().reasons() + " and Segment Analyzed";
} else {
return getComponent().reasons();
}
}
public double confidenceLevel() {
if (segmentConfidenceLevel() != 0) {
return (getComponent().confidenceLevel() + segmentConfidenceLevel()) / 2;
} else {
return getComponent().confidenceLevel();
}
}
private double segmentConfidenceLevel() {
String segment = getStockInfo().get("marketsegment");
if (segment.equals("technology")) {
return .8;
} else if (segment.equals("auto")) {
return .2;
} else {
return 0;
}
}
}
| mit |
arnaudroger/SimpleFlatMapper | sfm-tuples/src/main/java/org/simpleflatmapper/tuple/Tuple14.java | 2495 | package org.simpleflatmapper.tuple;
public class Tuple14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> extends Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> {
private final T14 element13;
public Tuple14(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13) {
super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12);
this.element13 = element13;
}
public final T14 getElement13() {
return element13;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tuple14 tuple14 = (Tuple14) o;
if (element13 != null ? !element13.equals(tuple14.element13) : tuple14.element13 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (element13 != null ? element13.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple14{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
", element2=" + getElement2() +
", element3=" + getElement3() +
", element4=" + getElement4() +
", element5=" + getElement5() +
", element6=" + getElement6() +
", element7=" + getElement7() +
", element8=" + getElement8() +
", element9=" + getElement9() +
", element10=" + getElement10() +
", element11=" + getElement11() +
", element12=" + getElement12() +
", element13=" + getElement13() +
'}';
}
public <T15> Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> tuple15(T15 element14) {
return new Tuple15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), element14);
}
}
| mit |
cartermp/WMB | app/src/main/java/com/jmstudios/corvallistransit/utils/Utils.java | 3856 | package com.jmstudios.corvallistransit.utils;
import com.google.android.gms.maps.model.LatLng;
import com.jmstudios.corvallistransit.models.Stop;
import org.joda.time.DateTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
public class Utils {
private static final HashMap<String, Integer> monthPairs;
static {
monthPairs = new HashMap<String, Integer>();
monthPairs.put("Jan", 1);
monthPairs.put("Feb", 2);
monthPairs.put("Mar", 3);
monthPairs.put("Apr", 4);
monthPairs.put("May", 5);
monthPairs.put("Jun", 6);
monthPairs.put("Jul", 7);
monthPairs.put("Aug", 8);
monthPairs.put("Sep", 9);
monthPairs.put("Oct", 10);
monthPairs.put("Nov", 11);
monthPairs.put("Dec", 12);
}
public static String[] routeColors = new String[]{
"#00ADEF",
"#88279F",
"#F2652F",
"#8CC530",
"#BD5590",
"#034DAF",
"#f14a43",
"#00854F",
"#3cb50c",
"#FFAA0F",
"#005BEF",
"#61463F",
"#0076AF",
"#bb0a58",
"#3F288F",
};
/**
* Given a Stringified Date in RFC822Z format,
* converts it to a NodaTime DateTime object.
*
* @param ctsDateString RFC822Z format date string.
*/
public static DateTime convertToDateTime(String ctsDateString) {
String[] data = ctsDateString.split("\\s+");
String[] timeData = data[3].split(":");
/* Example: "15 Apr 14 16:57 -0700" */
int year = Integer.parseInt("20" + data[2]);
int monthOfYear = monthPairs.get(data[1]);
int dayOfMonth = Integer.parseInt(data[0]);
int hourOfDay = Integer.parseInt(timeData[0]);
int minuteOfHour = Integer.parseInt(timeData[1]);
return new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour);
}
public static List<Stop> filterTimes(List<Stop> stops) {
if (stops != null) {
LinkedHashSet<Stop> lhs = new LinkedHashSet<Stop>(stops);
for (Iterator<Stop> iterator = lhs.iterator(); iterator.hasNext(); ) {
Stop s = iterator.next();
if (s.eta() < 1 || s.eta() > 30) {
iterator.remove();
}
}
stops.clear();
stops.addAll(lhs);
}
return stops;
}
/**
* Guess what this does.
*/
public static List<Stop> getStopRange(List<Stop> stops, int start, int end) {
if (stops == null || stops.isEmpty()) {
return stops;
}
return stops.subList(start, stops.size() < end ? stops.size() : end);
}
/**
* Finds the index in the list of stops whose location
*/
public static int findStopByLocation(List<Stop> stops, LatLng location) {
if (stops == null || stops.isEmpty()) {
return -1;
}
int i;
int size = stops.size();
for (i = 0; i < size; i++) {
Stop s = stops.get(i);
if (s != null && locationsEqual(s.latitude, location.latitude,
s.longitude, location.longitude)) {
return i;
}
}
return -1;
}
public static boolean locationsEqual(double lat1, double lat2, double long1, double long2) {
if (Math.abs(lat1 - lat2) >= 0.000001) {
return false;
}
if (Math.abs(long1 - long2) >= 0.000001) {
return false;
}
return true;
}
public static int getCurrentDay() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.DAY_OF_WEEK);
}
}
| mit |
chrhsmt/sample_alljoyn | src/org/alljoyn/bus/samples/SampleInterface.java | 1839 | /*
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package org.alljoyn.bus.samples;
import org.alljoyn.bus.BusException;
import org.alljoyn.bus.annotation.BusInterface;
import org.alljoyn.bus.annotation.BusMethod;
@BusInterface (name = SampleInterface.IF_NAME)
public interface SampleInterface {
public static final String IF_NAME = "org.alljoyn.Bus.sample"; //com.my.well.known.name
@BusMethod
public String temp(String tmep) throws BusException;
// @BusMethod
// public String Ping(String str) throws BusException;
//
// @BusSignal(name="Ping1", sessionless=false)
// public String Ping1(String str) throws BusException;
//
// @BusMethod()
// public String Ping2(String str) throws BusException;
//
// @BusMethod
// public String Concatenate(String arg1, String arg2) throws BusException;
//
// @BusMethod
// public int Fibonacci(int arg1) throws BusException;
//
// @BusMethod
// public double Pi(int iterations) throws BusException;
//
// @BusMethod
// public String Chat(String str) throws BusException;
} | mit |
walison17/ProjetoControleVendas | SistemaVendas/src/relatorios/RelatorioFuncionarios.java | 7234 | /*
* 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 relatorios;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;
import tabelas.FuncionariosTableModel;
/**
*
* @author Walison Filipe
*/
public class RelatorioFuncionarios extends javax.swing.JFrame {
FuncionariosTableModel modeloTabela;
/**
* Creates new form RelatorioProdutos
*/
public RelatorioFuncionarios() {
initComponents();
modeloTabela = new FuncionariosTableModel();
jTableRelatorioClientes.setModel(modeloTabela);
formatarTabela();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTableRelatorioClientes = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Relatório de produtos");
setExtendedState(6);
jButton1.setText("Sair");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTableRelatorioClientes.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTableRelatorioClientes.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
jScrollPane1.setViewportView(jTableRelatorioClientes);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1089, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RelatorioFuncionarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RelatorioFuncionarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RelatorioFuncionarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RelatorioFuncionarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RelatorioFuncionarios().setVisible(true);
}
});
}
private void formatarTabela(){
DefaultTableCellRenderer centro = new DefaultTableCellRenderer() {
@Override
public void setValue(Object value) {
setForeground(Color.BLACK);
setHorizontalAlignment(JLabel.CENTER);
super.setValue(value);
}
};
/*jTableRelatorioClientes.getColumn("Cód.").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Nome").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Descrição").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Preço de custo").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Preço de venda").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Estoque atual").setCellRenderer(centro);
jTableRelatorioClientes.getColumn("Estoque mínimo").setCellRenderer(centro);*/
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTableRelatorioClientes;
// End of variables declaration//GEN-END:variables
}
| mit |
MatthijsKamstra/haxejava | 04lwjgl/code/lwjgl/org/lwjgl/opengl/GL.java | 23325 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
*/
package org.lwjgl.opengl;
import org.lwjgl.system.*;
import org.lwjgl.system.windows.*;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.*;
import static java.lang.Math.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL32.*;
import static org.lwjgl.opengl.GLX.*;
import static org.lwjgl.opengl.GLX11.*;
import static org.lwjgl.opengl.WGL.*;
import static org.lwjgl.system.APIUtil.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.ThreadLocalUtil.*;
import static org.lwjgl.system.linux.X11.*;
import static org.lwjgl.system.windows.GDI32.*;
import static org.lwjgl.system.windows.User32.*;
import static org.lwjgl.system.windows.WindowsUtil.*;
/**
* This class must be used before any OpenGL function is called. It has the following responsibilities:
* <ul>
* <li>Loads the OpenGL native library into the JVM process.</li>
* <li>Creates instances of {@link GLCapabilities} classes. A {@code GLCapabilities} instance contains flags for functionality that is available in an OpenGL
* context. Internally, it also contains function pointers that are only valid in that specific OpenGL context.</li>
* <li>Maintains thread-local state for {@code GLCapabilities} instances, corresponding to OpenGL contexts that are current in those threads.</li>
* </ul>
*
* <h3>Library lifecycle</h3>
* <p>The OpenGL library is loaded automatically when this class is initialized. Set the {@link Configuration#OPENGL_EXPLICIT_INIT} option to override this
* behavior. Manual loading/unloading can be achieved with the {@link #create} and {@link #destroy} functions. The name of the library loaded can be overridden
* with the {@link Configuration#OPENGL_LIBRARY_NAME} option. The maximum OpenGL version loaded can be set with the {@link Configuration#OPENGL_MAXVERSION}
* option. This can be useful to ensure that no functionality above a specific version is used during development.</p>
*
* <h3>GLCapabilities creation</h3>
* <p>Instances of {@code GLCapabilities} can be created with the {@link #createCapabilities} method. An OpenGL context must be current in the current thread
* before it is called. Calling this method is expensive, so the {@code GLCapabilities} instance should be associated with the OpenGL context and reused as
* necessary.</p>
*
* <h3>Thread-local state</h3>
* <p>Before a function for a given OpenGL context can be called, the corresponding {@code GLCapabilities} instance must be passed to the
* {@link #setCapabilities} method. The user is also responsible for clearing the current {@code GLCapabilities} instance when the context is destroyed or made
* current in another thread.</p>
*
* <p>Note that the {@link #createCapabilities} method implicitly calls {@link #setCapabilities} with the newly created instance.</p>
*/
public final class GL {
private static final APIVersion MAX_VERSION;
private static FunctionProvider functionProvider;
/** See {@link Configuration#OPENGL_CAPABILITIES_STATE}. */
private static final CapabilitiesState capabilitiesState;
private static WGLCapabilities capabilitiesWGL;
private static GLXCapabilities capabilitiesGLXClient;
private static GLXCapabilities capabilitiesGLX;
static {
MAX_VERSION = apiParseVersion(Configuration.OPENGL_MAXVERSION);
String capsStateType = Configuration.OPENGL_CAPABILITIES_STATE.get("ThreadLocal");
if ( "static".equals(capsStateType) )
capabilitiesState = new StaticCapabilitiesState();
else if ( "ThreadLocal".equals(capsStateType) )
capabilitiesState = new TLCapabilitiesState();
else
throw new IllegalStateException("Invalid " + Configuration.OPENGL_CAPABILITIES_STATE.getProperty() + " specified.");
if ( !Configuration.OPENGL_EXPLICIT_INIT.get(false) )
create();
}
private GL() {}
/** Loads the OpenGL native library, using the default library name. */
public static void create() {
SharedLibrary GL;
switch ( Platform.get() ) {
case LINUX:
GL = Library.loadNative(Configuration.OPENGL_LIBRARY_NAME, "libGL.so.1", "libGL.so");
break;
case MACOSX:
GL = Library.loadNative(Configuration.OPENGL_LIBRARY_NAME, "/System/Library/Frameworks/OpenGL.framework");
break;
case WINDOWS:
GL = Library.loadNative(Configuration.OPENGL_LIBRARY_NAME, "opengl32");
break;
default:
throw new IllegalStateException();
}
create(GL);
}
/**
* Loads the OpenGL native library, using the specified library name.
*
* @param libName the native library name
*/
public static void create(String libName) {
create(Library.loadNative(libName));
}
private abstract static class SharedLibraryGL extends SharedLibrary.Delegate {
SharedLibraryGL(SharedLibrary library) {
super(library);
}
abstract long getExtensionAddress(long name);
@Override
public long getFunctionAddress(ByteBuffer functionName) {
long address = getExtensionAddress(memAddress(functionName));
if ( address == NULL ) {
address = library.getFunctionAddress(functionName);
if ( address == NULL && DEBUG_FUNCTIONS )
apiLog("Failed to locate address for GL function " + memASCII(functionName));
}
return address;
}
}
private static void create(SharedLibrary OPENGL) {
FunctionProvider functionProvider;
try {
switch ( Platform.get() ) {
case WINDOWS:
functionProvider = new SharedLibraryGL(OPENGL) {
private final long wglGetProcAddress = library.getFunctionAddress("wglGetProcAddress");
@Override
long getExtensionAddress(long name) {
return callPP(wglGetProcAddress, name);
}
};
break;
case LINUX:
functionProvider = new SharedLibraryGL(OPENGL) {
private final long glXGetProcAddress;
{
long GetProcAddress = library.getFunctionAddress("glXGetProcAddress");
if ( GetProcAddress == NULL )
GetProcAddress = library.getFunctionAddress("glXGetProcAddressARB");
glXGetProcAddress = GetProcAddress;
}
@Override
long getExtensionAddress(long name) {
return glXGetProcAddress == NULL ? NULL : callPP(glXGetProcAddress, name);
}
};
break;
case MACOSX:
functionProvider = new SharedLibraryGL(OPENGL) {
@Override
long getExtensionAddress(long name) {
return NULL;
}
};
break;
default:
throw new IllegalStateException();
}
create(functionProvider);
} catch (RuntimeException e) {
OPENGL.free();
throw e;
}
}
/**
* Initializes OpenGL with the specified {@link FunctionProvider}. This method can be used to implement custom OpenGL library loading.
*
* @param functionProvider the provider of OpenGL function addresses
*/
public static void create(FunctionProvider functionProvider) {
if ( GL.functionProvider != null )
throw new IllegalStateException("OpenGL has already been created.");
GL.functionProvider = functionProvider;
}
/** Unloads the OpenGL native library. */
public static void destroy() {
if ( functionProvider == null )
return;
capabilitiesWGL = null;
capabilitiesGLX = null;
if ( functionProvider instanceof NativeResource )
((NativeResource)functionProvider).free();
functionProvider = null;
}
/** Returns the {@link FunctionProvider} for the OpenGL native library. */
public static FunctionProvider getFunctionProvider() {
return functionProvider;
}
/**
* Sets the {@link GLCapabilities} of the OpenGL context that is current in the current thread.
*
* <p>This {@code GLCapabilities} instance will be used by any OpenGL call in the current thread, until {@code setCapabilities} is called again with a
* different value.</p>
*/
public static void setCapabilities(GLCapabilities caps) {
capabilitiesState.set(caps);
}
/**
* Returns the {@link GLCapabilities} of the OpenGL context that is current in the current thread.
*
* @throws IllegalStateException if {@link #setCapabilities} has never been called in the current thread or was last called with a {@code null} value
*/
public static GLCapabilities getCapabilities() {
GLCapabilities caps = capabilitiesState.get();
if ( caps == null )
throw new IllegalStateException("No GLCapabilities instance set for the current thread. Possible solutions:\n" +
"\ta) Call GL.createCapabilities() after making a context current in the current thread.\n" +
"\tb) Call GL.setCapabilities() if a GLCapabilities instance already exists for the current context.");
return caps;
}
/**
* Returns the WGL capabilities.
*
* <p>This method may only be used on Windows.</p>
*/
public static WGLCapabilities getCapabilitiesWGL() {
if ( capabilitiesWGL == null )
capabilitiesWGL = createCapabilitiesWGLDummy();
return capabilitiesWGL;
}
/** Returns the GLX client capabilities. */
static GLXCapabilities getCapabilitiesGLXClient() {
if ( capabilitiesGLXClient == null )
capabilitiesGLXClient = initCapabilitiesGLX(true);
return capabilitiesGLXClient;
}
/**
* Returns the GLX capabilities.
*
* <p>This method may only be used on Linux.</p>
*/
public static GLXCapabilities getCapabilitiesGLX() {
if ( capabilitiesGLX == null )
capabilitiesGLX = initCapabilitiesGLX(false);
return capabilitiesGLX;
}
private static GLXCapabilities initCapabilitiesGLX(boolean client) {
long display = nXOpenDisplay(NULL);
try {
return createCapabilitiesGLX(display, client ? -1 : XDefaultScreen(display));
} finally {
XCloseDisplay(display);
}
}
/**
* Creates a new {@link GLCapabilities} instance for the OpenGL context that is current in the current thread.
*
* <p>Depending on the current context, the instance returned may or may not contain the deprecated functionality removed since OpenGL version 3.1.</p>
*
* <p>This method calls {@link #setCapabilities(GLCapabilities)} with the new instance before returning.</p>
*
* @return the GLCapabilities instance
*/
public static GLCapabilities createCapabilities() {
return createCapabilities(false);
}
/**
* Creates a new {@link GLCapabilities} instance for the OpenGL context that is current in the current thread.
*
* <p>Depending on the current context, the instance returned may or may not contain the deprecated functionality removed since OpenGL version 3.1. The
* {@code forwardCompatible} flag will force LWJGL to not load the deprecated functions, even if the current context exposes them.</p>
*
* <p>This method calls {@link #setCapabilities(GLCapabilities)} with the new instance before returning.</p>
*
* @param forwardCompatible if true, LWJGL will create forward compatible capabilities
*
* @return the GLCapabilities instance
*/
public static GLCapabilities createCapabilities(boolean forwardCompatible) {
GLCapabilities caps = null;
try {
// We don't have a current ContextCapabilities when this method is called
// so we have to use the native bindings directly.
long GetError = functionProvider.getFunctionAddress("glGetError");
long GetString = functionProvider.getFunctionAddress("glGetString");
long GetIntegerv = functionProvider.getFunctionAddress("glGetIntegerv");
if ( GetError == NULL || GetString == NULL || GetIntegerv == NULL )
throw new IllegalStateException("Core OpenGL functions could not be found. Make sure that the OpenGL library has been loaded correctly.");
int errorCode = callI(GetError);
if ( errorCode != GL_NO_ERROR )
apiLog(String.format("An OpenGL context was in an error state before the creation of its capabilities instance. Error: 0x%X" + errorCode));
int majorVersion;
int minorVersion;
try ( MemoryStack stack = stackPush() ) {
IntBuffer version = stack.ints(0);
// Try the 3.0+ version query first
callPV(GetIntegerv, GL_MAJOR_VERSION, memAddress(version));
if ( callI(GetError) == GL_NO_ERROR && 3 <= (majorVersion = version.get(0)) ) {
// We're on an 3.0+ context.
callPV(GetIntegerv, GL_MINOR_VERSION, memAddress(version));
minorVersion = version.get(0);
} else {
// Fallback to the string query.
long versionString = callP(GetString, GL_VERSION);
if ( versionString == NULL || callI(GetError) != GL_NO_ERROR )
throw new IllegalStateException("There is no OpenGL context current in the current thread.");
APIVersion apiVersion = apiParseVersion(memUTF8(versionString));
majorVersion = apiVersion.major;
minorVersion = apiVersion.minor;
}
}
if ( majorVersion < 1 || (majorVersion == 1 && minorVersion < 1) )
throw new IllegalStateException("OpenGL 1.1 is required.");
int[] GL_VERSIONS = {
5, // OpenGL 1.1 to 1.5
1, // OpenGL 2.0 to 2.1
3, // OpenGL 3.0 to 3.3
5, // OpenGL 4.0 to 4.5
};
Set<String> supportedExtensions = new HashSet<>(512);
int maxMajor = min(majorVersion, GL_VERSIONS.length);
if ( MAX_VERSION != null )
maxMajor = min(MAX_VERSION.major, maxMajor);
for ( int M = 1; M <= maxMajor; M++ ) {
int maxMinor = GL_VERSIONS[M - 1];
if ( M == majorVersion )
maxMinor = min(minorVersion, maxMinor);
if ( MAX_VERSION != null && M == MAX_VERSION.major )
maxMinor = min(MAX_VERSION.minor, maxMinor);
for ( int m = M == 1 ? 1 : 0; m <= maxMinor; m++ )
supportedExtensions.add(String.format("OpenGL%d%d", M, m));
}
if ( majorVersion < 3 ) {
// Parse EXTENSIONS string
String extensionsString = memASCII(checkPointer(callP(GetString, GL_EXTENSIONS)));
StringTokenizer tokenizer = new StringTokenizer(extensionsString);
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
} else {
// Use indexed EXTENSIONS
try ( MemoryStack stack = stackPush() ) {
IntBuffer pi = stack.ints(0);
callPV(GetIntegerv, GL_NUM_EXTENSIONS, memAddress(pi));
int extensionCount = pi.get(0);
long GetStringi = apiGetFunctionAddress(functionProvider, "glGetStringi");
for ( int i = 0; i < extensionCount; i++ )
supportedExtensions.add(memASCII(callP(GetStringi, GL_EXTENSIONS, i)));
// In real drivers, we may encounter the following weird scenarios:
// - 3.1 context without GL_ARB_compatibility but with deprecated functionality exposed and working.
// - Core or forward-compatible context with GL_ARB_compatibility exposed, but not working when used.
// We ignore these and go by the spec.
// Force forwardCompatible to true if the context is a forward-compatible context.
callPV(GetIntegerv, GL_CONTEXT_FLAGS, memAddress(pi));
if ( (pi.get(0) & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) != 0 )
forwardCompatible = true;
else {
// Force forwardCompatible to true if the context is a core profile context.
if ( (3 < majorVersion || 1 <= minorVersion) ) { // OpenGL 3.1+
if ( 3 < majorVersion || 2 <= minorVersion ) { // OpenGL 3.2+
callPV(GetIntegerv, GL_CONTEXT_PROFILE_MASK, memAddress(pi));
if ( (pi.get(0) & GL_CONTEXT_CORE_PROFILE_BIT) != 0 )
forwardCompatible = true;
} else
forwardCompatible = !supportedExtensions.contains("GL_ARB_compatibility");
}
}
}
}
return caps = new GLCapabilities(getFunctionProvider(), supportedExtensions, forwardCompatible);
} finally {
setCapabilities(caps);
}
}
/** Creates a dummy context and retrieves the WGL capabilities. */
private static WGLCapabilities createCapabilitiesWGLDummy() {
long hdc = wglGetCurrentDC(); // just use the current context if one exists
if ( hdc != NULL )
return createCapabilitiesWGL(hdc);
short classAtom = 0;
long hwnd = NULL;
long hglrc = NULL;
try ( MemoryStack stack = stackPush() ) {
WNDCLASSEX wc = WNDCLASSEX.callocStack(stack)
.cbSize(WNDCLASSEX.SIZEOF)
.style(CS_HREDRAW | CS_VREDRAW)
.hInstance(WindowsLibrary.HINSTANCE)
.lpszClassName(stack.UTF16("WGL"));
WNDCLASSEX.nlpfnWndProc(wc.address(), User32.Functions.DefWindowProc);
classAtom = RegisterClassEx(wc);
if ( classAtom == 0 )
throw new IllegalStateException("Failed to register WGL window class");
hwnd = checkPointer(nCreateWindowEx(
0, classAtom & 0xFFFF, NULL,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
0, 0, 1, 1,
NULL, NULL, NULL, NULL
));
hdc = checkPointer(GetDC(hwnd));
PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.callocStack(stack)
.nSize((short)PIXELFORMATDESCRIPTOR.SIZEOF)
.nVersion((short)1)
.dwFlags(PFD_SUPPORT_OPENGL); // we don't care about anything else
int pixelFormat = ChoosePixelFormat(hdc, pfd);
if ( pixelFormat == 0 )
windowsThrowException("Failed to choose an OpenGL-compatible pixel format");
if ( DescribePixelFormat(hdc, pixelFormat, pfd) == 0 )
windowsThrowException("Failed to obtain pixel format information");
if ( !SetPixelFormat(hdc, pixelFormat, pfd) )
windowsThrowException("Failed to set the pixel format");
hglrc = checkPointer(wglCreateContext(hdc));
wglMakeCurrent(hdc, hglrc);
return createCapabilitiesWGL(hdc);
} finally {
if ( hglrc != NULL ) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hglrc);
}
if ( hwnd != NULL )
DestroyWindow(hwnd);
if ( classAtom != 0 )
nUnregisterClass(classAtom & 0xFFFF, WindowsLibrary.HINSTANCE);
}
}
/**
* Creates a {@link WGLCapabilities} instance for the context that is current in the current thread.
*
* <p>This method may only be used on Windows.</p>
*/
public static WGLCapabilities createCapabilitiesWGL() {
long hdc = wglGetCurrentDC();
if ( hdc == NULL )
throw new IllegalStateException("Failed to retrieve the device context of the current OpenGL context");
return createCapabilitiesWGL(hdc);
}
/**
* Creates a {@link WGLCapabilities} instance for the specified device context.
*
* @param hdc the device context handle ({@code HDC})
*/
private static WGLCapabilities createCapabilitiesWGL(long hdc) {
String extensionsString = null;
long wglGetExtensionsString = functionProvider.getFunctionAddress("wglGetExtensionsStringARB");
if ( wglGetExtensionsString != NULL )
extensionsString = memASCII(callPP(wglGetExtensionsString, hdc));
else {
wglGetExtensionsString = functionProvider.getFunctionAddress("wglGetExtensionsStringEXT");
if ( wglGetExtensionsString != NULL )
extensionsString = memASCII(callP(wglGetExtensionsString));
}
Set<String> supportedExtensions = new HashSet<>(32);
if ( extensionsString != null ) {
StringTokenizer tokenizer = new StringTokenizer(extensionsString);
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
}
return new WGLCapabilities(functionProvider, supportedExtensions);
}
/**
* Creates a {@link GLXCapabilities} instance for the default screen of the specified X connection.
*
* <p>This method may only be used on Linux.</p>
*
* @param display the X connection handle ({@code DISPLAY})
*/
public static GLXCapabilities createCapabilitiesGLX(long display) {
return createCapabilitiesGLX(display, XDefaultScreen(display));
}
/**
* Creates a {@link GLXCapabilities} instance for the specified screen of the specified X connection.
*
* <p>This method may only be used on Linux.</p>
*
* @param display the X connection handle ({@code DISPLAY})
* @param screen the screen index
*/
public static GLXCapabilities createCapabilitiesGLX(long display, int screen) {
int majorVersion;
int minorVersion;
try ( MemoryStack stack = stackPush() ) {
IntBuffer piMajor = stack.ints(0);
IntBuffer piMinor = stack.ints(0);
if ( glXQueryVersion(display, piMajor, piMinor) == 0 )
throw new IllegalStateException("Failed to query GLX version");
majorVersion = piMajor.get(0);
minorVersion = piMinor.get(0);
if ( majorVersion != 1 )
throw new IllegalStateException("Invalid GLX major version: " + majorVersion);
}
Set<String> supportedExtensions = new HashSet<>(32);
int[][] GLX_VERSIONS = {
{ 1, 2, 3, 4 }
};
for ( int major = 1; major <= GLX_VERSIONS.length; major++ ) {
int[] minors = GLX_VERSIONS[major - 1];
for ( int minor : minors ) {
if ( major < majorVersion || (major == majorVersion && minor <= minorVersion) )
supportedExtensions.add("GLX" + Integer.toString(major) + Integer.toString(minor));
}
}
if ( 1 <= minorVersion ) {
long extensionsString;
if ( screen == -1 ) {
long glXGetClientString = functionProvider.getFunctionAddress("glXGetClientString");
extensionsString = callPP(glXGetClientString, display, GLX_EXTENSIONS);
} else {
long glXQueryExtensionsString = functionProvider.getFunctionAddress("glXQueryExtensionsString");
extensionsString = callPP(glXQueryExtensionsString, display, screen);
}
StringTokenizer tokenizer = new StringTokenizer(memASCII(extensionsString));
while ( tokenizer.hasMoreTokens() )
supportedExtensions.add(tokenizer.nextToken());
}
return new GLXCapabilities(functionProvider, supportedExtensions);
}
/** Manages the thread-local {@link GLCapabilities} state. */
private interface CapabilitiesState {
void set(GLCapabilities caps);
GLCapabilities get();
}
/** Default {@link CapabilitiesState} implementation using {@link ThreadLocalState}. */
private static class TLCapabilitiesState implements CapabilitiesState {
@Override
public void set(GLCapabilities caps) { tlsGet().capsGL = caps; }
@Override
public GLCapabilities get() { return tlsGet().capsGL; }
}
/** Optional, write-once {@link CapabilitiesState}. */
private static class StaticCapabilitiesState implements CapabilitiesState {
private static final List<Field> flags;
private static final List<Field> funcs;
static {
if ( Checks.DEBUG ) {
Field[] fields = GLCapabilities.class.getFields();
flags = new ArrayList<>(512);
funcs = new ArrayList<>(256);
for ( Field f : fields )
(f.getType() == Boolean.TYPE ? flags : funcs).add(f);
} else {
flags = null;
funcs = null;
}
}
private static GLCapabilities tempCaps;
@Override
public void set(GLCapabilities caps) {
if ( Checks.DEBUG )
checkCapabilities(caps);
tempCaps = caps;
}
private static void checkCapabilities(GLCapabilities caps) {
if ( caps != null && tempCaps != null && !apiCompareCapabilities(flags, funcs, tempCaps, caps) )
apiLog("An OpenGL context with different functionality detected! The ThreadLocal capabilities state must be used.");
}
@Override
public GLCapabilities get() {
return WriteOnce.caps;
}
private static final class WriteOnce {
// This will be initialized the first time get() above is called
private static final GLCapabilities caps = StaticCapabilitiesState.tempCaps;
static {
if ( caps == null )
throw new IllegalStateException("The static GLCapabilities instance is null");
}
}
}
} | mit |
dingxwsimon/codingquestions | src/array/HeapSort.java | 1730 | /**
* @(#) HeapSort.java Apr 6, 2010 10:07:04 PM
* Copyright (C) 2009 GeeYee Inc. 60606, Chicago, IL, USA
* All right reserved
*/
package array;
import java.util.Arrays;
/**
* Class <code>HeapSort</code>
*
* @author Xiaowen dingxwsimon@gmail.com
* @since Apr 6, 2010 10:07:04 PM
*
*/
public class HeapSort {
// max heap
// only sift the data[low] to the right place
public static void sift(int[] data, int low, int high) {
int i, j;
i = low; // low is the parent
j = 2 * i + 1; // j is the child
while (j < high) {
// decide left or right child
if (j + 1 < high && data[j] < data[j + 1])
j = j + 1;
// if the child if larger than parent, swap
if (data[i] < data[j]) {
swap(data, i, j);
i = j;
j = 2 * i + 1;
} else
break;
}
}
public static void heapsort(int[] data) {
int length = data.length;
for (int i = length / 2 - 1; i >= 0; i--) {
sift(data, i, length - 1);
}
for (int i = length - 1; i >= 1; i--) {
swap(data, 0, i);
sift(data, 0, i - 1);
}
}
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data = {2, 13, 1, 12, 11, 7, 9, 10, 20, 6};
HeapSort.heapsort(data);
System.out.println(Arrays.toString(data));
}
}
| mit |
sbaychev/spring-coverage-jpa-service | src/main/java/com/pickcoverage/domain/repository/IJewelryRepository.java | 327 | package com.pickcoverage.domain.repository;
import com.pickcoverage.domain.coverages.Jewelry;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by stefanbaychev on 3/30/17.
*/
public interface IJewelryRepository extends IActiveRepository<Jewelry>, JpaSpecificationExecutor<Jewelry> {
}
| mit |
kiarash96/Bobby | src/bobby/scene/enemies/Zombie.java | 2405 | /*
* The MIT License
*
* Copyright 2015 Kiarash Korki <kiarash96@users.sf.net>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bobby.scene.enemies;
import bobby.scene.SceneManager;
import bobby.scene.Sprite;
import bobby.state.GameLevel;
import java.awt.Graphics;
/**
*
* @author Kiarash Korki <kiarash96@users.sf.net>
*/
public class Zombie extends Enemy {
// moves from minX to maxX
private double minX, maxX;
private double dx;
private int direction;
private Sprite animation;
public static int WIDTH = 60;
public static int HEIGHT = 66;
public Zombie(SceneManager sm, double x, double dist, double speed) {
super(sm, x, GameLevel.GROUND_LEVEL - HEIGHT, WIDTH, HEIGHT);
minX = Math.min(x, x + dist);
maxX = Math.max(x, x + dist);
dx = speed;
direction = (speed > 0 ? -1 : +1);
animation = new Sprite();
animation.loadAnimatoion("rc/img/enemy/zombie/", "idle", "png", 2);
animation.scale(w, h);
animation.setDelay(75);
}
@Override
public void update() {
if ((dx > 0 && x + dx > maxX) || (dx < 0 && x - dx < minX)) {
dx *= -1;
direction *= -1;
}
x += dx;
animation.nextFrame();
}
@Override
public void draw(Graphics g) {
super.drawWithOffset(g, animation.getCurrentImage(), x, y, w, h, direction);
}
}
| mit |
tslaats/SE2017-Team1 | CRVisualization/drawings/ConditionStackedFlipped.java | 1824 | package drawings;
import java.awt.*;
import javax.swing.JPanel;
import resources.Constants;
import utils.TestUtil;
public class ConditionStackedFlipped extends JPanel {
private static final long serialVersionUID = 1L;
/*
* test case:
* - act1 = new ConresActivity(0, new Point(50, 35), "Activity 1", "ROLE", false, false, false);
* - act2 = new ConresActivity(0, new Point(50, 235), "Activity 2", "ROLE", false, false, false);
* - rel = new ConresRelation(act1, act2, "cond")
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// ACTIVITY 1
Point center1 = new Point(100, 100);
TestUtil.drawAct(g2d, center1, "ROLE", "Activity 1", false, false, false);
// ACTIVITY 2
Point center2 = new Point(100, 300);
TestUtil.drawAct(g2d, center2, "ROLE", "Activity 2", false, false, false);
// CONDITION
int circleCondX = TestUtil.getLeftX(center2) + Constants.ACTIVITY_WIDTH / 2 + Constants.DOT_SIZE / 2;
int circleCondY = TestUtil.getUpperY(center2) - Constants.DOT_SIZE / 2;
int triangleCondX = TestUtil.getLeftX(center2) + Constants.ACTIVITY_WIDTH / 2 + Constants.DOT_SIZE / 2;
int triangleCondY = TestUtil.getUpperY(center2) - Constants.DOT_SIZE;
int lineCondStartX = TestUtil.getLeftX(center1) + Constants.ACTIVITY_WIDTH / 2 + Constants.DOT_SIZE / 2;
int lineCondEndX = TestUtil.getUpperY(center1) + Constants.ACTIVITY_HEIGHT;
TestUtil.drawCond(g2d, circleCondX, circleCondY, triangleCondX, triangleCondY,
lineCondStartX, lineCondEndX, 'D', 0, Constants.DOT_SIZE / 2);
}
public static void main(String[] args) {
String fileName = "images/cond_stack_flip";
ConditionStackedFlipped graphDrawing = new ConditionStackedFlipped();
TestUtil.drawAndSave(graphDrawing, fileName);
}
} | mit |
stuartervine/aws-sugar | src/com/github/stuartervine/awssugar/Receiver.java | 173 | package com.github.stuartervine.awssugar;
public interface Receiver {
void start(String queueName);
void stop();
ExplicitReceiver explicit(String queueName);
}
| mit |
CoolDude9090/Homework-Manager | src/net/cooldude/homeworkmanager/api/HomeworkTask.java | 3652 | package net.cooldude.homeworkmanager.api;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import net.cooldude.homeworkmanager.HomeworkManager;
import net.cooldude.homeworkmanager.api.util.TimeUtil;
import org.joda.time.DateTime;
public class HomeworkTask {
public static final String TASK_EXTENSION = ".hwtask";
private final String filename;
private String displayname;
private DateTime dueDate;
private HomeworkSubject subject;
private String description;
private boolean hidden;
private boolean complete;
public HomeworkTask() {
this.filename = HomeworkManager.RANDOM.nextInt(Integer.MAX_VALUE) + "_untitled";
}
public HomeworkTask(String filename) {
this.filename = filename;
}
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public DateTime getDueDate() {
return dueDate;
}
public void setDueDate(DateTime dueDate) {
this.dueDate = dueDate;
}
public HomeworkSubject getSubject() {
return subject;
}
public void setSubject(HomeworkSubject subject) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isComplete() {
return complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public String getFilename() {
return filename;
}
// DON'T DO THIS! ITS TERRIBLE PRACTICE!!!!
public HomeworkTask recreate(String filename) {
HomeworkTask task = new HomeworkTask(filename);
task.setComplete(isComplete());
task.setDescription(getDescription());
task.setDisplayname(getDisplayname());
task.setDueDate(getDueDate());
task.setHidden(isHidden());
task.setSubject(getSubject());
return task;
}
public void saveToFile() {
DataFileManager dfm = DataFileManager.instance;
dfm.openFile(DataFileManager.FILES_DIR + "tasks/" + getFilename() + TASK_EXTENSION);
dfm.addProperty("displayname", displayname);
dfm.addProperty("duedate", TimeUtil.encodeToString(dueDate));
dfm.addProperty("subject", subject.getUUID());
dfm.addProperty("description", description.replace("\n", "\\n").replace("=", "%%equal"));
dfm.addProperty("hidden", hidden);
dfm.addProperty("complete", complete);
try {
dfm.writeFile();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Unable to save file properly. You may have lost data about the most recently changed / created homework task!");
}
dfm.closeFile();
}
public static HomeworkTask loadTaskFromFile(File f) {
DataFileManager dfm = DataFileManager.instance;
HomeworkTask task = new HomeworkTask(f.getName().replace(TASK_EXTENSION, ""));
dfm.loadFile(DataFileManager.FILES_DIR + "tasks/" + f.getName());
task.complete = Boolean.parseBoolean(dfm.getProperty("complete").getValue());
task.hidden = Boolean.parseBoolean(dfm.getProperty("hidden").getValue());
task.description = dfm.getProperty("description").getValue().replace("\\n", "\n").replace("%%equal", "=");
task.displayname = dfm.getProperty("displayname").getValue();
task.dueDate = TimeUtil.decodeFromString(dfm.getProperty("duedate").getValue());
task.subject = HomeworkSubject.getRegisteredSubjects().get(Integer.parseInt(dfm.getProperty("subject").getValue()));
dfm.closeFile();
return task;
}
@Override
public String toString() {
return displayname;
}
}
| mit |
zalando/nakadi | core-services/src/test/java/org/zalando/nakadi/validation/JsonSchemaEnrichmentTest.java | 2067 | package org.zalando.nakadi.validation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.DefaultResourceLoader;
import org.zalando.nakadi.domain.CleanupPolicy;
import org.zalando.nakadi.domain.EventType;
import org.zalando.nakadi.utils.EventTypeTestBuilder;
import java.io.IOException;
import java.util.UUID;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.zalando.nakadi.utils.TestUtils.readFile;
import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONObjectAs;
public class JsonSchemaEnrichmentTest {
private JsonSchemaEnrichment loader;
@Before
public void before() throws IOException {
loader = new JsonSchemaEnrichment(new DefaultResourceLoader(), "classpath:schema_metadata.json");
}
@Test
public void enforceStrict() throws Exception {
final JSONArray testCases = new JSONArray(
readFile("strict-validation.json"));
for (final Object testCaseObject : testCases) {
final JSONObject testCase = (JSONObject) testCaseObject;
final String description = testCase.getString("description");
final JSONObject original = testCase.getJSONObject("original_schema");
final JSONObject effective = testCase.getJSONObject("effective_schema");
final EventType eventType = EventTypeTestBuilder.builder().schema(original).build();
assertThat(description, loader.effectiveSchema(eventType), is(sameJSONObjectAs(effective)));
}
}
@Test
public void testMetadata() {
final String randomEventTypeName = UUID.randomUUID().toString();
for (final CleanupPolicy policy : CleanupPolicy.values()) {
final JSONObject metadata = loader.createMetadata(randomEventTypeName, policy);
Assert.assertNotNull(metadata);
Assert.assertTrue(metadata.toString(0).contains(randomEventTypeName));
}
}
} | mit |
YukiSora/shitake | app/src/main/java/moe/yukisora/shitake/AccountActivity.java | 1893 | package moe.yukisora.shitake;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import moe.yukisora.shitake.ui.account.ProfileFragment;
import moe.yukisora.shitake.ui.account.RegisterFragment;
public class AccountActivity extends AppCompatActivity {
public static final String REGISTER_PARAM = "isRegistering";
private ProfileFragment profileFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_generic);
Bundle b = getIntent().getExtras();
boolean isRegistering = false;
if (b != null) {
isRegistering = b.getBoolean(REGISTER_PARAM);
}
if (isRegistering) {
goToRegisterFragment();
} else {
goToProfileFragment();
}
}
private void goToRegisterFragment() {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.activity_main_vg_fragment, new RegisterFragment())
.commit();
}
@Override
public void onBackPressed() {
String tag = getSupportFragmentManager().findFragmentById(R.id.activity_main_vg_fragment).getTag();
String tag2 = tag != null ? tag : "";
if (tag2.equals("taunt")) {
goToProfileFragment();
} else if (tag2.equals("profile")) {
if (profileFragment == null || profileFragment.canExit()) {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
private void goToProfileFragment() {
profileFragment = new ProfileFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.activity_main_vg_fragment, profileFragment, "profile")
.commit();
}
}
| mit |
wascar10/nowel | src/main/java/fr/ironcraft/nowel/entity/model/stuff/ModelSantaHat.java | 1832 | package fr.ironcraft.nowel.entity.model.stuff;
import fr.ironcraft.nowel.Nowel;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.util.ResourceLocation;
public class ModelSantaHat extends ModelBase
{
public ModelRenderer h0;
public ModelRenderer h1;
public ModelRenderer h2;
public ModelRenderer h3;
public ModelRenderer h4;
ResourceLocation texture;
public ModelSantaHat()
{
textureWidth = 32;
textureHeight = 32;
texture = new ResourceLocation(Nowel.MODID, "textures/entity/hat/santa.png");
h0 = createModelRenderer(0, 0, -5F, -7F, -5F, 10, 1, 10);
h1 = createModelRenderer(0, 16, -4F, -9F, -4F, 8, 2, 8);
h2 = createModelRenderer(0, 16, -3F, -11F, -3F, 6, 2, 6);
h3 = createModelRenderer(0, 16, -2F, -12F, -2F, 4, 1, 4);
h4 = createModelRenderer(0, 16, -1F, -13F, -1F, 2, 1, 2);
}
private ModelRenderer createModelRenderer(int offsetX, int offsetY, float posX, float posY, float posZ, int sizeX, int sizeY, int sizeZ) {
float f = -1F;
ModelRenderer part = new ModelRenderer(this, offsetX, offsetY);
part.addBox(posX, posY, posZ, sizeX, sizeY, sizeZ);
part.setRotationPoint(0F, -22.5F, 0F);
part.setTextureSize(textureWidth, textureHeight);
return (part);
}
public void setRotationAngles(float angleX, float angleY)
{
h0.rotateAngleX = angleX;
h0.rotateAngleY = angleY;
this.copyModelAngles(h0, h1);
this.copyModelAngles(h0, h2);
this.copyModelAngles(h0, h3);
this.copyModelAngles(h0, h4);
}
public void render(float angleX, float angleY, float par2)
{
setRotationAngles(angleX, angleY);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
h0.render(par2);
h1.render(par2);
h2.render(par2);
h3.render(par2);
h4.render(par2);
}
} | mit |
bmaxwell921/SwapShip | core/src/main/swapship/common/OffensiveSpecialType.java | 100 | package main.swapship.common;
public enum OffensiveSpecialType {
MISSILE, BEAM, BOMB, NONE
}
| mit |
whitefang57/CreativeTools | src/main/java/com/whitefang/creativeTools/reference/Reference.java | 535 | package com.whitefang.creativetools.reference;
public class Reference {
public static final String MOD_ID = "creativetools";
public static final String MOD_NAME = "Creative Tools";
public static final String VERSION = "1.7.10-1.0";
public static final String CLIENT_PROXY_CLASS = "com.whitefang.creativetools.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.whitefang.creativetools.proxy.ServerProxy";
public static final String GUI_FACTORY_CLASS = "com.whitefang.creativetools.client.gui.GuiFactory";
}
| mit |
praneetloke/AzureStorageExplorerAndroid | app/src/main/java/com/pl/azurestorageexplorer/models/ARMStorageService.java | 685 | package com.pl.azurestorageexplorer.models;
/**
* Created by Praneet Loke on 7/30/2016.
*/
public class ARMStorageService {
private String id;
private String name;
private String location;
public ARMStorageService(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| mit |
nls-oskari/oskari-server | control-base/src/main/java/fi/nls/oskari/control/view/PublishPermissionHelper.java | 10228 | package fi.nls.oskari.control.view;
import fi.nls.oskari.analysis.AnalysisHelper;
import fi.nls.oskari.cache.JedisManager;
import fi.nls.oskari.control.ActionDeniedException;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.Role;
import fi.nls.oskari.domain.User;
import fi.nls.oskari.domain.map.MyPlaceCategory;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.domain.map.analysis.Analysis;
import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.analysis.service.AnalysisDbService;
import fi.nls.oskari.map.analysis.service.AnalysisDbServiceMybatisImpl;
import fi.nls.oskari.map.layer.OskariLayerService;
import fi.nls.oskari.myplaces.MyPlacesService;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.UserService;
import fi.nls.oskari.util.ConversionHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.oskari.map.userlayer.service.UserLayerDbService;
import org.oskari.permissions.PermissionService;
import org.oskari.permissions.model.*;
import org.oskari.service.util.ServiceFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Created by SMAKINEN on 17.8.2015.
*/
public class PublishPermissionHelper {
private static final Logger LOG = LogFactory.getLogger(PublishPermissionHelper.class);
private MyPlacesService myPlaceService = null;
private AnalysisDbService analysisService = null;
private UserLayerDbService userLayerService = null;
private OskariLayerService layerService = null;
private PermissionService permissionsService = null;
private static final String PREFIX_MYPLACES = "myplaces_";
private static final String PREFIX_ANALYSIS = "analysis_";
private static final String PREFIX_USERLAYER = "userlayer_";
public void init() {
if (myPlaceService == null) {
setMyPlacesService(OskariComponentManager.getComponentOfType(MyPlacesService.class));
}
if (analysisService == null) {
setAnalysisService(new AnalysisDbServiceMybatisImpl());
}
if (userLayerService == null) {
setUserLayerService(OskariComponentManager.getComponentOfType(UserLayerDbService.class));
}
if (permissionsService == null) {
setPermissionsService(OskariComponentManager.getComponentOfType(PermissionService.class));
}
if (layerService == null) {
setOskariLayerService(ServiceFactory.getMapLayerService());
}
}
public void setMyPlacesService(final MyPlacesService service) {
myPlaceService = service;
}
public void setAnalysisService(final AnalysisDbService service) {
analysisService = service;
}
public void setUserLayerService(final UserLayerDbService service) {
userLayerService = service;
}
public void setPermissionsService(final PermissionService service) {
permissionsService = service;
}
public void setOskariLayerService(final OskariLayerService service) {
layerService = service;
}
public void setupDrawPermission(final String drawLayerId, final User user) throws ActionException {
if(!myPlaceService.canModifyCategory(user, drawLayerId)) {
throw new ActionDeniedException("Trying to publish another users layer as drawlayer!");
}
Resource resource = myPlaceService.getResource(drawLayerId);
if(resource.hasPermission(user, myPlaceService.PERMISSION_TYPE_DRAW)) {
// clear up any previous DRAW permissions
resource.removePermissionsFromAllUsers(myPlaceService.PERMISSION_TYPE_DRAW);
}
try {
// add DRAW permission for all roles currently in the system
for(Role role: UserService.getInstance().getRoles()) {
final Permission perm = new Permission();
perm.setRoleId((int) role.getId());
perm.setType(myPlaceService.PERMISSION_TYPE_DRAW);
resource.addPermission(perm);
}
} catch (Exception e) {
LOG.error(e, "Error generating DRAW permissions for myplaces layer");
}
permissionsService.saveResource(resource);
}
JSONArray getPublishableLayers(final JSONArray selectedLayers, final User user) throws ActionException {
if(selectedLayers == null || user == null) {
throw new ActionParamsException("Could not get selected layers");
}
final JSONArray filteredList = new JSONArray();
LOG.debug("Selected layers:", selectedLayers);
String userUuid = user.getUuid();
try {
for (int i = 0; i < selectedLayers.length(); ++i) {
JSONObject layer = selectedLayers.getJSONObject(i);
final String layerId = layer.getString("id");
if (layerId.startsWith(PREFIX_MYPLACES)) {
// check publish right for published myplaces layer
if (hasRightToPublishMyPlaceLayer(layerId, userUuid, user.getScreenname())) {
filteredList.put(layer);
}
} else if (layerId.startsWith(PREFIX_ANALYSIS)) {
// check publish right for published analysis layer
if (hasRightToPublishAnalysisLayer(layerId, user)) {
filteredList.put(layer);
}
} else if (layerId.startsWith(PREFIX_USERLAYER)) {
// check publish rights for user layer
if (hasRightToPublishUserLayer(layerId, user)) {
filteredList.put(layer);
}
} else if (hasRightToPublishLayer(layerId, user)) {
// check publish right for normal layer
filteredList.put(layer);
}
}
} catch (Exception e) {
LOG.error(e, "Error parsing myplaces layers from published layers", selectedLayers);
}
LOG.debug("Filtered layers:", filteredList);
return filteredList;
}
private boolean hasRightToPublishMyPlaceLayer(final String layerId, final String userUuid, final String publisherName) {
final long categoryId = ConversionHelper.getLong(layerId.substring(PREFIX_MYPLACES.length()), -1);
if (categoryId == -1) {
LOG.warn("Error parsing layerId:", layerId);
return false;
}
final List<Long> publishedMyPlaces = new ArrayList<Long>();
publishedMyPlaces.add(categoryId);
final List<MyPlaceCategory> myPlacesLayers = myPlaceService.getMyPlaceLayersById(publishedMyPlaces);
for (MyPlaceCategory place : myPlacesLayers) {
if (place.isOwnedBy(userUuid)) {
myPlaceService.updatePublisherName(categoryId, userUuid, publisherName); // make it public
return true;
}
}
LOG.warn("Found my places layer in selected that isn't users own or isn't published any more! LayerId:", layerId, "User UUID:", userUuid);
return false;
}
private boolean hasRightToPublishAnalysisLayer(final String layerId, final User user) {
final long analysisId = AnalysisHelper.getAnalysisIdFromLayerId(layerId);
if(analysisId == -1) {
return false;
}
final Analysis analysis = analysisService.getAnalysisById(analysisId);
if (!analysis.getUuid().equals(user.getUuid())) {
LOG.warn("Found analysis layer in selected that isn't users own! LayerId:", layerId, "User UUID:", user.getUuid(), "Analysis UUID:", analysis.getUuid());
return false;
}
final Set<String> permissions = permissionsService.getResourcesWithGrantedPermissions(
ResourceType.analysislayer, user, PermissionType.PUBLISH);
LOG.debug("Analysis layer publish permissions", permissions);
final String permissionKey = "analysis+"+analysis.getId();
LOG.debug("PublishPermissions:", permissions);
boolean hasPermission = permissions.contains(permissionKey);
if (hasPermission) {
// write publisher name for analysis
analysisService.updatePublisherName(analysisId, user.getUuid(), user.getScreenname());
} else {
LOG.warn("Found analysis layer in selected that isn't publishable any more! Permissionkey:", permissionKey, "User:", user);
}
return hasPermission;
}
private boolean hasRightToPublishUserLayer(final String layerId, final User user) {
final long id = ConversionHelper.getLong(layerId.substring(PREFIX_USERLAYER.length()), -1);
if (id == -1) {
LOG.warn("Error parsing layerId:", layerId);
return false;
}
final UserLayer userLayer = userLayerService.getUserLayerById(id);
if (userLayer.isOwnedBy(user.getUuid())) {
userLayerService.updatePublisherName(id, user.getUuid(), user.getScreenname());
return true;
} else {
return false;
}
}
private boolean hasRightToPublishLayer(final String layerId, final User user) {
// layerId might be external so don't use it straight up
int id = ConversionHelper.getInt(layerId, -1);
if (id == -1) {
// invalid id
LOG.warn("Invalid layer with id:", layerId);
return false;
}
final OskariLayer layer = layerService.find(id);
if (layer == null) {
LOG.warn("Couldn't find layer with id:", id);
return false;
}
boolean hasPermission = permissionsService.findResource(ResourceType.maplayer, Integer.toString(layer.getId()))
.filter(r -> r.hasPermission(user, PermissionType.PUBLISH)).isPresent();
if (!hasPermission) {
LOG.warn("User tried to publish layer with no publish permission. LayerID:", layerId, "- User:", user);
}
return hasPermission;
}
}
| mit |
nayan92/ic-hack | OpenOMR/openomr/omr_engine/PitchCalculation.java | 4129 | /***************************************************************************
* Copyright (C) 2006 by Arnaud Desaedeleer *
* arnaud@desaedeleer.com *
* *
* This file is part of OpenOMR *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
package openomr.omr_engine;
public class PitchCalculation
{
public final int KEY_TREBLE = 0;
public final int KEY_BASS = 1;
public final int KEY_ALTO = 2;
private int note;
private int origNote;
private int duration;
//private int xPosition;
public PitchCalculation()
{
note = 0;
duration = 3;
//key = KEY_TREBLE;
//timesig = 0;
}
public void setNote(int yPos, int noteDistance, int refPos)
{
origNote = (int) Math.floor((refPos - yPos) / (noteDistance/2.0));
//System.out.printf("yPos=%d, refPos=%d, noteDistance=%d, note=%d\n", yPos, refPos, noteDistance, note);
note = origNote;
note = calcNotePitch(origNote);
}
public void setDuration(int duration)
{
this.duration = duration;
}
public int getDuration()
{
return duration;
}
private int calcNotePitch(int origNote)
{
int num = origNote / 7;
int tempNote = origNote;
if (tempNote < 0)
{
while (true)
{
if (tempNote > -7)
break;
tempNote+=7;
}
}
else if (tempNote > 6)
{
while (true)
{
if (tempNote < 7)
break;
tempNote-=7;
}
}
if (tempNote >= 0 && tempNote <= 6)
{
switch (tempNote)
{
case 0: return 0+7*num;
case 1: return 1+7*num;
case 2: return 3+7*num;
case 3: return 5+7*num;
case 4: return 7+7*num;
case 5: return 8+7*num;
case 6: return 10+7*num;
}
}
else if (tempNote < 0 && tempNote >= -6)
{
switch (tempNote)
{
case -1: return -2+7*num;
case -2: return -4+7*num;
case -3: return -6+7*num;
case -4: return -8+7*num;
case -5: return -9+7*num;
case -6: return -11+7*num;
}
}
return -1;
}
public int getNote()
{
return note;
}
public void printNote()
{
int tempNote = origNote;
if (tempNote < 0)
{
while (true)
{
if (tempNote > 0)
break;
tempNote+=7;
}
}
if (tempNote % 7 == 0)
System.out.print("E ");
else if (tempNote % 7 == 1)
System.out.print("F ");
else if (tempNote % 7 == 2)
System.out.print("G ");
else if (tempNote % 7 == 3)
System.out.print("A ");
else if (tempNote % 7 == 4)
System.out.print("B ");
else if (tempNote % 7 == 5)
System.out.print("C ");
else if (tempNote % 7 == 6)
System.out.print("D ");
System.out.println("- Duration " + duration);
}
}
| mit |
jmusun1/sampleheroku | src/main/java/com/pge/ev/FileReader.java | 6431 | package com.pge.ev;
import java.util.*;
import java.io.*;
public class FileReader
{
public static double[] readPeaksTieredRateFile()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Rate_Components_Peaks.txt").getPath()));
lineData = inFile.nextLine();//Gets rid of header
inLine = new Scanner(lineData);
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find tieredRateFile");
}
double tempRate = 0;
double[] returnArray = new double[6];
for(int i = 0; i < 6; i++)
{
inFile.nextLine();
inLine = new Scanner(inFile.nextLine());
while(inLine.hasNext())
{
tempRate += inLine.nextDouble();
}
returnArray[i] = tempRate;
tempRate = 0;
}
inFile.close();
inLine.close();
return returnArray;
}
public static double[][] getBreakdownRates()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Rate_Components_Peaks.txt").getPath()));
lineData = inFile.nextLine();//gets rid of header
inLine = new Scanner(lineData);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Can't find tieredRateFile");
}
double[][] returnArray = new double[13][6];//Component-Peak
for(int j = 0; j < 6; j++)
{
inFile.nextLine();//deletes the line that says the type of season and peak
inLine = new Scanner(inFile.nextLine());
for(int i = 0; i < 13; i++)
{
returnArray[i][j] = inLine.nextDouble();
}
}
inLine.close();
inFile.close();
return returnArray;
}
public static String[][] readWinterPeakTimes()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
inLine.useDelimiter(",");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Winter_Peak_Times.csv").getPath()));
lineData = inFile.nextLine();//gets rid of first line with the list of times
inLine = new Scanner(lineData);
inLine.useDelimiter(",");
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find Winter Peak Times File");
}
String[][] returnArray = new String[7][24];
for(int i = 0; i < 7; i++)
{
inLine = new Scanner(inFile.nextLine());
inLine.useDelimiter(",");
inLine.next();//gets rid of Day
for(int j = 0; j < 24; j++)
{
returnArray[i][j] = inLine.next();
}
}
inLine.close();
inFile.close();
return returnArray;
}
public static String[][] readSummerPeakTimes()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
inLine.useDelimiter(",");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Summer_Peak_Times.csv").getPath()));
lineData = inFile.nextLine();//gets rid of first line with the list of times
inLine = new Scanner(lineData);
inLine.useDelimiter(",");
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find Summer Peak Times File");
}
String[][] returnArray = new String[7][24];
for(int i = 0; i < 7; i++)
{
inLine = new Scanner(inFile.nextLine());
inLine.useDelimiter(",");
inLine.next();//gets rid of Day
for(int j = 0; j < 24; j++)
{
returnArray[i][j] = inLine.next();
}
}
inLine.close();
inFile.close();
return returnArray;
}
public static String[][] readSummerPeakTimesDST()//Daylight savings time
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
inLine.useDelimiter(",");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Summer_Peak_Times_DaylightSavings.csv").getPath()));
lineData = inFile.nextLine();//gets rid of first line with the list of times
inLine = new Scanner(lineData);
inLine.useDelimiter(",");
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find Summer Peak Daylight Savings Time File");
}
String[][] returnArray = new String[7][24];
for(int i = 0; i < 7; i++)
{
inLine = new Scanner(inFile.nextLine());
inLine.useDelimiter(",");
inLine.next();//gets rid of Day
for(int j = 0; j < 24; j++)
{
returnArray[i][j] = inLine.next();
}
}
inLine.close();
inFile.close();
return returnArray;
}
public static String[][] readWinterPeakTimesDST()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
inLine.useDelimiter(",");
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/EV_Winter_Peak_Times_DaylightSavings.csv").getPath()));
lineData = inFile.nextLine();//gets rid of first line with the list of times
inLine = new Scanner(lineData);
inLine.useDelimiter(",");
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find Winter Peak Daylight Savings Times File");
}
String[][] returnArray = new String[7][24];
for(int i = 0; i < 7; i++)
{
inLine = new Scanner(inFile.nextLine());
inLine.useDelimiter(",");
inLine.next();//gets rid of Day
for(int j = 0; j < 24; j++)
{
returnArray[i][j] = inLine.next();
}
}
inLine.close();
inFile.close();
return returnArray;
}
public static List<String> readHolidaysFile()
{
Scanner inFile = new Scanner("");
String lineData = "";
Scanner inLine = new Scanner("");
List<String> list = new ArrayList<>();
try
{
inFile = new Scanner(new File(FileReader.class.getClassLoader().getResource("RateFiles/Holidays.txt").getPath()));
lineData = inFile.nextLine();//gets rid of first line
inLine = new Scanner(lineData);
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("Can't find Holidays File");
}
while(inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
inFile.close();
inLine.close();
return list;
}
}
| mit |
nking/curvature-scale-space-corners-and-transformations | src/algorithms/imageProcessing/FilterGrid.java | 6266 | package algorithms.imageProcessing;
/**
* adapted from
* http://www.peterkovesi.com/matlabfns/FrequencyFilt/filtergrid.m
* which has copyright:
* Copyright (c) 1996-2013 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% peter.kovesi at uwa edu au
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2013
*
* Note that http://pydoc.net/Python/phasepack/1.4/phasepack.filtergrid/
* was also useful in finding ifftshift.
*
* Generates grid for constructing frequency domain filters
%
% Usage: [radius, u1, u2] = filtergrid(rows, cols)
% [radius, u1, u2] = filtergrid([rows, cols])
%
% Arguments: rows, cols - Size of image/filter
%
% Returns:
*
* @author nichole
*/
public class FilterGrid {
/**
* usage: filtergrid(nRows, nCols)
*
* @param nRows
* @param nCols
* @returns [radius, u1, u2] where
radius - Grid of size [nRows nCols] containing normalised
radius values from 0 to 0.5. Grid is quadrant
shifted so that 0 frequency is at radius(1,1)
u1, u2 - Grids containing normalised frequency values
ranging from -0.5 to 0.5 in x and y directions
respectively. u1 and u2 are quadrant shifted.
NOTE: the returned results use notation a[row][col]
*/
public FilterGridProducts filtergrid(int nRows, int nCols) {
/*
Set up X and Y spatial frequency matrices, u1 and u2, with ranges
normalised to +/- 0.5 The following code adjusts things appropriately for
odd and even values of rows and columns so that the 0 frequency point is
placed appropriately.
if mod(cols,2)
u1range = [-(cols-1)/2:(cols-1)/2]/(cols-1);
else
u1range = [-cols/2:(cols/2-1)]/cols;
end
if mod(rows,2)
u2range = [-(rows-1)/2:(rows-1)/2]/(rows-1);
else
u2range = [-rows/2:(rows/2-1)]/rows;
end
[u1,u2] = meshgrid(u1range, u2range);
*/
double[] u1Range = new double[nCols];
if ((nCols & 1) == 1) {
//u1range = [-(cols-1)/2:(cols-1)/2]/(cols-1);
//if nCols=3, this becomes [-1, 0, 1] --> [-0.5, 0, 0.5]
u1Range[0] = -(nCols-1)/2.;
for (int i = 1; i < nCols; ++i) {
u1Range[i] = u1Range[0] + i;
}
for (int i = 0; i < nCols; ++i) {
u1Range[i] /= (nCols - 1.);
}
} else {
//u1range = [-cols/2:(cols/2-1)]/cols;
//if nCols=4, this becomes [-2, -1, 0, 1] --> [-0.5, -0.25, 0, 0.25]
u1Range[0] = -nCols/2.;
for (int i = 1; i < nCols; ++i) {
u1Range[i] = u1Range[0] + i;
}
for (int i = 0; i < nCols; ++i) {
u1Range[i] /= (double)(nCols);
}
}
double[] u2Range = new double[nRows];
if ((nRows & 1) == 1) {
//u2range = [-(rows-1)/2:(rows-1)/2]/(rows-1);
//if nRows=3, this becomes [-1, 0, 1] --> [-0.5, 0, 0.5]
u2Range[0] = -(nRows-1)/2.;
for (int i = 1; i < nRows; ++i) {
u2Range[i] = u2Range[0] + i;
}
for (int i = 0; i < nRows; ++i) {
u2Range[i] /= (nRows - 1.);
}
} else {
//u2range = [-rows/2:(rows/2-1)]/rows;
//if nRows=4, this becomes [-2, -1, 0, 1] --> [-0.5, -0.25, 0, 0.25]
u2Range[0] = -nRows/2.;
for (int i = 1; i < nRows; ++i) {
u2Range[i] = u2Range[0] + i;
}
for (int i = 0; i < nRows; ++i) {
u2Range[i] /= (double)(nRows);
}
}
// nRows X nCols
//[u1,u2] = meshgrid(u1range, u2range);
double[][] u1 = new double[nRows][];
double[][] u2 = new double[nRows][];
for (int i = 0; i < nRows; ++i) {
u1[i] = new double[nCols];
u2[i] = new double[nCols];
System.arraycopy(u1Range, 0, u1[i], 0, nCols);
}
for (int i = 0; i < nRows; ++i) {
double v = u2Range[i];
for (int j = 0; j < nCols; ++j) {
u2[i][j] = v;
}
}
ImageProcessor imageProcessor = new ImageProcessor();
u1 = imageProcessor.ifftShift(u1);
u2 = imageProcessor.ifftShift(u2);
int len0 = u1.length;
int len1 = u1[0].length;
double[][] radius = new double[len0][];
for (int i = 0; i < len0; ++i) {
radius[i] = new double[len1];
for (int j = 0; j < len1; ++j) {
double v = u1[i][j] * u1[i][j] + u2[i][j] * u2[i][j];
radius[i][j] = Math.sqrt(v);
}
}
FilterGridProducts products = new FilterGridProducts(radius, u1, u2);
return products;
}
public class FilterGridProducts {
private final double[][] radius;
private final double[][] u1;
private final double[][] u2;
public FilterGridProducts(double[][] theRadius, double[][] theU1,
double[][] theU2) {
radius = theRadius;
u1 = theU1;
u2 = theU2;
}
/**
* @return the radius
*/
public double[][] getRadius() {
return radius;
}
/**
* @return the u1
*/
public double[][] getU1() {
return u1;
}
/**
* @return the u2
*/
public double[][] getU2() {
return u2;
}
}
}
| mit |
JohannaMoose/eda132 | Assignment 3 - Machine Learning/src/helpers/Math.java | 2182 | package helpers;
import java.util.regex.Pattern;
/**
* Created by Johanna on 2016-03-05.
*/
public class Math {
final static String Digits = "(\\p{Digit}+)";
final static String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final static String Exp = "[eE][+-]?"+Digits;
final static String fpRegex =
("[\\x00-\\x20]*"+ // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd
// edition, section 3.10.2.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.("+Digits+")("+Exp+")?)|"+
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" +
"[fFdD]?))" +
"[\\x00-\\x20]*");// Optional trailing "whitespace"
public static boolean isDouble(String value){
return Pattern.matches(fpRegex, value);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/automanage/azure-resourcemanager-automanage/src/main/java/com/azure/resourcemanager/automanage/fluent/BestPracticesVersionsClient.java | 3574 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automanage.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.automanage.fluent.models.BestPracticeInner;
/** An instance of this class provides access to all the operations defined in BestPracticesVersionsClient. */
public interface BestPracticesVersionsClient {
/**
* Get information about a Automanage best practice version.
*
* @param bestPracticeName The Automanage best practice name.
* @param versionName The Automanage best practice version name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return information about a Automanage best practice version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
BestPracticeInner get(String bestPracticeName, String versionName);
/**
* Get information about a Automanage best practice version.
*
* @param bestPracticeName The Automanage best practice name.
* @param versionName The Automanage best practice version name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return information about a Automanage best practice version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BestPracticeInner> getWithResponse(String bestPracticeName, String versionName, Context context);
/**
* Retrieve a list of Automanage best practices versions.
*
* @param bestPracticeName The Automanage best practice name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response of the list best practice operation.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<BestPracticeInner> listByTenant(String bestPracticeName);
/**
* Retrieve a list of Automanage best practices versions.
*
* @param bestPracticeName The Automanage best practice name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response of the list best practice operation.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<BestPracticeInner> listByTenant(String bestPracticeName, Context context);
}
| mit |
intercom/intercom-cordova | intercom-plugin/src/android/CordovaHeaderInterceptor.java | 260 | package io.intercom.android.sdk.api;
import android.content.Context;
public class CordovaHeaderInterceptor {
public static void setCordovaVersion(Context context, String cordovaVersion) {
HeaderInterceptor.setCordovaVersion(context, cordovaVersion);
}
}
| mit |
Hamhec/FLOCI | src/com/handi/floci/modules/conceptclassification/HierarchyGenerator.java | 5703 | package com.handi.floci.modules.conceptclassification;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.semanticweb.HermiT.Reasoner;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDataRange;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
public class HierarchyGenerator {
private Reasoner m_reasoner;
private OWLOntologyManager m_manager;
private OWLOntology m_ontology;
private String ontologyFilePath;
public HierarchyGenerator(File ontologyFile) throws OWLOntologyCreationException {
ontologyFilePath = ontologyFile.getAbsolutePath();
// Get hold of an ontology manager
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Load the local copy
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(ontologyFile);
m_reasoner = new Reasoner(ontology);
m_manager = manager;
m_ontology = ontology;
}
public void reload() throws OWLOntologyCreationException {
// Get hold of an ontology manager
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
// Load the local copy
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(ontologyFilePath));
m_reasoner = new Reasoner(ontology);
m_manager = manager;
m_ontology = ontology;
}
@SuppressWarnings("unchecked")
public void getConceptsHierarchy(TreeView<String> hierarchyTree) {
TreeItem<String> placeholderItem = new TreeItem<String> ("");
JSONObject json = new JSONObject();
JSONArray links = new JSONArray();
JSONArray nodes = getConceptsJSONList();
OWLClass thing = m_manager.getOWLDataFactory().getOWLThing();
printHierarchy(thing, placeholderItem, links);
json.put("nodes", nodes);
json.put("links", links);
FileWriter file = null;
try {
file = new FileWriter("D:\\Development\\Workspace\\Java\\FLOCI\\src\\com\\handi\\floci\\modules\\display\\data.json");
file.write(json.toJSONString());
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
file.flush();
file.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
TreeItem<String> rootItem = placeholderItem.getChildren().get(0);
rootItem.setExpanded(true);
hierarchyTree.setRoot(rootItem);
}
public void getAllProperties(ListView<OWLObjectProperty> propertiesList) {
for (OWLObjectProperty property : m_ontology.getObjectPropertiesInSignature()) {
propertiesList.getItems().add(property);
}
}
public void getAllAttributes(ListView<OWLDataProperty> attributeList) {
for (OWLDataProperty attribute : m_ontology.getDataPropertiesInSignature()) {
attributeList.getItems().add(attribute);
}
}
public ObservableList<OWLNamedIndividual> getAllIndividuals() {
ObservableList<OWLNamedIndividual> individuals = FXCollections.observableArrayList();
for (OWLNamedIndividual individual : m_ontology.getIndividualsInSignature()) { // getFlattened returns the <E> of a Node<E>
individuals.add(individual);
}
return individuals;
}
@SuppressWarnings("unchecked")
private void printHierarchy(OWLClass clazz, TreeItem<String> parent, JSONArray links) {
if(clazz != null) {
//Only print satisfiable classes
if (m_reasoner.isSatisfiable(clazz)) {
// Create the tree node and add it to its parent
TreeItem<String> clazzItem = new TreeItem<String> (labelFor(clazz));
parent.getChildren().add(clazzItem);
// Find the children and recurse
for (OWLClass child : m_reasoner.getSubClasses(clazz, true).getFlattened()) { // getFlattened returns the <E> of a Node<E>
if (!child.equals(clazz)) {
String label = labelFor(child);
if(!label.equals("Nothing")) {
// Create the Json link:
JSONObject link = new JSONObject();
link.put("source", labelFor(clazz));
link.put("target", label);
links.add(link);
}
printHierarchy(child, clazzItem, links);
}
}
}
}
}
@SuppressWarnings("unchecked")
private JSONArray getConceptsJSONList() {
JSONArray nodes = new JSONArray();
for (OWLClass clazz: m_ontology.getClassesInSignature()) {
JSONObject node = new JSONObject();
node.put("name", labelFor(clazz));
nodes.add(node);
}
return nodes;
}
private String labelFor(OWLClass clazz) {
if(clazz != null)
return clazz.getIRI().getFragment();
return null;
}
// Getters
public OWLOntology getOntology() {
return this.m_ontology;
}
public OWLOntologyManager getOntologyManager() {
return this.m_manager;
}
public Reasoner getReasoner(){
return this.m_reasoner;
}
public String getOntologyFilePath() {
return this.ontologyFilePath;
}
}
| mit |
yrsegal/ModTweaker2 | src/main/java/modtweaker2/mods/tconstruct/handlers/TiCTweaks.java | 4431 | package modtweaker2.mods.tconstruct.handlers;
import static modtweaker2.helpers.InputHelper.toIItemStack;
import static modtweaker2.helpers.InputHelper.toStack;
import java.util.LinkedList;
import java.util.List;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import modtweaker2.helpers.LogHelper;
import modtweaker2.mods.tconstruct.TConstructHelper;
import modtweaker2.utils.BaseListAddition;
import modtweaker2.utils.BaseListRemoval;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.Optional;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import tconstruct.library.crafting.PatternBuilder;
import tconstruct.library.crafting.PatternBuilder.ItemKey;
@ZenClass("mods.tconstruct.Tweaks")
public class TiCTweaks {
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Disabling for 0.5, will do this properly for 0.6 **/
// Tweaks for enabling / disabling Patterns
/*
* @ZenMethod public static void removePattern(IItemStack stack) {
* MineTweakerAPI.apply(new DisablePattern(toStack(stack))); }
*
* private static class DisablePattern implements IUndoableAction { private
* String key; private MaterialSet set; private List list; private ItemStack
* stack; private final ItemStack disable;
*
* public DisablePattern(ItemStack disable) { this.disable = disable; }
*
* //Loops through the pattern mappings to find an entry with the same
* material name
*
* @Override public void apply() { for (Entry<List, ItemStack> entry :
* TConstructRegistry.patternPartMapping.entrySet()) { ItemStack check =
* entry.getValue(); if (check.isItemEqual(disable)) { list =
* entry.getKey(); stack = entry.getValue(); break; } }
*
* TConstructRegistry.patternPartMapping.remove(list); }
*
* @Override public boolean canUndo() { return true; }
*
* @Override public void undo() {
* TConstructRegistry.patternPartMapping.put(list, stack); }
*
* @Override public String describe() { return
* "Disabling creation of the pattern for: " + disable.getDisplayName(); }
*
* @Override public String describeUndo() { return
* "Enabling creation of the pattern for: " + disable.getDisplayName(); }
*
* @Override public Object getOverrideKey() { return null; } }
*/
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ZenMethod
public static void addRepairMaterial(IItemStack stack, String material, int value) {
ItemStack input = toStack(stack);
MineTweakerAPI.apply(new Add(PatternBuilder.instance.new ItemKey(input.getItem(), input.getItemDamage(), value, material)));
}
// Tweaks for setting repair materials
private static class Add extends BaseListAddition<ItemKey> {
public Add(ItemKey recipe) {
super("Repair Material", PatternBuilder.instance.materials);
recipes.add(recipe);
}
@Override
protected String getRecipeInfo(ItemKey recipe) {
return LogHelper.getStackDescription(new ItemStack(recipe.item, 1, recipe.damage));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ZenMethod
public static void removeRepairMaterial(IIngredient output, @Optional String material) {
List<ItemKey> recipes = new LinkedList<ItemKey>();
for (ItemKey recipe : PatternBuilder.instance.materials) {
IItemStack clone = toIItemStack(new ItemStack(recipe.item, 1, recipe.damage));
if ((material != null && material.equalsIgnoreCase(recipe.key)) || (material == null)) {
if (output.matches(clone)) {
recipes.add(recipe);
}
}
}
if(!recipes.isEmpty()) {
MineTweakerAPI.apply(new Remove(recipes));
}
}
// Removes a recipe, apply is never the same for anything, so will always
// need to override it
private static class Remove extends BaseListRemoval<ItemKey> {
public Remove(List<ItemKey> recipes) {
super("Repair Material", PatternBuilder.instance.materials, recipes);
}
@Override
protected String getRecipeInfo(ItemKey recipe) {
return LogHelper.getStackDescription(new ItemStack(recipe.item, 1, recipe.damage));
}
}
}
| mit |
TeamworkGuy2/JParameter | src/twg2/cli/ParameterParserException.java | 661 | package twg2.cli;
/**
* @author TeamworkGuy2
* @since 2015-4-30
*/
public class ParameterParserException {
private ParameterParserExceptionType errorType;
private String message;
private Throwable cause;
/**
* @param message
* @param cause
* @param errorType
*/
public ParameterParserException(ParameterParserExceptionType errorType, String message, Throwable cause) {
this.errorType = errorType;
this.message = message;
this.cause = cause;
}
public ParameterParserExceptionType getParseErrorType() {
return errorType;
}
public String getMessage() {
return message;
}
public Throwable getCause() {
return cause;
}
}
| mit |
crossoverJie/springboot-cloud | sbc-user/user/src/test/java/com/crossoverJie/sbcuser/SbcUserApplicationTests.java | 907 | package com.crossoverJie.sbcuser;
import com.alibaba.fastjson.JSON;
import com.crossoverJie.order.feign.api.OrderServiceClient;
import com.crossoverJie.order.vo.req.OrderNoReqVO;
import com.crossoverJie.order.vo.res.OrderNoResVO;
import com.crossoverJie.sbcorder.common.res.BaseResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SbcUserApplicationTests {
@Autowired
private OrderServiceClient orderServiceClient ;
@Test
public void contextLoads() {
OrderNoReqVO vo = new OrderNoReqVO() ;
vo.setReqNo("qwqe");
BaseResponse<OrderNoResVO> orderNo = orderServiceClient.getOrderNo(vo);
System.out.println(JSON.toJSON(orderNo));
}
}
| mit |
laboratoriobridge/res-api | src/main/java/br/ufsc/bridge/res/dab/write/builder/medicoesobservacoes/avaliacao/AlturaComprimentoBuilder.java | 1733 | package br.ufsc.bridge.res.dab.write.builder.medicoesobservacoes.avaliacao;
import java.util.Date;
import lombok.Getter;
import br.ufsc.bridge.res.dab.write.builder.base.ArquetypeWrapper;
import br.ufsc.bridge.res.dab.write.builder.base.ParentArquetypeWrapper;
import br.ufsc.bridge.res.util.RDateUtil;
@Getter
public class AlturaComprimentoBuilder<PARENT extends ParentArquetypeWrapper<?>> extends ArquetypeWrapper<PARENT> {
private String value;
private Date dataEvento;
public AlturaComprimentoBuilder(PARENT parent, Date dataEvento, String altura) {
super(parent);
this.value = altura;
this.dataEvento = dataEvento;
}
@Override
protected String openTags() {
return "<Altura__fslash__comprimento><name><value>Altura / comprimento</value></name><language>"
+ "<terminology_id><value>ISO_639-1</value></terminology_id><code_string>pt</code_string>"
+ "</language><encoding><terminology_id><value>IANA_character-sets</value></terminology_id>"
+ "<code_string>UTF-8</code_string></encoding><subject></subject><data><Qualquer_evento_as_Point_Event>"
+ "<name><value>Qualquer evento</value></name><time><oe:value>";
}
private String openTagAltura() {
return "</oe:value></time><data><Altura__fslash__comprimento><name>"
+ "<value>Altura / comprimento</value></name><value><magnitude>";
}
@Override
protected String closeTags() {
return "</magnitude><units>cm</units></value></Altura__fslash__comprimento></data><state/>"
+ "</Qualquer_evento_as_Point_Event></data></Altura__fslash__comprimento>";
}
@Override
public String getValue() {
if (this.value != null) {
return RDateUtil.dateToISOEHR(this.dataEvento) + this.openTagAltura() + this.value;
}
return null;
}
}
| mit |
tbian7/pst | hackerrank/src/google/Caesar.java | 560 | package google;
import java.util.ArrayList;
import java.util.List;
public class Caesar {
public static String caesarRotate(String plainText, int K) {
if (plainText == null)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < plainText.length(); i++) {
char c = plainText.charAt(i);
if (c >= 'a' && c <= 'z') {
sb.append((char) ((c - 'a' + K) % 26 + 'a'));
} else if (c >= 'A' && c <= 'Z') {
sb.append((char) ((c - 'A' + K) % 26 + 'A'));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
| mit |
DataVault/datavault | datavault-worker/src/main/java/org/datavaultplatform/worker/tasks/Delete.java | 8550 | package org.datavaultplatform.worker.tasks;
import java.io.File;
import java.lang.reflect.Constructor;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.datavaultplatform.common.event.Error;
import org.datavaultplatform.common.event.InitStates;
import org.datavaultplatform.common.event.UpdateProgress;
import org.datavaultplatform.common.event.delete.DeleteComplete;
import org.datavaultplatform.common.event.delete.DeleteStart;
import org.datavaultplatform.common.io.Progress;
import org.datavaultplatform.common.storage.ArchiveStore;
import org.datavaultplatform.common.storage.Device;
import org.datavaultplatform.common.task.Context;
import org.datavaultplatform.common.task.Task;
import org.datavaultplatform.worker.operations.FileSplitter;
import org.datavaultplatform.worker.operations.ProgressTracker;
import org.datavaultplatform.worker.queue.EventSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Delete extends Task{
private static final Logger logger = LoggerFactory.getLogger(Delete.class);
private String archiveId = null;
private String userID = null;
private int numOfChunks = 0;
private String depositId = null;
private String bagID = null;
private long archiveSize = 0;
private EventSender eventStream = null;
// Maps the model ArchiveStore Id to the storage equivalent
HashMap<String, ArchiveStore> archiveStores = new HashMap<>();
@Override
public void performAction(Context context) {
this.eventStream = (EventSender)context.getEventStream();
logger.info("Delete job - performAction()");
Map<String, String> properties = getProperties();
this.depositId = properties.get("depositId");
this.bagID = properties.get("bagId");
this.userID = properties.get("userId");
this.numOfChunks = Integer.parseInt(properties.get("numOfChunks"));
this.archiveSize = Long.parseLong(properties.get("archiveSize"));
if (this.isRedeliver()) {
eventStream.send(new Error(this.jobID, this.depositId, "Delete stopped: the message had been redelivered, please investigate")
.withUserId(this.userID));
return;
}
this.initStates();
logger.info("bagID: " + this.bagID);
//userStores = this.setupUserFileStores();
this.setupArchiveFileStores();
try {
String tarFileName = this.bagID + ".tar";
Path tarPath = context.getTempDir().resolve(tarFileName);
File tarFile = tarPath.toFile();
eventStream.send(new DeleteStart(this.jobID, this.depositId).withNextState(0)
.withUserId(this.userID));
eventStream.send(new UpdateProgress(this.jobID, this.depositId, 0, this.archiveSize, "Deposit delete started ...")
.withUserId(this.userID));
for (String archiveStoreId : archiveStores.keySet() ) {
ArchiveStore archiveStore = archiveStores.get(archiveStoreId);
this.archiveId = properties.get(archiveStoreId);
logger.info("archiveId: " + this.archiveId);
Device archiveFs = ((Device)archiveStore);
if(archiveFs.hasMultipleCopies()) {
deleteMultipleCopiesFromArchiveStorage(context, archiveFs, tarFileName, tarFile);
} else {
deleteFromArchiveStorage(context, archiveFs, tarFileName, tarFile);
}
}
eventStream.send(new DeleteComplete(this.jobID, this.depositId).withNextState(1)
.withUserId(this.userID));
} catch (Exception e) {
String msg = "Deposit delete failed: " + e.getMessage();
logger.error(msg, e);
eventStream.send(new Error(jobID, depositId, msg)
.withUserId(userID));
throw new RuntimeException(e);
}
}
private void initStates() {
ArrayList<String> states = new ArrayList<>();
states.add("Deleting from archive"); // 0
states.add("Delete complete"); // 1
eventStream.send(new InitStates(this.jobID, this.depositId, states)
.withUserId(userID));
}
private void setupArchiveFileStores() {
// Connect to the archive storage(s). Look out! There are two classes called archiveStore.
for (org.datavaultplatform.common.model.ArchiveStore archiveFileStore : archiveFileStores ) {
try {
Class<?> clazz = Class.forName(archiveFileStore.getStorageClass());
Constructor<?> constructor = clazz.getConstructor(String.class, Map.class);
Object instance = constructor.newInstance(archiveFileStore.getStorageClass(), archiveFileStore.getProperties());
archiveStores.put(archiveFileStore.getID(), (ArchiveStore)instance);
} catch (Exception e) {
String msg = "Deposit failed: could not access archive filesystem : " + archiveFileStore.getStorageClass();
logger.error(msg, e);
eventStream.send(new Error(this.jobID, this.depositId, msg).withUserId(this.userID));
throw new RuntimeException(e);
}
}
}
private void deleteMultipleCopiesFromArchiveStorage(Context context, Device archiveFs, String tarFileName, File tarFile) throws Exception {
Progress progress = new Progress();
ProgressTracker tracker = new ProgressTracker(progress, this.jobID, this.depositId, this.archiveSize, this.eventStream);
Thread trackerThread = new Thread(tracker);
trackerThread.start();
logger.info("deleteMultipleCopiesFromArchiveStorage for deposit : {}",this.depositId);
List<String> locations = archiveFs.getLocations();
for(String location : locations) {
logger.info("Delete from location : {}",location);
try {
if (context.isChunkingEnabled()) {
for( int chunkNum = 1; chunkNum <= this.numOfChunks; chunkNum++) {
Path chunkPath = context.getTempDir().resolve(tarFileName+FileSplitter.CHUNK_SEPARATOR+chunkNum);
File chunkFile = chunkPath.toFile();
String chunkArchiveId = this.archiveId+FileSplitter.CHUNK_SEPARATOR+chunkNum;
archiveFs.delete(chunkArchiveId,chunkFile, progress,location);
logger.info("---------deleteMultipleCopiesFromArchiveStorage ------chunkArchiveId Deleted---- {} ",chunkArchiveId);
}
} else {
archiveFs.delete(this.archiveId,tarFile, progress,location);
logger.info("---------deleteMultipleCopiesFromArchiveStorage ------archiveId Deleted---- {} ",this.archiveId);
}
} finally {
// Stop the tracking thread
tracker.stop();
trackerThread.join();
}
}
}
private void deleteFromArchiveStorage(Context context, Device archiveFs, String tarFileName, File tarFile) throws Exception {
Progress progress = new Progress();
ProgressTracker tracker = new ProgressTracker(progress, this.jobID, this.depositId, this.archiveSize, this.eventStream);
Thread trackerThread = new Thread(tracker);
trackerThread.start();
logger.info("deleteFromArchiveStorage for deposit : {}",this.depositId);
try {
if (context.isChunkingEnabled()) {
for( int chunkNum = 1; chunkNum <= this.numOfChunks; chunkNum++) {
Path chunkPath = context.getTempDir().resolve(tarFileName+FileSplitter.CHUNK_SEPARATOR+chunkNum);
File chunkFile = chunkPath.toFile();
String chunkArchiveId = this.archiveId+FileSplitter.CHUNK_SEPARATOR+chunkNum;
archiveFs.delete(chunkArchiveId,chunkFile, progress);
logger.info("---------deleteFromArchiveStorage ------chunkArchiveId Deleted---- {} ",chunkArchiveId);
}
} else {
archiveFs.delete(this.archiveId,tarFile, progress);
logger.info("---------deleteFromArchiveStorage ------archiveId Deleted---- {} ",this.archiveId);
}
} finally {
// Stop the tracking thread
tracker.stop();
trackerThread.join();
}
}
} | mit |
BahodirBoydedayev/conferenceApp | src/main/java/app/security/CustomUserDetails.java | 1328 | package app.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import app.users.User;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class CustomUserDetails implements UserDetails {
private User user;
private List<GrantedAuthority> authorities;
public CustomUserDetails(User user) {
this.user = user;
this.authorities = user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getLogin();
}
@Override
public boolean isAccountNonExpired() {
return isEnabled();
}
@Override
public boolean isAccountNonLocked() {
return isEnabled();
}
@Override
public boolean isCredentialsNonExpired() {
return isEnabled();
}
@Override
public boolean isEnabled() {
return true;
}
}
| mit |
dhenry/game-of-thrones-api | src/main/java/Main.java | 3213 | import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import model.GameState;
import model.TidesOfBattleResponse;
import spark.ModelAndView;
import spark.ResponseTransformer;
import spark.template.freemarker.FreeMarkerEngine;
import java.util.HashMap;
import java.util.Map;
import static spark.Spark.*;
public class Main {
private static final GameState gameState = new GameState();
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/state", "application/json", (request1, response1) ->
new ObjectMapper().writeValueAsString(gameState.getCurrentGame()));
get("/roundOneCard", "application/json", (request1, response1) ->
new ObjectMapper().writeValueAsString(gameState.getCurrentGame().playRoundOneCard()));
get("/roundTwoCard", "application/json", (request1, response1) ->
new ObjectMapper().writeValueAsString(gameState.getCurrentGame().playRoundTwoCard()));
get("/roundThreeCard", "application/json", (request1, response1) ->
new ObjectMapper().writeValueAsString(gameState.getCurrentGame().playRoundThreeCard()));
get("/wildlings", "application/json", (request1, response1) ->
new ObjectMapper().writeValueAsString(gameState.getCurrentGame().getWildlingsStrength()));
get("/newGame", "application/json", (request1, response1) -> {
gameState.newGame();
return new ObjectMapper().writeValueAsString(gameState.getCurrentGame());
});
get("/tides", "application/json", (request1, response1) -> {
String tides1 = getTidesOfBattleCard();
String tides2 = getTidesOfBattleCard();
String body = request1.body().toString();
return new TidesOfBattleResponse(body, body, tides1, tides2);
}, JsonUtil.json());
get("/battleWildlings", "application/json", (request1, response1) -> {
boolean wonBattle = Boolean.parseBoolean(request1.queryParams("won"));
return new ObjectMapper().writeValueAsString(gameState.getCurrentGame().battleWildlings(wonBattle));
});
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
after((req, res) -> {
res.type("application/json");
});
}
private static class JsonUtil {
public static String toJson(Object object) {
return new Gson().toJson(object);
}
public static ResponseTransformer json() {
return JsonUtil::toJson;
}
}
private static String getTidesOfBattleCard() {
if (gameState.getCurrentGame() != null && gameState.getCurrentGame().hasTidesOfBattle()) {
return gameState.getCurrentGame().drawTidesOfBattleCard();
} else {
gameState.newGame();
return gameState.getCurrentGame().drawTidesOfBattleCard();
}
}
}
| mit |
ugent-cros/cros-core | app/utilities/frontendSimulator/SchedulerSimulator.java | 3054 | package utilities.frontendSimulator;
import models.Assignment;
import models.Drone;
import play.Logger;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Benjamin on 14/04/2015.
*/
public class SchedulerSimulator implements Runnable {
private boolean run = true;
private NotificationSimulator notificationSimulator;
private ExecutorService pool = null;
private Drone availableDrone = null;
private int counter = 0;
public SchedulerSimulator(NotificationSimulator notificationSimulator) {
this.notificationSimulator = notificationSimulator;
}
@Override
public void run() {
pool = Executors.newFixedThreadPool(10);
try {
availableDrone = Drone.FIND.where().eq("status", Drone.Status.AVAILABLE).findList().get(0);
while (run) {
List<Assignment> found = Assignment.FIND.where().eq("progress", 0).findList();
while (found.isEmpty() && run) {
found = Assignment.FIND.where().eq("progress", 0).findList();
}
int amount = Assignment.FIND.findRowCount();
if(found.size() + counter > amount)
throw new RuntimeException("InitDB detected");
Thread.sleep(5000);
for(int i = 0; i < found.size() && run; ++i) {
counter++;
Assignment assignment = found.get(i);
while (availableDrone == null && run) {
try {
Thread.sleep(2000);
availableDrone = Drone.FIND.where().eq("status", Drone.Status.AVAILABLE).findList().get(0);
} catch (InterruptedException e) {
Logger.error(e.getMessage(), e);
}
}
if(run) {
// Update drone
availableDrone.setStatus(Drone.Status.FLYING);
availableDrone.update();
// Update assignment
assignment.setAssignedDrone(availableDrone);
assignment.setProgress(1);
assignment.update();
pool.execute((new AssignmentSimulator(assignment, availableDrone, notificationSimulator)));
availableDrone = null;
}
}
}
} catch(Exception ex) {
// An error occured in the sheduler thread, most likely due to initDB during execution.
pool.shutdownNow();
run = false;
if(availableDrone != null) {
try {
availableDrone.setStatus(Drone.Status.AVAILABLE);
availableDrone.update();
} catch(Exception e) {
// Attempt to reset drone failed
}
}
}
}
}
| mit |
cm-heclouds/JAVA-HTTP-SDK | javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/dtu/ModifyDtuParser.java | 2402 | package cmcc.iot.onenet.javasdk.api.dtu;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cmcc.iot.onenet.javasdk.api.AbstractAPI;
import cmcc.iot.onenet.javasdk.exception.OnenetApiException;
import cmcc.iot.onenet.javasdk.http.HttpPostMethod;
import cmcc.iot.onenet.javasdk.http.HttpPutMethod;
import cmcc.iot.onenet.javasdk.request.RequestInfo.Method;
import cmcc.iot.onenet.javasdk.response.BasicResponse;
import cmcc.iot.onenet.javasdk.utils.Config;
public class ModifyDtuParser extends AbstractAPI {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private String name;
private String filepath;
private HttpPutMethod HttpMethod;
private Integer id;
/**
* TCP透传更新
* @param id :parserId ,Integer
* @param name:名字, String
* @param filepath:路径,String
* @param key:masterkey 或者 设备apikey
*/
public ModifyDtuParser(Integer id, String name, String filepath, String key) {
this.name = name;
this.filepath = filepath;
this.key = key;
this.method = Method.PUT;
Map<String, Object> headmap = new HashMap<String, Object>();
HttpMethod = new HttpPutMethod(method);
headmap.put("api-key", key);
HttpMethod.setHeader(headmap);
if (id == null) {
throw new OnenetApiException("parser id is required ");
}
this.url = Config.getString("test.url") + "/dtu/parser/" + id;
Map<String, String> fileMap = new HashMap<String, String>();
fileMap.put("parser", filepath);
Map<String, String> stringMap = new HashMap<String, String>();
stringMap.put("name", name);
((HttpPutMethod) HttpMethod).setEntity(stringMap, fileMap);
HttpMethod.setcompleteUrl(url, null);
}
public BasicResponse executeApi() {
BasicResponse response = null;
try {
HttpResponse httpResponse = HttpMethod.execute();
response = mapper.readValue(httpResponse.getEntity().getContent(), BasicResponse.class);
response.setJson(mapper.writeValueAsString(response));
return response;
} catch (Exception e) {
logger.error("json error {}", e.getMessage());
throw new OnenetApiException(e.getMessage());
} finally {
try {
HttpMethod.httpClient.close();
} catch (Exception e) {
logger.error("http close error: {}", e.getMessage());
throw new OnenetApiException(e.getMessage());
}
}
}
}
| mit |
ksaua/remock | src/main/java/no/saua/remock/internal/RemockTestExecutionListener.java | 684 | package no.saua.remock.internal;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* Resets all spies and mocks on every test
*/
public class RemockTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
ApplicationContext applicationContext = testContext.getApplicationContext();
for (Resettable resettable : applicationContext.getBeansOfType(Resettable.class).values()) {
resettable.reset();
}
}
}
| mit |
rongcloud/server-sdk-java | src/main/java/io/rong/messages/InfoNtfMessage.java | 1212 | package io.rong.messages;
import io.rong.util.GsonUtil;
/**
*
* 提示条(小灰条)通知消息。此类型消息没有 Push 通知。
*
*/
public class InfoNtfMessage extends BaseMessage {
private String message = "";
private String extra = "";
private transient static final String TYPE = "RC:InfoNtf";
public InfoNtfMessage(String message, String extra) {
this.message = message;
this.extra = extra;
}
@Override
public String getType() {
return TYPE;
}
/**
* 获取提示条消息内容。
*
* @return String
*/
public String getMessage() {
return message;
}
/**
* @param message 设置提示条消息内容。
*
*
*/
public void setMessage(String message) {
this.message = message;
}
/**
* 获取附加信息(如果开发者自己需要,可以自己在 App 端进行解析)。
*
* @return String
*/
public String getExtra() {
return extra;
}
/**
* @param extra 设置附加信息(如果开发者自己需要,可以自己在 App 端进行解析)。
*
*
*/
public void setExtra(String extra) {
this.extra = extra;
}
@Override
public String toString() {
return GsonUtil.toJson(this, InfoNtfMessage.class);
}
} | mit |
haducloc/appslandia-common | src/test/java/com/appslandia/common/formatters/BooleanFormatterTest.java | 1666 | package com.appslandia.common.formatters;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.appslandia.common.base.FormatProvider;
import com.appslandia.common.base.FormatProviderImpl;
import com.appslandia.common.base.Language;
public class BooleanFormatterTest {
BooleanFormatter booleanFormatter;
@Before
public void initialize() {
booleanFormatter = new BooleanFormatter();
Assert.assertEquals(booleanFormatter.getArgumentType(), Boolean.class);
}
@Test
public void test() {
FormatProvider formatProvider = new FormatProviderImpl(Language.getCurrent());
try {
Boolean v = booleanFormatter.parse("true", formatProvider);
Assert.assertTrue(v);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
try {
Boolean v = booleanFormatter.parse("false", formatProvider);
Assert.assertFalse(v);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void test_null() {
FormatProvider formatProvider = new FormatProviderImpl(Language.getCurrent());
try {
Boolean val = booleanFormatter.parse(null, formatProvider);
Assert.assertNull(val);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
try {
booleanFormatter.parse("", formatProvider);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex instanceof FormatterException);
}
}
@Test
public void test_invalid() {
FormatProvider formatProvider = new FormatProviderImpl(Language.getCurrent());
try {
booleanFormatter.parse("tru-e", formatProvider);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex instanceof FormatterException);
}
}
}
| mit |
savinovalex/MatrixMult | src/com/company/NumberMutable.java | 131 | package com.company;
/**
* Just a marker for users. if (O instanceof NumberMutable) ...
*/
public interface NumberMutable {
}
| mit |
oscarguindzberg/multibit-hd | mbhd-swing/src/test/java/org/multibit/hd/ui/fest/use_cases/sidebar/tools/verify_network/ShowThenFinishVerifyNetworkUseCase.java | 1328 | package org.multibit.hd.ui.fest.use_cases.sidebar.tools.verify_network;
import org.fest.swing.fixture.FrameFixture;
import org.multibit.hd.ui.fest.use_cases.AbstractFestUseCase;
import org.multibit.hd.ui.languages.MessageKey;
import java.util.Map;
/**
* <p>Use case to provide the following to FEST testing:</p>
* <ul>
* <li>Verify the "tools" screen verify network wizard shows</li>
* </ul>
* <p>Requires the "tools" screen to be showing</p>
*
* @since 0.0.1
*
*/
public class ShowThenFinishVerifyNetworkUseCase extends AbstractFestUseCase {
public ShowThenFinishVerifyNetworkUseCase(FrameFixture window) {
super(window);
}
@Override
public void execute(Map<String, Object> parameters) {
// Click on Verify network
window
.button(MessageKey.SHOW_VERIFY_NETWORK_WIZARD.getKey())
.click();
// Verify the "verify network" wizard appears
assertLabelText(MessageKey.VERIFY_NETWORK_TITLE);
// Verify Finish is present
window
.button(MessageKey.FINISH.getKey())
.requireVisible()
.requireEnabled();
// Click Finish
window
.button(MessageKey.FINISH.getKey())
.click();
// Verify the underlying screen is back
window
.button(MessageKey.SHOW_SIGN_WIZARD.getKey())
.requireVisible()
.requireEnabled();
}
}
| mit |
csap-platform/csap-core | csap-core-service/src/main/java/org/csap/agent/model/HealthManager.java | 55080 | package org.csap.agent.model ;
import java.lang.management.ManagementFactory ;
import java.text.DecimalFormat ;
import java.text.Format ;
import java.text.SimpleDateFormat ;
import java.util.ArrayList ;
import java.util.Arrays ;
import java.util.Date ;
import java.util.Iterator ;
import java.util.List ;
import java.util.Map ;
import java.util.Optional ;
import java.util.Set ;
import java.util.TreeMap ;
import java.util.regex.Matcher ;
import java.util.stream.Collectors ;
import java.util.stream.Stream ;
import org.apache.commons.lang3.StringUtils ;
import org.csap.agent.CsapApis ;
import org.csap.agent.CsapConstants ;
import org.csap.agent.container.C7 ;
import org.csap.agent.integrations.CsapEvents ;
import org.csap.agent.integrations.MetricsPublisher ;
import org.csap.agent.linux.OutputFileMgr ;
import org.csap.agent.services.HostKeys ;
import org.csap.agent.services.OsManager ;
import org.csap.agent.services.ServiceOsManager ;
import org.csap.helpers.CSAP ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import com.fasterxml.jackson.databind.JsonNode ;
import com.fasterxml.jackson.databind.ObjectMapper ;
import com.fasterxml.jackson.databind.node.ArrayNode ;
import com.fasterxml.jackson.databind.node.ObjectNode ;
public class HealthManager {
final Logger logger = LoggerFactory.getLogger( getClass( ) ) ;
public static final String HEALTH_SUMMARY = "summary" ;
public static final String HEALTH_DETAILS = "details" ;
public static final String RUNAWAY_KILL = "/runaway/kill/" ;
CsapApis csapApis ;
ObjectMapper jsonMapper ;
HealthForAdmin healthForAdmin ;
HealthForAgent healthForAgent ;
final com.sun.management.OperatingSystemMXBean osStats = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean( ) ;
public HealthManager (
CsapApis csapApis,
ObjectMapper jsonMapper ) {
this.csapApis = csapApis ;
this.jsonMapper = jsonMapper ;
healthForAdmin = new HealthForAdmin( csapApis, jsonMapper ) ;
healthForAgent = new HealthForAgent( csapApis, jsonMapper ) ;
}
public HealthForAdmin admin ( ) {
return healthForAdmin ;
}
public HealthForAgent agent ( ) {
return healthForAgent ;
}
public ArrayNode buildServiceAlertReport ( String project , String filter ) {
if ( project == null ) {
project = csapApis.application( ).getActiveProjectName( ) ;
}
// ArrayList<String> lifeCycleHostList = csapApp
// .getLifeCycleToHostMap().get(clusterFilter);
var requestedPackage = csapApis.application( ).getProject( project ) ;
var includeKubernetesCheck = false ;
if ( csapApis.application( ).isAdminProfile( ) ) {
includeKubernetesCheck = true ; // detects k8s crashed processes
}
var serviceReport = jsonMapper.createArrayNode( ) ;
var healthReport = build_health_report(
ServiceAlertsEnum.ALERT_LEVEL, includeKubernetesCheck,
requestedPackage ) ;
JsonNode detailByHost = healthReport.path( HealthManager.HEALTH_DETAILS ) ;
CSAP.asStream( detailByHost.fieldNames( ) ).forEach( hostName -> {
CSAP.jsonStream( detailByHost.path( hostName ) )
.filter( JsonNode::isObject )
.map( alert -> (ObjectNode) alert )
.filter( alert -> alert.has( "source" ) )
.filter( alert -> alert.path( "source" ).asText( "-" ).matches( Matcher.quoteReplacement(
filter ) ) )
.filter( alert -> alert.path( "category" ).asText( "none" ).startsWith( "os-process" ) )
.forEach( alert -> {
alert.put( "host", hostName ) ;
serviceReport.add( alert ) ;
} ) ;
} ) ;
return serviceReport ;
}
public ObjectNode build_health_report (
double alertLevel ,
boolean includeKubernetesWarnings ,
Project project ) {
logger.debug( "alertLevel: {}, includeKubernetesWarnings: {}", alertLevel, includeKubernetesWarnings,
project ) ;
var timer = csapApis.metrics( ).startTimer( ) ;
ObjectNode healthReport = jsonMapper.createObjectNode( ) ;
ObjectNode summaryReport = healthReport.putObject( "summary" ) ;
ObjectNode detailReport = healthReport.putObject( "details" ) ;
if ( csapApis.application( ).isAdminProfile( ) ) {
buildErrorReportsForAdmin( summaryReport, detailReport, alertLevel, includeKubernetesWarnings, project ) ;
} else {
ObjectNode agentHealthReport = build_health_report_for_agent( alertLevel, includeKubernetesWarnings,
null ) ;
ArrayNode errors = (ArrayNode) agentHealthReport.get( HEALTH_SUMMARY ) ;
// ObjectNode states = (ObjectNode) agentHealthReport.get( "states" ) ;
if ( errors.size( ) > 0 ) {
summaryReport.set( csapApis.application( ).getCsapHostName( ), agentHealthReport.get(
HEALTH_SUMMARY ) ) ;
detailReport.set( csapApis.application( ).getCsapHostName( ), agentHealthReport.get(
HEALTH_DETAILS ) ) ;
// healthReport.set( "states", states ) ;
}
}
logger.debug( "healthReport: {}", CSAP.jsonPrint( healthReport ) ) ;
csapApis.metrics( ).stopTimer( timer, csapApis.application( ).PERFORMANCE_ID + "build.errors" ) ;
return healthReport ;
}
private void buildErrorReportsForAdmin (
ObjectNode summaryReport ,
ObjectNode detailReport ,
double alertLevel ,
boolean includeKubernetesWarnings ,
Project requestedProject ) {
// var notes = getReleasePackageStream()
//// .filter( releasePackage -> releasePackage.getLifeCycleToHostMap().get(
// getCurrentLifeCycle() ) != null )
// .map( ReleasePackage::getLifeCycleToHostMap )
// .map( Object::toString )
// .collect( Collectors.joining( "\n\n" ) ) ;
//
// logger.info( "notes: {}", notes ) ;
csapApis.application( ).getReleasePackageStream( )
.filter( project -> project.getHostsForEnvironment( csapApis.application( )
.getCsapHostEnvironmentName( ) ) != null )
.filter( project -> {
if ( ( requestedProject == null ) || // default to all packages
( requestedProject == csapApis.application( ).getRootProject( ).getAllPackagesModel( ) ) ||
( project.getName( ).equals( requestedProject.getName( ) ) ) ) {
return true ;
}
return false ;
} )
.forEach( matchedProject -> {
logger.debug( "using hosts in: {}", matchedProject.getName( ) ) ;
var lifecycleHosts = matchedProject.getHostsForEnvironment( csapApis.application( )
.getCsapHostEnvironmentName( ) ) ;
Set<String> kubernetesRunningServices = csapApis.application( ).getHostStatusManager( )
.findRunningKubernetesServices( lifecycleHosts ) ;
for ( String host : lifecycleHosts ) {
// logger.info("Health check on: " + host) ;
ObjectNode hostStatusJson = null ;
if ( csapApis.application( ).getHostStatusManager( ) != null ) {
hostStatusJson = csapApis.application( ).getHostStatusManager( ).getResponseFromHost(
host ) ;
}
ObjectNode hostErrorReport = getAlertsOnRemoteAgent( alertLevel,
includeKubernetesWarnings, host,
hostStatusJson ) ;
JsonNode summaryErrors = hostErrorReport.path( "summary" ) ;
JsonNode detailErrors = hostErrorReport.path( "details" ) ;
summaryReport.set( host, summaryErrors ) ;
detailReport.set( host, detailErrors ) ;
if ( includeKubernetesWarnings &&
( kubernetesRunningServices.size( ) > 0 )
&& summaryErrors.isArray( )
&& ( summaryErrors.size( ) > 0 )
&& summaryErrors.toString( ).contains( ServiceAlertsEnum.KUBERNETES_PROCESS_CHECKS ) ) {
summaryReport.set( host,
filter_errors_for_kubernetes_summary_active_or_crashed(
summaryErrors,
kubernetesRunningServices,
host ) ) ;
detailReport.set( host,
filter_errors_for_kubernetes_details_active_or_crashed(
detailErrors,
kubernetesRunningServices,
host ) ) ;
}
// filter empty hosts
if ( summaryReport.get( host ).size( ) == 0 ) {
summaryReport.remove( host ) ;
}
}
logger.debug( "kubernetes services: {},\n errorsByHost: {}",
kubernetesRunningServices, CSAP.jsonPrint( summaryReport ) ) ;
} ) ;
return ;
}
private JsonNode filter_errors_for_kubernetes_summary_active_or_crashed (
JsonNode summaryErrors ,
Set<String> kubernetesRunningServices ,
String host ) {
ArrayNode translatedErrors = jsonMapper.createArrayNode( ) ;
CSAP.jsonStream( summaryErrors ).forEach( error -> {
String errorMessage = error.asText( ) ;
if ( errorMessage.contains( ServiceAlertsEnum.KUBERNETES_PROCESS_CHECKS ) ) {
Optional<String> foundRunningInstance = kubernetesRunningServices
.stream( )
.filter( runningService -> errorMessage.contains( runningService ) )
.findFirst( ) ;
if ( foundRunningInstance.isEmpty( ) ) {
String convertedText = ServiceAlertsEnum.fromK8sToCrashOrKill( errorMessage ) ;
translatedErrors.add( convertedText ) ;
}
} else {
translatedErrors.add( errorMessage ) ;
}
} ) ;
return translatedErrors ;
}
private JsonNode filter_errors_for_kubernetes_details_active_or_crashed (
JsonNode detailErrors ,
Set<String> kubernetesRunningServices ,
String host ) {
ArrayNode filteredErrors = jsonMapper.createArrayNode( ) ;
CSAP.jsonStream( detailErrors ).forEach( error -> {
String type = error.path( ServiceAlertsEnum.ALERT_TYPE ).asText( ) ;
String serviceName = error.path( ServiceAlertsEnum.ALERT_SOURCE ).asText( ) ;
if ( type.equals( ServiceAlertsEnum.TYPE_KUBERNETES_PROCESS_CHECK ) ) {
Optional<String> foundRunningInstance = kubernetesRunningServices
.stream( )
.filter( serviceName::startsWith )
.findFirst( ) ;
if ( foundRunningInstance.isEmpty( ) ) {
( (ObjectNode) error ).put( ServiceAlertsEnum.ALERT_TYPE,
ServiceAlertsEnum.TYPE_PROCESS_CRASH_OR_KILL ) ;
filteredErrors.add( error ) ;
} else {
// found a running instance on another host - drop this alert
}
} else {
filteredErrors.add( error ) ;
}
} ) ;
return filteredErrors ;
}
private ObjectNode build_health_report_for_agent (
double alertLevel ,
boolean includeKubernetesWarnings ,
String clusterFilter ) {
logger.debug( "Health check" ) ;
ObjectNode alertMessages = jsonMapper.createObjectNode( ) ;
ArrayNode errorArray = alertMessages.putArray( HEALTH_SUMMARY ) ;
try {
alertMessages = alertsBuilder(
alertLevel,
includeKubernetesWarnings,
csapApis.application( ).getCsapHostName( ),
(ObjectNode) csapApis.osManager( ).getHostRuntime( ),
clusterFilter ) ;
} catch ( Exception e ) {
if ( logger.isDebugEnabled( ) ) {
logger.error( "Failed checking VM heath", e ) ;
}
errorArray.add( csapApis.application( ).getCsapHostName( ) + ": " + "Failed HealthCheck reason: " + e
.getMessage( ) ) ;
}
return alertMessages ;
}
public ObjectNode getAlertsOnRemoteAgent (
double alertLevel ,
boolean includeKubernetesWarnings ,
String hostName ,
ObjectNode hostStatusJson ) {
logger.debug( "Health check on: {}", hostName ) ;
ObjectNode alertReport = jsonMapper.createObjectNode( ) ;
ArrayNode summaryErrors = alertReport.putArray( HEALTH_SUMMARY ) ;
ArrayNode detailErrors = alertReport.putArray( HEALTH_DETAILS ) ;
if ( hostStatusJson == null ) {
// errorArray.add( "No response found" ) ;
summaryErrors.add( hostName + " - Agent response does not contain hostStats." ) ;
detailErrors.add( hostName + " - Agent response does not contain hostStats." ) ;
return alertReport ;
} else {
try {
alertReport = alertsBuilder( alertLevel, includeKubernetesWarnings, hostName, hostStatusJson, null ) ;
} catch ( Exception e ) {
if ( logger.isDebugEnabled( ) ) {
logger.error( "failed health check evalutation: {}", CSAP.buildCsapStack( e ) ) ;
}
summaryErrors.add( hostName + ": " + "Failed HealthCheck reason: " + e.getMessage( ) ) ;
detailErrors.add( hostName + ": " + "Failed HealthCheck reason: " + e.getMessage( ) ) ;
return alertReport ;
}
}
return alertReport ;
}
/**
*
* Add errors to errorList.
*
* @param hostName
* @param errorList
* @param responseFromHostStatusJson
* @param clusterFilter
*/
public ObjectNode alertsBuilder (
double alertLevel ,
boolean includeKubernetesWarnings ,
String hostName ,
ObjectNode responseFromHostStatusJson ,
String clusterFilter ) {
ObjectNode alertReport = jsonMapper.createObjectNode( ) ;
ArrayNode summaryReport = alertReport.putArray( HEALTH_SUMMARY ) ;
ArrayNode detailReport = alertReport.putArray( HEALTH_DETAILS ) ;
if ( responseFromHostStatusJson.has( "error" ) ) {
summaryReport.add( hostName + ": " + responseFromHostStatusJson
.path( "error" )
.textValue( ) ) ;
ServiceAlertsEnum.addHostSourceDetailAlert( alertReport, hostName, "response-error",
responseFromHostStatusJson
.path( "error" )
.textValue( ), -1, -1 ) ;
// return result;
return alertReport ;
}
ObjectNode hostStatsNode = (ObjectNode) responseFromHostStatusJson.path( HostKeys.hostStats.jsonId ) ;
if ( hostStatsNode == null ) {
summaryReport.add( hostName + ": " + "Host response missing attribute: hostStats" ) ;
ServiceAlertsEnum.addHostSourceDetailAlert( alertReport, hostName, "response-error",
"missing-host", -1, -1 ) ;
// return result;
return alertReport ;
}
alertsForHostCpu( hostStatsNode, hostName, alertLevel, summaryReport, alertReport ) ;
alertsForHostMemory( hostStatsNode, hostName, summaryReport, alertReport ) ;
alertsForHostFileSystems( hostStatsNode, hostName, alertLevel, summaryReport, alertReport ) ;
ObjectNode serviceHealthCollected = (ObjectNode) responseFromHostStatusJson.path( "services" ) ;
if ( serviceHealthCollected == null ) {
summaryReport.add( hostName + ": " + "Host response missing attribute: services" ) ;
detailReport.add( hostName + ": " + "Host response missing attribute: services" ) ;
// return result;
return alertReport ;
}
alertsForServices( hostName, clusterFilter, serviceHealthCollected, summaryReport,
alertLevel, includeKubernetesWarnings, alertReport ) ;
return alertReport ;
}
private void alertsForServices (
String hostName ,
String clusterFilter ,
ObjectNode serviceHealthCollected ,
ArrayNode summaryErrors ,
double alertLevel ,
boolean includeKubernetesWarnings ,
ObjectNode healthReport ) {
StringBuilder serviceMessages = new StringBuilder( ) ;
logger.debug( "hostName: {}, clusterFilter: {}, csapApis.application().isAgentProfile: {} ", hostName,
clusterFilter,
csapApis.application( ).isAgentProfile( ) ) ;
csapApis.application( )
.getAllPackages( )
// .getServicesWithKubernetesFiltering( hostName )
.getServicesOnHost( hostName )
.filter( serviceInstance -> {
if ( StringUtils.isNotEmpty( clusterFilter ) ) {
return serviceInstance.getLifecycle( ).startsWith( clusterFilter ) ;
} else {
// logger.debug( serviceInstance.toSummaryString() ) ;
return true ;
}
} )
.filter( serviceInstance -> {
if ( csapApis.application( ).isAgentProfile( ) ) {
return serviceInstance.filterInactiveKubernetesWorker( ) ;
} else {
return serviceHealthCollected.has( serviceInstance.getServiceName_Port( ) ) ;
}
} )
.forEach( serviceInstance -> {
if ( ! serviceHealthCollected.has( serviceInstance.getServiceName_Port( ) ) ) {
String message = hostName + ": " + serviceInstance.getServiceName_Port( )
+ " No status found" ;
serviceMessages.append( message + "\n" ) ;
summaryErrors.add( message ) ;
} else {
try {
List<String> serviceAlerts = ServiceAlertsEnum.getServiceAlertsAndUpdateCpu(
serviceInstance, alertLevel,
includeKubernetesWarnings,
serviceHealthCollected.get( serviceInstance.getServiceName_Port( ) ),
csapApis.application( ).rootProjectEnvSettings( ),
healthReport ) ;
// if ( serviceInstance.getServiceName().contains( "crashed" )) {
logger.debug( "{} : serviceAlerts: {}, health: {} ",
serviceInstance.toSummaryString( ),
serviceAlerts,
CSAP.jsonPrint( serviceHealthCollected.get( serviceInstance
.getServiceName_Port( ) ) ) ) ;
for ( String alertDescription : serviceAlerts ) {
summaryErrors.add( alertDescription ) ;
serviceMessages.append( alertDescription + "\n" ) ;
}
} catch ( Exception e ) {
logger.error( "Failed parsing messages{}", CSAP.buildCsapStack( e ) ) ;
}
}
} ) ;
if ( serviceMessages.length( ) > 0 ) {
addNagiosStateMessage( healthReport, "processes", MetricsPublisher.NAGIOS_WARN, serviceMessages
.toString( ) ) ;
}
}
private void alertsForHostFileSystems (
ObjectNode hostStatsNode ,
String hostName ,
double alertLevel ,
ArrayNode summaryAlerts ,
ObjectNode healthReport )
throws NumberFormatException {
logger.debug( "hostName: {}, alertLevel: {}", hostName, alertLevel ) ;
StringBuilder diskMessages = new StringBuilder( ) ;
if ( hostStatsNode.has( "df" ) ) {
ObjectNode dfJson = (ObjectNode) hostStatsNode.path( "df" ) ;
Iterator<String> keyIter = dfJson.fieldNames( ) ;
while ( keyIter.hasNext( ) ) {
String mount = keyIter.next( ) ;
String perCentString = dfJson
.path( mount )
.asText( ) ;
String perCent = perCentString.substring( 0, perCentString.length( ) - 1 ) ;
int perCentInt = Integer.parseInt( perCent ) ;
int diskMax = (int) Math.round( csapApis.application( ).rootProjectEnvSettings( )
.getMaxDiskPercent( hostName ) * alertLevel ) ;
if ( ( csapApis.application( ).rootProjectEnvSettings( ).is_disk_monitored( hostName, mount ) )
&& perCentInt > diskMax ) {
// states.put("disk", MetricsPublisher.NAGIOS_WARN) ;
String message = hostName + ": " + " Disk usage on " + mount + " is: "
+ perCentString + ", max: " + diskMax + "%" ;
summaryAlerts.add( message ) ;
ServiceAlertsEnum.addHostSourceDetailAlert( healthReport, hostName, "disk-percent", mount,
perCentInt, diskMax ) ;
diskMessages.append( message + "\n" ) ;
}
}
} else {
summaryAlerts.add( hostName + ": " + "Host response missing attribute: hostStats.df" ) ;
}
if ( hostStatsNode.has( OsManager.IO_UTIL_IN_PERCENT ) ) {
int ioUsagePercentMax = (int) Math.round( csapApis.application( ).rootProjectEnvSettings( )
.getMaxDeviceIoPercent( hostName ) * alertLevel ) ;
CsapConstants.jsonStream( hostStatsNode.get( OsManager.IO_UTIL_IN_PERCENT ) )
.forEach( device -> {
int deviceUsage = device.get( "percentCapacity" ).asInt( ) ;
if ( deviceUsage > ioUsagePercentMax ) {
String message = hostName + ": " + " IO usage on " + device.get( "name" ) + " is: "
+ deviceUsage + "%, max: " + ioUsagePercentMax
+ "%. Run iostat -dx to investigate" ;
summaryAlerts.add( message ) ;
diskMessages.append( message + "\n" ) ;
ServiceAlertsEnum.addHostSourceDetailAlert( healthReport, hostName, "ioutil-percent",
device.path( "name" ).asText( ), deviceUsage, deviceUsage ) ;
}
} ) ;
}
if ( hostStatsNode.has( "readOnlyFS" ) ) {
ArrayNode readOnlyFS = (ArrayNode) hostStatsNode.path( "readOnlyFS" ) ;
for ( JsonNode item : readOnlyFS ) {
String message = hostName + ": Read Only Filesystem: " + item.asText( ) ;
summaryAlerts.add( message ) ;
diskMessages.append( message + "\n" ) ;
ServiceAlertsEnum.addHostSourceDetailAlert( healthReport, hostName, "fs-read-only", item.asText( ), -1,
-1 ) ;
}
} else {
summaryAlerts
.add( hostName + ": " + "Host response missing attribute: hostStats.readOnlyFS" ) ;
}
if ( diskMessages.length( ) > 0 ) {
addNagiosStateMessage( healthReport, "disk", MetricsPublisher.NAGIOS_WARN, diskMessages.toString( ) ) ;
}
}
private void alertsForHostMemory (
ObjectNode hostStatsNode ,
String hostName ,
ArrayNode errorArray ,
ObjectNode alertReport ) {
if ( hostStatsNode.has( "memoryAggregateFreeMb" ) ) {
int minFree = csapApis.application( ).rootProjectEnvSettings( )
.getMinFreeMemoryMb( hostName ) ;
int freeMem = hostStatsNode
.path( "memoryAggregateFreeMb" )
.asInt( ) ;
logger.debug( "freeMem: {} , minFree: {}", freeMem, minFree ) ;
if ( freeMem < minFree ) {
String message = hostName + ": " + " available memory " + freeMem
+ " < min configured: " + minFree ;
errorArray.add( message ) ;
ServiceAlertsEnum.addHostDetailAlert( alertReport, hostName, "cpu-memory-free-min", freeMem, minFree ) ;
addNagiosStateMessage( alertReport, "memory", MetricsPublisher.NAGIOS_WARN, message ) ;
}
} else {
errorArray.add( hostName + ": "
+ "Host response missing attribute: hostStats.memoryAggregateFreeMb" ) ;
}
}
private void alertsForHostCpu (
ObjectNode hostStatusResponse ,
String hostName ,
double alertLevel ,
ArrayNode errorArray ,
ObjectNode alertReport ) {
int hostLoad = ( (Double) hostStatusResponse
.path( "cpuLoad" )
.asDouble( ) ).intValue( ) ;
int maxLoad = (int) Math.round( csapApis.application( ).rootProjectEnvSettings( )
.getMaxHostCpuLoad( hostName ) * alertLevel ) ;
if ( hostLoad >= maxLoad ) {
String message = hostName + ": " + "current load " + hostLoad + " >= max configured: "
+ maxLoad ;
errorArray.add( message ) ;
ServiceAlertsEnum.addHostDetailAlert( alertReport, hostName, "cpu-load", hostLoad, maxLoad ) ;
addNagiosStateMessage( alertReport, "cpuLoad", MetricsPublisher.NAGIOS_WARN, message ) ;
}
int hostCpu = ( (Double) hostStatusResponse
.path( "cpu" )
.asDouble( ) ).intValue( ) ;
int maxCpu = (int) Math.round( csapApis.application( ).rootProjectEnvSettings( )
.getMaxHostCpu( hostName ) * alertLevel ) ;
if ( hostCpu >= maxCpu ) {
String message = hostName + ": " + "current mpstat cpu " + hostCpu + " >= max configured: "
+ maxCpu ;
errorArray.add( message ) ;
ServiceAlertsEnum.addHostDetailAlert( alertReport, hostName, "cpu-percent", hostCpu, maxCpu ) ;
addNagiosStateMessage( alertReport, "hostCpu", MetricsPublisher.NAGIOS_WARN, message ) ;
}
int hostCpuIoWait = ( (Double) hostStatusResponse
.path( "cpuIoWait" )
.asDouble( ) ).intValue( ) ;
int maxCpuIoWait = (int) Math.round( csapApis.application( ).rootProjectEnvSettings( )
.getMaxHostCpuIoWait( hostName ) * alertLevel ) ;
if ( hostCpuIoWait >= maxCpuIoWait ) {
String message = hostName + ": " + "current mpstat cpu IoWait " + hostCpuIoWait + " >= max configured: "
+ maxCpuIoWait ;
errorArray.add( message ) ;
ServiceAlertsEnum.addHostDetailAlert( alertReport, hostName, "cpu-iowait", hostCpuIoWait, maxCpuIoWait ) ;
addNagiosStateMessage( alertReport, "hostCpuIoWait", MetricsPublisher.NAGIOS_WARN, message ) ;
}
}
/**
*
* Only agents use state
*
* @param stateNode
* @param State
* @param message
*/
private void addNagiosStateMessage ( ObjectNode errorNode , String monitor , String state , String message ) {
ObjectNode stateNode = (ObjectNode) errorNode.get( "states" ) ;
if ( stateNode != null ) {
ObjectNode item = stateNode.putObject( monitor ) ;
item.put( "status", state ) ;
item.put( "message", message ) ;
}
}
static final List<String> csapAdminServices = Arrays.asList( CsapConstants.AGENT_NAME, CsapConstants.ADMIN_NAME ) ;
public void killRunaways ( ) {
if ( csapApis.application( ).isAdminProfile( ) ) {
return ;
}
logger.debug( "Checking services on host to see if we need to be killed" ) ;
findServicesWithResourceRunaway( ).forEach( this::killServiceRunaway ) ;
}
public Stream<ServiceInstance> findServicesWithResourceRunaway ( ) {
// @formatter:off
Stream<ServiceInstance> run_away_stream = csapApis.application( ).getActiveProject( )
.getServicesOnHost( csapApis.application( ).getCsapHostName( ) )
.filter( service -> {
return service.getDefaultContainer( ).isActive( ) ;
} )
// .filter( ServiceInstance::isActive )
.filter( ServiceInstance::is_not_os_process_monitor )
.filter( serviceInstance -> ! csapAdminServices.contains( serviceInstance.getName( ) ) )
// .filter( serviceInstance -> serviceInstance.getDisk() != null )
.filter( this::isServiceResourceRunawayAndTimeToKill ) ;
// @formatter:on
return run_away_stream ;
}
private boolean isServiceResourceRunawayAndTimeToKill ( ServiceInstance serviceDefinition ) {
var isTimeToKill = false ;
var reasons = new ArrayList<String>( ) ;
// long maxAllowedDisk = ServiceAlertsEnum.getMaxDiskInMb( serviceDefinition, application
// .rootProjectEnvSettings( ) ) ;
var maxAllowedDisk = ServiceAlertsEnum.getEffectiveLimit( serviceDefinition, csapApis.application( )
.rootProjectEnvSettings( ), ServiceAlertsEnum.diskSpace ) ;
double resourceThresholdMultiplier = csapApis.application( ).rootProjectEnvSettings( )
.getAutoStopServiceThreshold( serviceDefinition.getHostName( ) ) ;
long diskKillThreshold = Math.round( maxAllowedDisk * resourceThresholdMultiplier ) ;
int currentDisk = 0 ;
try {
for ( ContainerState csapServiceResults : serviceDefinition.getContainerStatusList( ) ) {
currentDisk = csapServiceResults.getDiskUsageInMb( ) ;
logger.debug( "{} : currentDisk: {}, threshold: {}, maxAllowed: {}, maxThresh: {}",
serviceDefinition.getName( ), currentDisk,
resourceThresholdMultiplier, maxAllowedDisk, diskKillThreshold ) ;
if ( currentDisk > diskKillThreshold ) {
isTimeToKill = true ;
reasons.add( "currentDisk: " + " Collected: " + currentDisk + ", kill limit: "
+ diskKillThreshold ) ;
}
for ( ServiceAlertsEnum alert : ServiceAlertsEnum.values( ) ) {
int lastCollectedValue = 0 ;
switch ( alert ) {
case threads:
lastCollectedValue = csapServiceResults.getThreadCount( ) ;
break ;
case sockets:
lastCollectedValue = csapServiceResults.getSocketCount( ) ;
break ;
case openFileHandles:
lastCollectedValue = csapServiceResults.getFileCount( ) ;
break ;
default:
continue ;
}
long maxAllowed = ServiceAlertsEnum.getEffectiveLimit(
serviceDefinition,
csapApis.application( ).rootProjectEnvSettings( ),
alert ) ;
long killThreshold = Math.round( maxAllowed * resourceThresholdMultiplier ) ;
logger.debug( "{} : Item: {} lastCollectedValue: {}, threshold: {}, maxAllowed: {}, maxThresh: {}",
serviceDefinition.getName( ), alert, lastCollectedValue, resourceThresholdMultiplier,
maxAllowed,
killThreshold ) ;
if ( lastCollectedValue > killThreshold ) {
isTimeToKill = true ;
reasons.add(
alert.value + " Collected: " + lastCollectedValue + ", kill limit: "
+ killThreshold ) ;
}
}
csapServiceResults.setResourceViolations( reasons ) ;
}
} catch ( Exception e ) {
logger.warn( "{} Failed runaway processing: {}",
serviceDefinition.getName( ),
CSAP.buildCsapStack( e ) ) ;
}
return isTimeToKill ;
}
private void killServiceRunaway ( ServiceInstance serviceInstance ) {
logger.debug( "Killing service as Service limits exceeded for "
+ serviceInstance.getServiceName_Port( ) ) ;
ArrayList<String> params = new ArrayList<String>( ) ;
StringBuilder reasons = new StringBuilder( ) ;
for ( ContainerState csapServiceResults : serviceInstance.getContainerStatusList( ) ) {
if ( csapServiceResults.getResourceViolations( ).size( ) > 1 ) {
reasons.append( "1 of " + csapServiceResults.getResourceViolations( ).size( ) + ": " ) ;
}
if ( csapServiceResults.getResourceViolations( ).size( ) > 0 ) {
reasons.append( csapServiceResults.getResourceViolations( ).get( 0 ) ) ;
break ;
}
}
// trigger a system event as well.
csapApis.events( ).publishEvent( CsapEvents.CSAP_SYSTEM_CATEGORY + RUNAWAY_KILL
+ serviceInstance.getName( ),
reasons.toString( ), null,
serviceInstance.buildRuntimeState( ) ) ;
// log a user event so it is found easier
csapApis.events( ).publishEvent( CsapEvents.CSAP_USER_SERVICE_CATEGORY + "/"
+ serviceInstance.getName( ),
RUNAWAY_KILL + ": " + reasons,
null,
serviceInstance.buildRuntimeState( ) ) ;
serviceInstance.getDefaultContainer( ).setAutoKillInProgress( true ) ;
try {
OutputFileMgr outputFileMgr = new OutputFileMgr( csapApis.application( ).getCsapWorkingFolder( ),
"/" + serviceInstance.getName( ) + "_runaway" ) ;
if ( serviceInstance.is_docker_server( ) ) {
csapApis.osManager( ).getServiceManager( ).killServiceUsingDocker(
serviceInstance,
outputFileMgr,
params,
Application.SYS_USER ) ;
} else {
csapApis.osManager( ).getServiceManager( ).run_service_script(
Application.SYS_USER,
ServiceOsManager.KILL_FILE,
serviceInstance.getServiceName_Port( ), params,
null,
outputFileMgr.getBufferedWriter( ) ) ;
}
} catch ( Exception e ) {
logger.error( "Failed to kill: {}", CSAP.buildCsapStack( e ) ) ;
}
}
public ObjectNode statusForAdminOrAgent (
double alertLevel ,
boolean includeKubernetesWarnings ) {
var timer = csapApis.metrics( ).startTimer( ) ;
ObjectNode statusReport = jsonMapper.createObjectNode( ) ;
ObjectNode healthReport = build_health_report( alertLevel, includeKubernetesWarnings, null ) ;
JsonNode summaryHostToErrors = healthReport.path( HealthManager.HEALTH_SUMMARY ) ;
ObjectNode hostSection = statusReport.putObject( "vm" ) ;
if ( summaryHostToErrors.size( ) == 0 ) {
statusReport.put( "Healthy", true ) ;
} else {
statusReport.put( "Healthy", false ) ;
statusReport.set( csapApis.application( ).VALIDATION_ERRORS, summaryHostToErrors ) ;
}
ObjectNode serviceToRuntimeNode = build_host_status_using_cached_data( ) ;
hostSection.put( "cpuCount", Integer.parseInt(
serviceToRuntimeNode
.path( "cpuCount" )
.asText( ) ) ) ;
double newKB = Math.round( Double.parseDouble(
serviceToRuntimeNode
.path( "cpuLoad" )
.asText( ) )
* 10.0 )
/ 10.0 ;
hostSection.put( "cpuLoad", newKB ) ;
hostSection.put( "host", csapApis.application( ).getCsapHostName( ) ) ;
hostSection.put( "project", csapApis.application( ).getActiveProject( ).getName( ) ) ;
hostSection.put( "application", csapApis.application( ).getName( ) ) ;
hostSection.put( "environment", csapApis.application( ).getCsapHostEnvironmentName( ) ) ;
// used for host discovery
hostSection.put( EnvironmentSettings.LOADBALANCER_URL, csapApis.application( ).rootProjectEnvSettings( )
.getLoadbalancerUrl( ) ) ;
int totalServicesActive = 0 ;
int totalServices = 0 ;
for ( ServiceInstance instance : csapApis.application( ).getServicesOnHost( ) ) {
if ( ! instance.is_files_only_package( ) ) { // Scripts should be
// ignored
totalServices++ ;
if ( instance.getDefaultContainer( ).isRunning( ) ) {
totalServicesActive++ ;
}
}
}
ObjectNode serviceNode = statusReport.putObject( "services" ) ;
serviceNode.put( "total", totalServices ) ;
serviceNode.put( "active", totalServicesActive ) ;
csapApis.metrics( ).stopTimer( timer, csapApis.application( ).PERFORMANCE_ID + "status" ) ;
return statusReport ;
}
public ObjectNode buildCollectionSummaryReport ( Map<String, ObjectNode> hostToAgentReport , String packageName ) {
logger.debug( "hostToAgentReport {}", hostToAgentReport ) ;
var filteredReport = jsonMapper.createObjectNode( ) ;
var hostFilterReport = filteredReport.putArray( "hosts" ) ;
var serviceFilterReport = filteredReport.putObject( "services" ) ;
for ( String hostName : hostToAgentReport.keySet( ) ) {
ObjectNode agentCollection = hostToAgentReport.get( hostName ) ;
var hostSummary = hostFilterReport.addObject( ) ;
hostSummary.put( "name", hostName ) ;
var cpuStats = hostSummary.putObject( "cpu" ) ;
cpuStats.put( "cores", agentCollection.at( "/hostStats/cpuCount" ).asInt( ) ) ;
cpuStats.put( "load", agentCollection.at( "/hostStats/cpuLoad" ).asDouble( ) ) ;
cpuStats.put( "usage", agentCollection.at( "/hostStats/cpu" ).asInt( ) ) ;
cpuStats.put( "io-wait", agentCollection.at( "/hostStats/cpuIoWait" ).asInt( ) ) ;
hostSummary.set( "memory", agentCollection.at( "/hostStats/memory" ) ) ;
// CSAP.jsonStream( agentCollection.path( HostKeys.services.json() ) )
// // .filter( serviceReport ->
// serviceReport.at("/containers/0/healthReportCollected/isHealthy").asBoolean(true)
// ==
// // false )
// .forEach( serviceReport -> {
agentCollection.path( HostKeys.services.json( ) ).fieldNames( ).forEachRemaining( serviceInstanceName -> {
logger.debug( "processing: {}", serviceInstanceName ) ;
var serviceReport = agentCollection.path( HostKeys.services.json( ) ).path( serviceInstanceName ) ;
CSAP.jsonStream( serviceReport.path( ContainerState.JSON_KEY ) )
// only aggregate containers with missing items
// .filter( containerReport -> containerReport.at( healthPath )
// .asBoolean( true ) == false )
.forEach( containerReport -> {
var serviceName = serviceReport.path( "serviceName" ).asText( ) ;
ServiceInstance serviceWithConfiguration = //
csapApis.application( ).getServiceInstance( serviceInstanceName, hostName,
packageName ) ;
var clusterType = serviceReport.path( ClusterType.CLUSTER_TYPE ).asText( ) ;
var testReport = serviceFilterReport.path( serviceName ) ;
ObjectNode aggregatedServiceReport ;
if ( testReport.isMissingNode( ) ) {
aggregatedServiceReport = serviceFilterReport.putObject( serviceName ) ;
if ( serviceWithConfiguration != null ) {
aggregatedServiceReport.put( "runtime", serviceWithConfiguration.getRuntime( ) ) ;
aggregatedServiceReport.put( "cluster", serviceWithConfiguration.getCluster( ) ) ;
if ( serviceWithConfiguration.getClusterType( ) == ClusterType.KUBERNETES ) {
aggregatedServiceReport.put( "runtime", ClusterType.KUBERNETES.getJson( ) ) ;
}
}
aggregatedServiceReport.putArray( "instances" ) ;
} else {
aggregatedServiceReport = (ObjectNode) testReport ;
}
var serviceInstances = (ArrayNode) aggregatedServiceReport.path( "instances" ) ;
var instanceReport = serviceInstances.addObject( ) ;
instanceReport.put( "host", hostName ) ;
// aggregatedServiceReport.put( ClusterType.CLUSTER_TYPE, clusterType ) ;
if ( clusterType.equals( ClusterType.KUBERNETES.getJson( ) ) ) {
instanceReport.put( "podIp", containerReport.path( "podIp" ).asText( ) ) ;
instanceReport.put( "podNamespace", containerReport.path( "podNamespace" ).asText( ) ) ;
}
for ( ServiceAlertsEnum alert : ServiceAlertsEnum.values( ) ) {
instanceReport.put( alert.getName( ), containerReport.path( alert.value ).asInt(
-1 ) ) ;
}
} ) ;
} ) ;
}
return filteredReport ;
}
public ArrayNode build_host_report ( String projectName ) {
var host_report = jsonMapper.createArrayNode( ) ;
if ( csapApis.application( ).isAgentProfile( ) ) {
csapApis.osManager( ).checkForProcessStatusUpdate( ) ;
var hostDetailReport = host_report.addObject( ) ;
hostDetailReport.put( "name", csapApis.application( ).getCsapHostName( ) ) ;
// hostDetailReport.setAll( agentReport ) ;
try {
hostDetailReport.setAll( (ObjectNode) csapApis.osManager( ).getHostRuntime( ) ) ;
} catch ( Exception e ) {
logger.warn( "Failed getting agent {}", CSAP.buildCsapStack( e ) ) ;
}
} else {
Project project = csapApis.application( ).getProject( projectName ) ;
var environmentHostnames = project.getHostsForEnvironment( csapApis.application( )
.getCsapHostEnvironmentName( ) ) ;
// logger.info( "lifeCycleHostList: {}", lifeCycleHostList );
for ( var host : environmentHostnames ) {
var hostDetailReport = host_report.addObject( ) ;
hostDetailReport.put( "name", host ) ;
ObjectNode agentReport = csapApis.application( ).getHostStatusManager( ).getHostAsJson( host ) ;
if ( agentReport != null ) {
hostDetailReport.setAll( agentReport ) ;
} else {
hostDetailReport.put( "errors", "status-not-found" ) ;
}
}
}
return host_report ;
}
public ObjectNode build_host_summary_report ( String projectName ) {
var summaryReport = jsonMapper.createObjectNode( ) ;
var serviceCount = 0 ;
var hostCount = 1 ;
var hostAllProjectCount = 1 ;
var kubernetesEventCount = 0 ;
var podCount = 0 ;
var podRestartCount = 0 ;
var volumeCount = 0 ;
var kubernetesNodeCount = 0 ;
var kubernetesMetrics = false ;
var hostSessions = summaryReport.putArray( "host-sessions" ) ;
long lastOpMills = -1 ;
summaryReport.put( "lastOp", csapApis.application( ).getLastOpMessage( ) ) ;
if ( csapApis.application( ).isAgentProfile( ) ) {
summaryReport.put( "deploymentBacklog", csapApis.osManager( ).getServiceManager( )
.getOpsQueued( ) ) ;
csapApis.osManager( ).checkForProcessStatusUpdate( ) ;
var hostLogin = hostSessions.addObject( ) ;
hostLogin.put( "name", csapApis.application( ).getCsapHostName( ) ) ;
var agentHostReport = build_host_status_using_cached_data( ) ;
hostLogin.set( "sessions", agentHostReport.path( "vmLoggedIn" ) ) ;
if ( csapApis.isKubernetesInstalledAndActive( ) ) {
kubernetesEventCount = (int) csapApis.kubernetes( ).eventCount( null ) ;
kubernetesMetrics = ! agentHostReport.path( "kubernetes" ).path( "metrics" ).path( "current" ).path(
"cores" ).isMissingNode( ) ;
kubernetesNodeCount = (int) csapApis.kubernetes( ).nodeCount( ) ;
var podCountsReport = csapApis.kubernetes( ).podCountsReport( null ) ;
podCount = podCountsReport.path( "count" ).asInt( ) ;
podRestartCount = podCountsReport.path( "restarts" ).asInt( ) ;
volumeCount = (int) csapApis.kubernetes( ).listingsBuilder( ).persistentVolumeCount(
null ) ;
serviceCount = csapApis.application( ).getServicesOnHost( ).size( ) ;
}
} else {
hostAllProjectCount = csapApis.application( ).getAllHostsInAllPackagesInCurrentLifecycle( ).size( ) ;
summaryReport.put( "deploymentBacklog", csapApis.application( ).getHostStatusManager( )
.totalOpsQueued( ) ) ;
Project project = csapApis.application( ).getProject( projectName ) ;
project.getAllPackagesModel( ).getHostsCurrentLc( ) ;
var environmentHostNames = project.getHostsForEnvironment( csapApis.application( )
.getCsapHostEnvironmentName( ) ) ;
hostCount = environmentHostNames.size( ) ;
for ( var host : environmentHostNames ) {
ObjectNode agent_status = csapApis.application( ).getHostStatusManager( ).getHostAsJson( host ) ;
if ( agent_status != null ) {
var hostStatus = agent_status.path( HostKeys.hostStats.jsonId ) ;
var loggedIn = hostStatus.path( "vmLoggedIn" ) ;
if ( loggedIn.size( ) > 0 ) {
var hostLogin = hostSessions.addObject( ) ;
hostLogin.put( "name", host ) ;
hostLogin.set( "sessions", hostStatus.get( "vmLoggedIn" ) ) ;
}
serviceCount += agent_status.path( "services" ).size( ) ;
// logger.info("hostStatus: {}", CSAP.jsonPrint( hostStatus ) ) ;
long hostOpMillis = hostStatus.path( "lastOpMillis" ).longValue( ) ;
logger.debug( "{} hostOpMillis: {} , {}", host, hostOpMillis, hostStatus.path( "lastOp" ) ) ;
if ( hostOpMillis > lastOpMills ) {
lastOpMills = hostOpMillis ;
summaryReport.put( "lastOp", host + ":" + hostStatus.path( "lastOp" ).asText( "-" ) ) ;
}
var hostEventCount = hostStatus.path( "kubernetes" ).path( "eventCount" ).asInt( ) ;
if ( hostEventCount > 0 ) {
kubernetesEventCount = hostEventCount ;
}
var hostPodCount = hostStatus.path( "kubernetes" ).path( "podReport" ).path( "count" ).asInt( ) ;
if ( hostPodCount > 0 ) {
podCount = hostPodCount ;
}
var hostPodRestartCount = hostStatus.path( "kubernetes" )
.path( "podReport" ).path( "restarts" ).asInt( ) ;
if ( hostPodRestartCount > 0 ) {
podRestartCount = hostPodRestartCount ;
}
var hostNodeCount = hostStatus.path( "kubernetes" ).path( "nodeCount" ).asInt( ) ;
if ( hostNodeCount > 0 ) {
kubernetesNodeCount = hostNodeCount ;
}
var hostKubMetrics = hostStatus.path( "kubernetes" ).path( "metrics" ).path( "current" ).path(
"cores" ) ;
if ( ! hostKubMetrics.isMissingNode( ) ) {
kubernetesMetrics = true ;
}
var hostVolumeCount = hostStatus.path( "kubernetes" ).path( "volumeClaimCount" ).asInt( ) ;
if ( hostVolumeCount > 0 ) {
volumeCount = hostVolumeCount ;
}
} else {
logger.debug( "No status found for host" ) ;
}
}
}
summaryReport.put( "services", serviceCount ) ;
summaryReport.put( "hosts", hostCount ) ;
summaryReport.put( "hosts-all-projects", hostAllProjectCount ) ;
summaryReport.put( "kubernetesNodes", kubernetesNodeCount ) ;
summaryReport.put( "kubernetesMetrics", kubernetesMetrics ) ;
summaryReport.put( "volumeCount", volumeCount ) ;
summaryReport.put( "kubernetesEvents", kubernetesEventCount ) ;
summaryReport.put( "podCount", podCount ) ;
summaryReport.put( "podRestartCount", podRestartCount ) ;
return summaryReport ;
}
public ObjectNode build_host_status_using_cached_data ( ) {
return build_host_status_using_cached_data( null ) ;
}
public ObjectNode build_host_status_using_cached_data (
String kubernetesNamespace ) {
var timer = csapApis.metrics( ).startTimer( ) ;
ObjectNode hostStatus = jsonMapper.createObjectNode( ) ;
try {
// NEEDS TO BE FAST : < 1ms. Use background caching as needed
addCpuMetrics( hostStatus ) ;
try {
var version = "2.1" ;
var linux = csapApis.application( ).findServiceByNameOnCurrentHost( "csap-package-linux" ) ;
if ( linux != null ) {
version = linux.getDefaultContainer( ).getDeployedArtifacts( ) ;
}
hostStatus.put( "osVersion", version ) ;
} catch ( Exception e ) {
logger.warn( "Failed to get os version {}", CSAP.buildCsapStack( e ) ) ;
}
hostStatus.put( "processCount", csapApis.osManager( ).numberOfProcesses( ) ) ;
hostStatus.put( "csapCount", csapApis.application( ).getServicesOnHost( ).size( ) ) ;
hostStatus.put( "linuxInterfaceCount", csapApis.osManager( )
.getCachedNetworkInterfaceCount( ) ) ;
hostStatus.put( "linuxServiceCount", csapApis.osManager( )
.getCachedLinuxServiceCount( ) ) ;
hostStatus.put( "linuxPackageCount", csapApis.osManager( )
.getCachedLinuxPackageCount( ) ) ;
hostStatus.put( "diskCount", csapApis.osManager( ).getDiskCount( ) ) ;
if ( csapApis.isContainerProviderInstalledAndActive( ) ) {
var dockerSummaryReport = csapApis.containerIntegration( )
.getCachedSummaryReport( ) ;
var dockerInstance = csapApis.application( ).findServiceByNameOnCurrentHost( C7.dockerService
.val( ) ) ;
if ( dockerInstance != null ) {
dockerSummaryReport.put( "dockerStorage", dockerInstance.getDefaultContainer( ).getDiskUsageInMb( )
/ 1024 ) ;
} else {
dockerSummaryReport.put( "dockerStorage", -1 ) ;
}
hostStatus.set( C7.definitionSettings.val( ), dockerSummaryReport ) ;
}
if ( csapApis.isKubernetesInstalledAndActive( ) ) {
// very costly - slim down to minimum
// hostStatus.set( "kubernetes", csapApis.getKubernetesIntegration(
// ).buildSummary( kubernetesNamespace ) ) ;
// hmmmm - this is triggering work -- remote apis could hang --- causing
// disastter
JsonNode summaryReport = jsonMapper.createObjectNode( ) ;
if ( csapApis.application( ).kubeletInstance( ).isKubernetesMaster( )
|| kubernetesNamespace != null ) {
// full report ONLY on masters, or on specific UI requests
summaryReport = csapApis.kubernetes( )
.buildSummaryReport( kubernetesNamespace ) ;
} else {
// run metrics report only - typically agent heartbeats on non masters
summaryReport = csapApis.kubernetes( ).getCachedNodeHealthMetrics( ) ;
}
hostStatus.set( "kubernetes", summaryReport ) ;
}
ObjectNode memory = hostStatus.putObject( "memory" ) ;
memory.put( "total", getGb( osStats.getTotalPhysicalMemorySize( ) ) ) ;
memory.put( "free", getGb( osStats.getFreePhysicalMemorySize( ) ) ) ;
memory.put( "swapTotal", getGb( osStats.getTotalSwapSpaceSize( ) ) ) ;
memory.put( "swapFree", getGb( osStats.getFreeSwapSpaceSize( ) ) ) ;
var availableBytes = csapApis.osManager( ).getMemoryAvailbleLessCache( ) * 1024L * 1024L ;
memory.put( "available", getGb( availableBytes ) ) ;
hostStatus.set( "users", csapApis.application( ).getActiveUsers( ).getActive( ) ) ;
hostStatus.put( "lastOp", csapApis.application( ).getLastOpMessage( ) ) ;
hostStatus.set( "vmLoggedIn", csapApis.osManager( ).getVmLoggedIn( ) ) ;
hostStatus.put( "motd", csapApis.application( ).getMotdMessage( ) ) ;
Format tsFormater = new SimpleDateFormat( "HH:mm:ss" ) ;
hostStatus.put( "timeStamp", tsFormater.format( new Date( ) ) ) ;
hostStatus.put( "lastOpMillis", csapApis.application( ).getLastOpMillis( ) ) ;
} catch ( Exception e ) {
hostStatus.put( "error", "Reason: " + CSAP.buildCsapStack( e ) ) ;
logger.info( "Failed build health: {}", CSAP.buildCsapStack( e ) ) ;
}
csapApis.metrics( ).stopTimer( timer, csapApis.application( ).PERFORMANCE_ID + "status.host" ) ;
return hostStatus ;
}
public void addCpuMetrics ( ObjectNode hostStatus ) {
var currentLoad = osStats.getSystemLoadAverage( ) ;
if ( csapApis.application( ).isDesktopHost( ) && ( currentLoad == -1.0 ) ) {
currentLoad = 9.3 ;
}
hostStatus.put( "cpuLoad", currentLoad ) ;
hostStatus.put( "cpuCount", osStats.getAvailableProcessors( ) ) ;
if ( csapApis.application( ).rootProjectEnvSettings( ).getMetricToSecondsMap( ).size( ) > 0 ) {
hostStatus.put( "cpu", csapApis.application( ).metricManager( ).getLatestCpuUsage( ) ) ;
hostStatus.put( "cpuIoWait", csapApis.application( ).metricManager( ).getLatestIoWait( ) ) ;
}
}
Double byteToGb = 1024 * 1024 * 1024D ;
DecimalFormat gbFormat = new DecimalFormat( "#.#GB" ) ;
String getGb ( long num ) {
// logger.info( "num: {}" , num );
return gbFormat.format( num / byteToGb ) ;
}
public int getCpuCount ( ) {
return osStats.getAvailableProcessors( ) ;
}
public ArrayNode buildServiceRuntimes ( ServiceInstance definitionService ) {
logger.debug( definitionService.toString( ) ) ;
boolean addKubernetesMaster = false ;
ArrayNode serviceRuntimes = jsonMapper.createArrayNode( ) ;
ServiceInstance runtimeService = definitionService ;
ObjectNode hostStatus ;
if ( csapApis.application( ).isAgentProfile( ) ) {
hostStatus = build_host_status_using_cached_data( ) ;
} else {
hostStatus = jsonMapper.createObjectNode( ) ;
ObjectNode hostAgentStatus = csapApis.application( )
.getHostStatusManager( )
.getHostAsJson( definitionService.getHostName( ) ) ;
if ( hostAgentStatus != null ) {
hostStatus = (ObjectNode) hostAgentStatus.path( HostKeys.hostStats.jsonId ) ;
ObjectNode collectedServiceStatus = csapApis.application( )
.getHostStatusManager( )
.getServiceRuntime(
definitionService.getHostName( ),
definitionService.getServiceName_Port( ) ) ;
if ( collectedServiceStatus != null ) {
try {
// rebuild service, using collected data
runtimeService = ServiceInstance.buildInstance( jsonMapper, collectedServiceStatus ) ;
// add in any required fields
runtimeService.setProcessFilter( definitionService.getProcessFilter( ) ) ;
} catch ( Exception e ) {
logger.warn( "Failed building service, {}", CSAP.buildCsapStack( e ) ) ;
}
} else {
logger.debug( "Did not find any results for service: {}, empty data will be used",
definitionService.getServiceName_Port( ) ) ;
definitionService.getDefaultContainer( ) ;
}
} else {
definitionService.getDefaultContainer( ) ; // initialize with default container
runtimeService = definitionService ;
}
}
logger.debug( "runtimeService: {}", runtimeService ) ;
int containerIndex = 0 ;
for ( ContainerState container : runtimeService.getContainerStatusList( ) ) {
// kubernetes filtering
boolean inactiveKubernetesWorkerService = //
runtimeService.is_cluster_kubernetes( )
&& ( ! definitionService.isKubernetesMaster( ) )
&& ( ! container.isRunning( ) ) ;
if ( addKubernetesMaster ) {
// when no active instances on any host - include master
inactiveKubernetesWorkerService = runtimeService.is_cluster_kubernetes( ) && ! definitionService
.isKubernetesMaster( ) ;
}
logger.debug( "filterInactiveKubernetes: {}", inactiveKubernetesWorkerService ) ;
if ( ! inactiveKubernetesWorkerService ) {
ObjectNode uiInstanceData = runtimeService.build_ui_service_instance( container, containerIndex++ ) ; // gets
// runtime
// fields
if ( hostStatus.path( "cpuCount" ).asInt( ) == 0 ) {
uiInstanceData.put( "deployedArtifacts", "host-not-connected" ) ;
}
add_definition_values_used_by_ui( definitionService, uiInstanceData, hostStatus ) ;
if ( definitionService.isKubernetesMaster( ) ) {
uiInstanceData.put( "kubernetes-master", true ) ;
}
uiInstanceData.put( "replicaCount", runtimeService.getKubernetesReplicaCount( ).asInt( -1 ) ) ;
serviceRuntimes.add( uiInstanceData ) ;
}
}
return serviceRuntimes ;
}
private void add_definition_values_used_by_ui (
ServiceInstance definition ,
ObjectNode uiInstanceData ,
ObjectNode hostStatus ) {
logger.debug( "{} : {}", definition.toSummaryString( ), CSAP.jsonPrint( uiInstanceData ) ) ;
if ( csapApis.application( ).isRunningOnDesktop( ) ) {
// using definition host for long name support
uiInstanceData.put( ServiceBase.HOSTNAME_JSON, definition.getHostName( ) ) ;
}
uiInstanceData.put( "mavenId", definition.getMavenId( ) ) ;
// uiInstanceData.put( ServiceAttributes.servletContext.json(),
// definition.getContext() ) ;
uiInstanceData.put( "launchUrl", definition.getUrl( ) ) ;
uiInstanceData.put( "javaHttp", definition.isJavaOverHttpCollectionEnabled( ) ) ;
String serviceId = definition.getName( ) + "-" + ( uiInstanceData.path( "containerIndex" ).asInt( 0 ) + 1 ) ;
uiInstanceData.put( "serviceHealth", definition.getHealthUrl( serviceId ) ) ;
uiInstanceData.put( "jmx", definition.getJmxPort( ) ) ;
uiInstanceData.put( "jmxrmi", definition.isJmxRmi( ) ) ;
if ( definition.isRemoteCollection( ) ) {
uiInstanceData.put( "jmx", definition.getCollectHost( ) + ":" + definition.getCollectPort( ) ) ;
}
uiInstanceData.put( ServiceAttributes.startOrder.json( ), definition.getRawAutoStart( ) ) ;
uiInstanceData.put( "lc", definition.getLifecycle( ) ) ;
// host stats for instance
uiInstanceData.put( "cpuCount", hostStatus.path( "cpuCount" ).asText( "-" ) ) ;
uiInstanceData.put( "cpuLoad", hostStatus.path( "cpuLoad" ).asText( "-" ) ) ;
double newKB = Math.round( hostStatus.path( "cpuLoad" ).asDouble( 0 ) * 10.0 ) / 10.0 ;
uiInstanceData.put( "cpuLoad", Double.toString( newKB ) ) ;
uiInstanceData.put( "motd", hostStatus.path( "motd" ).asText( "-" ) ) ;
uiInstanceData.put( "users", hostStatus.path( "users" ).asText( "-" ) ) ;
uiInstanceData.put( "lastOp", hostStatus.path( "lastOp" ).asText( "-" ) ) ;
if ( hostStatus.has( "du" ) ) {
uiInstanceData.put( "du", hostStatus.path( "du" ).asInt( ) ) ;
}
}
public List<String> getHealthServiceIds ( ) {
var healthIds = csapApis.application( )
.getAllPackages( )
.getServicesOnHost( csapApis.application( ).getCsapHostName( ) )
.filter( ServiceInstance::isApplicationHealthEnabled )
.flatMap( ServiceInstance::getIds )
.collect( Collectors.toList( ) ) ;
return healthIds ;
}
public Map<String, Map<String, String>> buildHealthUrls ( ) {
Map<String, Map<String, String>> healthUrlsByService ;
if ( csapApis.application( ).isAdminProfile( ) ) {
//
healthUrlsByService = csapApis.application( ).getAllPackages( )
.getServiceConfigStreamInCurrentLC( )
.flatMap( serviceInstancesEntry -> serviceInstancesEntry.getValue( ).stream( ) )
.filter( ServiceInstance::isApplicationHealthEnabled )
.filter( service -> discoveredHealthUrls( service ) != null )
.collect( Collectors.toMap(
ServiceInstance::getName,
this::discoveredHealthUrls,
( a , b ) -> {
a.putAll( b ) ;
return a ;
}, // merge all hosts
( ) -> new TreeMap<String, Map<String, String>>( String.CASE_INSENSITIVE_ORDER ) ) ) ;
} else {
healthUrlsByService = csapApis.application( )
.getAllPackages( )
.getServicesOnHost( csapApis.application( ).getCsapHostName( ) )
.filter( ServiceInstance::isApplicationHealthEnabled )
.collect( Collectors.toMap(
ServiceInstance::getName,
ServiceInstance::getHealthUrls,
( a , b ) -> a, // merge function should never be used on a single host
( ) -> new TreeMap<String, Map<String, String>>( String.CASE_INSENSITIVE_ORDER ) ) ) ; // want
// them
// sorted
}
return healthUrlsByService ;
}
private Map<String, String> discoveredHealthUrls ( ServiceInstance serviceInstance ) {
ObjectNode collectedRuntime = csapApis.application( ).getHostStatusManager( ).getHostAsJson( serviceInstance
.getHostName( ) ) ;
if ( collectedRuntime == null ) {
return null ;
}
JsonNode serviceCollected = collectedRuntime
.at( "/" + HostKeys.services.json( ) + "/" + serviceInstance.getServiceName_Port( ) ) ;
return serviceInstance.getHealthUrls( serviceCollected ) ;
}
}
| mit |
eduardodaluz/xfire | xfire-core/src/main/org/codehaus/xfire/wsdl11/WSDL11Transport.java | 415 | package org.codehaus.xfire.wsdl11;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.transport.Transport;
/**
* Indicates that a particular transport supports WSDL 1.1 generation.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public interface WSDL11Transport extends Transport
{
public String getName();
public String getServiceURL(Service service);
}
| mit |
Azure/azure-sdk-for-java | sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/implementation/mdesrc/cryptography/KeyEncryptionKeyAlgorithm.java | 431 | /*
* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.
*/
package com.azure.cosmos.encryption.implementation.mdesrc.cryptography;
/**
* Represents the encryption algorithms supported for key encryption.
*
*/
public enum KeyEncryptionKeyAlgorithm {
/**
* RSA public key cryptography algorithm with Optimal Asymmetric Encryption Padding (OAEP) padding.
*/
RSA_OAEP
}
| mit |
Vovkasquid/compassApp | alljoyn/alljoyn_java/samples/android/basic/client/src/org/alljoyn/bus/samples/basicclient/Client.java | 15912 | /*
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package org.alljoyn.bus.samples.basicclient;
import org.alljoyn.bus.BusAttachment;
import org.alljoyn.bus.BusException;
import org.alljoyn.bus.BusListener;
import org.alljoyn.bus.Mutable;
import org.alljoyn.bus.ProxyBusObject;
import org.alljoyn.bus.SessionListener;
import org.alljoyn.bus.SessionOpts;
import org.alljoyn.bus.Status;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Client extends Activity {
/* Load the native alljoyn_java library. */
static {
System.loadLibrary("alljoyn_java");
}
private static final int MESSAGE_PING = 1;
private static final int MESSAGE_PING_REPLY = 2;
private static final int MESSAGE_POST_TOAST = 3;
private static final int MESSAGE_START_PROGRESS_DIALOG = 4;
private static final int MESSAGE_STOP_PROGRESS_DIALOG = 5;
private static final String TAG = "BasicClient";
private EditText mEditText;
private ArrayAdapter<String> mListViewArrayAdapter;
private ListView mListView;
private Menu menu;
/* Handler used to make calls to AllJoyn methods. See onCreate(). */
private BusHandler mBusHandler;
private ProgressDialog mDialog;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_PING:
String cat = (String) msg.obj;
mListViewArrayAdapter.add("Cat args: " + cat);
break;
case MESSAGE_PING_REPLY:
String ret = (String) msg.obj;
mListViewArrayAdapter.add("Reply: " + ret);
mEditText.setText("");
break;
case MESSAGE_POST_TOAST:
Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_LONG).show();
break;
case MESSAGE_START_PROGRESS_DIALOG:
mDialog = ProgressDialog.show(Client.this,
"",
"Finding Basic Service.\nPlease wait...",
true,
true);
break;
case MESSAGE_STOP_PROGRESS_DIALOG:
mDialog.dismiss();
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mListViewArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mListView = (ListView) findViewById(R.id.ListView);
mListView.setAdapter(mListViewArrayAdapter);
mEditText = (EditText) findViewById(R.id.EditText);
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_UP) {
/* Call the remote object's cat method. */
Message msg = mBusHandler.obtainMessage(BusHandler.CAT,
view.getText().toString());
mBusHandler.sendMessage(msg);
}
return true;
}
});
/* Make all AllJoyn calls through a separate handler thread to prevent blocking the UI. */
HandlerThread busThread = new HandlerThread("BusHandler");
busThread.start();
mBusHandler = new BusHandler(busThread.getLooper());
/* Connect to an AllJoyn object. */
mBusHandler.sendEmptyMessage(BusHandler.CONNECT);
mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
this.menu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.quit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
/* Disconnect to prevent resource leaks. */
mBusHandler.sendEmptyMessage(BusHandler.DISCONNECT);
}
/* This class will handle all AllJoyn calls. See onCreate(). */
class BusHandler extends Handler {
/*
* Name used as the well-known name and the advertised name of the service this client is
* interested in. This name must be a unique name both to the bus and to the network as a
* whole.
*
* The name uses reverse URL style of naming, and matches the name used by the service.
*/
private static final String SERVICE_NAME = "org.alljoyn.Bus.sample";
private static final short CONTACT_PORT=25;
private BusAttachment mBus;
private ProxyBusObject mProxyObj;
private BasicInterface mBasicInterface;
private int mSessionId;
private boolean mIsInASession;
private boolean mIsConnected;
private boolean mIsStoppingDiscovery;
/* These are the messages sent to the BusHandler from the UI. */
public static final int CONNECT = 1;
public static final int JOIN_SESSION = 2;
public static final int DISCONNECT = 3;
public static final int CAT = 4;
public BusHandler(Looper looper) {
super(looper);
mIsInASession = false;
mIsConnected = false;
mIsStoppingDiscovery = false;
}
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
/* Connect to a remote instance of an object implementing the BasicInterface. */
case CONNECT: {
org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
/*
* All communication through AllJoyn begins with a BusAttachment.
*
* A BusAttachment needs a name. The actual name is unimportant except for internal
* security. As a default we use the class name as the name.
*
* By default AllJoyn does not allow communication between devices (i.e. bus to bus
* communication). The second argument must be set to Receive to allow communication
* between devices.
*/
mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive);
/*
* Create a bus listener class
*/
mBus.registerBusListener(new BusListener() {
@Override
public void foundAdvertisedName(String name, short transport, String namePrefix) {
logInfo(String.format("MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)", name, transport, namePrefix));
/*
* This client will only join the first service that it sees advertising
* the indicated well-known name. If the program is already a member of
* a session (i.e. connected to a service) we will not attempt to join
* another session.
* It is possible to join multiple session however joining multiple
* sessions is not shown in this sample.
*/
if(!mIsConnected) {
Message msg = obtainMessage(JOIN_SESSION);
msg.arg1 = transport;
msg.obj = name;
sendMessage(msg);
}
}
});
/* To communicate with AllJoyn objects, we must connect the BusAttachment to the bus. */
Status status = mBus.connect();
logStatus("BusAttachment.connect()", status);
if (Status.OK != status) {
finish();
return;
}
/*
* Now find an instance of the AllJoyn object we want to call. We start by looking for
* a name, then connecting to the device that is advertising that name.
*
* In this case, we are looking for the well-known SERVICE_NAME.
*/
status = mBus.findAdvertisedName(SERVICE_NAME);
logStatus(String.format("BusAttachement.findAdvertisedName(%s)", SERVICE_NAME), status);
if (Status.OK != status) {
finish();
return;
}
break;
}
case (JOIN_SESSION): {
/*
* If discovery is currently being stopped don't join to any other sessions.
*/
if (mIsStoppingDiscovery) {
break;
}
/*
* In order to join the session, we need to provide the well-known
* contact port. This is pre-arranged between both sides as part
* of the definition of the chat service. As a result of joining
* the session, we get a session identifier which we must use to
* identify the created session communication channel whenever we
* talk to the remote side.
*/
short contactPort = CONTACT_PORT;
SessionOpts sessionOpts = new SessionOpts();
sessionOpts.transports = (short)msg.arg1;
Mutable.IntegerValue sessionId = new Mutable.IntegerValue();
Status status = mBus.joinSession((String) msg.obj, contactPort, sessionId, sessionOpts, new SessionListener() {
@Override
public void sessionLost(int sessionId, int reason) {
mIsConnected = false;
logInfo(String.format("MyBusListener.sessionLost(sessionId = %d, reason = %d)", sessionId,reason));
mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG);
}
});
logStatus("BusAttachment.joinSession() - sessionId: " + sessionId.value, status);
if (status == Status.OK) {
/*
* To communicate with an AllJoyn object, we create a ProxyBusObject.
* A ProxyBusObject is composed of a name, path, sessionID and interfaces.
*
* This ProxyBusObject is located at the well-known SERVICE_NAME, under path
* "/sample", uses sessionID of CONTACT_PORT, and implements the BasicInterface.
*/
mProxyObj = mBus.getProxyBusObject(SERVICE_NAME,
"/sample",
sessionId.value,
new Class<?>[] { BasicInterface.class });
/* We make calls to the methods of the AllJoyn object through one of its interfaces. */
mBasicInterface = mProxyObj.getInterface(BasicInterface.class);
mSessionId = sessionId.value;
mIsConnected = true;
mHandler.sendEmptyMessage(MESSAGE_STOP_PROGRESS_DIALOG);
}
break;
}
/* Release all resources acquired in the connect. */
case DISCONNECT: {
mIsStoppingDiscovery = true;
if (mIsConnected) {
Status status = mBus.leaveSession(mSessionId);
logStatus("BusAttachment.leaveSession()", status);
}
mBus.disconnect();
getLooper().quit();
break;
}
/*
* Call the service's Cat method through the ProxyBusObject.
*
* This will also print the String that was sent to the service and the String that was
* received from the service to the user interface.
*/
case CAT: {
try {
if (mBasicInterface != null) {
sendUiMessage(MESSAGE_PING, msg.obj + " and " + msg.obj);
String reply = mBasicInterface.cat((String) msg.obj, (String) msg.obj);
sendUiMessage(MESSAGE_PING_REPLY, reply);
}
} catch (BusException ex) {
logException("BasicInterface.cat()", ex);
}
break;
}
default:
break;
}
}
/* Helper function to send a message to the UI thread. */
private void sendUiMessage(int what, Object obj) {
mHandler.sendMessage(mHandler.obtainMessage(what, obj));
}
}
private void logStatus(String msg, Status status) {
String log = String.format("%s: %s", msg, status);
if (status == Status.OK) {
Log.i(TAG, log);
} else {
Message toastMsg = mHandler.obtainMessage(MESSAGE_POST_TOAST, log);
mHandler.sendMessage(toastMsg);
Log.e(TAG, log);
}
}
private void logException(String msg, BusException ex) {
String log = String.format("%s: %s", msg, ex);
Message toastMsg = mHandler.obtainMessage(MESSAGE_POST_TOAST, log);
mHandler.sendMessage(toastMsg);
Log.e(TAG, log, ex);
}
/*
* print the status or result to the Android log. If the result is the expected
* result only print it to the log. Otherwise print it to the error log and
* Sent a Toast to the users screen.
*/
private void logInfo(String msg) {
Log.i(TAG, msg);
}
}
| mit |
elBukkit/HeroesHotbar | src/main/java/com/elmakers/mine/bukkit/heroes/HotbarPlugin.java | 2501 | package com.elmakers.mine.bukkit.heroes;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandExecutor;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.elmakers.mine.bukkit.heroes.utilities.CompatibilityUtils;
import com.herocraftonline.heroes.Heroes;
/**
* This is the main Plugin class for the Heroes Hotbar plugin.
*/
public class HotbarPlugin extends JavaPlugin {
private HotbarController controller;
private Plugin heroesPlugin;
/*
* Plugin interface
*/
@Override
public void onLoad() {
}
@Override
public void onEnable() {
try {
heroesPlugin = getServer().getPluginManager().getPlugin("Heroes");
if (heroesPlugin == null || !(heroesPlugin instanceof Heroes)) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[HeroesHotbar] Heroes could not be found, HeroesHotbar plugin will not load.");
return;
}
} catch (Throwable ex) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[HeroesHotbar] There was an error finding the Heroes plugin, HeroesHotbar plugin will not load.");
getLogger().warning(ex.getMessage());
return;
}
initialize();
}
@Override
public void onDisable() {
if (controller != null) {
controller.clear();
}
}
/**
* Initialization, set up commands, listeners and controller
*/
protected void initialize() {
CompatibilityUtils.initialize(this);
saveDefaultConfig();
// Set up controller
if (controller == null) {
controller = new HotbarController(this, (Heroes) heroesPlugin);
}
controller.initialize();
// Set up command executors
CommandExecutor skillsMenuCommand = new SkillsMenuCommandExecutor(controller);
getCommand("skillmenu").setExecutor(skillsMenuCommand);
CommandExecutor giveSkillCommand = new GiveSkillCommandExecutor(controller);
getCommand("giveskill").setExecutor(giveSkillCommand);
// Set up listeners
InventoryListener inventoryListener = new InventoryListener(controller);
getServer().getPluginManager().registerEvents(inventoryListener, this);
PlayerListener playerListener = new PlayerListener(controller);
getServer().getPluginManager().registerEvents(playerListener, this);
}
}
| mit |
brain-murphy/calcproject | src/PopDynamics/PowerMethod.java | 2174 | package PopDynamics;
import java.util.Arrays;
import static General.Ops.*;
/**
* Calculates the power method
* Created by Justin Joe
*/
public class PowerMethod {
private double eigenValApprox;
private double[][] eigenVecApprox;
private double iterationNum;
public PowerMethod(double eigenValApprox, double[][] eigenVecApprox, double iterationNum) {
this.eigenValApprox = eigenValApprox;
this.eigenVecApprox = eigenVecApprox;
this.iterationNum = iterationNum;
}
/**
* Calculates the approximations of the dominant eigen value and eigen vector for the matrix
* using the power iteration method
* @param a the matrix for which the eigen values and eigen vectors are being calculated
* @param vecApprox the initial approximation for the eigen vector
* @return the updated info
*/
public void power_method(double[][] a, double[][] vecApprox, double tol) {
double error = 100;
while (error > tol && iterationNum <= 100) {
double temp = eigenValApprox;
vecApprox = scalarMult(matrixMult(a, vecApprox), (1 / vecApprox[0][0]));
eigenValApprox = vecApprox[0][0];
iterationNum++;
double norm = 0;
for (int i = 0; i < vecApprox.length; i++) {
norm += Math.pow(vecApprox[i][0], 2);
}
norm = Math.sqrt(norm);
eigenVecApprox = scalarMult(vecApprox, (1 / norm));
error = Math.abs(temp - eigenValApprox);
}
if (iterationNum >= 100) {
System.out.println("Did not converge to tolerance after 100 iterations.");
} else {
System.out.println("Approximate Eigenvalue: " + getEigenValue());
System.out.println("Approximate Eigenvector: " + Arrays.deepToString(getEigenVec()));
System.out.println("Iterations needed: " + getIterationNum());
}
}
public double getEigenValue() {
return eigenValApprox;
}
public double[][] getEigenVec() {
return eigenVecApprox;
}
public double getIterationNum() {
return iterationNum;
}
} | mit |
djun100/AndroidDynamicLoader | Host/src/com/dianping/loader/ForwardActivity.java | 3031 | package com.dianping.loader;
import java.util.List;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.dianping.app.BaseActivity;
import com.dianping.app.MyApplication;
/**
* 根据URL Map处理外部链接打开URL Scheme的跳转逻辑
* <p>
* 在AndroidManifest.xml中注册应用的host为ForwardActivity<br>
*
* @author Yimin
*
*/
public class ForwardActivity extends BaseActivity {
private FrameLayout rootView;
private boolean launched;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new FrameLayout(this);
rootView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
rootView.setId(android.R.id.primary);
setContentView(rootView);
launched = savedInstanceState == null ? false : savedInstanceState
.getBoolean("launched");
if (!(getApplication() instanceof MyApplication)) {
TextView text = new TextView(this);
text.setText("无法载入页面 #401"); // #401
text.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
rootView.addView(text);
return;
}
doForward();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("launched", launched);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
setResult(resultCode, data);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
protected void doForward() {
if (launched)
return;
Intent intent = getIntent();
Intent i = new Intent(intent.getAction(), intent.getData());
if (intent.getExtras() != null) {
i.putExtras(intent.getExtras());
}
intent = urlMap(i);
try {
// check if it open myself to avoid infinite loop
List<ResolveInfo> l = getPackageManager().queryIntentActivities(
intent, 0);
if (l.size() == 1) {
ResolveInfo ri = l.get(0);
if (getPackageName().equals(ri.activityInfo.packageName)) {
if (getClass().getName().equals(ri.activityInfo.name)) {
throw new Exception("infinite loop");
}
}
} else if (l.size() > 1) {
// should not happen, do we allow this?
}
startActivityForResult(intent, 1);
launched = true;
} catch (Exception e) {
TextView text = new TextView(this);
text.setText("无法载入页面 #402"); // #402
text.append("\n" + e.toString());
text.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
rootView.addView(text);
Log.e("loader", "unable to forward " + getIntent(), e);
}
}
}
| mit |
andy-sheng/leetcode | 453. Minimum Moves to Equal Array Elements.java | 334 | public class Solution {
public int minMoves(int[] nums) {
int min = nums[0];
for (int num:nums) {
if (num < min) {
min = num;
}
}
int result = 0;
for (int num:nums) {
result += num - min;
}
return result;
}
}
| mit |
EdwinMindcraft/AdvancedMaterials | src/main/java/mod/mindcraft/advancedmaterials/tileentity/TileEntityNuclearReactor.java | 18124 | package mod.mindcraft.advancedmaterials.tileentity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import mod.mindcraft.advancedmaterials.integration.component.ItemNuclearReactorComponent;
import mod.mindcraft.advancedmaterials.integration.component.ItemNuclearReactorFluidComponent;
import mod.mindcraft.advancedmaterials.integration.recipes.NuclearFusionRecipe;
import mod.mindcraft.advancedmaterials.integration.registry.NuclearFusionRegistry;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ITickable;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import net.minecraftforge.fluids.IFluidTank;
import cofh.api.energy.IEnergyProvider;
public class TileEntityNuclearReactor extends TileEntity implements ISidedInventory, ITickable, IEnergyProvider, IFluidHandler, IFluidTank {
public ItemStack[] stack = new ItemStack[54];
public int[] stackHeat = new int[54];
public int hullHeat = 200;
public int prevTemp = 200;
public int energy = 0;
public int prevEnergy = 0;
public FluidStack storedFluid;
public TileEntityNuclearReactor() {
}
@Override
public int getSizeInventory() {
return 54;
}
@Override
public ItemStack getStackInSlot(int index) {
return stack[index];
}
@Override
public ItemStack decrStackSize(int index, int count) {
if (stack[index] == null)
return null;
ItemStack is = stack[index].copy();
if (stack[index].stackSize <= count)
stack[index] = null;
else
stack[index].stackSize -= count;
if (stack[index] != null)
is.stackSize -= stack[index].stackSize;
return is;
}
@Override
public ItemStack removeStackFromSlot(int index) {
if (stack[index] == null)
return null;
ItemStack is = stack[index].copy();
stack[index] = null;
return is;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
this.stack[index] = stack;
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory(EntityPlayer player) {
}
@Override
public void closeInventory(EntityPlayer player) {
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return stack.getItem() instanceof ItemNuclearReactorComponent;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {
}
@Override
public int getFieldCount() {
return 0;
}
@Override
public void clear() {
}
@Override
public String getName() {
return null;
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public IChatComponent getDisplayName() {
return null;
}
@Override
public int getEnergyStored(EnumFacing from) {
return energy;
}
@Override
public int getMaxEnergyStored(EnumFacing from) {
return 10000000;
}
@Override
public boolean canConnectEnergy(EnumFacing from) {
return true;
}
@Override
public int extractEnergy(EnumFacing from, int maxExtract, boolean simulate) {
int extract = Math.min(energy, maxExtract);
if (!simulate)
energy -= extract;
return extract;
}
@Override
public void update() {
if (worldObj.isRemote)
return;
ItemStack[][] map = new ItemStack[6][9];
this.prevTemp = this.hullHeat;
this.prevEnergy = this.energy;
if (worldObj.getBiomeGenForCoords(pos).temperature * (worldObj.isRaining() ? 200 : 250) > hullHeat)
hullHeat += Math.min(worldObj.getBiomeGenForCoords(pos).temperature * 10 * ((hullHeat - worldObj.getBiomeGenForCoords(pos).temperature * (worldObj.isRaining() ? 200 : 250)) / 10000), 5);
else if (worldObj.getBiomeGenForCoords(pos).temperature * (worldObj.isRaining() ? 200 : 250) < hullHeat)
hullHeat -= Math.min(((2F - worldObj.getBiomeGenForCoords(pos).temperature) * 10) * ((hullHeat - worldObj.getBiomeGenForCoords(pos).temperature * (worldObj.isRaining() ? 200 : 250)) / 10000), 5);
int[][] heatMap = new int[6][9];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
map[i][j] = this.stack[i * 9 + j];
heatMap[i][j] = this.stackHeat[i * 9 + j];
if (map[i][j] != null && map[i][j].getItem() instanceof ItemNuclearReactorComponent) {
ItemNuclearReactorComponent item = (ItemNuclearReactorComponent) map[i][j].getItem();
if (item.component.maxAbsorbedHeat != -1) {
heatMap[i][j] = map[i][j].getItemDamage();
stackHeat[i*9+j] = map[i][j].getItemDamage();
}
}
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if (map[i][j] != null && map[i][j].getItem() instanceof ItemNuclearReactorComponent) {
ItemNuclearReactorComponent item = (ItemNuclearReactorComponent) map[i][j].getItem();
if ((item.component.maxTemperature == -1 ? Integer.MAX_VALUE : item.component.maxTemperature) < hullHeat || (item.component.minTemperature == -1 ? Integer.MIN_VALUE : item.component.minTemperature) > hullHeat)
continue;
heatMap[i][j] += calcHeat(item, map, i, j);
heatMap[i][j] = transferHeat(item, map, heatMap, i, j);
//System.out.println(heatMap[i][j]);
//System.out.println(heatMap[i][j] + " " + this.stackHeat[i * 9 + j]);
energy += calcPower(item, map, i, j);
if (energy > getMaxEnergyStored(EnumFacing.UP))
energy = getMaxEnergyStored(EnumFacing.UP);
}
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if (map[i][j] != null && map[i][j].getItem() instanceof ItemNuclearReactorComponent) {
ItemNuclearReactorComponent item = (ItemNuclearReactorComponent) map[i][j].getItem();
if ((item.component.maxTemperature == -1 ? Integer.MAX_VALUE : item.component.maxTemperature) < hullHeat || (item.component.minTemperature == -1 ? Integer.MIN_VALUE : item.component.minTemperature) > hullHeat)
continue;
dissipateHeat(item, map, heatMap, i, j);
hullHeat += Math.max(heatMap[i][j] - this.stackHeat[i * 9 + j], 0);
}
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if (map[i][j] != null && map[i][j].getItem() instanceof ItemNuclearReactorComponent) {
ItemNuclearReactorComponent item = (ItemNuclearReactorComponent) map[i][j].getItem();
if ((item.component.maxTemperature == -1 ? Integer.MAX_VALUE : item.component.maxTemperature) < hullHeat || (item.component.minTemperature == -1 ? Integer.MIN_VALUE : item.component.minTemperature) > hullHeat)
continue;
if (item.component.duration != -1) {
map[i][j].setItemDamage(map[i][j].getItemDamage() + 1);
if (map[i][j].getItemDamage() >= item.component.duration)
map[i][j] = null;
}
if (item.component.maxAbsorbedHeat != -1) {
map[i][j].setItemDamage(heatMap[i][j]);
if (map[i][j].getItemDamage() >= item.component.maxAbsorbedHeat)
map[i][j] = null;
}
}
}
}
if (hullHeat > 100000)
worldObj.createExplosion(null, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 40F, true);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
this.stack[i * 9 + j] = map[i][j];
this.stackHeat[i * 9 + j] = heatMap[i][j];
}
}
if (hullHeat < 0)
hullHeat = 0;
ArrayList<FluidStack> fluids = new ArrayList<FluidStack>();
HashMap<Integer, FluidStack> fluidMap = new HashMap<Integer, FluidStack>();
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j++) {
if (map[i][j] != null && map[i][j].getItem() instanceof ItemNuclearReactorFluidComponent) {
ItemNuclearReactorComponent item = (ItemNuclearReactorComponent) map[i][j].getItem();
//System.out.println((item.component.maxTemperature == -1 ? Integer.MIN_VALUE : item.component.maxTemperature) < hullHeat);
if ((item.component.maxTemperature == -1 ? Integer.MAX_VALUE : item.component.maxTemperature) < hullHeat || (item.component.minTemperature == -1 ? Integer.MIN_VALUE : item.component.minTemperature) > hullHeat)
continue;
//System.out.println("Working");
FluidStack stack = ((ItemNuclearReactorFluidComponent)map[i][j].getItem()).getFluid(map[i][j]);
boolean inputed = false;
for (int k = 0; k < fluids.size(); k++) {
if (fluids.get(k).getFluid().equals(stack.getFluid())) {
inputed = true;
fluids.set(k, new FluidStack(fluids.get(k).getFluid(), fluids.get(k).amount + stack.amount));
}
}
if (!inputed)
fluids.add(stack);
//System.out.println(stack.getFluid().getName());
fluidMap.put(i * 9 + j, stack);
}
}
}
FluidStack[] array = new FluidStack[fluids.size()];
for (int i = 0; i < fluids.size(); i++) {
array[i] = fluids.get(i);
}
NuclearFusionRecipe recipe = NuclearFusionRegistry.getRecipe(array);
//System.out.println(recipe == null);
if (recipe != null && (storedFluid == null || (recipe.getOutput().getFluid().equals(storedFluid.getFluid()) && recipe.getOutput().amount + storedFluid.amount <= getCapacity()))) {
for (FluidStack stack : recipe.getInputs()) {
for(Entry<Integer, FluidStack> entry : fluidMap.entrySet()) {
if (entry.getValue().containsFluid(stack)) {
this.stack[entry.getKey()].setItemDamage(this.stack[entry.getKey()].getItemDamage() + stack.amount);
if (((ItemNuclearReactorFluidComponent)this.stack[entry.getKey()].getItem()).getFluid(this.stack[entry.getKey()]).amount <= 0)
this.stack[entry.getKey()] = null;
break;
}
}
}
if (storedFluid == null)
storedFluid = recipe.getOutput().copy();
else
storedFluid.amount += recipe.getOutput().amount;
}
worldObj.markBlockForUpdate(pos);
}
private int transferHeat(ItemNuclearReactorComponent item, ItemStack[][] map, int[][] heatMap, int x, int y) {
int num = 0;
int heat = heatMap[x][y] * 1;
int newHeat = heatMap[x][y] * 1;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == j || i == -j)
continue;
int posX = x+i;
if (posX < 0 || posX > 5 || y+j < 0 || y+j > 8 || map[posX][y+j] == null || !(map[posX][y+j].getItem() instanceof ItemNuclearReactorComponent) || ((ItemNuclearReactorComponent)map[posX][y+j].getItem()).component.absorption == 0)
continue;
num++;
}
}
if (num == 0)
return newHeat;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (i == j || i == -j)
continue;
if (x+i < 0 || x+i > 5 || y+j < 0 || y+j > 8 || map[x+i][y+j] == null || !(map[x+i][y+j].getItem() instanceof ItemNuclearReactorComponent) || ((ItemNuclearReactorComponent)map[x+i][y+j].getItem()).component.absorption == 0)
continue;
int toTransfer = (int) Math.ceil((float)heat / (float)num);
if (newHeat - toTransfer < 0)
toTransfer = newHeat;
ItemNuclearReactorComponent component = (ItemNuclearReactorComponent) map[x+i][y+j].getItem();
toTransfer = Math.min(toTransfer, Math.min(component.component.absorption == -1 ? Integer.MAX_VALUE : component.component.absorption, item.component.distrib == -1 ? Integer.MAX_VALUE : item.component.distrib));
// System.out.println(newHeat);
newHeat -= toTransfer;
// System.out.println(newHeat);
heatMap[x+i][y+j] += toTransfer;
heatMap[x][y] -= toTransfer;
}
}
return newHeat;
}
private void dissipateHeat(ItemNuclearReactorComponent item, ItemStack[][] map, int[][] heatMap, int x, int y) {
int coolGain = item.component.cool;
float coolMul = 1;
if (x > 0 && map[x - 1][y] != null && map[x - 1][y].getItem() instanceof ItemNuclearReactorComponent)
coolMul *= ((ItemNuclearReactorComponent)map[x - 1][y].getItem()).component.coolMul;
if (y > 0 && map[x][y - 1] != null && map[x][y - 1].getItem() instanceof ItemNuclearReactorComponent)
coolMul *= ((ItemNuclearReactorComponent)map[x][y - 1].getItem()).component.coolMul;
if (x < 5 && map[x + 1][y] != null && map[x + 1][y].getItem() instanceof ItemNuclearReactorComponent)
coolMul *= ((ItemNuclearReactorComponent)map[x + 1][y].getItem()).component.coolMul;
if (y < 8 && map[x][y + 1] != null && map[x][y + 1].getItem() instanceof ItemNuclearReactorComponent)
coolMul *= ((ItemNuclearReactorComponent)map[x][y + 1].getItem()).component.coolMul;
coolGain *= coolMul;
heatMap[x][y] -= coolGain;
if (heatMap[x][y] < 0) {
heatMap[x][y] = 0;
}
}
private int calcHeat(ItemNuclearReactorComponent item, ItemStack[][] map, int x, int y) {
int heatGain = item.component.heat;
float heatMul = 1;
if (x > 0 && map[x - 1][y] != null && map[x - 1][y].getItem() instanceof ItemNuclearReactorComponent)
heatMul *= ((ItemNuclearReactorComponent)map[x - 1][y].getItem()).component.heatMul;
if (y > 0 && map[x][y - 1] != null && map[x][y - 1].getItem() instanceof ItemNuclearReactorComponent)
heatMul *= ((ItemNuclearReactorComponent)map[x][y - 1].getItem()).component.heatMul;
if (x < 5 && map[x + 1][y] != null && map[x + 1][y].getItem() instanceof ItemNuclearReactorComponent)
heatMul *= ((ItemNuclearReactorComponent)map[x + 1][y].getItem()).component.heatMul;
if (y < 8 && map[x][y + 1] != null && map[x][y + 1].getItem() instanceof ItemNuclearReactorComponent)
heatMul *= ((ItemNuclearReactorComponent)map[x][y + 1].getItem()).component.heatMul;
heatGain *= heatMul;
if (item.component.fromHull) {
heatGain += Math.min(hullHeat, item.component.absorption);
hullHeat -= heatGain;
}
return heatGain;
}
private int calcPower(ItemNuclearReactorComponent item, ItemStack[][] map, int x, int y) {
int powerGain = item.component.power;
float powerMul = 1;
if (x > 0 && map[x - 1][y] != null && map[x - 1][y].getItem() instanceof ItemNuclearReactorComponent)
powerMul *= ((ItemNuclearReactorComponent)map[x - 1][y].getItem()).component.powerMul;
if (y > 0 && map[x][y - 1] != null && map[x][y - 1].getItem() instanceof ItemNuclearReactorComponent)
powerMul *= ((ItemNuclearReactorComponent)map[x][y - 1].getItem()).component.powerMul;
if (x < 5 && map[x + 1][y] != null && map[x + 1][y].getItem() instanceof ItemNuclearReactorComponent)
powerMul *= ((ItemNuclearReactorComponent)map[x + 1][y].getItem()).component.powerMul;
if (y < 8 && map[x][y + 1] != null && map[x][y + 1].getItem() instanceof ItemNuclearReactorComponent)
powerMul *= ((ItemNuclearReactorComponent)map[x][y + 1].getItem()).component.powerMul;
powerGain *= powerMul;
return powerGain;
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbt = new NBTTagCompound();
writeToNBT(nbt);
return new S35PacketUpdateTileEntity(pos, getBlockMetadata(), nbt);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.getNbtCompound());
worldObj.markBlockForUpdate(pos);
}
@Override
public int[] getSlotsForFace(EnumFacing side) {
return new int[] {};
}
@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) {
return false;
}
@Override
public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) {
return false;
}
@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
NBTTagList list = new NBTTagList();
compound.setInteger("HullHeat", hullHeat);
compound.setInteger("PrevHullHeat", prevTemp);
compound.setInteger("Energy", energy);
compound.setInteger("PrevEnergy", prevEnergy);
NBTTagCompound nbt = new NBTTagCompound();
if (storedFluid != null)
storedFluid.writeToNBT(nbt);
for (int i = 0; i < stack.length; i++) {
if (stack[i] == null)
continue;
NBTTagCompound tmp = new NBTTagCompound();
stack[i].writeToNBT(tmp);
tmp.setShort("Slot", (short)i);
tmp.setInteger("Heat", stackHeat[i]);
list.appendTag(tmp);
}
compound.setTag("Fluid", nbt);
compound.setTag("Inventory", list);
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
hullHeat = compound.getInteger("HullHeat");
prevTemp = compound.getInteger("PrevHullHeat");
energy = compound.getInteger("Energy");
prevEnergy = compound.getInteger("PrevEnergy");
storedFluid = FluidStack.loadFluidStackFromNBT(compound.getCompoundTag("Fluid"));
NBTTagList list = compound.getTagList("Inventory", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound nbt = list.getCompoundTagAt(i);
stack[nbt.getShort("Slot")] = ItemStack.loadItemStackFromNBT(nbt);
stackHeat[nbt.getShort("Slot")] = nbt.getInteger("Heat");
}
}
//TODO Fluid
@Override
public int fill(EnumFacing from, FluidStack resource, boolean doFill) {
return 0;
}
@Override
public FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain) {
return null;
}
@Override
public FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain) {
return null;
}
@Override
public boolean canFill(EnumFacing from, Fluid fluid) {
return false;
}
@Override
public boolean canDrain(EnumFacing from, Fluid fluid) {
return true;
}
@Override
public FluidTankInfo[] getTankInfo(EnumFacing from) {
return new FluidTankInfo[] {getInfo()};
}
@Override
public FluidStack getFluid() {
return null;
}
@Override
public int getFluidAmount() {
return 0;
}
@Override
public int getCapacity() {
return 16000;
}
@Override
public FluidTankInfo getInfo() {
return new FluidTankInfo(this);
}
@Override
public int fill(FluidStack resource, boolean doFill) {
return 0;
}
@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
return null;
}
} | mit |
personalised-semantic-search/GSorsOx | GSorsOx/src/cs/ox/ac/uk/sors/TopKAlgorithms.java | 4675 | package cs.ox.ac.uk.sors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.deri.iris.api.basics.ITuple;
public class TopKAlgorithms {
protected static Set<ITuple> getSkiline(PreferencesGraph preferenceModel) {
Set<ITuple> vertices = new HashSet<ITuple>();
for (ITuple tuple : preferenceModel.g.vertexSet()) {
if (preferenceModel.g.inDegreeOf(tuple) == 0) {
vertices.add(tuple);
}
}
return vertices;
}
public static List<ITuple> getTopK(PreferencesGraph p, int k) {
PreferencesGraph preferenceModel = new PreferencesGraph(p);
List<ITuple> topk = new ArrayList<ITuple>();
int nbNodes = preferenceModel.getVertexesSize();
int toBeAdded = 0;
if (k > nbNodes)
toBeAdded = nbNodes;
else
toBeAdded = k;
//System.out.println("Nodes before: "+preferenceModel.getVertexesSize());
while (toBeAdded > 0) {
Set<ITuple> skiline = getSkiline(preferenceModel);
int sizeSkiline = skiline.size();
if (toBeAdded >= sizeSkiline) {
topk.addAll(skiline);
preferenceModel.g.removeAllVertices(skiline);
toBeAdded -= sizeSkiline;
} else {
for (Iterator<ITuple> it = skiline.iterator(); it.hasNext()
&& toBeAdded > 0;) {
ITuple t = it.next();
topk.add(t);
toBeAdded--;
}
}
if (preferenceModel.getVertexesSize()==0) toBeAdded=0;
}
//System.out.println("Nodes after: "+preferenceModel.getVertexesSize());
return topk;
}
public static List<ITuple> topkPrefsGen(PreferencesGraph pg,
Map<String, Double> probabilisticModel, double t, int k) {
PreferencesGraph g = CombinationAlgorithms.combPrefsGen(pg,
probabilisticModel, t);
//System.out.println(g);
return getTopK(g, k);
}
public static List<ITuple> topkPrefsRank(Map<ITuple, Integer> ranks, int k) {
List<ITuple> topk = new ArrayList<ITuple>();
List<Integer> orderedValues = CombinationAlgorithms
.rmDuplicatesInt(CombinationAlgorithms.asSortedListAsc(ranks
.values()));
Map<Integer, Set<ITuple>> depthMap = new HashMap<Integer, Set<ITuple>>();
for (ITuple t : ranks.keySet()) {
int rank = ranks.get(t);
if (!depthMap.containsKey(rank)) {
depthMap.put(rank, new HashSet<ITuple>());
}
depthMap.get(rank).add(t);
}
int toBeAdded = (k > ranks.keySet().size()) ? ranks.keySet().size() : k;
int i = 0;
System.out.println("Nodes before: "+ ranks.keySet().size());
while (toBeAdded > 0) {
Set<ITuple> skiline = depthMap.get(orderedValues.get(i));
int sizeSkiline = skiline.size();
if (toBeAdded >= sizeSkiline) {
topk.addAll(skiline);
toBeAdded -= sizeSkiline;
} else {
for (Iterator<ITuple> it = skiline.iterator(); it.hasNext()
&& toBeAdded > 0;) {
ITuple t = it.next();
topk.add(t);
toBeAdded--;
}
}
i++;
}
System.out.println("Nodes after: "+ ranks.keySet().size());
return topk;
}
public static List<ITuple> topkPrefsRank(PreferencesGraph pg,
Map<String, Double> probabilisticModel, Function f, int k) {
Map<ITuple, Integer> ranks = CombinationAlgorithms.combPrefsRank(pg,
probabilisticModel, Function.Max);
List<ITuple> topk = new ArrayList<ITuple>();
List<Integer> orderedValues = CombinationAlgorithms
.rmDuplicatesInt(CombinationAlgorithms.asSortedListAsc(ranks
.values()));
Map<Integer, Set<ITuple>> depthMap = new HashMap<Integer, Set<ITuple>>();
for (ITuple t : ranks.keySet()) {
int rank = ranks.get(t);
if (!depthMap.containsKey(rank)) {
depthMap.put(rank, new HashSet<ITuple>());
}
depthMap.get(rank).add(t);
}
int toBeAdded = (k >= ranks.keySet().size()) ? ranks.keySet().size()
: k;
int i = 0;
while (toBeAdded > 0) {
Set<ITuple> skiline = depthMap.get(orderedValues.get(i));
int sizeSkiline = skiline.size();
if (toBeAdded >= sizeSkiline) {
topk.addAll(skiline);
toBeAdded -= sizeSkiline;
} else {
for (Iterator<ITuple> it = skiline.iterator(); it.hasNext()
&& toBeAdded > 0;) {
ITuple t = it.next();
topk.add(t);
toBeAdded--;
}
}
i++;
}
return topk;
}
public static List<ITuple> topkPrefsPT(PreferencesGraph pg,
Map<String, Double> probabilisticModel, double p, int k) {
PreferencesGraph g = CombinationAlgorithms.combPrefsPT(pg,
probabilisticModel, p);
return getTopK(g, k);
}
public static List<ITuple> topkPrefsSort(PreferencesGraph pg,
Map<String, Double> probabilisticModel, int k) {
PreferencesGraph g = CombinationAlgorithms.combPrefsSort(pg,
probabilisticModel);
return getTopK(g, k);
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/M_BusSlavePortSetupObject.java | 455 | /**
*/
package COSEM.COSEMObjects;
import COSEM.InterfaceClasses.M_Bus_slave_port_setup;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>MBus Slave Port Setup Object</b></em>'.
* <!-- end-user-doc -->
*
*
* @see COSEM.COSEMObjects.COSEMObjectsPackage#getM_BusSlavePortSetupObject()
* @model
* @generated
*/
public interface M_BusSlavePortSetupObject extends M_Bus_slave_port_setup {
} // M_BusSlavePortSetupObject
| mit |
andrey-yemelyanov/competitive-programming | cp-book/ch1/medium/_10919_Prerequisites.java | 1819 | package helvidios.cp.ch1.medium;
import java.util.Scanner;
public class _10919_Prerequisites {
public static void main(String... args){
String data = "3 2\r\n" +
"0123 9876 2222\r\n" +
"2 1 8888 2222\r\n" +
"3 2 9876 2222 7654 \r\n" +
"3 2\r\n" +
"0123 9876 2222\r\n" +
"2 2 8888 2222\r\n" +
"3 2 7654 9876 2222\r\n" +
"0\r\n" +
"\r\n" +
"";
Scanner scanner = new Scanner(data);
while(scanner.hasNext()){
int takenCoursesCount = scanner.nextInt();
if(takenCoursesCount == 0) break;
int categoryCount = scanner.nextInt();
int[] takenCourses = new int[takenCoursesCount];
for(int course = 0; course < takenCoursesCount; course++){
takenCourses[course] = scanner.nextInt();
}
boolean meetsRequirements = true;
for(int category = 0; category < categoryCount; category++){
int categoryCourseCount = scanner.nextInt();
int categoryMinCourseCount = scanner.nextInt();
int[] categoryCourses = new int[categoryCourseCount];
for(int i = 0; i < categoryCourses.length; i++)
categoryCourses[i] = scanner.nextInt();
if(!meetsCategoryRequirements(takenCourses, categoryCourses, categoryMinCourseCount))
meetsRequirements = false;
}
if(meetsRequirements) System.out.println("yes");
else System.out.println("no");
}
scanner.close();
}
private static boolean meetsCategoryRequirements(
int[] takenCourses,
int[] categoryCourses,
int mandatoryCourseCount){
int count = 0;
for(int course : takenCourses){
if(contains(categoryCourses, course))
count++;
}
return count >= mandatoryCourseCount;
}
private static boolean contains(int[] array, int element){
for(int i = 0; i < array.length; i++)
if(array[i] == element) return true;
return false;
}
}
| mit |
dvsa/motr-webapp | webapp/src/main/java/uk/gov/dvsa/motr/web/system/binder/factory/AwsKmsDecryptorFactory.java | 879 | package uk.gov.dvsa.motr.web.system.binder.factory;
import uk.gov.dvsa.motr.web.config.Config;
import uk.gov.dvsa.motr.web.encryption.AwsKmsDecryptor;
import uk.gov.dvsa.motr.web.encryption.Decryptor;
import javax.inject.Inject;
import static com.amazonaws.regions.Region.getRegion;
import static com.amazonaws.regions.Regions.fromName;
import static uk.gov.dvsa.motr.web.system.SystemVariable.REGION;
public class AwsKmsDecryptorFactory implements BaseFactory<Decryptor> {
private final Config config;
@Inject
public AwsKmsDecryptorFactory(Config config) {
this.config = config;
}
@Override
public Decryptor provide() {
return new AwsKmsDecryptor(
getRegion(
fromName(
config.getValue(REGION)
)
)
);
}
}
| mit |
karask/bitcoinpos | app/src/main/java/gr/cryptocurrencies/bitcoinpos/HistoryFragment.java | 34785 | package gr.cryptocurrencies.bitcoinpos;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import gr.cryptocurrencies.bitcoinpos.database.PointOfSaleDb;
import gr.cryptocurrencies.bitcoinpos.database.TxStatus;
import gr.cryptocurrencies.bitcoinpos.database.UpdateDbHelper;
import gr.cryptocurrencies.bitcoinpos.network.BlockchainInfoHelper;
import gr.cryptocurrencies.bitcoinpos.network.BlockcypherHelper;
import gr.cryptocurrencies.bitcoinpos.network.RestBitcoinHelper;
import gr.cryptocurrencies.bitcoinpos.utilities.CurrencyUtils;
import gr.cryptocurrencies.bitcoinpos.utilities.DateUtilities;
import com.opencsv.CSVWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class HistoryFragment extends ListFragment implements FragmentIsNowVisible { //SwipeRefreshLayout.OnRefreshListener
private PointOfSaleDb mDbHelper;
private List<HashMap<String,String>> mTransactionHistoryItemList;
private SwipeRefreshLayout mSwipeLayout;
private Timer mTimer;
private SharedPreferences sharedPref;
private String mLocalCurrency=null;
private boolean acceptTestnet;
// datepicker values
private int mStartYear, mStartMonth, mEndYear, mEndMonth;
private int secondsAfterTxCreatedToCancel=3600;
private int millisecondsIntervalToRefreshView=5000;
// Write external storage permission code
final private int WRITE_EXTERNAL_PERMISSION_CODE = 123;
public BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BlockchainInfoHelper.CUSTOM_BROADCAST_ACTION.equals(action)) {
new RefreshHistoryView().execute("");
//using this async task to update view, needs to pass an empty string
}
}
};
public HistoryFragment () {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//getting shared preferences
//using getActivity instead of getContext, getContext was added in API 23
sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
mLocalCurrency = sharedPref.getString(getString(R.string.local_currency_key), getString(R.string.default_currency_code));
acceptTestnet = sharedPref.getBoolean(getString(R.string.accept_testnet_key), false);
}
@Override
public void onResume() {
super.onResume();
//refresh view
updateTransactionHistoryFromCursor(UpdateDbHelper.getTransactionHistoryDbCursor());
updateTransactionHistoryView();
//set broadcast receiver to update history view when broadcast is received
getActivity().registerReceiver(mReceiver,
new IntentFilter(BlockchainInfoHelper.CUSTOM_BROADCAST_ACTION));
// set invalid dates for report export
mStartYear = -1;
mStartMonth = -1;
mEndYear = -1;
mEndMonth = -1;
// timer runs and updates the database //transferred from onCreate //is cancelled at onStop
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
Log.d("HISTORY UPDATE", "Updating transaction history items!");
updateStatusTx(UpdateDbHelper.getTransactionHistoryDbCursor());
//update database items, if a change has happened to the status of a transaction, the history view is updated also
}
}, 1, millisecondsIntervalToRefreshView);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_history, container, false);
// SwipeRefreshLayout removed
// mSwipeLayout = (SwipeRefreshLayout) fragmentView.findViewById(R.id.history_swipe_container);
// mSwipeLayout.setOnRefreshListener(this);
// mSwipeLayout.setColorSchemeResources(
// R.color.colorPrimary,
// R.color.colorAccent,
// R.color.colorPrimaryDark);
return fragmentView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.add(Menu.NONE, R.id.transactions_report, 500, R.string.transactions_report);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
item.setIcon(R.drawable.ic_file_chart_white_24dp);
}
// implementing SwipeRefreshLayout.OnRefreshListener
// @Override
// public void onRefresh() {
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// Log.d("HISTORY UPDATE", "Updating transaction history items!");
// updateStatusTx(UpdateDbHelper.getTransactionHistoryDbCursor());
// //update database items, if a change has happened to the status of a transaction, the history view is updated also
//
// mSwipeLayout.setRefreshing(false);
// }
// }, 2000);
// }
private class RefreshHistoryView extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
return params[0];
}
@Override
public void onPostExecute(String result) {
//get all database items, sort by date, create listview and update view
updateTransactionHistoryFromCursor(UpdateDbHelper.getTransactionHistoryDbCursor());
updateTransactionHistoryView();
}
}
private void updateStatusTx(Cursor c) {
if(c.moveToFirst()) {
do {
if ("0".equals(c.getString(4))) {//ongoing transaction
String txId = c.getString(0);
String bitcoinAddress = c.getString(6);
//double btcAmount = c.getDouble(5);
//double amountSatoshi = btcAmount * 100000000;
String crypto = c.getString(8);
if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTC))) {
boolean mainNet=true;
BlockchainInfoHelper.updateOngoingTxToConfirmedByTxId(txId,bitcoinAddress,mainNet);
}
else if (crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTCTEST))) {
boolean mainNet=false;
BlockchainInfoHelper.updateOngoingTxToConfirmedByTxId(txId,bitcoinAddress,mainNet);
}
else if (crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.LTC))) {
BlockcypherHelper.updateOngoingTxToConfirmedByTxId(txId,bitcoinAddress);
}
else if (crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BCH))) {
RestBitcoinHelper.updateOngoingTxToConfirmedByTxId(txId,bitcoinAddress);
}
}
else if ("1".equals(c.getString(4))){//confirmed transaction
//tx is confirmed
}
else if ("2".equals(c.getString(4))) {//pending transaction
int timeUnixEpoch = Integer.parseInt(c.getString(3));//createdAt time
int timeDevice = (int) (System.currentTimeMillis()/1000);// get current time to check for cancelled transactions
//getting row id for checking pending transactions that dont have txID, when checked the transaction is updated and the txId is set
int rowId = c.getInt(7);
String bitcoinAddress = c.getString(6);
double btcAmount = c.getDouble(5);
int amountSatoshi = (int) Math.round(btcAmount * 100000000);//getting INT from DOUBLE value that was saved before, for precise value of satoshis
String crypto = c.getString(8);// get saved cryptocurrency from db
if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTC))) {
boolean mainNet = true;
BlockchainInfoHelper.updatePendingTxToOngoingOrConfirmed( bitcoinAddress, amountSatoshi, rowId, timeUnixEpoch, mainNet );
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTCTEST))) {
boolean mainNet = false;
BlockchainInfoHelper.updatePendingTxToOngoingOrConfirmed( bitcoinAddress, amountSatoshi, rowId, timeUnixEpoch, mainNet );
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.LTC))) {
BlockcypherHelper.updatePendingTxToOngoingOrConfirmed( bitcoinAddress, amountSatoshi, rowId, timeUnixEpoch );
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BCH))) {
boolean mainNet = true;
RestBitcoinHelper.updatePendingTxToOngoingOrConfirmed( bitcoinAddress, amountSatoshi, rowId, timeUnixEpoch, mainNet );
}
if(timeDevice-timeUnixEpoch>secondsAfterTxCreatedToCancel){
UpdateDbHelper.updateDbTransaction(null, null, rowId, TxStatus.PENDING,TxStatus.CANCELLED);
}
}
} while (c.moveToNext());
}
}
private void updateTransactionHistoryFromCursor(Cursor c) {
mTransactionHistoryItemList = new ArrayList<HashMap<String,String>>();
if (c.moveToFirst()) {
do {
HashMap<String, String> item = new HashMap<String, String>();
// Get BTC double value and convert to string without scientific notation
DecimalFormat df = new DecimalFormat("#.########");
String btc8DecimalAmount = df.format(c.getDouble(5));
String cryptoAcronym = c.getString(8);
int isConfirmedImage;
if("1".equals(c.getString(4))) {
isConfirmedImage = R.drawable.ic_tick_green_24dp;
}
else if("2".equals(c.getString(4))){
isConfirmedImage = R.drawable.ic_tx;
}
else if("3".equals(c.getString(4))){
isConfirmedImage = R.drawable.ic_x;
}
else {
isConfirmedImage = R.drawable.ic_warning_orange_24dp;
}
//item.put(PointOfSaleDb.TRANSACTIONS_COLUMN_TX_ID, c.getString(0));
item.put(PointOfSaleDb.TRANSACTIONS_COLUMN_LOCAL_AMOUNT, c.getString(1) + " " + c.getString(2));
item.put(PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_AMOUNT, btc8DecimalAmount + " " + cryptoAcronym);
item.put(PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT, DateUtilities.getRelativeTimeString(c.getString(3)));
item.put(PointOfSaleDb.TRANSACTIONS_COLUMN_TX_STATUS, Integer.toString(isConfirmedImage));
mTransactionHistoryItemList.add(item);
} while (c.moveToNext());
}
}
// TODO should only check and update UI instead of re-creating the adapter
private void updateTransactionHistoryView() {
// define key strings in hashmap
String[] from = {
PointOfSaleDb.TRANSACTIONS_COLUMN_LOCAL_AMOUNT,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_AMOUNT,
PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT,
PointOfSaleDb.TRANSACTIONS_COLUMN_TX_STATUS
};
// define ids of view in list view fragment to bind to
int[] to = { R.id.transaction_history_amount, R.id.transaction_history_btc_amount, R.id.transaction_history_date, R.id.transaction_history_is_confirmed };
// checking that activity is not null before proceeding since sometime through the lifecycle of the fragment
// the getActivity() returns null!
if(getActivity() != null) {
// Instantiating an adapter to store each items -- R.layout.fragment_history defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity(), mTransactionHistoryItemList, R.layout.transaction_history_item, from, to);
setListAdapter(adapter);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.transactions_report) {
getTransactionsReport();
return true;
}
return super.onOptionsItemSelected(item);
}
private void getTransactionsReport() {
if(mTransactionHistoryItemList.size() == 0) {
Toast.makeText(getActivity(), getString(R.string.no_transaction_yet), Toast.LENGTH_SHORT).show();
} else {
showDatePicker();
}
}
// display dialog with explanation of why the permission is needed
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton(getString(R.string.ok), okListener)
.setNegativeButton(getString(R.string.cancel), null)
.create()
.show();
}
private Cursor getTransactionHistoryInRangeCursor(int startYear, int startMonth, int endYear, int endMonth) {
// get DB helper
mDbHelper = PointOfSaleDb.getInstance(getActivity());
// Each row in the list stores amount and date of transaction -- retrieves history from DB
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// get the following columns:
String[] tableColumns = { PointOfSaleDb.TRANSACTIONS_COLUMN_TX_ID,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_AMOUNT,
PointOfSaleDb.TRANSACTIONS_COLUMN_LOCAL_AMOUNT,
PointOfSaleDb.TRANSACTIONS_COLUMN_LOCAL_CURRENCY,
PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT,
PointOfSaleDb.TRANSACTIONS_COLUMN_MERCHANT_NAME,
PointOfSaleDb.TRANSACTIONS_COLUMN_PRODUCT_NAME,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_ADDRESS,
PointOfSaleDb.TRANSACTIONS_COLUMN_EXCHANGE_RATE,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY };
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, 1, 0,0);
long startInUnixTime = start.getTimeInMillis() / 1000L;
Calendar end = Calendar.getInstance();
end.set(endYear, endMonth, 31, 0,0);
long endInUnixTime = end.getTimeInMillis() / 1000L;
// date in db used to be yyyy-mm-dd ...
//String paddedStartMonth = String.format("%02d", mStartMonth +1); // +1 since index starts from 0
//String paddedEndMonth = String.format("%02d", mEndMonth +1 +1); // 2nd +1 for sql <= text comparison
String whereClause = PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT + " >= " + startInUnixTime + " and " +
PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT + " <= " + endInUnixTime + " and " +
PointOfSaleDb.TRANSACTIONS_COLUMN_TX_STATUS + " = 1";
//PointOfSaleDb.TRANSACTIONS_COLUMN_IS_CONFIRMED + " = 1"; // previously checking if transaction is confirmed (==1)
String sortOrder = PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT + " DESC";
Cursor c = db.query(PointOfSaleDb.TRANSACTIONS_TABLE_NAME, tableColumns, whereClause, null, null, null, sortOrder);
return c;
}
/**
* Displays the start and end date picker dialog
*/
private void showDatePicker() {
// Inflate your custom layout containing 2 DatePickers
LayoutInflater inflater = (LayoutInflater) getLayoutInflater(null);
View customView = inflater.inflate(R.layout.custom_date_picker, null);
// Define your date pickers
final DatePicker dpStartDate = (DatePicker) customView.findViewById(R.id.dpStartDate);
// remove day selection
((ViewGroup) dpStartDate).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
final DatePicker dpEndDate = (DatePicker) customView.findViewById(R.id.dpEndDate);
// remove day selection
((ViewGroup) dpEndDate).findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).setVisibility(View.GONE);
// Build the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(customView); // Set the view of the dialog to your custom layout
builder.setTitle(getString(R.string.select_time_period));
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
boolean areDatesValid = checkValidDates(dpStartDate.getYear(), dpStartDate.getMonth(), dpEndDate.getYear(), dpEndDate.getMonth());
if(areDatesValid) {
mStartYear = dpStartDate.getYear();
mStartMonth = dpStartDate.getMonth();
mEndYear = dpEndDate.getYear();
mEndMonth = dpEndDate.getMonth();
getStoragePermission();
} else {
Toast.makeText(getActivity(), R.string.date_range_not_valid, Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// set invalid dates for report export
mStartYear = -1;
mStartMonth = -1;
mEndYear = -1;
mEndMonth = -1;
dialog.dismiss();
}
});
// Create and show the dialog
builder.create().show();
}
private boolean checkValidDates(int startYear, int startMonth, int endYear, int endMonth) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
String startDateStr = String.format("%d-%02d", startYear, (startMonth +1)); // +1 since first index is 0
Date startDate = dateFormat.parse(startDateStr);
String endDateStr = String.format("%d-%02d", endYear, (endMonth +1));
Date endDate = dateFormat.parse(endDateStr);
if(startDate.compareTo(endDate) > 0)
return false;
else
return true;
} catch (ParseException pe) {
pe.printStackTrace();
}
return false;
}
private void getStoragePermission() {
if(mStartYear != -1) {
Cursor transactionsInRange = getTransactionHistoryInRangeCursor(mStartYear, mStartMonth, mEndYear, mEndMonth);
if(transactionsInRange.getCount() == 0) {
Toast.makeText(getActivity(), R.string.no_transactions_in_date_range, Toast.LENGTH_SHORT).show();
} else {
if(Build.VERSION.SDK_INT < 23) {
exportReportInRange(mStartYear, mStartMonth, mEndYear, mEndMonth, transactionsInRange);
} else {
// check for write external storage permission
int hasWriteExternalStorage = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteExternalStorage != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showMessageOKCancel(getString(R.string.access_external_storage_required_message),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_EXTERNAL_PERMISSION_CODE);
}
});
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_EXTERNAL_PERMISSION_CODE);
return;
} else {
exportReportInRange(mStartYear, mStartMonth, mEndYear, mEndMonth, transactionsInRange);
}
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case WRITE_EXTERNAL_PERMISSION_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
exportReportInRange(mStartYear, mStartMonth, mEndYear, mEndMonth, null);
} else {
// Permission Denied
Toast.makeText(getActivity(), R.string.no_access_to_download_folder, Toast.LENGTH_LONG).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void exportReportInRange(int startYear, int startMonth, int endYear, int endMonth, Cursor confirmedTxsInRange) {
Cursor c;
StringBuilder csvStr = new StringBuilder();
double totalBitcoins = 0;
// get Downloads folders path and construct csv filename
File downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
int counter = 1;
File csvFile;
csvFile = new File(downloadsPath.toString() + "/BitcoinPoS-" + counter + ".csv");
while(csvFile.exists()) {
counter++;
csvFile = new File(downloadsPath.toString() + "/BitcoinPoS-" + counter + ".csv");
}
try {
FileOutputStream fos = new FileOutputStream(csvFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
CSVWriter writer = new CSVWriter(osw);
// add headers
String[] headers = {
"Transaction Id",
"Cryptocurrency", // added Cryptocurrency column in .csv
"Cryptocurrency Amount", //"Bitcoin Amount",
"Local Amount",
"Local Currency",
"Exchange Rate (Cryptocurrency->Local)", //"Exchange Rate (BTC->Local)",
"Created At (UTC)",
"Merchant Name",
"Product Name",
"Cryptocurrency Address" // bitcoin address
};
writer.writeNext(headers);
if (confirmedTxsInRange == null)
c = getTransactionHistoryInRangeCursor(startYear, startMonth, endYear, endMonth);
else
c = confirmedTxsInRange;
// for each tx enter a row in csv file
// for each unconfirmed transaction check if confirmed
if (c.moveToFirst()) {
do {
// Get BTC double value and convert to string without scientific notation
DecimalFormat df = new DecimalFormat("#.########");
double amount = c.getDouble(1);
String btc8DecimalAmount = df.format(amount);
// Get only product name from "name[-|-]0.5" strings that DB contains
String dbProduct = c.getString(6) == null ? "" : c.getString(6);
String productName = dbProduct.substring(0, dbProduct.lastIndexOf("[-|-]"));
String[] row = {
c.getString(0),
c.getString(9), // added Cryptocurrency column in .csv
btc8DecimalAmount,
c.getString(2),
c.getString(3),
c.getString(8) == null ? "" : c.getString(8), // exchange rate
DateUtilities.getRelativeTimeString(c.getString(4)), // date
c.getString(5), // merchant name
productName,
c.getString(7) //cryptocurrency address // bitcoin address
};
writer.writeNext(row);
// sum all (double) amounts
totalBitcoins += amount;
} while (c.moveToNext());
}
// write total amount of bitcoins
//String[] totalAmountString = { "Total in bitcoins: " + String.format("%.8f", totalBitcoins) };
//writer.writeNext(totalAmountString);
writer.close();
osw.close();
fos.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Toast.makeText(getActivity(), getString(R.string.csv_file_saved, csvFile.getName()), Toast.LENGTH_LONG).show();
}
// implementing FragmentIsNotVisible, our interface so that view pager can act when one of its fragments becomes visible
@Override
public void doWhenFragmentBecomesVisible() {
}
@Override
public void onPause(){
super.onPause();
if(mTimer != null){
mTimer.cancel();
//cancel timer task, assign null and stop checks
}
getActivity().unregisterReceiver(mReceiver);
//unregister the receiver when paused, we dont need to check for status changes
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//setting listeners for click to show info about the selected tx and long click to show dialog and ask to delete the tx
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
showDialogToDeleteTx(arg2);
return true;
}
});
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
getTransactionsAfterClick(i);
}
});
}
private void showDialogToDeleteTx(final int selectedItem) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.delete_transaction_message));
builder.setCancelable(true);
builder.setPositiveButton(
getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//get method to delete transaction
UpdateDbHelper.getTransactionsAndDeleteAfterLongClick(selectedItem);
}
});
builder.setNegativeButton(
getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
private void showInfoDialog(String btcAddress, String txId, String status, String crypto, double amount) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
if(txId==null) {
txId = getString(R.string.no_id);
}
String title = getString(R.string.bitcoin_tx_title);
String acronymCrypto = String.valueOf(CurrencyUtils.CurrencyType.BTC);
String paymentCryptoType = String.valueOf(CurrencyUtils.CurrencyType.BTC);
if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTC))) {
title = getString(R.string.bitcoin_tx_title);
acronymCrypto = String.valueOf(CurrencyUtils.CurrencyType.BTC);
paymentCryptoType = acronymCrypto;
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BCH))) {
title = getString(R.string.bitcoin_cash_tx_title);
acronymCrypto = String.valueOf(CurrencyUtils.CurrencyType.BCH);
paymentCryptoType = acronymCrypto;
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.LTC))) {
title = getString(R.string.litecoin_tx_title);
acronymCrypto = String.valueOf(CurrencyUtils.CurrencyType.LTC);
paymentCryptoType = acronymCrypto;
}
else if(crypto.equals(String.valueOf(CurrencyUtils.CurrencyType.BTCTEST))) {
title = getString(R.string.bitcoin_testnet_tx_title);
acronymCrypto = getString(R.string.btctest);
paymentCryptoType = getString(R.string.bitcoin_testnet_show_in_title);
}
DecimalFormat formatter = new DecimalFormat("#.########", DecimalFormatSymbols.getInstance( Locale.ENGLISH ));
String amountStr = formatter.format(amount);
String info = "\n" +getString(R.string.payment_address) + " (" + paymentCryptoType + ")" + ":\n" + btcAddress + "\n\n" + getString(R.string.transaction_id) + ":\n" + txId + "\n\n" +
getString(R.string.payment_amount) + ":\n" + amountStr + " " + acronymCrypto + "\n\n" + getString(R.string.transaction_status) + ":\n" + status;
builder.setTitle(title);
builder.setMessage(info);
builder.setCancelable(true);
builder.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getTransactionsAfterClick(id);
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
//get transaction info to show in dialog after clicking on an item of the history listview
private void getTransactionsAfterClick(int selectedItem) {
// get DB helper
mDbHelper = PointOfSaleDb.getInstance(getActivity());
// Each row in the list stores amount and date of transaction -- retrieves history from DB
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// get the following columns:
String[] tableColumns = { PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT,
PointOfSaleDb.TRANSACTIONS_COLUMN_TX_ID,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_ADDRESS,
PointOfSaleDb.TRANSACTIONS_COLUMN_TX_STATUS,
"_ROWID_",// getting also _ROWID_ to delete the selected tx
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY,
PointOfSaleDb.TRANSACTIONS_COLUMN_CRYPTOCURRENCY_AMOUNT };
String sortOrder = PointOfSaleDb.TRANSACTIONS_COLUMN_CREATED_AT + " DESC";
Cursor c = db.query(PointOfSaleDb.TRANSACTIONS_TABLE_NAME, tableColumns, null, null, null, null, sortOrder);
//moving to position of the cursor according to the selected item to delete the transaction
if(c.moveToPosition(selectedItem)) {
String crypto = c.getString(5);
String status;
if(c.getInt(3)==0){status=getString(R.string.payment_unconfirmed);}
else if(c.getInt(3)==1){status=getString(R.string.payment_confirmed);}
else if(c.getInt(3)==2){status=getString(R.string.payment_pending);}
else {status=getString(R.string.payment_cancelled);}
double amount = c.getDouble(6);
//show dialog
showInfoDialog(c.getString(2),c.getString(1),status, crypto, amount);
}
}
}
| mit |
desperateCoder/FileTo | src/main/java/de/c4/model/messages/file/FileTransferAnswer.java | 195 | package main.java.de.c4.model.messages.file;
public class FileTransferAnswer {
public long id;
public boolean accepted = false;
public int serverPort;
public FileTransferAnswer() {
}
}
| mit |
ITSFactory/itsfactory.siri.bindings.v13 | src/main/java/eu/datex2/schema/_1_0/_1_0/TravelTimeValue.java | 7436 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.27 at 08:11:57 PM EEST
//
package eu.datex2.schema._1_0._1_0;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* Derived/computed travel time information relating to a specific group of locations.
*
* <p>Java class for TravelTimeValue complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TravelTimeValue">
* <complexContent>
* <extension base="{http://datex2.eu/schema/1_0/1_0}BasicDataValue">
* <sequence>
* <element name="travelTime" type="{http://datex2.eu/schema/1_0/1_0}Seconds" minOccurs="0"/>
* <element name="travelTimeTrendType" type="{http://datex2.eu/schema/1_0/1_0}TravelTimeTrendTypeEnum" minOccurs="0"/>
* <element name="travelTimeType" type="{http://datex2.eu/schema/1_0/1_0}TravelTimeTypeEnum" minOccurs="0"/>
* <element name="freeFlowSpeed" type="{http://datex2.eu/schema/1_0/1_0}KilometresPerHour" minOccurs="0"/>
* <element name="freeFlowTravelTime" type="{http://datex2.eu/schema/1_0/1_0}Seconds" minOccurs="0"/>
* <element name="normallyExpectedTravelTime" type="{http://datex2.eu/schema/1_0/1_0}Seconds" minOccurs="0"/>
* <element name="vehicleType" type="{http://datex2.eu/schema/1_0/1_0}VehicleTypeEnum" maxOccurs="unbounded" minOccurs="0"/>
* <element name="travelTimeValueExtension" type="{http://datex2.eu/schema/1_0/1_0}ExtensionType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TravelTimeValue", propOrder = {
"travelTime",
"travelTimeTrendType",
"travelTimeType",
"freeFlowSpeed",
"freeFlowTravelTime",
"normallyExpectedTravelTime",
"vehicleType",
"travelTimeValueExtension"
})
public class TravelTimeValue
extends BasicDataValue
{
protected Float travelTime;
protected TravelTimeTrendTypeEnum travelTimeTrendType;
protected TravelTimeTypeEnum travelTimeType;
protected Float freeFlowSpeed;
protected Float freeFlowTravelTime;
protected Float normallyExpectedTravelTime;
protected List<VehicleTypeEnum> vehicleType;
protected ExtensionType travelTimeValueExtension;
/**
* Gets the value of the travelTime property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getTravelTime() {
return travelTime;
}
/**
* Sets the value of the travelTime property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setTravelTime(Float value) {
this.travelTime = value;
}
/**
* Gets the value of the travelTimeTrendType property.
*
* @return
* possible object is
* {@link TravelTimeTrendTypeEnum }
*
*/
public TravelTimeTrendTypeEnum getTravelTimeTrendType() {
return travelTimeTrendType;
}
/**
* Sets the value of the travelTimeTrendType property.
*
* @param value
* allowed object is
* {@link TravelTimeTrendTypeEnum }
*
*/
public void setTravelTimeTrendType(TravelTimeTrendTypeEnum value) {
this.travelTimeTrendType = value;
}
/**
* Gets the value of the travelTimeType property.
*
* @return
* possible object is
* {@link TravelTimeTypeEnum }
*
*/
public TravelTimeTypeEnum getTravelTimeType() {
return travelTimeType;
}
/**
* Sets the value of the travelTimeType property.
*
* @param value
* allowed object is
* {@link TravelTimeTypeEnum }
*
*/
public void setTravelTimeType(TravelTimeTypeEnum value) {
this.travelTimeType = value;
}
/**
* Gets the value of the freeFlowSpeed property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getFreeFlowSpeed() {
return freeFlowSpeed;
}
/**
* Sets the value of the freeFlowSpeed property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setFreeFlowSpeed(Float value) {
this.freeFlowSpeed = value;
}
/**
* Gets the value of the freeFlowTravelTime property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getFreeFlowTravelTime() {
return freeFlowTravelTime;
}
/**
* Sets the value of the freeFlowTravelTime property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setFreeFlowTravelTime(Float value) {
this.freeFlowTravelTime = value;
}
/**
* Gets the value of the normallyExpectedTravelTime property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getNormallyExpectedTravelTime() {
return normallyExpectedTravelTime;
}
/**
* Sets the value of the normallyExpectedTravelTime property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setNormallyExpectedTravelTime(Float value) {
this.normallyExpectedTravelTime = value;
}
/**
* Gets the value of the vehicleType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the vehicleType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVehicleType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link VehicleTypeEnum }
*
*
*/
public List<VehicleTypeEnum> getVehicleType() {
if (vehicleType == null) {
vehicleType = new ArrayList<VehicleTypeEnum>();
}
return this.vehicleType;
}
/**
* Gets the value of the travelTimeValueExtension property.
*
* @return
* possible object is
* {@link ExtensionType }
*
*/
public ExtensionType getTravelTimeValueExtension() {
return travelTimeValueExtension;
}
/**
* Sets the value of the travelTimeValueExtension property.
*
* @param value
* allowed object is
* {@link ExtensionType }
*
*/
public void setTravelTimeValueExtension(ExtensionType value) {
this.travelTimeValueExtension = value;
}
}
| mit |
karim/adila | database/src/main/java/adila/db/htc5fa31mg5fdug_htc20desire20620g20dual20sim.java | 287 | // This file is automatically generated.
package adila.db;
/*
* HTC Desire 620G dual sim
*
* DEVICE: htc_a31mg_dug
* MODEL: HTC Desire 620G dual sim
*/
final class htc5fa31mg5fdug_htc20desire20620g20dual20sim {
public static final String DATA = "HTC|Desire 620G dual sim|";
}
| mit |
ljshj/actor-platform | actor-sdk/sdk-core/core/core-js/src/main/java/im/actor/core/js/JsFacade.java | 57870 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.js;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.user.client.Event;
import im.actor.core.*;
import im.actor.core.api.ApiAuthSession;
import im.actor.core.api.ApiDialog;
import im.actor.core.api.rpc.ResponseLoadArchived;
import im.actor.core.entity.BotCommand;
import im.actor.core.entity.EntityConverter;
import im.actor.core.entity.MentionFilterResult;
import im.actor.core.entity.MessageSearchEntity;
import im.actor.core.entity.Peer;
import im.actor.core.entity.PeerSearchEntity;
import im.actor.core.entity.PeerSearchType;
import im.actor.core.entity.PeerType;
import im.actor.core.entity.User;
import im.actor.core.js.annotations.UsedByApp;
import im.actor.core.js.entity.*;
import im.actor.core.js.modules.JsBindedValueCallback;
import im.actor.core.js.providers.JsNotificationsProvider;
import im.actor.core.js.providers.JsPhoneBookProvider;
import im.actor.core.js.providers.JsCallsProvider;
import im.actor.core.js.providers.electron.JsElectronApp;
import im.actor.core.js.utils.HtmlMarkdownUtils;
import im.actor.core.js.utils.IdentityUtils;
import im.actor.core.network.RpcCallback;
import im.actor.core.network.RpcException;
import im.actor.core.viewmodel.CommandCallback;
import im.actor.core.viewmodel.UserVM;
import im.actor.runtime.Log;
import im.actor.runtime.Storage;
import im.actor.runtime.actors.messages.*;
import im.actor.runtime.actors.messages.Void;
import im.actor.runtime.function.Consumer;
import im.actor.runtime.js.JsFileSystemProvider;
import im.actor.runtime.js.JsLogProvider;
import im.actor.runtime.js.fs.JsBlob;
import im.actor.runtime.js.fs.JsFile;
import im.actor.runtime.js.mvvm.JsDisplayListCallback;
import im.actor.runtime.js.utils.JsPromise;
import im.actor.runtime.js.utils.JsPromiseDispatcher;
import im.actor.runtime.js.utils.JsPromiseExecutor;
import im.actor.runtime.markdown.MarkdownParser;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportPackage;
import org.timepedia.exporter.client.Exportable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ExportPackage("actor")
@Export("ActorApp")
@UsedByApp
public class JsFacade implements Exportable {
private static final String TAG = "JsMessenger";
private static final String APP_NAME = "Actor Web App";
private static final int APP_ID = 3;
private static final String APP_KEY = "278f13e07eee8398b189bced0db2cf66703d1746e2b541d85f5b42b1641aae0e";
private JsMessenger messenger;
private JsFileSystemProvider provider;
private Peer lastVisiblePeer;
@Export
@UsedByApp
public JsFacade() {
}
@UsedByApp
public void init(JsConfig config) {
provider = (JsFileSystemProvider) Storage.getFileSystemRuntime();
String clientName = IdentityUtils.getClientName();
String uniqueId = IdentityUtils.getUniqueId();
ConfigurationBuilder configuration = new ConfigurationBuilder();
configuration.setApiConfiguration(new ApiConfiguration(APP_NAME, APP_ID, APP_KEY, clientName, uniqueId));
configuration.setPhoneBookProvider(new JsPhoneBookProvider());
configuration.setNotificationProvider(new JsNotificationsProvider());
configuration.setCallsProvider(new JsCallsProvider());
// Setting locale
String locale = LocaleInfo.getCurrentLocale().getLocaleName();
if (locale.equals("default")) {
Log.d(TAG, "Default locale found");
configuration.addPreferredLanguage("en");
} else {
Log.d(TAG, "Locale found:" + locale);
configuration.addPreferredLanguage(locale.toLowerCase());
}
// Setting timezone
int offset = new Date().getTimezoneOffset();
String timeZone = TimeZone.createTimeZone(offset).getID();
Log.d(TAG, "TimeZone found:" + timeZone + " for delta " + offset);
configuration.setTimeZone(timeZone);
// LocaleInfo.getCurrentLocale().getLocaleName()
// Is Web application
configuration.setPlatformType(PlatformType.WEB);
// Device Category
// Only Desktop is supported for JS library
configuration.setDeviceCategory(DeviceCategory.DESKTOP);
// Adding endpoints
for (String endpoint : config.getEndpoints()) {
configuration.addEndpoint(endpoint);
}
if (config.getLogHandler() != null) {
final JsLogCallback callback = config.getLogHandler();
JsLogProvider.setLogCallback(new JsLogProvider.LogCallback() {
@Override
public void log(String tag, String level, String message) {
callback.log(tag, level, message);
}
});
}
messenger = new JsMessenger(configuration.build());
Log.d(TAG, "JsMessenger created");
}
@UsedByApp
public boolean isLoggedIn() {
return messenger.isLoggedIn();
}
@UsedByApp
public int getUid() {
return messenger.myUid();
}
@UsedByApp
public boolean isElectron() {
return messenger.isElectron();
}
// Auth
@UsedByApp
public String getAuthState() {
return Enums.convert(messenger.getAuthState());
}
@UsedByApp
public String getAuthPhone() {
return "" + messenger.getAuthPhone();
}
@UsedByApp
public void requestSms(String phone, final JsAuthSuccessClosure success,
final JsAuthErrorClosure error) {
try {
long res = Long.parseLong(phone);
messenger.requestStartPhoneAuth(res).start(new CommandCallback<AuthState>() {
@Override
public void onResult(AuthState res) {
success.onResult(Enums.convert(res));
}
@Override
public void onError(Exception e) {
String tag = "INTERNAL_ERROR";
String message = "Internal error";
boolean canTryAgain = false;
if (e instanceof RpcException) {
tag = ((RpcException) e).getTag();
message = e.getMessage();
canTryAgain = ((RpcException) e).isCanTryAgain();
}
error.onError(tag, message, canTryAgain, getAuthState());
}
});
} catch (Exception e) {
Log.e(TAG, e);
im.actor.runtime.Runtime.postToMainThread(new Runnable() {
@Override
public void run() {
error.onError("PHONE_NUMBER_INVALID", "Invalid phone number", false,
getAuthState());
}
});
}
}
@UsedByApp
public void requestCodeEmail(String email, final JsAuthSuccessClosure success,
final JsAuthErrorClosure error) {
messenger.requestStartEmailAuth(email).start(new CommandCallback<AuthState>() {
@Override
public void onResult(AuthState res) {
success.onResult(Enums.convert(res));
}
@Override
public void onError(Exception e) {
String tag = "INTERNAL_ERROR";
String message = "Internal error";
boolean canTryAgain = false;
if (e instanceof RpcException) {
tag = ((RpcException) e).getTag();
message = e.getMessage();
canTryAgain = ((RpcException) e).isCanTryAgain();
}
error.onError(tag, message, canTryAgain, getAuthState());
}
});
}
@UsedByApp
public void sendCode(String code, final JsAuthSuccessClosure success,
final JsAuthErrorClosure error) {
try {
messenger.validateCode(code).start(new CommandCallback<AuthState>() {
@Override
public void onResult(AuthState res) {
success.onResult(Enums.convert(res));
}
@Override
public void onError(Exception e) {
String tag = "INTERNAL_ERROR";
String message = "Internal error";
boolean canTryAgain = false;
if (e instanceof RpcException) {
tag = ((RpcException) e).getTag();
message = e.getMessage();
canTryAgain = ((RpcException) e).isCanTryAgain();
}
error.onError(tag, message, canTryAgain, getAuthState());
}
});
} catch (Exception e) {
Log.e(TAG, e);
im.actor.runtime.Runtime.postToMainThread(new Runnable() {
@Override
public void run() {
error.onError("PHONE_CODE_INVALID", "Invalid code number", false,
getAuthState());
}
});
}
}
@UsedByApp
public void signUp(String name, final JsAuthSuccessClosure success,
final JsAuthErrorClosure error) {
messenger.signUp(name, null, null).start(new CommandCallback<AuthState>() {
@Override
public void onResult(AuthState res) {
success.onResult(Enums.convert(res));
}
@Override
public void onError(Exception e) {
String tag = "INTERNAL_ERROR";
String message = "Internal error";
boolean canTryAgain = false;
if (e instanceof RpcException) {
tag = ((RpcException) e).getTag();
message = e.getMessage();
canTryAgain = ((RpcException) e).isCanTryAgain();
}
error.onError(tag, message, canTryAgain, getAuthState());
}
});
}
@UsedByApp
public JsPromise loadSessions() {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.loadSessions().start(new CommandCallback<List<ApiAuthSession>>() {
@Override
public void onResult(List<ApiAuthSession> res) {
JsArray<JsAuthSession> jsSessions = JsArray.createArray().cast();
for (ApiAuthSession session : res) {
jsSessions.push(JsAuthSession.create(session));
}
resolve(jsSessions);
}
@Override
public void onError(Exception e) {
Log.e(TAG, e);
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise terminateSession(final int id) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.terminateSession(id).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
Log.e(TAG, e);
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise terminateAllSessions() {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.terminateAllSessions().start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
Log.e(TAG, e);
reject(e.getMessage());
}
});
}
});
}
// Dialogs
@UsedByApp
public void bindDialogs(JsDisplayListCallback<JsDialog> callback) {
if (callback == null) {
return;
}
messenger.getSharedDialogList().subscribe(callback, false);
}
@UsedByApp
public void unbindDialogs(JsDisplayListCallback<JsDialog> callback) {
if (callback == null) {
return;
}
messenger.getSharedDialogList().unsubscribe(callback);
}
@UsedByApp
public void bindGroupDialogs(JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getDialogsGroupedList().subscribe(callback);
}
@UsedByApp
public void unbindGroupDialogs(JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getDialogsGroupedList().unsubscribe(callback);
}
// Contacts
@UsedByApp
public void bindContacts(JsDisplayListCallback<JsContact> callback) {
if (callback == null) {
return;
}
messenger.getSharedContactList().subscribe(callback, true);
}
@UsedByApp
public void unbindContacts(JsDisplayListCallback<JsContact> callback) {
if (callback == null) {
return;
}
messenger.getSharedContactList().unsubscribe(callback);
}
// Search
@UsedByApp
public void bindSearch(JsDisplayListCallback<JsSearchEntity> callback) {
if (callback == null) {
return;
}
messenger.getSharedSearchList().subscribe(callback, false);
}
@UsedByApp
public void unbindSearch(JsDisplayListCallback<JsSearchEntity> callback) {
if (callback == null) {
return;
}
messenger.getSharedSearchList().unsubscribe(callback);
}
// Chats
@UsedByApp
public void preInitChat(JsPeer peer) {
messenger.onConversationPreLoad(peer.convert());
}
@UsedByApp
public JsMessagesBind bindMessages(JsPeer peer, JsMessagesBindClosure callback) {
if (callback == null) {
return null;
}
Peer peerC = peer.convert();
return new JsMessagesBind(callback, messenger.getSharedChatList(peerC), messenger.getConversationVM(peerC));
}
public JsPromise editMessage(JsPeer peer, String id, String newText) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.updateMessage(peer.convert(), newText, Long.parseLong(id)).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public void deleteMessage(JsPeer peer, String id) {
messenger.deleteMessages(peer.convert(), new long[]{Long.parseLong(id)});
}
@UsedByApp
public JsPromise deleteChat(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.deleteChat(peer.convert()).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "deleteChat:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "deleteChat:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise clearChat(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.clearChat(peer.convert()).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "clearChat:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "clearChat:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise archiveChat(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.archiveChat(peer.convert()).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "archiveChat:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "archiveChat:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise favoriteChat(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.favouriteChat(peer.convert()).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "favouriteChat:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "favouriteChat:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise unfavoriteChat(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.unfavoriteChat(peer.convert()).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "unfavouriteChat:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "unfavouriteChat:error");
reject(e.getMessage());
}
});
}
});
}
// Peers
@UsedByApp
public JsPeer getUserPeer(int uid) {
return JsPeer.create(Peer.user(uid));
}
@UsedByApp
public JsPeer getGroupPeer(int gid) {
return JsPeer.create(Peer.group(gid));
}
// Stickers
@UsedByApp
public JsArray<JsSticker> getStickers() {
return messenger.getStickers().get();
}
@UsedByApp
public void bindStickers(JsBindedValueCallback callback) {
messenger.getStickers().subscribe(callback);
}
@UsedByApp
public void unbindStickers(JsBindedValueCallback callback) {
messenger.getStickers().unsubscribe(callback);
}
// Users
@UsedByApp
public JsUser getUser(int uid) {
return messenger.getJsUser(uid).get();
}
@UsedByApp
public void bindUser(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUser(uid).subscribe(callback);
}
@UsedByApp
public void unbindUser(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUser(uid).unsubscribe(callback);
}
@UsedByApp
public void bindUserOnline(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUserOnline(uid).subscribe(callback);
}
@UsedByApp
public void unbindUserOnline(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUserOnline(uid).unsubscribe(callback);
}
@UsedByApp
public void bindUserBlocked(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUserBlocked(uid).subscribe(callback);
}
@UsedByApp
public void unbindUserBlocked(int uid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsUserBlocked(uid).unsubscribe(callback);
}
@UsedByApp
public JsPromise blockUser(final int uid) {
return JsPromise.from(messenger.blockUser(uid));
}
@UsedByApp
public JsPromise unblockUser(final int uid) {
return JsPromise.from(messenger.unblockUser(uid));
}
@UsedByApp
public JsPromise isStarted(final int uid) {
return JsPromise.from(messenger.isStarted(uid));
}
// Groups
@UsedByApp
public JsGroup getGroup(int gid) {
return messenger.getJsGroup(gid).get();
}
@UsedByApp
public void bindGroup(int gid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsGroup(gid).subscribe(callback);
}
@UsedByApp
public void unbindGroup(int gid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsGroup(gid).unsubscribe(callback);
}
@UsedByApp
public void bindGroupOnline(int gid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsGroupOnline(gid).subscribe(callback);
}
@UsedByApp
public void unbindGroupOnline(int gid, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsGroupOnline(gid).unsubscribe(callback);
}
// Calls
@UsedByApp
public JsPromise doCall(final int uid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.doCall(uid).start(new CommandCallback<Long>() {
@Override
public void onResult(Long res) {
Log.d(TAG, "doCall:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "doCall:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise doGroupCall(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.doGroupCall(gid).start(new CommandCallback<Long>() {
@Override
public void onResult(Long res) {
Log.d(TAG, "doGroupCall:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "doGroupCall:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public void answerCall(String callId) {
messenger.answerCall(Long.parseLong(callId));
}
@UsedByApp
public void endCall(String callId) {
messenger.endCall(Long.parseLong(callId));
}
@UsedByApp
public void toggleCallMute(String callId) {
messenger.toggleCallMute(Long.parseLong(callId));
}
@UsedByApp
public void bindCall(String id, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsCall(id).subscribe(callback);
}
@UsedByApp
public void unbindCall(String id, JsBindedValueCallback callback) {
if (callback == null) {
return;
}
messenger.getJsCall(id).unsubscribe(callback);
}
// Event Bus
@UsedByApp
public void bindEventBus(JsEventBusCallback callback) {
if (callback == null) {
return;
}
messenger.subscribeEventBus(callback);
}
@UsedByApp
public void unbindEventBus(JsEventBusCallback callback) {
if (callback == null) {
return;
}
messenger.unsubscribeEventBus(callback);
}
// Actions
@UsedByApp
public void sendMessage(JsPeer peer, String text) {
messenger.sendMessageWithMentionsDetect(peer.convert(), text);
}
@UsedByApp
public void sendFile(JsPeer peer, JsFile file) {
String descriptor = provider.registerUploadFile(file);
messenger.sendDocument(peer.convert(),
file.getName(), file.getMimeType(), descriptor);
}
@UsedByApp
public void sendPhoto(final JsPeer peer, final JsFile file) {
messenger.sendPhoto(peer.convert(), file);
}
@UsedByApp
public void sendAnimation(final JsPeer peer, final JsFile file) {
messenger.sendAnimation(peer.convert(), file);
}
@UsedByApp
public void sendClipboardPhoto(final JsPeer peer, final JsBlob blob) {
messenger.sendClipboardPhoto(peer.convert(), blob);
}
@UsedByApp
public void sendVoiceMessage(final JsPeer peer, int duration, final JsBlob blob) {
String descriptor = provider.registerUploadFile(blob);
messenger.sendAudio(peer.convert(), "voice.opus", duration, descriptor);
}
@UsedByApp
public void sendSticker(JsPeer peer, JsSticker sticker) {
messenger.sendSticker(peer.convert(), sticker.getSticker());
}
// Drafts
@UsedByApp
public void saveDraft(JsPeer peer, String text) {
messenger.saveDraft(peer.convert(), text);
}
@UsedByApp
public String loadDraft(JsPeer peer) {
return messenger.loadDraft(peer.convert());
}
@UsedByApp
public JsArray<JsMentionFilterResult> findMentions(int gid, String query) {
List<MentionFilterResult> res = messenger.findMentions(gid, query);
JsArray<JsMentionFilterResult> mentions = JsArray.createArray().cast();
for (MentionFilterResult m : res) {
mentions.push(JsMentionFilterResult.create(m));
}
return mentions;
}
@UsedByApp
public JsArray<JsBotCommand> findBotCommands(int uid, String query) {
JsArray<JsBotCommand> commands = JsArray.createArray().cast();
for (BotCommand c : messenger.getUser(uid).getBotCommands().get()) {
if (c.getSlashCommand().startsWith(query)) {
commands.push(JsBotCommand.create(c.getSlashCommand(), c.getDescription()));
}
}
return commands;
}
// Typing
@UsedByApp
public void onTyping(JsPeer peer) {
messenger.onTyping(peer.convert());
}
@UsedByApp
public JsTyping getTyping(JsPeer peer) {
return messenger.getTyping(peer.convert()).get();
}
@UsedByApp
public void bindTyping(JsPeer peer, JsBindedValueCallback callback) {
messenger.getTyping(peer.convert()).subscribe(callback);
}
@UsedByApp
public void unbindTyping(JsPeer peer, JsBindedValueCallback callback) {
messenger.getTyping(peer.convert()).unsubscribe(callback);
}
// Updating state
@UsedByApp
public void bindConnectState(JsBindedValueCallback callback) {
messenger.getOnlineStatus().subscribe(callback);
}
@UsedByApp
public void unbindConnectState(JsBindedValueCallback callback) {
messenger.getOnlineStatus().unsubscribe(callback);
}
@UsedByApp
public void bindGlobalCounter(JsBindedValueCallback callback) {
messenger.getGlobalCounter().subscribe(callback);
}
@UsedByApp
public void unbindGlobalCounter(JsBindedValueCallback callback) {
messenger.getGlobalCounter().unsubscribe(callback);
}
@UsedByApp
public void bindTempGlobalCounter(JsBindedValueCallback callback) {
messenger.getTempGlobalCounter().subscribe(callback);
}
@UsedByApp
public void unbindTempGlobalCounter(JsBindedValueCallback callback) {
messenger.getTempGlobalCounter().unsubscribe(callback);
}
// Events
@UsedByApp
public void onAppVisible() {
// Ignore for electron runtime
if (isElectron()) {
return;
}
messenger.getJsIdleModule().onVisible();
}
@UsedByApp
public void onAppHidden() {
// Ignore for electron runtime
if (isElectron()) {
return;
}
messenger.getJsIdleModule().onHidden();
}
@UsedByApp
public void onConversationOpen(JsPeer peer) {
Log.d(TAG, "onConversationOpen | " + peer);
lastVisiblePeer = peer.convert();
messenger.onConversationOpen(lastVisiblePeer);
onUserVisible(peer);
}
@UsedByApp
public void onConversationClosed(JsPeer peer) {
Log.d(TAG, "onConversationClosed | " + peer);
if (lastVisiblePeer != null && lastVisiblePeer.equals(peer.convert())) {
lastVisiblePeer = null;
Log.d(TAG, "onConversationClosed | Closing");
}
messenger.onConversationClosed(peer.convert());
}
@UsedByApp
public void onUserVisible(JsPeer peer) {
if (peer.convert().getPeerType() == PeerType.PRIVATE) {
messenger.onUserVisible(peer.getPeerId());
}
}
@UsedByApp
public void onDialogsOpen() {
messenger.onDialogsOpen();
}
@UsedByApp
public void onDialogsClosed() {
messenger.onDialogsClosed();
}
@UsedByApp
public void onProfileOpen(int uid) {
messenger.onProfileOpen(uid);
}
@UsedByApp
public void onProfileClosed(int uid) {
messenger.onProfileClosed(uid);
}
@UsedByApp
public void onDialogsEnd() {
messenger.loadMoreDialogs();
}
@UsedByApp
public JsPromise loadArchivedDialogs() {
return loadArchivedDialogs(true);
}
@UsedByApp
public JsPromise loadMoreArchivedDialogs() {
return loadArchivedDialogs(false);
}
@UsedByApp
private JsPromise loadArchivedDialogs(final boolean init) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.loadArchivedDialogs(init, new RpcCallback<ResponseLoadArchived>() {
@Override
public void onResult(ResponseLoadArchived response) {
JsArray<JsDialogShort> res = JsArray.createArray().cast();
for (ApiDialog d : response.getDialogs()) {
res.push(JsDialogShort.create(messenger.buildPeerInfo(EntityConverter.convert(d.getPeer())), d.getUnreadCount()));
}
Log.d(TAG, "loadArchivedDialogs:result");
resolve(res);
}
@Override
public void onError(RpcException e) {
Log.d(TAG, "loadArchivedDialogs:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise loadBlockedUsers() {
return JsPromise.from(messenger.loadBlockedUsers()
.map(users -> {
JsArray<JsUser> res = JsArray.createArray().cast();
for (User u : users) {
res.push(getUser(u.getUid()));
}
return res;
})
);
}
@UsedByApp
public void onChatEnd(JsPeer peer) {
messenger.loadMoreHistory(peer.convert());
}
// Profile
@UsedByApp
public JsPromise editMyName(final String newName) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.editMyName(newName).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "editMyName:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "editMyName:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise editMyNick(final String newNick) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.editMyNick(newNick).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "editMyNick:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "editMyNick:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise editMyAbout(final String newAbout) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.editMyAbout(newAbout).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "editMyAbout:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "editMyAbout:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise findAllText(final JsPeer peer, final String query) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findTextMessages(peer.convert(), query).start(new CommandCallback<List<MessageSearchEntity>>() {
@Override
public void onResult(List<MessageSearchEntity> res) {
resolve(convertSearchRes(res));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findAllText:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise findAllPhotos(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findAllPhotos(peer.convert()).start(new CommandCallback<List<MessageSearchEntity>>() {
@Override
public void onResult(List<MessageSearchEntity> res) {
resolve(convertSearchRes(res));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findAllText:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise findAllDocs(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findAllDocs(peer.convert()).start(new CommandCallback<List<MessageSearchEntity>>() {
@Override
public void onResult(List<MessageSearchEntity> res) {
resolve(convertSearchRes(res));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findAllText:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise findAllLinks(final JsPeer peer) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findAllLinks(peer.convert()).start(new CommandCallback<List<MessageSearchEntity>>() {
@Override
public void onResult(List<MessageSearchEntity> res) {
resolve(convertSearchRes(res));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findAllText:error");
reject(e.getMessage());
}
});
}
});
}
private JsArray<JsMessageSearchEntity> convertSearchRes(List<MessageSearchEntity> res) {
JsArray<JsMessageSearchEntity> jsRes = JsArray.createArray().cast();
for (MessageSearchEntity e : res) {
jsRes.push(JsMessageSearchEntity.create(e.getRid() + "",
messenger.buildPeerInfo(Peer.user(e.getSenderId())),
messenger.getFormatter().formatDate(e.getDate()),
JsContent.createContent(e.getContent(),
e.getSenderId())));
}
return jsRes;
}
@UsedByApp
public JsPromise findGroups() {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findPeers(PeerSearchType.GROUPS).start(new CommandCallback<List<PeerSearchEntity>>() {
@Override
public void onResult(List<PeerSearchEntity> res) {
Log.d(TAG, "findGroups:result");
JsArray<JsPeerSearchResult> jsRes = JsArray.createArray().cast();
for (PeerSearchEntity s : res) {
if (s.getPeer().getPeerType() == PeerType.GROUP) {
jsRes.push(JsPeerSearchResult.create(messenger.buildPeerInfo(s.getPeer()),
s.getDescription(), s.getMembersCount(), (int) (s.getDate() / 1000L),
messenger.buildPeerInfo(Peer.user(s.getCreatorUid())), s.isPublic(),
s.isJoined()));
} else if (s.getPeer().getPeerType() == PeerType.PRIVATE) {
jsRes.push(JsPeerSearchResult.create(messenger.buildPeerInfo(s.getPeer())));
}
// jsRes.push();
}
resolve(jsRes);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findGroups:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public void changeMyAvatar(final JsFile file) {
String descriptor = provider.registerUploadFile(file);
messenger.changeMyAvatar(descriptor);
}
@UsedByApp
public void removeMyAvatar() {
messenger.removeMyAvatar();
}
@UsedByApp
public JsPromise editName(final int uid, final String newName) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.editName(uid, newName).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "editName:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "editName:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise joinGroupViaLink(final String url) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.joinGroupViaToken(url).start(new CommandCallback<Integer>() {
@Override
public void onResult(Integer res) {
Log.d(TAG, "joinGroupViaLink:result");
resolve(JsPeer.create(Peer.group(res)));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "joinGroupViaLink:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise editGroupTitle(final int gid, final String newTitle) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.editGroupTitle(gid, newTitle).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "editGroupTitle:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "editGroupTitle:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise editGroupAbout(final int gid, final String newAbout) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.editGroupAbout(gid, newAbout).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
Log.e(TAG, e);
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public void changeGroupAvatar(final int gid, final JsFile file) {
String descriptor = provider.registerUploadFile(file);
messenger.changeGroupAvatar(gid, descriptor);
}
@UsedByApp
public void removeGroupAvatar(final int gid) {
messenger.removeGroupAvatar(gid);
}
@UsedByApp
public JsPromise createGroup(final String title, final JsFile file, final int[] uids) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
String avatarDescriptor = file != null ? provider.registerUploadFile(file) : null;
//noinspection ConstantConditions
messenger.createGroup(title, avatarDescriptor, uids).start(new CommandCallback<Integer>() {
@Override
public void onResult(Integer res) {
Log.d(TAG, "createGroup:result");
resolve(JsPeer.create(Peer.group(res)));
}
@Override
public void onError(Exception e) {
Log.d(TAG, "createGroup:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise inviteMember(final int gid, final int uid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.inviteMember(gid, uid).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "inviteMember:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "inviteMember:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise kickMember(final int gid, final int uid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.kickMember(gid, uid).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "kickMember:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "kickMember:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise leaveGroup(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.leaveGroup(gid).start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
Log.d(TAG, "leaveGroup:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "leaveGroup:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise getIntegrationToken(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.requestIntegrationToken(gid).start(new CommandCallback<String>() {
@Override
public void onResult(String res) {
Log.d(TAG, "getIntegrationToken:result");
resolve(res);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "getIntegrationToken:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise revokeIntegrationToken(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.revokeIntegrationToken(gid).start(new CommandCallback<String>() {
@Override
public void onResult(String res) {
Log.d(TAG, "revokeIntegrationToken:result");
resolve(res);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "revokeIntegrationToken:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise getInviteLink(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.requestInviteLink(gid).start(new CommandCallback<String>() {
@Override
public void onResult(String res) {
Log.d(TAG, "getInviteLink:result");
resolve(res);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "getInviteLink:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise revokeInviteLink(final int gid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.revokeInviteLink(gid).start(new CommandCallback<String>() {
@Override
public void onResult(String res) {
Log.d(TAG, "revokeInviteLink:result");
resolve(res);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "revokeInviteLink:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise addContact(final int uid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.addContact(uid).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "addContact:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "addContact:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise addLike(final JsPeer peer, final String rid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.addReaction(peer.convert(), Long.parseLong(rid), "\u2764")
.start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise removeLike(final JsPeer peer, final String rid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.removeReaction(peer.convert(), Long.parseLong(rid), "\u2764")
.start(new CommandCallback<Void>() {
@Override
public void onResult(Void res) {
resolve();
}
@Override
public void onError(Exception e) {
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise findUsers(final String query) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
messenger.findUsers(query).start(new CommandCallback<UserVM[]>() {
@Override
public void onResult(UserVM[] users) {
Log.d(TAG, "findUsers:result");
JsArray<JsUser> jsUsers = JsArray.createArray().cast();
for (UserVM user : users) {
jsUsers.push(messenger.getJsUser(user.getId()).get());
}
resolve(jsUsers);
}
@Override
public void onError(Exception e) {
Log.d(TAG, "findUsers:error");
reject(e.getMessage());
}
});
}
});
}
@UsedByApp
public JsPromise removeContact(final int uid) {
return JsPromise.create(new JsPromiseExecutor() {
@Override
public void execute() {
//noinspection ConstantConditions
messenger.removeContact(uid).start(new CommandCallback<Boolean>() {
@Override
public void onResult(Boolean res) {
Log.d(TAG, "removeContact:result");
resolve();
}
@Override
public void onError(Exception e) {
Log.d(TAG, "removeContact:error");
reject(e.getMessage());
}
});
}
});
}
// Settings
@UsedByApp
public void changeNotificationsEnabled(JsPeer peer, boolean isEnabled) {
messenger.changeNotificationsEnabled(peer.convert(), isEnabled);
}
@UsedByApp
public boolean isNotificationsEnabled(JsPeer peer) {
return messenger.isNotificationsEnabled(peer.convert());
}
@UsedByApp
public void changeAnimationAutoPlayEnabled(boolean isEnabled) {
messenger.changeAnimationAutoPlayEnabled(isEnabled);
}
@UsedByApp
public boolean isAnimationAutoPlayEnabled() {
return messenger.isAnimationAutoPlayEnabled();
}
@UsedByApp
public boolean isSendByEnterEnabled() {
return messenger.isSendByEnterEnabled();
}
@UsedByApp
public void changeSendByEnter(boolean sendByEnter) {
messenger.changeSendByEnter(sendByEnter);
}
@UsedByApp
public boolean isGroupsNotificationsEnabled() {
return messenger.isGroupNotificationsEnabled();
}
@UsedByApp
public void changeGroupNotificationsEnabled(boolean enabled) {
messenger.changeGroupNotificationsEnabled(enabled);
}
@UsedByApp
public boolean isOnlyMentionNotifications() {
return messenger.isGroupNotificationsOnlyMentionsEnabled();
}
@UsedByApp
public void changeIsOnlyMentionNotifications(boolean enabled) {
messenger.changeGroupNotificationsOnlyMentionsEnabled(enabled);
}
@UsedByApp
public boolean isSoundEffectsEnabled() {
return messenger.isConversationTonesEnabled();
}
@UsedByApp
public boolean isShowNotificationsTextEnabled() {
return messenger.isShowNotificationsText();
}
@UsedByApp
public void changeIsShowNotificationTextEnabled(boolean value) {
messenger.changeShowNotificationTextEnabled(value);
}
@UsedByApp
public void changeSoundEffectsEnabled(boolean enabled) {
messenger.changeConversationTonesEnabled(enabled);
}
@UsedByApp
public String renderMarkdown(final String markdownText) {
try {
return HtmlMarkdownUtils.processText(markdownText, MarkdownParser.MODE_FULL);
} catch (Exception e) {
Log.e("Markdown", e);
return "[Error while processing text]";
}
}
@UsedByApp
public void handleLinkClick(Event event) {
Element target = Element.as(event.getEventTarget());
String href = target.getAttribute("href");
if (href.startsWith("send:")) {
String msg = href.substring("send:".length());
msg = URL.decode(msg);
if (lastVisiblePeer != null) {
messenger.sendMessage(lastVisiblePeer, msg);
event.preventDefault();
}
} else {
if (JsElectronApp.isElectron()) {
JsElectronApp.openUrlExternal(href);
event.preventDefault();
}
}
}
}
| mit |
Wurmcraft/WurmTweaks | src/main/java/wurmcraft/wurmatron/common/network/server/SendConfigSettings.java | 8194 | package wurmcraft.wurmatron.common.network.server;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import wurmcraft.wurmatron.common.config.Settings;
import wurmcraft.wurmatron.common.network.CustomMessage;
import java.io.IOException;
public class SendConfigSettings extends CustomMessage.ClientMessage<SendConfigSettings> {
private NBTTagCompound data;
public SendConfigSettings () {
}
public SendConfigSettings (EntityPlayer player) {
data.setBoolean("debug", Settings.debug);
data.setBoolean("Avaritia", Settings.Avaritia);
data.setBoolean("AdvancedSolarPanels", Settings.AdvancedSolarPanels);
data.setBoolean("AM2", Settings.AM2);
data.setBoolean("AE2", Settings.AE2);
data.setBoolean("EnderIO", Settings.EnderIO);
data.setBoolean("BigReactors", Settings.BigReactors);
data.setBoolean("BloodMagic", Settings.BloodMagic);
data.setBoolean("Botania", Settings.Botania);
data.setBoolean("BuildCraft", Settings.BuildCraft);
data.setBoolean("CarpentersBlocks", Settings.CarpentersBlocks);
data.setBoolean("Chisel", Settings.Chisel);
data.setBoolean("ComputerCraft", Settings.ComputerCraft);
data.setBoolean("CraftHeraldry", Settings.CraftHeraldry);
data.setBoolean("DraconicEvolution", Settings.DraconicEvolution);
data.setBoolean("IronChest", Settings.IronChest);
data.setBoolean("EnderStorage", Settings.EnderStorage);
data.setBoolean("ExtraCells", Settings.ExtraCells);
data.setBoolean("ExtraUtilities", Settings.ExtraUtilities);
data.setBoolean("GalaticCraft", Settings.GalaticCraft);
data.setBoolean("GraviSuite", Settings.GraviSuite);
data.setBoolean("ImmersiveEngineering", Settings.ImmersiveEngineering);
data.setBoolean("IC2", Settings.IC2);
data.setBoolean("JABBA", Settings.JABBA);
data.setBoolean("MalisisDoors", Settings.MalisisDoors);
data.setBoolean("Mekanism", Settings.Mekanism);
data.setBoolean("MineFactoryReloaded", Settings.MineFactoryReloaded);
data.setBoolean("OpenBlocks", Settings.OpenBlocks);
data.setBoolean("OpenComputers", Settings.OpenComputers);
data.setBoolean("OpenModularTurrets", Settings.OpenModularTurrets);
data.setBoolean("PowerConverters", Settings.PowerConverters);
data.setBoolean("QuarryPlus", Settings.QuarryPlus);
data.setBoolean("Railcraft", Settings.Railcraft);
data.setBoolean("tinker_io", Settings.TinkerIO);
data.setBoolean("ShinColle", Settings.ShinColle);
data.setBoolean("weightingscales", Settings.TFCScales);
data.setBoolean("tfccellars", Settings.TFCCellars);
data.setBoolean("simplyjetpacks", Settings.SimplyJetpacks);
data.setBoolean("WR-CBE|Core", Settings.WirelessRedstone);
data.setBoolean("tfcm", Settings.TFCMisc);
data.setBoolean("SolarExpansion", Settings.SolarExpansion);
data.setBoolean("TConstruct", Settings.TConstruct);
data.setBoolean("TechReborn", Settings.TechReborn);
data.setBoolean("Thaumcraft", Settings.Thaumcraft);
data.setBoolean("ThermalDynamics", Settings.ThermalDynamics);
data.setBoolean("ThermalExpansion", Settings.ThermalExpansion);
data.setBoolean("BiblioWoodsTFC", Settings.BiblioWoodsTFC);
data.setBoolean("Ztones", Settings.Ztones);
data.setBoolean("SoulShards", Settings.SoulShards);
data.setBoolean("IC2NuclearControl", Settings.IC2NuclearControl);
data.setBoolean("Thaumcraft", Settings.Thaumcraft);
data.setBoolean("irontank", Settings.IronTank);
data.setBoolean("CompactMachines", Settings.CompactMachines);
data.setBoolean("LogisticsPipes", Settings.LogisticsPipes);
data.setBoolean("ProjRed", Settings.ProjRed);
data.setBoolean("powersuits", Settings.powersuits);
data.setBoolean("RouterReborn", Settings.RouterReborn);
data.setBoolean("InterdictionPillar", Settings.InterdictionPillar);
data.setBoolean("qCraft", Settings.qCraft);
data.setBoolean("academy-craft", Settings.AcademyCraft);
data.setBoolean("ElectroMagic", Settings.ElectroMagic);
data.setBoolean("ThaumicTinkerer", Settings.ThaumicTinkerer);
}
@Override
protected void read (PacketBuffer buff) throws IOException {
data = buff.readNBTTagCompoundFromBuffer();
}
@Override
protected void write (PacketBuffer buff) throws IOException {
buff.writeNBTTagCompoundToBuffer(data);
}
@Override
public void process (EntityPlayer player, Side side) {
Settings.debug = data.getBoolean("data");
Settings.Avaritia = data.getBoolean("Avaritia");
Settings.AdvancedSolarPanels = data.getBoolean("AdvancedSolarPanels");
Settings.AM2 = data.getBoolean("AM2");
Settings.AE2 = data.getBoolean("AE2");
Settings.EnderIO = data.getBoolean("EnderIO");
Settings.BigReactors = data.getBoolean("BigReactors");
Settings.BloodMagic = data.getBoolean("BloodMagic");
Settings.Botania = data.getBoolean("Botania");
Settings.BuildCraft = data.getBoolean("BuildCraft");
Settings.CarpentersBlocks = data.getBoolean("CarpentersBlocks");
Settings.Chisel = data.getBoolean("Chisel");
Settings.ComputerCraft = data.getBoolean("ComputerCraft");
Settings.CraftHeraldry = data.getBoolean("CraftHeraldry");
Settings.DraconicEvolution = data.getBoolean("DraconicEvolution");
Settings.IronChest = data.getBoolean("IronChest");
Settings.EnderStorage = data.getBoolean("EnderStorage");
Settings.ExtraCells = data.getBoolean("ExtraCells");
Settings.ExtraUtilities = data.getBoolean("ExtraUtilities");
Settings.GalaticCraft = data.getBoolean("GalaticCraft");
Settings.GraviSuite = data.getBoolean("GraviSuite");
Settings.ImmersiveEngineering = data.getBoolean("ImmersiveEngineering");
Settings.IC2 = data.getBoolean("IC2");
Settings.JABBA = data.getBoolean("JABBA");
Settings.MalisisDoors = data.getBoolean("MalisisDoors");
Settings.Mekanism = data.getBoolean("Mekanism");
Settings.MineFactoryReloaded = data.getBoolean("MineFactoryReloaded");
Settings.OpenBlocks = data.getBoolean("OpenBlocks");
Settings.OpenComputers = data.getBoolean("OpenComputers");
Settings.OpenModularTurrets = data.getBoolean("OpenModularTurrets");
Settings.PowerConverters = data.getBoolean("PowerConverters");
Settings.QuarryPlus = data.getBoolean("QuarryPlus");
Settings.Railcraft = data.getBoolean("Railcraft");
Settings.TinkerIO = data.getBoolean("tinker_io");
Settings.ShinColle = data.getBoolean("ShinColle");
Settings.TFCScales = data.getBoolean("weightingscales");
Settings.TFCCellars = data.getBoolean("tfccellars");
Settings.SimplyJetpacks = data.getBoolean("simplyjetpacks");
Settings.WirelessRedstone = data.getBoolean("WR-CBE|Core");
Settings.TFCMisc = data.getBoolean("tfcm");
Settings.SolarExpansion = data.getBoolean("SolarExpansion");
Settings.TConstruct = data.getBoolean("TConstruct");
Settings.TechReborn = data.getBoolean("TechReborn");
Settings.Thaumcraft = data.getBoolean("Thaumcraft");
Settings.ThermalDynamics = data.getBoolean("ThermalDynamics");
Settings.ThermalExpansion = data.getBoolean("ThermalExpansion");
Settings.BiblioWoodsTFC = data.getBoolean("BiblioWoodsTFC");
Settings.Ztones = data.getBoolean("Ztones");
Settings.SoulShards = data.getBoolean("SoulShards");
Settings.IC2NuclearControl = data.getBoolean("IC2NuclearControl");
Settings.Thaumcraft = data.getBoolean("Thaumcraft");
Settings.IronTank = data.getBoolean("irontank");
Settings.CompactMachines = data.getBoolean("CompactMachines");
Settings.LogisticsPipes = data.getBoolean("LogisticsPipes");
Settings.ProjRed = data.getBoolean("ProjRed");
Settings.powersuits = data.getBoolean("powersuits");
Settings.RouterReborn = data.getBoolean("RouterReborn");
Settings.InterdictionPillar = data.getBoolean("InterdictionPillar");
Settings.qCraft = data.getBoolean("qCraft");
Settings.AcademyCraft = data.getBoolean("AcademyCraft");
Settings.ElectroMagic = data.getBoolean("ElectroMagic");
Settings.ThaumicTinkerer = data.getBoolean("ThaumicTinkerer");
}
}
| mit |
TardisX1/Rebellion | src/run.java | 1235 | import java.awt.*;
import java.io.Serializable;
import javax.swing.JFrame;
public class run implements Serializable{
static String title = "Rebellion";
static Beginning begin = new Beginning(title);
static Map map = new Map(title);
static Data data = new Data(title);
static Base base = new Base(title);
static Bag bag = new Bag(title);
static Shop shop = new Shop(title);
static JFrame[] frames = { begin,map,data,bag,shop,base};
public static void main(String args[]) throws InterruptedException {
for (int index = 0; index < frames.length; index++) {
frames[index].setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frames[index].setPreferredSize(new Dimension(1000,900));
screencentre(frames[index]);
frames[index].pack();
}
frames[0].setVisible(true);
}
//使框架显示在屏幕中央
public static void screencentre(JFrame frame) {
Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
int screenWidth = screenSize.width; // 获取屏幕的宽
int screenHeight = screenSize.height; // 获取屏幕的高
frame.setLocation(screenWidth/4, screenHeight/15);// 设置窗口居中显示
}
} | mit |