repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Zeral-Zhang/bookPromotion | src/main/java/com/zeral/service/IProductInfoService.java | 1575 | package com.zeral.service;
import java.util.List;
import com.zeral.bean.PageBean;
import com.zeral.po.ProductInfo;
public interface IProductInfoService extends IBaseService<ProductInfo> {
public int findMaxPage(int rows);
public ProductInfo findDetail(String productId);
public void update(ProductInfo productInfo);
/**
* 通过商品发布用户查找商品分页信息
*/
public List<ProductInfo> findByUserId(PageBean pageBean, String userId);
/**
* 通过商品名称模糊查询
* @param pageBean
* @param name
* @return
*/
List<ProductInfo> findByNameLike(PageBean pageBean, String name);
/**
* 根据商品类型和名称模糊查询
* @param pageBean
* @param name
* @return
*/
List<ProductInfo> findByTypeAndNameLike(PageBean pageBean, String productTypeId, String name);
/**
* 根据商品类型查询商品列表信息
* @param pageBean
* @param productTypeId
* @return
*/
List<ProductInfo> findByType(PageBean pageBean, String productTypeId);
/**
* 根据商品发布用户的学院查找商品列表信息
* @param pageBean
* @param schoolInfoId
* @return
*/
public List<ProductInfo> findByUserSchoolInfoId(PageBean pageBean, String schoolInfoId);
/**
* 通过id查找商品修改其状态
* @param productId
*/
public void updateProductState(String productId, Integer state);
/**
* 分页查询所有上架商品
* @param pageBean
* @return
*/
public List<ProductInfo> findAllSalling(PageBean pageBean);
}
| gpl-3.0 |
TobiasSchwirten/tuiodroid | TUIOdroid/gen/tuioDroid/impl/BuildConfig.java | 156 | /** Automatically generated file. DO NOT MODIFY */
package tuioDroid.impl;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | gpl-3.0 |
hgs1217/Paper-Melody | app/src/main/java/com/papermelody/fragment/CommentFragment.java | 12442 | package com.papermelody.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.papermelody.R;
import com.papermelody.model.Comment;
import com.papermelody.model.OnlineMusic;
import com.papermelody.model.response.CommentInfo;
import com.papermelody.model.response.CommentResponse;
import com.papermelody.util.App;
import com.papermelody.util.NetworkFailureHandler;
import com.papermelody.util.RetrofitClient;
import com.papermelody.util.SocialSystemAPI;
import com.papermelody.widget.CommentRecyclerViewAdapter;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import static com.papermelody.model.OnlineMusic.SERIAL_ONLINEMUSIC;
/**
* Created by HgS_1217_ on 2017/4/10.
*/
public class CommentFragment extends BaseFragment {
/**
* 用例:用户评论
* 用户评论页面,作为Fragment放置于OnlineListenActivity中
*/
@BindView(R.id.current_comment_list)
RecyclerView commentList;
@BindView(R.id.user_newest_comment_not_exist)
TextView userNoComment;
@BindView(R.id.my_comment_name)
TextView myCommentName;
@BindView(R.id.my_comment_context)
TextView myCommentContext;
@BindView(R.id.my_comment_time)
TextView myCommentTime;
@BindView(R.id.my_comment_icon)
ImageView my_icon;
@BindView(R.id.my_comment_overall)
LinearLayout my_comment_overall;
@BindView(R.id.all_comment_title)
TextView refocusPos;
@BindView(R.id.cuurently_no_comment)
TextView noComment;
private boolean hasUser;
private String author = "AnnonymousUser";
private SocialSystemAPI api;
private OnlineMusic onlineMusic;
private Context context;
private CommentRecyclerViewAdapter adapter;
private CommentRecyclerViewAdapter.OnItemClickListener commentOnItemClickListener = new
CommentRecyclerViewAdapter.OnItemClickListener() {
@Override
public void OnItemClick() {
//Click activated only on 'Comment Button'
}
};
public static CommentFragment newInstance(OnlineMusic onlineMusic) {
CommentFragment fragment = new CommentFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(OnlineMusic.SERIAL_ONLINEMUSIC, onlineMusic);
fragment.setArguments(bundle);
return fragment;
}
private void checkIfHasUser() {
try {
author = App.getUser().getUsername();
hasUser = true;
} catch (NullPointerException e) {
Log.d("TAG_USER", "NO USER LOGGED");
//ToastUtil.showShort("登录了发表评论可以保存记录哦!");
hasUser = false;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onlineMusic = (OnlineMusic) getArguments().getSerializable(SERIAL_ONLINEMUSIC);
checkIfHasUser();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstance) {
View view = inflater.inflate(R.layout.fragment_comment, container, false);
ButterKnife.bind(this, view);
checkIfHasUser();
my_comment_overall.setVisibility(View.GONE);
userNoComment.setVisibility(View.GONE);
context = getActivity();
api = RetrofitClient.getSocialSystemAPI();
checkIfHasUser();
initGetCommentList();
initView();
return view;
}
public void initGetCommentList() {
if (hasUser)
userNoComment.setText("数据正在拼命加载中...");
else
userNoComment.setText(getString(R.string.not_logged_in));
userNoComment.setVisibility(View.VISIBLE);
String musicID = String.valueOf(onlineMusic.getMusicID());
addSubscription(api.getComment(musicID)
.flatMap(NetworkFailureHandler.httpFailureFilter)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(response -> ((CommentResponse) response).getResult().getComments()) /*list的commentinfo*/
.subscribe(
commentList -> {
List<Comment> comments = new ArrayList<>();
for (CommentInfo info : commentList) {
comments.add(new Comment(getActivity(), info));
}
Collections.sort(comments, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Comment a = (Comment) o1;
Comment b = (Comment) o2;
return b.getCreateTime().compareTo(
a.getCreateTime());
}
});
//System.out.print("sorted!");
SimpleDateFormat sDateFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Log.d("TAG", "before init View: " + comments.get(0).getCreateTime());
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG2", "!!!!!");
initRecyclerView(comments);
refreshMyComment(comments);
},
NetworkFailureHandler.basicErrorHandler
));
}
private String removeLabel(String labels, String label, String ready) {
if (!ready.contains(label) && !ready.contains(labels)) return ready;
String[] x = ready.split(labels);
for (int i = 0; i < x.length; ++i) {
if (x[i] != "" || x[i].length() > 0) {
Log.d("PYJ", x[i]);
return x[i];
}
}
return getString(R.string.errorReadComment);
}
private void refreshMyComment(List<Comment> list) {
if (list.size() > 0)
noComment.setVisibility(View.GONE);
else
noComment.setVisibility(View.VISIBLE);
if (!hasUser) {
userNoComment.setText(R.string.not_logged_in);
my_comment_overall.setVisibility(View.GONE);
userNoComment.setVisibility(View.VISIBLE);
} else {
boolean hasCommented = false;
for (Comment singleComment : list) {
//Log.d("TESTR", singleComment.getAuthorAvatarUrl());
if (singleComment.getAuthor().equals(author)) {
hasCommented = true;
my_comment_overall.setVisibility(View.VISIBLE);
userNoComment.setVisibility(View.GONE);
myCommentContext.setText(removeLabel(getString(R.string.__labelForSplit), getString(R.string.__label), singleComment.getContent()));
myCommentTime.setText(timeLongToString(Long.parseLong(
singleComment.getCreateTime())));
myCommentName.setText(singleComment.getAuthor());
try {
Log.d("PYJ", "my_icon:" + singleComment.getAuthorAvatarUrl());
if (singleComment.getAuthorAvatarUrl().length() < 3)
my_icon.setBackground(getResources().getDrawable(R.drawable.ic_account_circle_black_24dp));
else
Picasso.with(context).load(singleComment.getAuthorAvatarUrl()).into(my_icon);
} catch (Exception e) {
}
break;
}
}
if (!hasCommented) {
userNoComment.setText(R.string.user_comment_not_exist);
my_comment_overall.setVisibility(View.GONE);
userNoComment.setVisibility(View.VISIBLE);
}
}
}
private void initRecyclerView(List<Comment> comments) {
adapter = new CommentRecyclerViewAdapter(context, comments);
adapter.setOnItemClickListener(commentOnItemClickListener);
commentList.setAdapter(adapter);
commentList.setLayoutManager(new LinearLayoutManager(context));
commentList.setItemAnimator(new DefaultItemAnimator());
}
private String timeLongToString(Long m) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date(m));
return time;
}
private void initView() {
/*refreshbtn.setOnClickListener((View vx)->
{
//commentList.setAdapter(new ArrayAdapter<String>(HistoryActivity.this,
// android.R.layout.simple_list_item_1, getData()));
}
);
*/
/*
button.setOnClickListener((View v) -> {
String comment = editText.getText().toString();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String createtime = sDateFormat.format(new java.util.Date());
Log.d("TAG", createtime);
String author = "AnonymousUser"; //FIXME: 这里先方便上传,不然每次要登录
String musicID = String.valueOf(onlineMusic.getMusicID());
boolean hasUser = true;
try {
author = App.getUser().getUsername();
} catch (NullPointerException e) {
ToastUtil.showShort("登录了发表评论可以保存记录哦!");
hasUser = false;
}
addSubscription(api.uploadComment(musicID, author, comment, createtime)
.flatMap(NetworkFailureHandler.httpFailureFilter)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(response -> (HttpResponse) response)
.subscribe(
upload_com_res -> {
ToastUtil.showShort(R.string.upload_comment_success);
},
NetworkFailureHandler.basicErrorHandler
));
try {
Thread.sleep(10);
editText.setText("");
editText.setHint(R.string.add_new_comment_here);
initGetCommentList();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (hasUser) {
userNoComment.setVisibility(View.GONE);
myCommentContext.setText("");
}
hideInput(context, this.getView());
refocusPos.requestFocus();
Log.d("TAG-ref", "OKKKKKK");
}
);*/
}
private void hideInput(Context context, View view) {
InputMethodManager inputMethodManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
| gpl-3.0 |
Rabiator1/SWG-Station-Chat | src/main/java/chat/protocol/request/RGetAnyAvatar.java | 849 | package chat.protocol.request;
import java.nio.ByteBuffer;
import chat.protocol.GenericRequest;
import chat.util.ChatUnicodeString;
public class RGetAnyAvatar extends GenericRequest {
private ChatUnicodeString name = new ChatUnicodeString();
private ChatUnicodeString address = new ChatUnicodeString();
public ChatUnicodeString getName() {
return name;
}
public void setName(ChatUnicodeString name) {
this.name = name;
}
public ChatUnicodeString getAddress() {
return address;
}
public void setAddress(ChatUnicodeString address) {
this.address = address;
}
@Override
public ByteBuffer serialize() {
// TODO Auto-generated method stub
return null;
}
@Override
public void deserialize(ByteBuffer buf) {
type = buf.getShort();
track = buf.getInt();
name.deserialize(buf);
address.deserialize(buf);
}
}
| gpl-3.0 |
tghoward/geopaparazzi | plugins/geopaparazzi_default_import_plugins/src/main/java/eu/geopaparazzi/plugins/defaultexports/ImportWmsMenuEntry.java | 7275 | /*
* Geopaparazzi - Digital field mapping on Android based devices
* Copyright (C) 2016 HydroloGIS (www.hydrologis.com)
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.geopaparazzi.plugins.defaultexports;
import android.content.Context;
import java.io.File;
import java.util.List;
import java.util.Set;
import eu.geopaparazzi.library.core.ResourcesManager;
import eu.geopaparazzi.library.network.NetworkUtilities;
import eu.geopaparazzi.library.plugin.types.MenuEntry;
import eu.geopaparazzi.library.util.FileUtilities;
import eu.geopaparazzi.library.util.GPDialogs;
import eu.geopaparazzi.library.util.IActivitySupporter;
import eu.geopaparazzi.mapsforge.BaseMapSourcesManager;
import gov.nasa.worldwind.AddWMSDialog;
import gov.nasa.worldwind.ogc.OGCBoundingBox;
import gov.nasa.worldwind.ogc.wms.WMSCapabilityInformation;
import gov.nasa.worldwind.ogc.wms.WMSLayerCapabilities;
/**
* @author Andrea Antonello (www.hydrologis.com)
*/
public class ImportWmsMenuEntry extends MenuEntry implements AddWMSDialog.OnWMSLayersAddedListener {
private final Context serviceContext;
private IActivitySupporter clickActivityStarter;
public ImportWmsMenuEntry(Context context) {
this.serviceContext = context;
}
@Override
public String getLabel() {
return "WMS";//serviceContext.getString(eu.geopaparazzi.core.R.string.gpx);
}
@Override
public void onClick(IActivitySupporter clickActivityStarter) {
this.clickActivityStarter = clickActivityStarter;
Context context = clickActivityStarter.getContext();
if (!NetworkUtilities.isNetworkAvailable(context)) {
GPDialogs.infoDialog(context, context.getString(eu.geopaparazzi.core.R.string.available_only_with_network), null);
return;
}
AddWMSDialog addWMSDialog = AddWMSDialog.newInstance(null);
addWMSDialog.setOnAddWMSLayersListener(this);
addWMSDialog.show(clickActivityStarter.getSupportFragmentManager(), "wms import");
}
@Override
public void onWMSLayersAdded(String baseurl, String forcedWmsVersion, List<AddWMSDialog.LayerInfo> layersToAdd) {
for (AddWMSDialog.LayerInfo li : layersToAdd) {
String layerName = li.getName();
StringBuilder sb = new StringBuilder();
String wmsversion = "1.1.1";
if (forcedWmsVersion != null) {
wmsversion = forcedWmsVersion;
} else if (li.caps.getVersion() != null) {
wmsversion = li.caps.getVersion();
}
WMSCapabilityInformation capabilityInformation = li.caps.getCapabilityInformation();
// for (String imageFormat : capabilityInformation.getImageFormats()) {
// if (imageFormat.toLowerCase().endsWith("png") || imageFormat.toLowerCase().endsWith("jpeg"))
// sb.append("format=").append(imageFormat).append("\n");
// break;
// }
List<WMSLayerCapabilities> layerCapabilities = capabilityInformation.getLayerCapabilities();
for (WMSLayerCapabilities layerCapability : layerCapabilities) {
String srs = null;
Set<String> crsList = layerCapability.getCRS();
if (crsList.size() == 0) {
crsList = layerCapability.getSRS();
}
for (String crs : crsList) {
if (crs.equals("CRS:84") || crs.equals("EPSG:4326")) {
srs = crs;
boolean doLonLat = false;
if (crs.equals("CRS:84")) {
doLonLat = true;
} else if (crs.equals("EPSG:4326") && !wmsversion.equals("1.3.0")) {
doLonLat = true;
}
String bboxStr;
if (doLonLat) {
bboxStr = "XXX,YYY,XXX,YYY";
} else {
bboxStr = "YYY,XXX,YYY,XXX";
}
String srsLabel = "SRS";
if (wmsversion.equals("1.3.0")) {
srsLabel = "CRS";
}
sb.append("url=" + baseurl.trim() + "?REQUEST=GetMap&SERVICE=WMS&VERSION=" + wmsversion //
+ "&LAYERS=" + layerName + "&STYLES=&FORMAT=image/png&BGCOLOR=0xFFFFFF&TRANSPARENT=TRUE&" + srsLabel + "=" //
+ srs + "&BBOX=" + bboxStr + "&WIDTH=256&HEIGHT=256\n");
sb.append("minzoom=1\n");
sb.append("maxzoom=22\n");
sb.append("defaultzoom=17\n");
sb.append("format=png\n");
sb.append("type=wms\n");
sb.append("description=").append(layerName).append("\n");
break;
}
}
if (srs == null) {
// TODO
return;
}
for (OGCBoundingBox bbox : layerCapability.getBoundingBoxes()) {
String crs = bbox.getCRS();
if (crs.equals("CRS:84") || crs.equals("EPSG:4326")) {
double centerX = bbox.getMinx() + (bbox.getMaxx() - bbox.getMinx()) / 2.0;
double centerY = bbox.getMiny() + (bbox.getMaxy() - bbox.getMiny()) / 2.0;
sb.append("center=");
sb.append(centerX).append(" ").append(centerY);
sb.append("\n");
}
}
}
try {
Context context = clickActivityStarter.getContext();
File applicationSupporterDir = ResourcesManager.getInstance(context).getApplicationSupporterDir();
File newMapurl = new File(applicationSupporterDir, layerName + ".mapurl");
sb.append("mbtiles=defaulttiles/_" + newMapurl.getName() + ".mbtiles\n");
String mapurlText = sb.toString();
FileUtilities.writefile(mapurlText, newMapurl);
BaseMapSourcesManager.INSTANCE.addBaseMapsFromFile(newMapurl);
GPDialogs.infoDialog(context, context.getString(eu.geopaparazzi.core.R.string.wms_mapurl_added) + newMapurl.getName(), null);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
| gpl-3.0 |
l2jserver2/l2jserver2 | l2jserver2-common/src/main/java/com/l2jserver/util/transformer/Transformer.java | 1930 | /*
* This file is part of l2jserver2 <l2jserver2.com>.
*
* l2jserver2 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 3 of the License, or
* (at your option) any later version.
*
* l2jserver2 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 l2jserver2. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.util.transformer;
/**
* An transformer can transform an {@link Object} into an {@link String} and the
* {@link String} back to an equivalent object.
*
* @param <T>
* the transformed type
*
* @author <a href="http://www.rogiel.com">Rogiel</a>
*/
public interface Transformer<T> {
/**
* Transform the object in a string
*
* @param type
* the type this transformer transforms. Useful when it can
* transform several types at once (such as an enum)
* @param value
* the object
* @return the string of the object
* @throws TransformException
* if any error occur while transforming
*/
String transform(Class<? extends T> type, T value)
throws TransformException;
/**
* Untransforms the string back to an object
*
* @param value
* the string
* @param type
* the type this transformer transforms. Useful when it can
* transform several types at once (such as an enum)
* @return the object
* @throws TransformException
* if any error occur while transforming
*/
T untransform(Class<? extends T> type, String value)
throws TransformException;
}
| gpl-3.0 |
awells111/RedditSP | src/main/java/com/wellsandwhistles/android/redditsp/views/liststatus/LoadingView.java | 2588 | package com.wellsandwhistles.android.redditsp.views.liststatus;
/** This file was either copied or modified from https://github.com/QuantumBadger/RedReader
* under the Free Software Foundation General Public License version 3*/
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wellsandwhistles.android.redditsp.R;
public final class LoadingView extends StatusListItemView {
private final TextView textView;
private static final int LOADING_INDETERMINATE = -1, LOADING_DONE = -2;
private final Handler loadingHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(final Message msg) {
if(textView != null) {
textView.setText(((String) msg.obj).toUpperCase());
}
if(msg.what == LOADING_INDETERMINATE) {
// TODO
} else if(msg.what == LOADING_DONE) {
// TODO
hideNoAnim();
} else {
// TODO progress is msg.what
}
}
};
public void setIndeterminate(final int textRes) {
sendMessage(getContext().getString(textRes), LOADING_INDETERMINATE);
}
public void setProgress(final int textRes, final float fraction) {
sendMessage(getContext().getString(textRes), Math.round(fraction * 100));
}
public void setDone(final int textRes) {
sendMessage(getContext().getString(textRes), LOADING_DONE);
}
private void sendMessage(final String text, final int what) {
final Message msg = Message.obtain();
msg.obj = text;
msg.what = what;
loadingHandler.sendMessage(msg);
}
public LoadingView(final Context context) {
this(context, R.string.download_waiting, true, true);
}
public LoadingView(final Context context, final int initialTextRes, final boolean progressBarEnabled, final boolean indeterminate) {
this(context, context.getString(initialTextRes), progressBarEnabled, indeterminate);
}
public LoadingView(final Context context, final String initialText, final boolean progressBarEnabled, final boolean indeterminate) {
super(context);
final LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
textView = new TextView(context);
textView.setText(initialText.toUpperCase());
textView.setTextSize(13.0f);
textView.setPadding((int)(15 * dpScale), (int)(10 * dpScale), (int)(10 * dpScale), (int)(10 * dpScale));
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
layout.addView(textView);
setContents(layout);
}
}
| gpl-3.0 |
uwol/ComputationalEconomy | src/main/java/io/github/uwol/compecon/economy/property/impl/GoodTypeOwnershipImpl.java | 2866 | /*
Copyright (C) 2013 u.wol@wwu.de
This file is part of ComputationalEconomy.
ComputationalEconomy 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 3 of the License, or
(at your option) any later version.
ComputationalEconomy 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 ComputationalEconomy. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.uwol.compecon.economy.property.impl;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyEnumerated;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import io.github.uwol.compecon.economy.agent.impl.AgentImpl;
import io.github.uwol.compecon.economy.materia.GoodType;
import io.github.uwol.compecon.economy.property.GoodTypeOwnership;
import io.github.uwol.compecon.economy.property.PropertyOwner;
@Entity
@Table(name = "GoodTypeOwnership")
public class GoodTypeOwnershipImpl implements GoodTypeOwnership {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
protected int id;
@ElementCollection
@CollectionTable(name = "GoodTypeOwnership_OwnedGoodTypes", joinColumns = @JoinColumn(name = "goodtypeownership_id"))
@MapKeyEnumerated(EnumType.STRING)
private Map<GoodType, Double> ownedGoodTypes = new HashMap<GoodType, Double>();
@OneToOne(targetEntity = AgentImpl.class)
@JoinColumn(name = "propertyOwner_id", nullable = false)
protected PropertyOwner propertyOwner;
public GoodTypeOwnershipImpl() {
for (final GoodType goodType : GoodType.values()) {
ownedGoodTypes.put(goodType, 0.0);
}
}
@Override
public int getId() {
return id;
}
@Override
public Map<GoodType, Double> getOwnedGoodTypes() {
return ownedGoodTypes;
}
@Override
public PropertyOwner getPropertyOwner() {
return propertyOwner;
}
public void setId(final int id) {
this.id = id;
}
public void setOwnedGoodTypes(final Map<GoodType, Double> ownedGoodTypes) {
this.ownedGoodTypes = ownedGoodTypes;
}
public void setPropertyOwner(final PropertyOwner propertyOwner) {
this.propertyOwner = propertyOwner;
}
@Override
public String toString() {
return "id=[" + id + "], propertyOwner=[" + propertyOwner + "], ownedGoodTypes=[" + ownedGoodTypes + "]";
}
}
| gpl-3.0 |
pxrg/SqlBuilder | SQLBuilder/src/com/builder/condition/LikeCondiction.java | 213 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.builder.condition;
/**
*
* @author prg
*/
public enum LikeCondiction {
ANYWHERE,START, END
}
| gpl-3.0 |
Zarius/Bukkit-OtherBlocks | test/com/gmail/zariust/otherdrops/BukkitMock.java | 60106 | package com.gmail.zariust.otherdrops;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.BlockChangeDelegate;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Difficulty;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.Sound;
import org.bukkit.TreeType;
import org.bukkit.Warning.WarningState;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.help.HelpMap;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.map.MapView;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scoreboard.ScoreboardManager;
import org.bukkit.util.Vector;
import com.avaje.ebean.config.ServerConfig;
import com.gmail.zariust.otherdrops.event.CustomDropTest;
public class BukkitMock {
static {
Bukkit.setServer(getServer());
}
// get a fake server - only real part is that .getLogger gets an actual
// logger object
// also: .getWorld("TestWorld") will return a mock world
public static Server getServer() {
return new Server() {
@Override
public void sendPluginMessage(Plugin arg0, String arg1, byte[] arg2) {
// TODO Auto-generated method stub
}
@Override
public Set<String> getListeningPluginChannels() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean useExactLoginLocation() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadWorld(World arg0, boolean arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadWorld(String arg0, boolean arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void unbanIP(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
@Override
public void setWhitelist(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setSpawnRadius(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setDefaultGameMode(GameMode arg0) {
// TODO Auto-generated method stub
}
@Override
public void savePlayers() {
// TODO Auto-generated method stub
}
@Override
public void resetRecipes() {
// TODO Auto-generated method stub
}
@Override
public void reloadWhitelist() {
// TODO Auto-generated method stub
}
@Override
public void reload() {
// TODO Auto-generated method stub
}
@Override
public Iterator<Recipe> recipeIterator() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Player> matchPlayer(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasWhitelist() {
// TODO Auto-generated method stub
return false;
}
@Override
public List<World> getWorlds() {
// TODO Auto-generated method stub
return null;
}
@Override
public File getWorldContainer() {
// TODO Auto-generated method stub
return null;
}
@Override
public World getWorld(UUID arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public World getWorld(String arg0) {
if (arg0.equalsIgnoreCase("TestWorld"))
return CustomDropTest.testWorld;
else if (arg0.equalsIgnoreCase("SecondWorld"))
return CustomDropTest.secondWorld;
return null;
}
@Override
public Set<OfflinePlayer> getWhitelistedPlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getViewDistance() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getVersion() {
// TODO Auto-generated method stub
return null;
}
@Override
public File getUpdateFolderFile() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getUpdateFolder() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getTicksPerMonsterSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getTicksPerAnimalSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getSpawnRadius() {
// TODO Auto-generated method stub
return 0;
}
@Override
public ServicesManager getServicesManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerId() {
// TODO Auto-generated method stub
return null;
}
@Override
public BukkitScheduler getScheduler() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Recipe> getRecipesFor(ItemStack arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public PluginManager getPluginManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public PluginCommand getPluginCommand(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Player getPlayerExact(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Player getPlayer(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<OfflinePlayer> getOperators() {
// TODO Auto-generated method stub
return null;
}
@Override
public Player[] getOnlinePlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getOnlineMode() {
// TODO Auto-generated method stub
return false;
}
@Override
public OfflinePlayer[] getOfflinePlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public OfflinePlayer getOfflinePlayer(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public Messenger getMessenger() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMaxPlayers() {
// TODO Auto-generated method stub
return 0;
}
@Override
public MapView getMap(short arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Logger getLogger() {
// TODO Auto-generated method stub
return Logger.getLogger("zarTest");
}
@Override
public String getIp() {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<String> getIPBans() {
// TODO Auto-generated method stub
return null;
}
@Override
public HelpMap getHelpMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public GameMode getDefaultGameMode() {
// TODO Auto-generated method stub
return null;
}
@Override
public ConsoleCommandSender getConsoleSender() {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, String[]> getCommandAliases() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getBukkitVersion() {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<OfflinePlayer> getBannedPlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getAllowNether() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowFlight() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowEnd() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean dispatchCommand(CommandSender arg0, String arg1)
throws CommandException {
// TODO Auto-generated method stub
return false;
}
@Override
public World createWorld(WorldCreator arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public MapView createMap(World arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Inventory createInventory(InventoryHolder arg0, int arg1,
String arg2) {
// TODO Auto-generated method stub
return null;
}
@Override
public Inventory createInventory(InventoryHolder arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Inventory createInventory(InventoryHolder arg0,
InventoryType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public void configureDbConfig(ServerConfig arg0) {
// TODO Auto-generated method stub
}
@Override
public void clearRecipes() {
// TODO Auto-generated method stub
}
@Override
public int broadcastMessage(String arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int broadcast(String arg0, String arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void banIP(String arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean addRecipe(Recipe arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getAmbientSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getConnectionThrottle() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getGenerateStructures() {
// TODO Auto-generated method stub
return false;
}
@Override
public ItemFactory getItemFactory() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMonsterSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getMotd() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getShutdownMessage() {
// TODO Auto-generated method stub
return null;
}
@Override
public WarningState getWarningState() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getWaterAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getWorldType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isHardcore() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isPrimaryThread() {
// TODO Auto-generated method stub
return false;
}
@Override
public ScoreboardManager getScoreboardManager() {
// TODO Auto-generated method stub
return null;
}
};
}
public static World getTestWorld_TestWorld() {
// TODO Auto-generated method stub
return new World() {
@Override
public String getName() {
// TODO Auto-generated method stub
return "TestWorld";
}
@Override
public boolean canGenerateStructures() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(Location arg0, float arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(Location arg0, float arg1,
boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3, boolean arg4) {
// TODO Auto-generated method stub
return false;
}
@Override
public Item dropItem(Location arg0, ItemStack arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Item dropItemNaturally(Location arg0, ItemStack arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean generateTree(Location arg0, TreeType arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean generateTree(Location arg0, TreeType arg1,
BlockChangeDelegate arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowAnimals() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowMonsters() {
// TODO Auto-generated method stub
return false;
}
@Override
public Biome getBiome(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getBlockAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getBlockAt(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getBlockTypeIdAt(Location arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getBlockTypeIdAt(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Chunk getChunkAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk getChunkAt(Block arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk getChunkAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Difficulty getDifficulty() {
// TODO Auto-generated method stub
return null;
}
@Override
public ChunkSnapshot getEmptyChunkSnapshot(int arg0, int arg1,
boolean arg2, boolean arg3) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Entity> getEntities() {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(
Class<T>... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(
Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<Entity> getEntitiesByClasses(Class<?>... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Environment getEnvironment() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getFullTime() {
// TODO Auto-generated method stub
return 0;
}
@Override
public ChunkGenerator getGenerator() {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getHighestBlockAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getHighestBlockAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getHighestBlockYAt(Location arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getHighestBlockYAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getHumidity(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getKeepSpawnInMemory() {
// TODO Auto-generated method stub
return false;
}
@Override
public List<LivingEntity> getLivingEntities() {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk[] getLoadedChunks() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMaxHeight() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getPVP() {
// TODO Auto-generated method stub
return false;
}
@Override
public List<Player> getPlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<BlockPopulator> getPopulators() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getSeaLevel() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getSeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Location getSpawnLocation() {
// TODO Auto-generated method stub
return null;
}
@Override
public double getTemperature(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getThunderDuration() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTicksPerAnimalSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTicksPerMonsterSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTime() {
// TODO Auto-generated method stub
return 0;
}
@Override
public UUID getUID() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getWeatherDuration() {
// TODO Auto-generated method stub
return 0;
}
@Override
public File getWorldFolder() {
// TODO Auto-generated method stub
return null;
}
@Override
public WorldType getWorldType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasStorm() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isAutoSave() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChunkLoaded(Chunk arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChunkLoaded(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isThundering() {
// TODO Auto-generated method stub
return false;
}
@Override
public void loadChunk(Chunk arg0) {
// TODO Auto-generated method stub
}
@Override
public void loadChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean loadChunk(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public void playEffect(Location arg0, Effect arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public <T> void playEffect(Location arg0, Effect arg1, T arg2) {
// TODO Auto-generated method stub
}
@Override
public void playEffect(Location arg0, Effect arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public <T> void playEffect(Location arg0, Effect arg1, T arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public boolean refreshChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean regenerateChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void save() {
// TODO Auto-generated method stub
}
@Override
public void setAutoSave(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setDifficulty(Difficulty arg0) {
// TODO Auto-generated method stub
}
@Override
public void setFullTime(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void setKeepSpawnInMemory(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setPVP(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setSpawnFlags(boolean arg0, boolean arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean setSpawnLocation(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setStorm(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setThunderDuration(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setThundering(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTicksPerAnimalSpawns(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTicksPerMonsterSpawns(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTime(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void setWeatherDuration(int arg0) {
// TODO Auto-generated method stub
}
@Override
public <T extends Entity> T spawn(Location arg0, Class<T> arg1)
throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public Arrow spawnArrow(Location arg0, Vector arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return null;
}
@Override
public LivingEntity spawnCreature(Location arg0, EntityType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public LivingEntity spawnCreature(Location arg0, CreatureType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public LightningStrike strikeLightning(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public LightningStrike strikeLightningEffect(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean unloadChunk(Chunk arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1, boolean arg2,
boolean arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunkRequest(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunkRequest(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public Set<String> getListeningPluginChannels() {
// TODO Auto-generated method stub
return null;
}
@Override
public void sendPluginMessage(Plugin arg0, String arg1, byte[] arg2) {
// TODO Auto-generated method stub
}
@Override
public List<MetadataValue> getMetadata(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasMetadata(String arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void removeMetadata(String arg0, Plugin arg1) {
// TODO Auto-generated method stub
}
@Override
public void setMetadata(String arg0, MetadataValue arg1) {
// TODO Auto-generated method stub
}
@Override
public void setBiome(int arg0, int arg1, Biome arg2) {
// TODO Auto-generated method stub
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3, boolean arg4, boolean arg5) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getAmbientSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getGameRuleValue(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getGameRules() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMonsterSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getWaterAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isChunkInUse(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isGameRule(String arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void playSound(Location arg0, Sound arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
}
@Override
public void setAmbientSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setAnimalSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean setGameRuleValue(String arg0, String arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setMonsterSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setWaterAnimalSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public Entity spawnEntity(Location arg0, EntityType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public FallingBlock spawnFallingBlock(Location arg0, Material arg1,
byte arg2) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public FallingBlock spawnFallingBlock(Location arg0, int arg1,
byte arg2) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
};
}
public static World getTestWorld_SecondWorld() {
// TODO Auto-generated method stub
return new World() {
@Override
public String getName() {
// TODO Auto-generated method stub
return "SecondWorld";
}
@Override
public boolean canGenerateStructures() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(Location arg0, float arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(Location arg0, float arg1,
boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3, boolean arg4) {
// TODO Auto-generated method stub
return false;
}
@Override
public Item dropItem(Location arg0, ItemStack arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Item dropItemNaturally(Location arg0, ItemStack arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean generateTree(Location arg0, TreeType arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean generateTree(Location arg0, TreeType arg1,
BlockChangeDelegate arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowAnimals() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getAllowMonsters() {
// TODO Auto-generated method stub
return false;
}
@Override
public Biome getBiome(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getBlockAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getBlockAt(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getBlockTypeIdAt(Location arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getBlockTypeIdAt(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Chunk getChunkAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk getChunkAt(Block arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk getChunkAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Difficulty getDifficulty() {
// TODO Auto-generated method stub
return null;
}
@Override
public ChunkSnapshot getEmptyChunkSnapshot(int arg0, int arg1,
boolean arg2, boolean arg3) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Entity> getEntities() {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(
Class<T>... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Entity> Collection<T> getEntitiesByClass(
Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<Entity> getEntitiesByClasses(Class<?>... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Environment getEnvironment() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getFullTime() {
// TODO Auto-generated method stub
return 0;
}
@Override
public ChunkGenerator getGenerator() {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getHighestBlockAt(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Block getHighestBlockAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getHighestBlockYAt(Location arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getHighestBlockYAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getHumidity(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getKeepSpawnInMemory() {
// TODO Auto-generated method stub
return false;
}
@Override
public List<LivingEntity> getLivingEntities() {
// TODO Auto-generated method stub
return null;
}
@Override
public Chunk[] getLoadedChunks() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMaxHeight() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getPVP() {
// TODO Auto-generated method stub
return false;
}
@Override
public List<Player> getPlayers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<BlockPopulator> getPopulators() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getSeaLevel() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getSeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Location getSpawnLocation() {
// TODO Auto-generated method stub
return null;
}
@Override
public double getTemperature(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getThunderDuration() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTicksPerAnimalSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTicksPerMonsterSpawns() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTime() {
// TODO Auto-generated method stub
return 0;
}
@Override
public UUID getUID() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getWeatherDuration() {
// TODO Auto-generated method stub
return 0;
}
@Override
public File getWorldFolder() {
// TODO Auto-generated method stub
return null;
}
@Override
public WorldType getWorldType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasStorm() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isAutoSave() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChunkLoaded(Chunk arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChunkLoaded(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isThundering() {
// TODO Auto-generated method stub
return false;
}
@Override
public void loadChunk(Chunk arg0) {
// TODO Auto-generated method stub
}
@Override
public void loadChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean loadChunk(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public void playEffect(Location arg0, Effect arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public <T> void playEffect(Location arg0, Effect arg1, T arg2) {
// TODO Auto-generated method stub
}
@Override
public void playEffect(Location arg0, Effect arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public <T> void playEffect(Location arg0, Effect arg1, T arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public boolean refreshChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean regenerateChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void save() {
// TODO Auto-generated method stub
}
@Override
public void setAutoSave(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setDifficulty(Difficulty arg0) {
// TODO Auto-generated method stub
}
@Override
public void setFullTime(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void setKeepSpawnInMemory(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setPVP(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setSpawnFlags(boolean arg0, boolean arg1) {
// TODO Auto-generated method stub
}
@Override
public boolean setSpawnLocation(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setStorm(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setThunderDuration(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setThundering(boolean arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTicksPerAnimalSpawns(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTicksPerMonsterSpawns(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setTime(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void setWeatherDuration(int arg0) {
// TODO Auto-generated method stub
}
@Override
public <T extends Entity> T spawn(Location arg0, Class<T> arg1)
throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public Arrow spawnArrow(Location arg0, Vector arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return null;
}
@Override
public LivingEntity spawnCreature(Location arg0, EntityType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public LivingEntity spawnCreature(Location arg0, CreatureType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public LightningStrike strikeLightning(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public LightningStrike strikeLightningEffect(Location arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean unloadChunk(Chunk arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunk(int arg0, int arg1, boolean arg2,
boolean arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunkRequest(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean unloadChunkRequest(int arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public Set<String> getListeningPluginChannels() {
// TODO Auto-generated method stub
return null;
}
@Override
public void sendPluginMessage(Plugin arg0, String arg1, byte[] arg2) {
// TODO Auto-generated method stub
}
@Override
public List<MetadataValue> getMetadata(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasMetadata(String arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void removeMetadata(String arg0, Plugin arg1) {
// TODO Auto-generated method stub
}
@Override
public void setMetadata(String arg0, MetadataValue arg1) {
// TODO Auto-generated method stub
}
@Override
public void setBiome(int arg0, int arg1, Biome arg2) {
// TODO Auto-generated method stub
}
@Override
public boolean createExplosion(double arg0, double arg1,
double arg2, float arg3, boolean arg4, boolean arg5) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getAmbientSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getGameRuleValue(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getGameRules() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMonsterSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getWaterAnimalSpawnLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isChunkInUse(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isGameRule(String arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void playSound(Location arg0, Sound arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
}
@Override
public void setAmbientSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setAnimalSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean setGameRuleValue(String arg0, String arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setMonsterSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void setWaterAnimalSpawnLimit(int arg0) {
// TODO Auto-generated method stub
}
@Override
public Entity spawnEntity(Location arg0, EntityType arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public FallingBlock spawnFallingBlock(Location arg0, Material arg1,
byte arg2) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public FallingBlock spawnFallingBlock(Location arg0, int arg1,
byte arg2) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
};
}
}
| gpl-3.0 |
241180/Oryx | oryx-dashboard/src/main/java/com/oryx/core/dashboard/view/dashboard/DashboardEdit.java | 2510 | package com.oryx.core.dashboard.view.dashboard;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.themes.ValoTheme;
/**
* Simple name editor Window.
*/
@SuppressWarnings("serial")
public class DashboardEdit extends Window {
private final TextField nameField = new TextField("Name");
private final DashboardEditListener listener;
public DashboardEdit(final DashboardEditListener listener,
final String currentName) {
this.listener = listener;
setCaption("Edit Dashboard");
setModal(true);
setClosable(false);
setResizable(false);
setWidth(300.0f, Unit.PIXELS);
addStyleName("edit-dashboard");
setContent(buildContent(currentName));
}
private Component buildContent(final String currentName) {
VerticalLayout result = new VerticalLayout();
result.setMargin(true);
result.setSpacing(true);
nameField.setValue(currentName);
nameField.addStyleName("caption-on-left");
nameField.focus();
result.addComponent(nameField);
result.addComponent(buildFooter());
return result;
}
private Component buildFooter() {
HorizontalLayout footer = new HorizontalLayout();
footer.setSpacing(true);
footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);
footer.setWidth(100.0f, Unit.PERCENTAGE);
Button cancel = new Button("Cancel");
cancel.addClickListener(new ClickListener() {
@Override
public void buttonClick(final ClickEvent event) {
close();
}
});
cancel.setClickShortcut(KeyCode.ESCAPE, null);
Button save = new Button("Save");
save.addStyleName(ValoTheme.BUTTON_PRIMARY);
save.addClickListener(new ClickListener() {
@Override
public void buttonClick(final ClickEvent event) {
listener.dashboardNameEdited(nameField.getValue());
close();
}
});
save.setClickShortcut(KeyCode.ENTER, null);
footer.addComponents(cancel, save);
footer.setExpandRatio(cancel, 1);
footer.setComponentAlignment(cancel, Alignment.TOP_RIGHT);
return footer;
}
public interface DashboardEditListener {
void dashboardNameEdited(String name);
}
}
| gpl-3.0 |
shivisuper/AndroMobile | AlaChat-Mobile/app/src/main/java/com/shivisuper/alachat_mobile/widgets/ChatLayout.java | 1958 | package com.shivisuper.alachat_mobile.widgets;
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.RelativeLayout;
/**
* Created by madhur on 17/01/15.
*/
public class ChatLayout extends RelativeLayout {
public ChatLayout(Context context) {
super(context);
}
public ChatLayout(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public ChatLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final float adjustVal = (float) 12.667;
if(getChildCount()<3)
return;
int imageViewWidth = getChildAt(0).getMeasuredWidth();
int timeWidth = getChildAt(1).getMeasuredWidth();
int messageHeight = getChildAt(2).getMeasuredHeight();
int messageWidth = getChildAt(2).getMeasuredWidth();
int layoutWidth = (int) (imageViewWidth + timeWidth + messageWidth + convertDpToPixel(adjustVal, getContext()));
setMeasuredDimension(layoutWidth, messageHeight);
}
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
* @param context Context to get resources and device specific display metrics
* @return A float value to represent px equivalent to dp depending on device density
*/
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
}
| gpl-3.0 |
mapzen/open | src/test/java/com/mapzen/open/activity/InitialActivityTest.java | 4373 | package com.mapzen.open.activity;
import com.mapzen.open.MapzenApplication;
import com.mapzen.open.TestMapzenApplication;
import com.mapzen.open.support.MapzenTestRunner;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import org.fest.assertions.api.Assertions;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.scribe.model.Token;
import android.content.Intent;
import android.net.Uri;
import javax.inject.Inject;
import static com.mapzen.open.support.TestHelper.initBaseActivity;
import static com.mapzen.open.support.TestHelper.initInitialActivity;
import static com.mapzen.open.util.MixpanelHelper.Event.INITIAL_LAUNCH;
import static com.mapzen.open.util.MixpanelHelper.Payload.LOGGED_IN_KEY;
import static org.fest.assertions.api.ANDROID.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.robolectric.Robolectric.application;
import static org.robolectric.Robolectric.buildActivity;
import static org.robolectric.Robolectric.getShadowApplication;
import static org.robolectric.Robolectric.shadowOf;
@RunWith(MapzenTestRunner.class)
public class InitialActivityTest {
private BaseActivity baseActivity;
@Inject MixpanelAPI mixpanelAPI;
@Before
public void setUp() throws Exception {
((TestMapzenApplication) Robolectric.application).inject(this);
baseActivity = initBaseActivity();
}
@Test
public void onCreate_shouldTrackAsLoggedOut() throws Exception {
initInitialActivity();
JSONObject expectedPayload = new JSONObject();
expectedPayload.put(LOGGED_IN_KEY, String.valueOf(false));
Mockito.verify(mixpanelAPI).track(eq(INITIAL_LAUNCH), refEq(expectedPayload));
}
@Test
public void onCreate_shouldTrackAsLoggedIn() throws Exception {
((MapzenApplication) application).setAccessToken(new Token("hokus", "bogus"));
initInitialActivity();
JSONObject expectedPayload = new JSONObject();
expectedPayload.put(LOGGED_IN_KEY, String.valueOf(true));
Mockito.verify(mixpanelAPI).track(eq(INITIAL_LAUNCH), refEq(expectedPayload));
}
@Test
public void shouldNotBeNull() throws Exception {
InitialActivity activity = initInitialActivity();
assertThat(activity).isNotNull();
}
@Test
public void shouldNotHaveActionBar() throws Exception {
InitialActivity activity = initInitialActivity();
assertThat(activity.getActionBar()).isNull();
}
@Test
public void onPreviouslyNotLoggedIn_ShouldOpenLoginActivity() throws Exception {
InitialActivity activity = initInitialActivity();
String activityStarted = shadowOf(activity).getNextStartedActivity()
.getComponent().toString();
Assertions.assertThat(activityStarted)
.isEqualTo("ComponentInfo{com.mapzen.open/com.mapzen.open.login.LoginActivity}");
}
@Test
public void onPreviouslyLoggedIn_ShouldOpenBaseActivity() {
simulateLogin();
InitialActivity activity = initInitialActivity();
String activityStarted = shadowOf(activity).getNextStartedActivity()
.getComponent().toString();
Assertions.assertThat(activityStarted)
.isEqualTo("ComponentInfo{com.mapzen.open/com.mapzen.open.activity.BaseActivity}");
}
@Test
public void shouldForwardIntentDataToLoginActivity() throws Exception {
String data = "http://maps.example.com/";
Intent intent = new Intent();
intent.setData(Uri.parse(data));
buildActivity(InitialActivity.class).withIntent(intent).create();
assertThat(getShadowApplication().getNextStartedActivity()).hasData(data);
}
@Test
public void shouldForwardIntentDataToBaseActivity() throws Exception {
simulateLogin();
String data = "http://maps.example.com/";
Intent intent = new Intent();
intent.setData(Uri.parse(data));
buildActivity(InitialActivity.class).withIntent(intent).create();
assertThat(getShadowApplication().getNextStartedActivity()).hasData(data);
}
private void simulateLogin() {
baseActivity.setAccessToken(new Token("token", "fun"));
}
}
| gpl-3.0 |
adriwankenobi/zeptictac | src/main/java/com/acerete/vo/deserializers/FieldDeserializer.java | 1234 | package com.acerete.vo.deserializers;
import java.io.IOException;
import java.util.Iterator;
import com.acerete.vo.Field;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class FieldDeserializer extends JsonDeserializer<Field> {
@Override
public Field deserialize(JsonParser parser, DeserializationContext ctx) throws IOException, JsonProcessingException {
JsonNode root = parser.getCodec().readTree(parser);
return parseField(root);
}
public static Field parseField(JsonNode node) throws IOException, JsonProcessingException {
Iterator<JsonNode> itWidth = node.iterator();
Field field = new Field();
int i = 0;
while (itWidth.hasNext()) {
JsonNode widthNode = itWidth.next();
Iterator<JsonNode> itHeight = widthNode.iterator();
int j = 0;
while (itHeight.hasNext()) {
JsonNode cellNode = itHeight.next();
char symbol = cellNode.asText().charAt(0);
field.set(i, j, symbol);
j++;
}
i++;
}
return field;
}
}
| gpl-3.0 |
interstar/art-toys-version-1 | src/art-toys/library/Uids.java | 117 | package arttoys.core;
public class Uids {
private int id=-1;
public int next() {
id++;
return id;
}
}
| gpl-3.0 |
rogerxu/design-patterns | src/main/java/demo/designpatterns/observer/Client.java | 328 | package demo.designpatterns.observer;
/**
* Created by rogerxu on 2017/7/17.
*/
public class Client {
public static void main(String[] args) {
SensorSystem system = new SensorSystem();
system.register(new Gate());
system.register(new Lighting());
system.register(new Surveillance());
system.soundTheAlarm();
}
}
| gpl-3.0 |
NRJD/BVApp1 | src/net/nightwhistler/pageturner/Configuration.java | 29447 | /*
* Copyright (C) 2012 Alex Kuiper
*
* This file is part of PageTurner
*
* PageTurner 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 3 of the License, or
* (at your option) any later version.
*
* PageTurner 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 PageTurner. If not, see <http://www.gnu.org/licenses/>.*
*/
package net.nightwhistler.pageturner;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Debug;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import com.google.inject.Inject;
import org.nrjd.bv.app.util.AppConstants;
import jedi.option.Option;
import net.nightwhistler.htmlspanner.FontFamily;
import net.nightwhistler.pageturner.activity.PageTurnerActivity;
import net.nightwhistler.pageturner.activity.ReadingActivity;
import net.nightwhistler.pageturner.dto.HighLight;
import net.nightwhistler.pageturner.dto.PageOffsets;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roboguice.inject.ContextSingleton;
import java.io.File;
import java.util.*;
import static java.util.Arrays.asList;
import static jedi.functional.FunctionalPrimitives.firstOption;
import static jedi.functional.FunctionalPrimitives.isEmpty;
import static jedi.functional.FunctionalPrimitives.select;
import static jedi.option.Options.none;
import static jedi.option.Options.option;
import static net.nightwhistler.pageturner.CustomOPDSSite.fromJSON;
import org.nrjd.bv.app.R;
/**
* Application configuration class which provides a friendly API to the various
* settings available.
*
* @author Alex Kuiper
*
*/
@ContextSingleton
public class Configuration {
private SharedPreferences settings;
private Context context;
private Map<String, FontFamily> fontCache = new HashMap<>();
public static enum ScrollStyle {
ROLLING_BLIND, PAGE_TIMER
}
public static enum AnimationStyle {
CURL, SLIDE, NONE
}
public static enum OrientationLock {
PORTRAIT, LANDSCAPE, REVERSE_PORTRAIT, REVERSE_LANDSCAPE, NO_LOCK
}
public static enum ColourProfile {
DAY, NIGHT
}
public static enum LibraryView {
BOOKCASE, LIST
}
public static enum CoverLabelOption {
ALWAYS, NEVER, WITHOUT_COVER
}
public static enum LibrarySelection {
BY_LAST_READ, LAST_ADDED, UNREAD, BY_TITLE, BY_AUTHOR;
}
public static enum ReadingDirection {
LEFT_TO_RIGHT, RIGHT_TO_LEFT;
}
public static enum LongShortPressBehaviour {
NORMAL, REVERSED
}
public static final String BASE_OPDS_FEED = "http://www.pageturner-reader.org/opds/feeds.xml";
public static final String BASE_SYNC_URL = "http://api.pageturner-reader.org/progress/";
public static final String KEY_SYNC_SERVER = "sync_server";
public static final String KEY_POS = "offset:";
public static final String KEY_IDX = "index:";
public static final String KEY_NAV_TAP_V = "nav_tap_v";
public static final String KEY_NAV_TAP_H = "nav_tap_h";
public static final String KEY_NAV_SWIPE_H = "nav_swipe_h";
public static final String KEY_NAV_SWIPE_V = "nav_swipe_v";
public static final String KEY_NAV_VOL = "nav_vol";
public static final String KEY_EMAIL = "email";
public static final String KEY_FULL_SCREEN = "full_screen";
public static final String KEY_COPY_TO_LIB = "copy_to_library";
public static final String KEY_STRIP_WHITESPACE = "strip_whitespace";
public static final String KEY_SCROLLING = "scrolling";
public static final String KEY_LAST_FILE = "last_file";
public static final String KEY_DEVICE_NAME = "device_name";
public static final String KEY_TEXT_SIZE = "itext_size";
public static final String KEY_MARGIN_H = "margin_h";
public static final String KEY_MARGIN_V = "margin_v";
public static final String KEY_LINE_SPACING = "line_spacing";
public static final String KEY_NIGHT_MODE = "night_mode";
public static final String KEY_SCREEN_ORIENTATION = "screen_orientation";
public static final String KEY_FONT_FACE = "font_face";
public static final String KEY_SERIF_FONT = "serif_font";
public static final String KEY_SANS_SERIF_FONT = "sans_serif_font";
public static final String PREFIX_DAY = "day";
public static final String PREFIX_NIGHT = "night";
public static final String KEY_BRIGHTNESS = "bright";
public static final String KEY_BACKGROUND = "bg";
public static final String KEY_LINK = "link";
public static final String KEY_TEXT = "text";
public static final String KEY_BRIGHTNESS_CTRL = "set_brightness";
public static final String KEY_SCROLL_STYLE = "scroll_style";
public static final String KEY_SCROLL_SPEED = "scroll_speed";
public static final String KEY_H_ANIMATION = "h_animation";
public static final String KEY_V_ANIMATION = "v_animation";
public static final String KEY_LIB_VIEW = "library_view";
public static final String KEY_LIB_SEL = "library_selection";
public static final String ACCESS_KEY = "access_key";
public static final String CALIBRE_SERVER = "calibre_server";
public static final String CALIBRE_USER = "calibre_user";
public static final String CALIBRE_PASSWORD = "calibre_password";
public static final String KEY_COVER_LABELS = "cover_labels";
public static final String KEY_KEEP_SCREEN_ON = "keep_screen_on";
public static final String KEY_OFFSETS = "offsets";
public static final String KEY_SHOW_PAGENUM = "show_pagenum";
public static final String KEY_OPDS_SITES = "opds_sites";
public static final String KEY_READING_DIRECTION = "reading_direction";
public static final String KEY_DIM_SYSTEM_UI = "dim_system_ui";
public static final String KEY_ACCEPT_SELF_SIGNED = "accept_self_signed";
public static final String KEY_LONG_SHORT = "long_short";
public static final String KEY_NOOK_TOP_BUTTONS_DIRECTION = "nook_touch_top_buttons_direction";
public static final String KEY_HIGHLIGHTS = "highlights";
public static final String KEY_ALLOW_STYLING = "allow_styling";
public static final String KEY_ALLOW_STYLE_COLOURS = "allow_style_colours";
public static final String KEY_LAST_TITLE = "last_title";
public static final String KEY_LAST_ACTIVITY = "last_activity";
public static final String KEY_ALWAYS_OPEN_LAST_BOOK = "always_open_last_book";
public static final String KEY_SCAN_FOLDER = "scan_folder";
public static final String KEY_USE_SCAN_FOLDER = "use_scan_folder";
// Flag for whether PageTurner is running on a Nook Simple Touch - an e-ink
// based Android device
// NB: Believe product/model field is "NOOK" on a Nook Touch and 'NookColor'
// on a Nook Color
public static final Boolean IS_NOOK_TOUCH = "NOOK".equals(Build.PRODUCT);
// Flag for any e-ink device. Currently only supports Nook Touch but could
// expand to other devices like the Sony PRS-T1
public static final Boolean IS_EINK_DEVICE = IS_NOOK_TOUCH;
//Which platform version to start text selection on.
public static final int TEXT_SELECTION_PLATFORM_VERSION = Build.VERSION_CODES.ICE_CREAM_SANDWICH;
private static final Logger LOG = LoggerFactory
.getLogger("Configuration");
private String defaultSerifFont;
private String defaultSansFont;
@Inject
public Configuration(Context context) {
this.settings = PreferenceManager.getDefaultSharedPreferences(context);
this.context = context;
if ( IS_NOOK_TOUCH ) {
defaultSerifFont = "serif";
defaultSansFont = "sans";
} else {
defaultSerifFont = "gen_book_bas";
defaultSansFont = "sans";
}
// On Nook Touch, preset some different defaults on first load
// (these values work better w/ e-ink)
if (IS_NOOK_TOUCH && this.settings.getString(KEY_DEVICE_NAME, null) == null) {
SharedPreferences.Editor editor = this.settings.edit();
editor.putString(KEY_FONT_FACE, "sans");
editor.putString(KEY_SERIF_FONT, "serif");
editor.putInt(KEY_TEXT_SIZE, 32);
editor.putString(KEY_SCROLL_STYLE, "timer"); // enum is ScrollStyle.PAGE_TIMER
final String no_animation = AnimationStyle.NONE.name().toLowerCase(Locale.US);
editor.putString(KEY_H_ANIMATION, no_animation);
editor.putString(KEY_V_ANIMATION, no_animation);
editor.putInt(PREFIX_DAY + "_" + KEY_LINK,
Color.rgb(0x40, 0x40, 0x40));
editor.putInt(PREFIX_NIGHT + "_" + KEY_TEXT, Color.WHITE);
editor.putInt(PREFIX_NIGHT + "_" + KEY_LINK,
Color.rgb(0xb0, 0xb0, 0xb0));
editor.commit();
}
}
public String getAppVersion() {
String version = "";
try {
version = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
// Huh? Really?
}
return version;
}
public String getUserAgent() {
return context.getString(R.string.app_name) + "-" + getAppVersion()
+ "/" + Build.MODEL + ";Android-" + Build.VERSION.RELEASE;
}
public Locale getLocale() {
String languageSetting = settings.getString("custom_lang", "default");
if ( "default".equalsIgnoreCase(languageSetting) ) {
return Locale.getDefault();
}
return new Locale(languageSetting);
}
public Class<? extends PageTurnerActivity> getLastActivity() {
String lastActivityString = settings.getString( KEY_LAST_ACTIVITY,
"net.nightwhistler.pageturner.activity.ReadingActivity" );
try {
return (Class<? extends PageTurnerActivity>) Class.forName( lastActivityString );
} catch ( ClassNotFoundException n ) {
return ReadingActivity.class;
}
}
public void setLastActivity( Class<? extends PageTurnerActivity> activityClass ) {
updateValue( KEY_LAST_ACTIVITY, activityClass.getCanonicalName() );
}
public String getBaseOPDSFeed() {
return BASE_OPDS_FEED;
}
public String getSyncServerURL() {
return settings.getString( KEY_SYNC_SERVER, BASE_SYNC_URL ).trim();
}
public boolean isAlwaysOpenLastBook() {
return settings.getBoolean(KEY_ALWAYS_OPEN_LAST_BOOK, false);
}
public boolean isVerticalTappingEnabled() {
return !isScrollingEnabled()
&& settings.getBoolean(KEY_NAV_TAP_V, true);
}
public boolean isHorizontalTappingEnabled() {
return !isScrollingEnabled()
&& settings.getBoolean(KEY_NAV_TAP_H, true);
}
public boolean isHorizontalSwipeEnabled() {
return !isScrollingEnabled()
&& settings.getBoolean(KEY_NAV_SWIPE_H, true);
}
public boolean isVerticalSwipeEnabled() {
return settings.getBoolean(KEY_NAV_SWIPE_V, true)
&& !isScrollingEnabled();
}
public boolean isAcceptSelfSignedCertificates() {
return settings.getBoolean(KEY_ACCEPT_SELF_SIGNED, false);
}
public boolean isAllowStyling() {
return settings.getBoolean(KEY_ALLOW_STYLING, true);
}
public int getLastPosition(String fileName) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
int pos = bookPrefs.getInt(KEY_POS, -1);
if ( pos != -1 ) {
return pos;
}
//Fall-back to older settings
String bookHash = Integer.toHexString(fileName.hashCode());
pos = settings.getInt(KEY_POS + bookHash, -1);
if (pos != -1) {
return pos;
}
// Fall-back for even older settings.
return settings.getInt(KEY_POS + fileName, -1);
}
private SharedPreferences getPrefsForBook( String fileName ) {
String bookHash = Integer.toHexString(fileName.hashCode());
return context.getSharedPreferences(bookHash, 0);
}
public void setPageOffsets(String fileName, List<List<Integer>> offsets) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
PageOffsets offsetsObject = PageOffsets.fromValues(this, offsets);
try {
String json = offsetsObject.toJSON();
updateValue(bookPrefs, KEY_OFFSETS, json);
} catch ( JSONException js ) {
LOG.error( "Error storing page offsets", js );
}
}
public Option<List<List<Integer>>> getPageOffsets(String fileName) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
String data = bookPrefs.getString(KEY_OFFSETS, "");
if ( data.length() == 0 ) {
return none();
}
try {
PageOffsets offsets = PageOffsets.fromJSON(data);
if (offsets == null || !offsets.isValid(this)) {
return none();
}
return option(offsets.getOffsets());
} catch ( JSONException js ) {
LOG.error( "Could not retrieve page offsets", js );
return none();
}
}
public List<HighLight> getHightLights( String fileName ) {
SharedPreferences prefs = getPrefsForBook(fileName);
if ( prefs.contains(KEY_HIGHLIGHTS) ) {
return HighLight.fromJSON(fileName, prefs.getString(KEY_HIGHLIGHTS, "[]"));
}
return new ArrayList<>();
}
public void storeHighlights( String fileName, List<HighLight> highLights ) {
SharedPreferences pref = getPrefsForBook(fileName);
updateValue(pref, KEY_HIGHLIGHTS, HighLight.toJSON(highLights));
}
public LongShortPressBehaviour getLongShortPressBehaviour() {
String value = settings.getString(KEY_LONG_SHORT,
LongShortPressBehaviour.NORMAL.name());
return LongShortPressBehaviour.valueOf( value.toUpperCase(Locale.US) );
}
public ReadingDirection getReadingDirection() {
String value = settings.getString(KEY_READING_DIRECTION,
ReadingDirection.LEFT_TO_RIGHT.name());
return ReadingDirection.valueOf(value.toUpperCase(Locale.US));
}
public void setLastPosition(String fileName, int position) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
updateValue(bookPrefs, KEY_POS, position);
}
public int getLastIndex(String fileName) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
int pos = bookPrefs.getInt( KEY_IDX, -1 );
if ( pos != -1 ) {
return pos;
}
//Fall-backs to older setting in central file
String bookHash = Integer.toHexString(fileName.hashCode());
pos = settings.getInt(KEY_IDX + bookHash, -1);
if (pos != -1) {
return pos;
}
// Fall-back for even older settings.
return settings.getInt(KEY_IDX + fileName, -1);
}
public List<CustomOPDSSite> getCustomOPDSSites() {
String sites = settings.getString(KEY_OPDS_SITES, "[]");
List<CustomOPDSSite> result = new ArrayList<>();
try {
JSONArray array = new JSONArray(sites);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
CustomOPDSSite site = fromJSON(obj);
result.add(site);
}
} catch (JSONException js) {
LOG.error( "Could not retrieve custom opds sites", js );
}
importOldCalibreSite(result);
return result;
}
private void importOldCalibreSite(List<CustomOPDSSite> sites) {
if (this.getCalibreServer() != null
&& this.getCalibreServer().length() > 0) {
CustomOPDSSite calibre = new CustomOPDSSite();
calibre.setName(context.getString(R.string.pref_calibre_server));
calibre.setUrl(getCalibreServer());
calibre.setUserName(getCalibreUser());
calibre.setPassword(getCalibrePassword());
sites.add(calibre);
updateValue(CALIBRE_SERVER, null);
storeCustomOPDSSites(sites);
}
}
public void storeCustomOPDSSites(List<CustomOPDSSite> sites) {
try {
JSONArray array = new JSONArray();
for (CustomOPDSSite site : sites) {
array.put(site.toJSON());
}
updateValue(KEY_OPDS_SITES, array.toString());
} catch ( JSONException js ) {
LOG.error( "Error storing custom sites", js );
}
}
public void setLastIndex(String fileName, int index) {
SharedPreferences bookPrefs = getPrefsForBook(fileName);
updateValue(bookPrefs, KEY_IDX, index);
}
public boolean isVolumeKeyNavEnabled() {
return !isScrollingEnabled() && settings.getBoolean(KEY_NAV_VOL, false);
}
public boolean isNookUpButtonForward() {
return !isScrollingEnabled()
&& "forward".equals(settings.getString(
KEY_NOOK_TOP_BUTTONS_DIRECTION, "backward"));
}
public String getSynchronizationEmail() {
return settings.getString(KEY_EMAIL, "").trim();
}
public boolean isShowPageNumbers() {
return settings.getBoolean(KEY_SHOW_PAGENUM, true);
}
public String getSynchronizationAccessKey() {
return settings.getString(ACCESS_KEY, "").trim();
}
public boolean isDimSystemUI() {
return isFullScreenEnabled() && settings.getBoolean(KEY_DIM_SYSTEM_UI, false);
}
public boolean isSyncEnabled() {
String email = getSynchronizationEmail();
return email.length() > 0;
}
public boolean isFullScreenEnabled() {
return settings.getBoolean(KEY_FULL_SCREEN, false);
}
public boolean isStripWhiteSpaceEnabled() {
return settings.getBoolean(KEY_STRIP_WHITESPACE, false);
}
public boolean isScrollingEnabled() {
return settings.getBoolean(KEY_SCROLLING, false);
}
public String getLastReadTitle() {
return settings.getString(KEY_LAST_TITLE, "");
}
public void setLastReadTitle(String title) {
updateValue(KEY_LAST_TITLE, title);
}
public String getLastOpenedFile() {
return settings.getString(KEY_LAST_FILE, "");
}
public void setLastOpenedFile(String fileName) {
updateValue(KEY_LAST_FILE, fileName);
}
public String getDeviceName() {
return settings.getString(KEY_DEVICE_NAME, Build.MODEL);
}
public int getTextSize() {
return settings.getInt(KEY_TEXT_SIZE, 18);
}
public void setTextSize(int textSize) {
updateValue(KEY_TEXT_SIZE, textSize);
}
public int getHorizontalMargin() {
return settings.getInt(KEY_MARGIN_H, 30);
}
public int getVerticalMargin() {
return settings.getInt(KEY_MARGIN_V, 25);
}
public int getLineSpacing() {
return settings.getInt(KEY_LINE_SPACING, 0);
}
public boolean isKeepScreenOn() {
return settings.getBoolean(KEY_KEEP_SCREEN_ON, false);
}
public int getTheme() {
if (getColourProfile() == ColourProfile.NIGHT) {
return R.style.Theme_Sherlock;
} else {
return R.style.Theme_Sherlock_Light_DarkActionBar;
}
}
public void setColourProfile(ColourProfile profile) {
if (profile == ColourProfile.DAY) {
updateValue(KEY_NIGHT_MODE, false);
} else {
updateValue(KEY_NIGHT_MODE, true);
}
}
public CoverLabelOption getCoverLabelOption() {
return CoverLabelOption.valueOf(settings.getString(KEY_COVER_LABELS,
CoverLabelOption.ALWAYS.name().toLowerCase(Locale.US)));
}
public ColourProfile getColourProfile() {
if (settings.getBoolean(KEY_NIGHT_MODE, false)) {
return ColourProfile.NIGHT;
} else {
return ColourProfile.DAY;
}
}
public OrientationLock getScreenOrientation() {
String orientation = settings.getString(KEY_SCREEN_ORIENTATION,
OrientationLock.NO_LOCK.name().toLowerCase(Locale.US));
return OrientationLock.valueOf(orientation.toUpperCase(Locale.US));
}
private void updateValue( SharedPreferences prefs, String key, Object value ) {
SharedPreferences.Editor editor = prefs.edit();
if (value == null) {
editor.remove(key);
} else if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new IllegalArgumentException("Unsupported type: "
+ value.getClass().getSimpleName());
}
editor.commit();
}
private void updateValue(String key, Object value) {
updateValue(settings, key, value);
}
private FontFamily loadFamilyFromAssets(String key, String baseName) {
Typeface basic = Typeface.createFromAsset(context.getAssets(), baseName
+ ".otf");
Typeface boldFace = Typeface.createFromAsset(context.getAssets(),
baseName + "-Bold.otf");
Typeface italicFace = Typeface.createFromAsset(context.getAssets(),
baseName + "-Italic.otf");
Typeface biFace = Typeface.createFromAsset(context.getAssets(),
baseName + "-BoldItalic.otf");
FontFamily fam = new FontFamily(key, basic);
fam.setBoldTypeface(boldFace);
fam.setItalicTypeface(italicFace);
fam.setBoldItalicTypeface(biFace);
return fam;
}
private FontFamily getFontFamily(String fontKey, String defaultVal) {
String fontFace = settings.getString(fontKey, defaultVal);
if (!fontCache.containsKey(fontFace)) {
if ("gen_book_bas".equals(fontFace)) {
fontCache.put(fontFace,
loadFamilyFromAssets(fontFace, "GentiumBookBasic"));
} else if ("gen_bas".equals(fontFace)) {
fontCache.put(fontFace,
loadFamilyFromAssets(fontFace, "GentiumBasic"));
} else if ("frankruehl".equalsIgnoreCase(fontFace)) {
fontCache.put(fontFace,
loadFamilyFromAssets(fontFace, "FrankRuehl"));
} else {
Typeface face = Typeface.SANS_SERIF;
if ("sans".equals(fontFace)) {
face = Typeface.SANS_SERIF;
} else if ("serif".equals(fontFace)) {
face = Typeface.SERIF;
} else if ("mono".equals(fontFace)) {
face = Typeface.MONOSPACE;
} else if ( "default".equals(fontFace) ) {
face = Typeface.DEFAULT;
}
fontCache.put(fontFace, new FontFamily(fontFace, face));
}
}
return fontCache.get(fontFace);
}
public FontFamily getSerifFontFamily() {
return getFontFamily(KEY_SERIF_FONT, defaultSerifFont );
}
public FontFamily getSansSerifFontFamily() {
return getFontFamily(KEY_SANS_SERIF_FONT, defaultSansFont );
}
public FontFamily getDefaultFontFamily() {
return getFontFamily(KEY_FONT_FACE, defaultSerifFont);
}
public int getBrightNess() {
// Brightness 0 means black screen :)
return Math.max(1, getProfileSetting(KEY_BRIGHTNESS, 50, 50));
}
public void setBrightness(int brightness) {
if (getColourProfile() == ColourProfile.DAY) {
updateValue("day_bright", brightness);
} else {
updateValue("night_bright", brightness);
}
}
public int getBackgroundColor() {
return getProfileSetting(KEY_BACKGROUND, Color.WHITE, Color.BLACK);
}
public int getTextColor() {
return getProfileSetting(KEY_TEXT, Color.BLACK, Color.GRAY);
}
public int getLinkColor() {
return getProfileSetting(KEY_LINK, Color.BLUE, Color.rgb(255, 165, 0));
}
public boolean isUseColoursFromCSS() {
String setting = KEY_ALLOW_STYLE_COLOURS;
boolean nightDefault = false;
boolean dayDefault = true;
if (getColourProfile() == ColourProfile.NIGHT) {
return settings.getBoolean(PREFIX_NIGHT + "_" + setting, nightDefault);
} else {
return settings.getBoolean(PREFIX_DAY + "_" + setting, dayDefault);
}
}
private int getProfileSetting(String setting, int dayDefault,
int nightDefault) {
if (getColourProfile() == ColourProfile.NIGHT) {
return settings.getInt(PREFIX_NIGHT + "_" + setting, nightDefault);
} else {
return settings.getInt(PREFIX_DAY + "_" + setting, dayDefault);
}
}
public boolean isBrightnessControlEnabled() {
return settings.getBoolean(KEY_BRIGHTNESS_CTRL, false);
}
public ScrollStyle getAutoScrollStyle() {
String style = settings.getString(KEY_SCROLL_STYLE,
ScrollStyle.ROLLING_BLIND.name().toLowerCase(Locale.US));
if ("rolling_blind".equals(style)) {
return ScrollStyle.ROLLING_BLIND;
} else {
return ScrollStyle.PAGE_TIMER;
}
}
public int getScrollSpeed() {
return settings.getInt(KEY_SCROLL_SPEED, 20);
}
public AnimationStyle getHorizontalAnim() {
String animH = settings.getString(KEY_H_ANIMATION, AnimationStyle.SLIDE
.name().toLowerCase(Locale.US));
return AnimationStyle.valueOf(animH.toUpperCase(Locale.US));
}
public AnimationStyle getVerticalAnim() {
String animV = settings.getString(KEY_V_ANIMATION, AnimationStyle.SLIDE
.name().toLowerCase(Locale.US));
return AnimationStyle.valueOf(animV.toUpperCase(Locale.US));
}
public LibraryView getLibraryView() {
String libView = settings.getString(KEY_LIB_VIEW, LibraryView.BOOKCASE
.name().toLowerCase(Locale.US));
return LibraryView.valueOf(libView.toUpperCase(Locale.US));
}
public void setLibraryView(LibraryView viewStyle) {
String libView = viewStyle.name().toLowerCase(Locale.US);
updateValue(KEY_LIB_VIEW, libView);
}
public LibrarySelection getLastLibraryQuery() {
String query = settings.getString(KEY_LIB_SEL,
LibrarySelection.LAST_ADDED.name().toLowerCase(Locale.US));
return LibrarySelection.valueOf(query.toUpperCase(Locale.US));
}
public void setLastLibraryQuery(LibrarySelection sel) {
updateValue(KEY_LIB_SEL, sel.name().toLowerCase(Locale.US));
}
public String getCalibreServer() {
return settings.getString(CALIBRE_SERVER, "");
}
public String getCalibreUser() {
return settings.getString(CALIBRE_USER, "");
}
public String getCalibrePassword() {
return settings.getString(CALIBRE_PASSWORD, "");
}
public Option<File> getStorageBase() {
return option(Environment.getExternalStorageDirectory());
}
public Option<File> getDownloadsFolder() {
return firstOption(
asList(
ContextCompat.getExternalFilesDirs( context, "Downloads" )
)
);
}
public Option<File> getLibraryFolder() {
// BVApp-Comment: 04/Oct/2015: Provided BV app books path for stroing the library files.
Option<File> libraryFolder = getStorageBase().map(
baseFolder -> new File(baseFolder.getAbsolutePath() + AppConstants.BOOKS_PATH) );
//If the library-folder on external storage exists, return it
if ( ! isEmpty(select(libraryFolder, File::exists))) {
return libraryFolder;
}
if ( ! isEmpty(libraryFolder) ) {
try {
boolean result = libraryFolder.unsafeGet().mkdirs();
if ( result ) {
return libraryFolder;
}
} catch ( Exception e ) {}
}
return firstOption(
asList(
ContextCompat.getExternalFilesDirs( context, "Books" )
)
);
}
public Option<File> getTTSFolder() {
return firstOption(
asList(
ContextCompat.getExternalCacheDirs( context )
)
);
}
public boolean getCopyToLibraryOnScan() {
return settings.getBoolean(KEY_COPY_TO_LIB, true);
}
public void setCopyToLibraryOnScan(boolean value) {
settings.edit()
.putBoolean(KEY_COPY_TO_LIB, value)
.commit();
}
public boolean getUseCustomScanFolder() {
return settings.getBoolean(KEY_USE_SCAN_FOLDER, false);
}
public void setUseCustomScanFolder(boolean value) {
settings.edit()
.putBoolean(KEY_USE_SCAN_FOLDER, value)
.commit();
}
/** Return the default folder path which is shown for the "scan for books" custom directory
*/
private String getDefaultScanFolder() {
return Configuration.IS_NOOK_TOUCH ?
"/media" : /* Nook's default internal content storage (accessible via USB) is under /media */
getStorageBase().unsafeGet().getAbsolutePath() + "/eBooks";
}
/** Return the folder path to show for the "scan for books" custom directory
*/
public String getScanFolder() {
return settings.getString(KEY_SCAN_FOLDER, getDefaultScanFolder());
}
/** Set the folder path to show for "scan for books" custom directory.
Will only save a setting if the default actually changed.
*/
public void setScanFolder(String value) {
SharedPreferences.Editor editor = settings.edit();
if(value == null || value.equals(getDefaultScanFolder())) {
if(!settings.contains(KEY_SCAN_FOLDER))
return;
editor.remove(KEY_SCAN_FOLDER);
} else if(new File(value).isDirectory()) {
editor.putString(KEY_SCAN_FOLDER, value);
}
editor.commit();
}
/**
* Returns the bytes of available memory left on the heap. Not totally sure
* if it works reliably.
*/
public static double getMemoryUsage() {
long max = Runtime.getRuntime().maxMemory();
long used = Runtime.getRuntime().totalMemory();
return (double) used / (double) max;
}
/*
Returns the available bitmap memory.
On newer Android versions this is the same as the normaL
heap memory.
*/
public static double getBitmapMemoryUsage() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
return getMemoryUsage();
}
long max = Runtime.getRuntime().maxMemory();
long used = Debug.getNativeHeapAllocatedSize();
return (double) used / (double) max;
}
}
| gpl-3.0 |
SamRuffleColes/up-down-london | UpDownLondon/src/main/java/uk/co/samcoles/updownlondon/ui/ProblemsActivity.java | 932 | package uk.co.samcoles.updownlondon.ui;
import uk.co.samcoles.updownlondon.R;
import android.app.Fragment;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class ProblemsActivity extends SimpleSinglePaneActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_problems, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
startAboutActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startAboutActivity() {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
}
@Override
protected Fragment onCreatePane() {
return new ProblemsFragment();
}
}
| gpl-3.0 |
CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectExpectedStudyFlagshipDAO.java | 3840 | /*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO 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 3 of the License, or
* at your option) any later version.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.data.dao;
import org.cgiar.ccafs.marlo.data.model.ProjectExpectedStudyFlagship;
import java.util.List;
public interface ProjectExpectedStudyFlagshipDAO {
/**
* This method removes a specific projectExpectedStudyFlagship value from the database.
*
* @param projectExpectedStudyFlagshipId is the projectExpectedStudyFlagship identifier.
* @return true if the projectExpectedStudyFlagship was successfully deleted, false otherwise.
*/
public void deleteProjectExpectedStudyFlagship(long projectExpectedStudyFlagshipId);
/**
* This method validate if the projectExpectedStudyFlagship identify with the given id exists in the system.
*
* @param projectExpectedStudyFlagshipID is a projectExpectedStudyFlagship identifier.
* @return true if the projectExpectedStudyFlagship exists, false otherwise.
*/
public boolean existProjectExpectedStudyFlagship(long projectExpectedStudyFlagshipID);
/**
* This method gets a projectExpectedStudyFlagship object by a given projectExpectedStudyFlagship identifier.
*
* @param projectExpectedStudyFlagshipID is the projectExpectedStudyFlagship identifier.
* @return a ProjectExpectedStudyFlagship object.
*/
public ProjectExpectedStudyFlagship find(long id);
/**
* This method gets a list of projectExpectedStudyFlagship that are active
*
* @return a list from ProjectExpectedStudyFlagship null if no exist records
*/
public List<ProjectExpectedStudyFlagship> findAll();
/**
* This method gets a projectExpectedStudyFlagship object by a given expectedStudy, Flagship and Phase identifier.
*
* @param expectedStudyId is the projectExpectedStudy identifier.
* @param flagshipId is the flagship/Module identifier.
* @param phaseId is the Phase identifier.
* @return a ProjectExpectedStudyFlagship object.
*/
public ProjectExpectedStudyFlagship findProjectExpectedStudyFlagshipbyPhase(Long expectedStudyId, Long flagshipId,
Long phaseId);
/**
* This method gets a list of projectExpectedStudyFlagship by a given projectExpectedStudy identifier.
*
* @param studyId is the projectExpectedStudy identifier.
* @return a list of projectExpectedStudyFlagship objects.
*/
public List<ProjectExpectedStudyFlagship> getAllStudyFlagshipsByStudy(long studyId);
/**
* This method saves the information of the given projectExpectedStudyFlagship
*
* @param projectExpectedStudyFlagship - is the projectExpectedStudyFlagship object with the new information to be
* added/updated.
* @return a number greater than 0 representing the new ID assigned by the database, 0 if the
* projectExpectedStudyFlagship was
* updated
* or -1 is some error occurred.
*/
public ProjectExpectedStudyFlagship save(ProjectExpectedStudyFlagship projectExpectedStudyFlagship);
}
| gpl-3.0 |
aslab/rct | higgs/trunk/code/ROS/unstable_exploratory_packages/higgs_arduino_java/msg_gen/java/ros/pkg/std_msgs/msg/MultiArrayLayout.java | 4000 | /* Auto-generated by genmsg_java.py for file /opt/ros/diamondback/stacks/ros_comm/messages/std_msgs/msg/MultiArrayLayout.msg */
package ros.pkg.std_msgs.msg;
import java.nio.ByteBuffer;
public class MultiArrayLayout extends ros.communication.Message {
public java.util.ArrayList<ros.pkg.std_msgs.msg.MultiArrayDimension> dim = new java.util.ArrayList<ros.pkg.std_msgs.msg.MultiArrayDimension>();
public long data_offset;
public MultiArrayLayout() {
}
public static java.lang.String __s_getDataType() { return "std_msgs/MultiArrayLayout"; }
public java.lang.String getDataType() { return __s_getDataType(); }
public static java.lang.String __s_getMD5Sum() { return "0fed2a11c13e11c5571b4e2a995a91a3"; }
public java.lang.String getMD5Sum() { return __s_getMD5Sum(); }
public static java.lang.String __s_getMessageDefinition() { return "# The multiarray declares a generic multi-dimensional array of a\n" +
"# particular data type. Dimensions are ordered from outer most\n" +
"# to inner most.\n" +
"\n" +
"MultiArrayDimension[] dim # Array of dimension properties\n" +
"uint32 data_offset # padding bytes at front of data\n" +
"\n" +
"# Accessors should ALWAYS be written in terms of dimension stride\n" +
"# and specified outer-most dimension first.\n" +
"# \n" +
"# multiarray(i,j,k) = data[data_offset + dim_stride[1]*i + dim_stride[2]*j + k]\n" +
"#\n" +
"# A standard, 3-channel 640x480 image with interleaved color channels\n" +
"# would be specified as:\n" +
"#\n" +
"# dim[0].label = \"height\"\n" +
"# dim[0].size = 480\n" +
"# dim[0].stride = 3*640*480 = 921600 (note dim[0] stride is just size of image)\n" +
"# dim[1].label = \"width\"\n" +
"# dim[1].size = 640\n" +
"# dim[1].stride = 3*640 = 1920\n" +
"# dim[2].label = \"channel\"\n" +
"# dim[2].size = 3\n" +
"# dim[2].stride = 3\n" +
"#\n" +
"# multiarray(i,j,k) refers to the ith row, jth column, and kth channel.\n" +
"================================================================================\n" +
"MSG: std_msgs/MultiArrayDimension\n" +
"string label # label of given dimension\n" +
"uint32 size # size of given dimension (in type units)\n" +
"uint32 stride # stride of given dimension\n" +
""; }
public java.lang.String getMessageDefinition() { return __s_getMessageDefinition(); }
public MultiArrayLayout clone() {
MultiArrayLayout c = new MultiArrayLayout();
c.deserialize(serialize(0));
return c;
}
public void setTo(ros.communication.Message m) {
deserialize(m.serialize(0));
}
public int serializationLength() {
int __l = 0;
__l += 4;
for(ros.pkg.std_msgs.msg.MultiArrayDimension val : dim) {
__l += val.serializationLength();
}
__l += 4; // data_offset
return __l;
}
public void serialize(ByteBuffer bb, int seq) {
bb.putInt(dim.size());
for(ros.pkg.std_msgs.msg.MultiArrayDimension val : dim) {
val.serialize(bb, seq);
}
bb.putInt((int)data_offset);
}
public void deserialize(ByteBuffer bb) {
int __dim_len = bb.getInt();
dim = new java.util.ArrayList<ros.pkg.std_msgs.msg.MultiArrayDimension>(__dim_len);
for(int __i=0; __i<__dim_len; __i++) {
ros.pkg.std_msgs.msg.MultiArrayDimension __tmp = new ros.pkg.std_msgs.msg.MultiArrayDimension();
__tmp.deserialize(bb);
dim.add(__tmp);;
}
data_offset = (long)(bb.getInt() & 0xffffffff);
}
@SuppressWarnings("all")
public boolean equals(Object o) {
if(!(o instanceof MultiArrayLayout))
return false;
MultiArrayLayout other = (MultiArrayLayout) o;
return
dim.equals(other.dim) &&
data_offset == other.data_offset &&
true;
}
@SuppressWarnings("all")
public int hashCode() {
final int prime = 31;
int result = 1;
long tmp;
result = prime * result + (this.dim == null ? 0 : this.dim.hashCode());
result = prime * result + (int)(this.data_offset ^ (this.data_offset >>> 32));
return result;
}
} // class MultiArrayLayout
| gpl-3.0 |
DanVanAtta/triplea | game-core/src/main/java/games/strategy/triplea/printgenerator/PrintGenerationData.java | 266 | package games.strategy.triplea.printgenerator;
import games.strategy.engine.data.GameData;
import java.io.File;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
class PrintGenerationData {
private final File outDir;
private final GameData data;
}
| gpl-3.0 |
kobreu/compiler | src/edu/tum/juna/ast/Block.java | 1702 | /*
* Generated by classgen, version 1.5
* 31.07.13 15:50
*/
package edu.tum.juna.ast;
public class Block extends SyntaxNode {
private SyntaxNode parent;
public StatList stats;
public LastStat last;
public Block(StatList stats, LastStat last) {
this.stats = stats;
if (stats != null)
stats.setParent(this);
this.last = last;
if (last != null)
last.setParent(this);
}
@Override
public SyntaxNode getParent() {
return parent;
}
@Override
public void setParent(SyntaxNode parent) {
this.parent = parent;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public void childrenAccept(Visitor visitor) {
if (stats != null)
stats.accept(visitor);
if (last != null)
last.accept(visitor);
}
@Override
public void traverseTopDown(Visitor visitor) {
accept(visitor);
if (stats != null)
stats.traverseTopDown(visitor);
if (last != null)
last.traverseTopDown(visitor);
}
@Override
public void traverseBottomUp(Visitor visitor) {
if (stats != null)
stats.traverseBottomUp(visitor);
if (last != null)
last.traverseBottomUp(visitor);
accept(visitor);
}
@Override
public String toString() {
return toString("");
}
public String toString(String tab) {
StringBuffer buffer = new StringBuffer();
buffer.append(tab);
buffer.append("Block(\n");
if (stats != null)
buffer.append(stats.toString(" " + tab));
else
buffer.append(tab + " null");
buffer.append("\n");
if (last != null)
buffer.append(last.toString(" " + tab));
else
buffer.append(tab + " null");
buffer.append("\n");
buffer.append(tab);
buffer.append(") [Block]");
return buffer.toString();
}
}
| gpl-3.0 |
javieriserte/bioUtils | src/seqManipulation/fastamanipulator/commands/misc/ReconstructDottedAlignmentCommand.java | 1415 | package seqManipulation.fastamanipulator.commands.misc;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import seqManipulation.dottedalignment.ReconstructDottedAlignment;
import seqManipulation.fastamanipulator.commands.FastaCommand;
import cmdGA2.SingleArgumentOption;
import pair.Pair;
/**
* Reconstruct a full alignment from a dotted alignment.
*
* For the reconstruction the index of a reference sequence must be provided.
* If 0 is provided as index, then the reference sequence is guessed.
* The index of the first sequence is 1.
*
* @author javier iserte
*
*/
public class ReconstructDottedAlignmentCommand extends FastaCommand<SingleArgumentOption<Integer>> {
public ReconstructDottedAlignmentCommand(InputStream inputstream, PrintStream output, SingleArgumentOption<Integer> option) {
super(inputstream, output, option);
}
@Override
protected List<String> performAction() {
Integer referenceIndex = (Integer)this.getOption().getValue();
List<Pair<String, String>> seqs = this.getSequences();
List<String> results = new ArrayList<String>();
List<Pair<String,String>> rec = ReconstructDottedAlignment.reconstruct(seqs, referenceIndex-1);
for (Pair<String, String> pair : rec) {
results.add(">" + pair.getFirst());
results.add(pair.getSecond());
}
return results;
}
}
| gpl-3.0 |
trackplus/Genji | src/main/java/com/aurel/track/persist/map/TApplicationContextMapBuilder.java | 6396 | /**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Id:$ */
package com.aurel.track.persist.map;
import java.util.Date;
import java.math.BigDecimal;
import org.apache.torque.Torque;
import org.apache.torque.TorqueException;
import org.apache.torque.map.MapBuilder;
import org.apache.torque.map.DatabaseMap;
import org.apache.torque.map.TableMap;
import org.apache.torque.map.ColumnMap;
import org.apache.torque.map.InheritanceMap;
/**
*/
public class TApplicationContextMapBuilder implements MapBuilder
{
/**
* The name of this class
*/
public static final String CLASS_NAME =
"com.aurel.track.persist.map.TApplicationContextMapBuilder";
/**
* The database map.
*/
private DatabaseMap dbMap = null;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return true if this DatabaseMapBuilder is built
*/
@Override
public boolean isBuilt()
{
return (dbMap != null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
@Override
public DatabaseMap getDatabaseMap()
{
return this.dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @throws TorqueException
*/
@Override
public synchronized void doBuild() throws TorqueException
{
if ( isBuilt() ) {
return;
}
dbMap = Torque.getDatabaseMap("track");
dbMap.addTable("TAPPLICATIONCONTEXT");
TableMap tMap = dbMap.getTable("TAPPLICATIONCONTEXT");
tMap.setJavaName("TApplicationContext");
tMap.setOMClass( com.aurel.track.persist.TApplicationContext.class );
tMap.setPeerClass( com.aurel.track.persist.TApplicationContextPeer.class );
tMap.setPrimaryKeyMethod(TableMap.ID_BROKER);
tMap.setPrimaryKeyMethodInfo(tMap.getName());
ColumnMap cMap = null;
// ------------- Column: OBJECTID --------------------
cMap = new ColumnMap( "OBJECTID", tMap);
cMap.setType( new Integer(0) );
cMap.setTorqueType( "INTEGER" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(true);
cMap.setNotNull(true);
cMap.setJavaName( "ObjectID" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setInheritance("false");
cMap.setPosition(1);
tMap.addColumn(cMap);
// ------------- Column: LOGGEDFULLUSERS --------------------
cMap = new ColumnMap( "LOGGEDFULLUSERS", tMap);
cMap.setType( new Integer(0) );
cMap.setTorqueType( "INTEGER" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(false);
cMap.setNotNull(false);
cMap.setJavaName( "LoggedFullUsers" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setInheritance("false");
cMap.setPosition(2);
tMap.addColumn(cMap);
// ------------- Column: LOGGEDLIMITEDUSERS --------------------
cMap = new ColumnMap( "LOGGEDLIMITEDUSERS", tMap);
cMap.setType( new Integer(0) );
cMap.setTorqueType( "INTEGER" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(false);
cMap.setNotNull(false);
cMap.setJavaName( "LoggedLimitedUsers" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setInheritance("false");
cMap.setPosition(3);
tMap.addColumn(cMap);
// ------------- Column: REFRESHCONFIGURATION --------------------
cMap = new ColumnMap( "REFRESHCONFIGURATION", tMap);
cMap.setType( new Integer(0) );
cMap.setTorqueType( "INTEGER" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(false);
cMap.setNotNull(true);
cMap.setJavaName( "RefreshConfiguration" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setDescription("In case of configuration change, this is set to the number of nodes. As each node updates its configuration, the count is decremented.");
cMap.setDefault("0");
cMap.setInheritance("false");
cMap.setPosition(4);
tMap.addColumn(cMap);
// ------------- Column: FIRSTTIME --------------------
cMap = new ColumnMap( "FIRSTTIME", tMap);
cMap.setType( new Integer(0) );
cMap.setTorqueType( "INTEGER" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(false);
cMap.setNotNull(true);
cMap.setJavaName( "FirstTime" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setDescription("When this is the first start after a version upgrade, go to site configuration");
cMap.setDefault("0");
cMap.setInheritance("false");
cMap.setPosition(5);
tMap.addColumn(cMap);
// ------------- Column: MOREPROPS --------------------
cMap = new ColumnMap( "MOREPROPS", tMap);
cMap.setType( "" );
cMap.setTorqueType( "VARCHAR" );
cMap.setUsePrimitive(false);
cMap.setPrimaryKey(false);
cMap.setNotNull(false);
cMap.setJavaName( "MoreProps" );
cMap.setAutoIncrement(false);
cMap.setProtected(false);
cMap.setDescription("This is a multi-purpose field. It contains a text in .properties format with a number of additional attributes.");
cMap.setInheritance("false");
cMap.setSize( 8191 );
cMap.setPosition(6);
tMap.addColumn(cMap);
tMap.setUseInheritance(false);
}
}
| gpl-3.0 |
spywhere/Physix | src/me/spywhere/Physix/ProgressiveDrop.java | 389 | package me.spywhere.Physix;
import org.bukkit.World;
import org.bukkit.block.Block;
public class ProgressiveDrop extends Thread {
private Physix plugin;
Block block;
World world;
protected ProgressiveDrop(Physix instance,Block block,World world)
{
plugin=instance;
this.block=block;
this.world=world;
}
public void run() {
plugin.applyStepPhysix(block,world);
}
}
| gpl-3.0 |
Noterik/smt_euscreenpublicationbuilderapp | src/org/springfield/lou/application/types/Bookmark.java | 1729 | package org.springfield.lou.application.types;
import org.springfield.lou.json.JSONField;
import org.springfield.lou.json.JSONSerializable;
public class Bookmark extends JSONSerializable{
private String id;
private String videoId;
private String title;
private String provider;
private String video;
private String screenshot;
private boolean isPublic;
@JSONField(field = "screenshot")
public String getScreenshot() {
return screenshot;
}
public void setScreenshot(String screenshot) {
this.screenshot = screenshot;
}
@JSONField(field = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JSONField(field = "videoId")
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
@JSONField(field = "video")
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
@JSONField(field = "isPublic")
public boolean getIsPublic() {
return this.isPublic;
}
public void setIsPublic(boolean isPublic) {
this.isPublic = isPublic;
}
@JSONField(field = "title")
public String getTitle(){
return this.title;
}
public void setTitle(String title){
this.title = title;
}
@JSONField(field = "provider")
public String getProvider(){
return this.provider;
}
public void setProvider(String provider){
this.provider = provider;
}
public Bookmark(String id, String video_id, String video, String screenshot, String title, String provider, boolean isPublic) {
setId(id);
setVideoId(videoId);
setVideo(video);
setScreenshot(screenshot);
setIsPublic(isPublic);
setTitle(title);
setProvider(provider);
}
}
| gpl-3.0 |
dmfs/jdav | src/org/dmfs/dav/rfc4791/filter/PropFilter.java | 5322 | /*
* Copyright (C) 2014 Marten Gajda <marten@dmfs.org>
*
* 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 org.dmfs.dav.rfc4791.filter;
import java.io.IOException;
import org.dmfs.dav.FilterBase;
import org.dmfs.xmlobjects.ElementDescriptor;
import org.dmfs.xmlobjects.QualifiedName;
import org.dmfs.xmlobjects.builder.AbstractObjectBuilder;
import org.dmfs.xmlobjects.serializer.SerializerContext;
import org.dmfs.xmlobjects.serializer.SerializerException;
import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter;
import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
/**
* A filter that matches based on the value or presence of a specific property.
*
* @author Marten Gajda <marten@dmfs.org>
*/
public final class PropFilter extends StructuredFilter
{
private final static QualifiedName ATTRIBUTE_NAME = QualifiedName.get("name");
public final static ElementDescriptor<PropFilter> DESCRIPTOR = ElementDescriptor.register(QualifiedName.get(NAMESPACE, "prop-filter"),
new AbstractObjectBuilder<PropFilter>()
{
@Override
public void writeAttributes(ElementDescriptor<PropFilter> descriptor, PropFilter object, IXmlAttributeWriter attributeWriter,
SerializerContext context) throws SerializerException, IOException
{
attributeWriter.writeAttribute(ATTRIBUTE_NAME, object.name, context);
};
@SuppressWarnings("unchecked")
@Override
public void writeChildren(ElementDescriptor<PropFilter> descriptor, PropFilter object, IXmlChildWriter childWriter, SerializerContext context)
throws SerializerException, IOException
{
if (object.isNotDefined)
{
childWriter.writeChild(FILTER_ISNOTDEFINED, null, context);
}
else
{
if (object.timeRange != null)
{
childWriter.writeChild(TimeRange.DESCRIPTOR, object.timeRange, context);
}
else if (object.textMatch != null)
{
childWriter.writeChild(TextMatch.DESCRIPTOR, object.textMatch, context);
}
if (object.filters != null)
{
for (ParamFilter filter : object.filters)
{
childWriter.writeChild((ElementDescriptor<ParamFilter>) filter.getElementDescriptor(), filter, context);
}
}
}
};
});
public final String name;
public final boolean isNotDefined;
public final TimeRange timeRange;
public final TextMatch textMatch;
public final ParamFilter[] filters;
/**
* Creates a filter that matches the presence of a specific property.
*
* @param name
* The name of the property.
*/
public PropFilter(String name)
{
this(name, false);
}
/**
* Creates a filter that matches the presence or absence of a specific property.
*
* @param name
* The name of the property.
* @param isNotDefined
* <code>true</code> to match when the property is absent, <code>false</code> to match when it's present.
*/
public PropFilter(String name, boolean isNotDefined)
{
this.name = name;
this.isNotDefined = isNotDefined;
this.timeRange = null;
this.textMatch = null;
this.filters = null;
}
/**
* Creates a filter that matches a property by a list of {@link ParamFilter}s.
*
* @param name
* The name of the property to match.
* @param filters
* Optional list of {@link ParamFilter}s.
*/
public PropFilter(String name, ParamFilter... filters)
{
this(name, (TextMatch) null, filters);
}
/**
* Creates a filter that matches a property by a specific time range and optionally a list of {@link ParamFilter}s.
*
* @param name
* The name of the property to match.
* @param timeRange
* The {@link TimeRange} to match.
* @param filters
* Optional list of {@link ParamFilter}s.
*/
public PropFilter(String name, TimeRange timeRange, ParamFilter... filters)
{
this.name = name;
this.isNotDefined = false;
this.timeRange = timeRange;
this.textMatch = null;
this.filters = filters;
}
/**
* Creates a filter that matches a property by a specific text value and optionally a list of {@link ParamFilter}s.
*
* @param name
* The name of the property to match.
* @param textMatch
* The text filter.
* @param filters
* Optional list of {@link ParamFilter}s.
*/
public PropFilter(String name, TextMatch textMatch, ParamFilter... filters)
{
this.name = name;
this.isNotDefined = false;
this.timeRange = null;
this.textMatch = textMatch;
this.filters = filters;
}
@Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
{
return DESCRIPTOR;
}
}
| gpl-3.0 |
jmrunge/cipres4 | src/main/java/ar/com/zir/cipres/ui/SkorpioViewImpl.java | 501 | /*
* 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 ar.com.zir.cipres.ui;
import ar.com.zir.skorpio.core.ui.AbstractSkorpioView;
import ar.com.zir.skorpio.core.ui.SkorpioView;
/**
*
* @author jmrunge
*/
public class SkorpioViewImpl extends AbstractSkorpioView implements SkorpioView {
@Override
public void showUserData(boolean show) {}
}
| gpl-3.0 |
vdmtools/vdmtools | spec/java2vdm/javaapi/lib/jp/vdmtools/VDM/jdk/JavaSqlConnection.java | 1915 | package jp.vdmtools.VDM.jdk;
import jp.vdmtools.VDM.CGException;
public interface JavaSqlConnection extends Nullable {
public static final Integer TRANSACTION_uNONE = Integer.valueOf(0);
public static final Integer TRANSACTION_uREAD_uUNCOMMITTED = Integer.valueOf(0);
public static final Integer TRANSACTION_uREAD_uCOMMITTED = Integer.valueOf(0);
public static final Integer TRANSACTION_uREPEATABLE_uREAD = Integer.valueOf(0);
public static final Integer TRANSACTION_uSERIALIZABLE = Integer.valueOf(0);
abstract public void close() throws CGException ;
abstract public void commit()throws CGException ;
abstract public Boolean isClosed()throws CGException ;
abstract public void rollback()throws CGException ;
abstract public JavaLangString getCatalog()throws CGException ;
abstract public JavaUtilMap getTypeMap()throws CGException ;
abstract public Boolean isReadOnly()throws CGException ;
abstract public void setReadOnly(final Boolean readOnly)throws CGException ;
abstract public void clearWarnings()throws CGException ;
abstract public Boolean getAutoCommit()throws CGException ;
abstract public void setAutoCommit(final Boolean autoCommit)throws CGException ;
abstract public JavaSqlStatement createStatement()throws CGException ;
abstract public JavaLangString nativeSQL(final JavaLangString sql)throws CGException ;
abstract public JavaSqlStatement createStatement(final Integer resultSetType,
final Integer resultSetConcurrency)throws CGException ;
abstract public void setCatalog(final JavaLangString catalog)throws CGException ;
abstract public Integer getTransactionIsolation()throws CGException ;
abstract public void setTransactionIsolation(final Integer level)throws CGException ;
}
| gpl-3.0 |
freaxmind/miage-m1 | genie-logiciel/Sprint 2/src/components/CVSParser.java | 4664 | package components;
import au.com.bytecode.opencsv.CSVReader;
import controllers.Parser;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Map;
import models.Node;
import models.ParseException;
import models.Link;
import models.Link.Direction;
import models.Relation;
/**
* Implementation of the parser inteface
*
* @author phongphong
*/
public class CSVParser implements Parser {
private CSVReader reader;
@Override
public void load(InputStream input) throws IOException {
this.reader = new CSVReader(new InputStreamReader(input), ';');
}
/**
* Convert a string to a Direction
*
* @param string direction
* @return direction enum
*/
public Direction stringToDirection(String direction) {
switch (direction) {
case "both":
return Direction.BOTH;
case "in":
return Direction.IN;
case "out":
return Direction.OUT;
default:
return Direction.BOTH;
}
}
/**
* This function construct a link from a line read in the file
*
* @param t_read CSVParser transforms each line read into a table of String
* @return link
*/
public Link getLinkFromFile(String[] t_read) throws ParseException {
if (t_read.length < 4) {
throw new ParseException("Not enough arguments in CSV line");
}
String name = t_read[1];
Direction direction = this.stringToDirection(t_read[3]);
//System.out.println(t_read.length);
//System.out.println(t_read[0]+" "+t_read[1]+" "+t_read[2]+" "+t_read[3]);
if (t_read.length > 4) { // with attributes
Map<String, String> attrs = new HashMap<>();
String[] columns = t_read[4].split("[|]");
for (String col : columns) {
String[] words = col.split("=");
if (words.length != 2) {
throw new ParseException("Attribute is not formatted correctly: " + col);
}
attrs.put(words[0], words[1]);
}
return new Link(name, direction, attrs);
} else { // without attributes
return new Link(name, direction);
}
}
public void addRelationToChildOfRoot(Node root, String source, String target, Link link) {
LinkedList<Node> listChild = (LinkedList<Node>) root.getChilds();
for (int i = 0; i < listChild.size(); i++) {
if (listChild.get(i).toString().compareTo(source) == 0) {
listChild.get(i).addDirectAndMirrorRelation(link, new Node(target));
}
}
}
/**
* This function parse a CSV file in to a graph
*/
@Override
public Node parse(Node root, Link rootLink) throws ParseException {
Link link;
String[] t_read;
Node source;
Node target;
int indexSource;
int indexTarget;
LinkedList<Node> listChild;
try {
reader.readNext(); // pass the CSV header
// for each line in the CSV file
while ((t_read = reader.readNext()) != null) {
// add source node to root if it doesn't exist, the index of the node will be the size of the list
// if it's existed, we recover the index of this node in the root
if (root.getByChildName(t_read[0]) == null) {
source = new Node(t_read[0]);
root.addDirectAndMirrorRelation(rootLink, source);
}
// add target node to root if it doesn't exist, the index of the node will be the size of the list
// if it's existed, we recover the index of this node in the root
if (root.getByChildName(t_read[2]) == null) {
target = new Node(t_read[2]);
root.addDirectAndMirrorRelation(rootLink, target);
}
// add the relation to source
link = this.getLinkFromFile(t_read);
// source.addDirectAndMirrorRelation(link, target);
root.getByChildName(t_read[0]).addDirectAndMirrorRelation(link, root.getByChildName(t_read[2]));
}
} catch (IOException ex) {
throw new ParseException("Error while reading CSV file: " + ex.getMessage());
}
return root;
}
} | gpl-3.0 |
emfinfo/basiclib | src/test/java/tests/MathLibTest.java | 3297 | package tests;
import ch.jcsinfo.math.MathLib;
import ch.jcsinfo.system.StackTracer;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* Test des méthodes principales de la classe correspondante.
*
* @author jcstritt
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MathLibTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
System.out.println();
}
@Test
public void test01_roundValue() {
StackTracer.printCurrentTestMethod();
final double delta = 1e-15;
final float p1 = 0.25f;
final double v1a = 4.62499999;
final double v1b = 4.625;
final double r1a = 4.50;
final double r1b = 4.75;
final float p2 = 0.5f;
final double v2a = 4.74999999;
final double v2b = 4.75;
final double r2a = 4.5;
final double r2b = 5.0;
final float p3 = 10f;
final double v3a = 104.499999;
final double v3b = 105;
final double r3a = 100;
final double r3b = 110;
final float p4 = 0.05f;
final double v4a = 104.499999;
final double v4b = 155;
final double r4a = 104.50;
final double r4b = 155;
System.out.println(" - " + v1a + " rounded to " + p1 + " = " + MathLib.roundDoubleValue(v1a, p1));
System.out.println(" - " + v1b + " rounded to " + p1 + " = " + MathLib.roundDoubleValue(v1b, p1));
System.out.println(" - " + v2a + " rounded to " + p2 + " = " + MathLib.roundDoubleValue(v2a, p2));
System.out.println(" - " + v2b + " rounded to " + p2 + " = " + MathLib.roundDoubleValue(v2b, p2));
System.out.println(" - " + v3a + " rounded to " + p3 + " = " + MathLib.roundDoubleValue(v3a, p3));
System.out.println(" - " + v3b + " rounded to " + p3 + " = " + MathLib.roundDoubleValue(v3b, p3));
System.out.println(" - " + v4a + " rounded to " + p4 + " = " + MathLib.convertToBigDecimal(v4a, p4));
System.out.println(" - " + v4b + " rounded to " + p4 + " = " + MathLib.convertToBigDecimal(v4b, p4));
assertEquals(MathLib.roundDoubleValue(v1a, p1), r1a, delta);
assertEquals(MathLib.roundDoubleValue(v1b, p1), r1b, delta);
assertEquals(MathLib.roundDoubleValue(v2a, p2), r2a, delta);
assertEquals(MathLib.roundDoubleValue(v2b, p2), r2b, delta);
assertEquals(MathLib.roundDoubleValue(v3a, p3), r3a, delta);
assertEquals(MathLib.roundDoubleValue(v3b, p3), r3b, delta);
assertEquals(MathLib.convertToBigDecimal(v4a, p4).doubleValue(), r4a, delta);
assertEquals(MathLib.convertToBigDecimal(v4b, p4).doubleValue(), r4b, delta);
}
@Test
public void test02_columnNameToIndex() {
StackTracer.printCurrentTestMethod();
String t[] = {"A", "Z", "AA", "FB"};
double expected[] = {0, 25, 26, 157};
int results[] = new int[4];
boolean ok[] = new boolean[4];
// on teste les 4 exemples
for (int i = 0; i < ok.length; i++) {
results[i] = MathLib.columnNameToIndex(t[i]);
ok[i] = results[i] == expected[i];
System.out.println(" - columnNameToIndex("+t[i]+") = "+ results[i]);
}
assertTrue(ok[0] && ok[1] && ok[2]);
}
}
| gpl-3.0 |
gunnarfloetteroed/java | experimental/src/main/java/stockholm/saleem/DistanceCalculation.java | 2128 | /*
* Copyright 2018 Mohammad Saleem
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* contact: salee@kth.se
*
*/
package stockholm.saleem;
/**
* Class to calculate distance between two points in different coordinate systems.
*
* @author Mohammad Saleem
*/
public class DistanceCalculation {
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
public static double calculateDistanceLatLon(double userLat, double userLng, double venueLat, double venueLng) {
double latDistance = Math.toRadians(userLat - venueLat);
double lngDistance = Math.toRadians(userLng - venueLng);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(userLat)) * Math.cos(Math.toRadians(venueLat))
* Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return AVERAGE_RADIUS_OF_EARTH * c;
}
public static double calculateDistanceUTM (double x, double y, double x1, double y1) {
double deltaX = x1 - x;
double deltaY = y1 - y;
double result = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
return result;
}
public static void main(String[] args) {
System.out.println("LatLong Distance: " + calculateDistanceLatLon(18.0368913403574, 59.3982038728158, 17.9426683336417, 59.4029594411987));
System.out.println("UTM Distance: " + calculateDistanceUTM(331768.41000000003, 6588139.140000001, 667048.16, 6588616.87));
}
}
| gpl-3.0 |
freddy-realirm/BPMNEditor-For-Protege-Essential | src/org/yaoqiang/bpmn/editor/dialog/panels/ItemDefinitionPanel.java | 4090 | package org.yaoqiang.bpmn.editor.dialog.panels;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import org.yaoqiang.bpmn.editor.dialog.XMLCheckboxPanel;
import org.yaoqiang.bpmn.editor.dialog.XMLComboPanel;
import org.yaoqiang.bpmn.editor.dialog.BPMNPanelContainer;
import org.yaoqiang.bpmn.editor.dialog.XMLTextPanel;
import org.yaoqiang.bpmn.editor.dialog.XMLPanel;
import org.yaoqiang.bpmn.editor.view.BPMNGraph;
import org.yaoqiang.bpmn.model.BPMNModelUtils;
import org.yaoqiang.bpmn.model.elements.XMLElement;
import org.yaoqiang.bpmn.model.elements.core.common.FlowElements;
import org.yaoqiang.bpmn.model.elements.core.common.ItemDefinition;
import org.yaoqiang.bpmn.model.elements.core.foundation.BaseElement;
import org.yaoqiang.bpmn.model.elements.data.DataObject;
import org.yaoqiang.bpmn.model.elements.data.DataObjectReference;
import com.mxgraph.model.mxCell;
/**
* ItemDefinitionPanel
*
* @author Shi Yaoqiang(shi_yaoqiang@yahoo.com)
*/
public class ItemDefinitionPanel extends XMLPanel {
private static final long serialVersionUID = 1L;
protected XMLComboPanel kindPanel;
protected XMLComboPanel structureRefPanel;
protected XMLPanel isCollectionPanel;
public ItemDefinitionPanel(BPMNPanelContainer pc, ItemDefinition owner) {
super(pc, owner);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
List<String> choices = new ArrayList<String>();
choices.add("Information");
choices.add("Physical");
kindPanel = new XMLComboPanel(pc, owner.get("itemKind"), null, choices, false, false, true);
isCollectionPanel = new XMLCheckboxPanel(pc, owner.get("isCollection"), false);
JPanel idKindPanel = new JPanel();
idKindPanel.setLayout(new BoxLayout(idKindPanel, BoxLayout.X_AXIS));
idKindPanel.add(new XMLTextPanel(pc, owner.get("id"), false));
idKindPanel.add(Box.createHorizontalGlue());
idKindPanel.add(kindPanel);
this.add(idKindPanel);
structureRefPanel = new XMLComboPanel(pc, owner.get("structureRef"), null, BPMNModelUtils.getDefinitions(owner).getTypes(), false, true, true);
JPanel collectionTypePanel = new JPanel();
collectionTypePanel.setLayout(new BoxLayout(collectionTypePanel, BoxLayout.X_AXIS));
collectionTypePanel.add(structureRefPanel);
collectionTypePanel.add(Box.createHorizontalGlue());
collectionTypePanel.add(isCollectionPanel);
this.add(collectionTypePanel);
}
public void saveObjects() {
if (!structureRefPanel.isEmpty()) {
kindPanel.saveObjects();
structureRefPanel.saveObjects();
boolean isCollectionOld = ((ItemDefinition)owner).isCollection();
isCollectionPanel.saveObjects();
boolean isCollectionNew = ((ItemDefinition)owner).isCollection();
if (isCollectionOld != isCollectionNew) {
BPMNGraph graph = getGraphComponent().getGraph();
for (XMLElement o : BPMNModelUtils.getAllDataObjects(BPMNModelUtils.getDefinitions(getOwner()),((ItemDefinition)owner).getId())) {
BaseElement data = (BaseElement) o;
boolean isColOld = Boolean.parseBoolean(data.get("isCollection").toValue());
data.set("isCollection", String.valueOf(isCollectionNew));
boolean isColNew = Boolean.parseBoolean(data.get("isCollection").toValue());
if (isColOld != isColNew) {
String style = " ";
if (isColNew) {
style = "/org/yaoqiang/graph/images/marker_multiple.png";
}
String dataId = data.getId();
if (data instanceof DataObject) {
for (DataObjectReference dataObjectRef : ((FlowElements)data.getParent()).getDataObjectRefs(dataId)) {
mxCell cell = (mxCell) graph.getModel().getCell(dataObjectRef.getId());
graph.setCellStyles("loopImage", style, new Object[] { cell });
}
} else {
mxCell cell = (mxCell) graph.getModel().getCell(dataId);
graph.setCellStyles("loopImage", style, new Object[] { cell });
}
}
}
graph.refresh();
}
super.saveObjects();
}
}
}
| gpl-3.0 |
yyamano/RESTx | src/java/org/mulesoft/restx/util/JsonProcessor.java | 5181 | /*
* RESTx: Sane, simple and effective data publishing and integration.
*
* Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mulesoft.restx.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* A service class that provides some static JSON processing methods.
*
*/
public class JsonProcessor
{
/**
* Serialize a complex object to JSON.
*
* @param obj The object to be serialized. The object has to be a string, number
* or boolean, or a HashMap and/or ArrayList consisting of those basic
* types or further HashMaps and ArrayLists.
*
* @return The JSON string representation of the object.
*/
public static String dumps(Object obj) throws JSONException
{
Class oclass = obj.getClass();
if (oclass == Map.class) {
// The JSON library offers a specific class for maps...
return (new JSONObject(obj)).toString();
}
else if (oclass == Collection.class) {
// ... and another for arrays.
return (new JSONArray(obj)).toString();
}
else {
// But all other (normal) types are different. For some reason
// the JSON library doesn't seem to handle this well.
// So, we solve the issue by putting this other type of object
// into a list, use JSONArray(), convert to string and strip off
// the leading and trailing '[' and ']'. Then we have the proper
// JSON-stype string representation of that type, which we can
// return. This is extremely kludgy. One of these days we might
// get around to fix this.
//
ArrayList al = new ArrayList();
al.add(obj);
String buf = (new JSONArray(al)).toString();
return buf.substring(1, buf.length() - 1);
}
}
/**
* Deserializes a JSON string into a complex object.
*
* @param str A JSON string, representing a complex object.
*
* @return A complex object, which will be a string, number or boolean, or a
* map or collection containing any of the other types.
*/
public static Object loads(String str) throws JSONException
{
JSONTokener t = new JSONTokener(str);
Object v = t.nextValue();
if (v.getClass() == JSONArray.class) {
v = jsonListTranscribe((JSONArray) v);
}
else if (v.getClass() == JSONObject.class) {
v = jsonObjectTranscribe((JSONObject) v);
}
return v;
}
/**
* Transcribes a JSONObject into a map.
*
* @param obj Instance of {@link JSONObject}.
* @return A string representing the JSON serialization.
* @throws JSONException
*/
protected static Map<?,?> jsonObjectTranscribe(JSONObject obj) throws JSONException
{
HashMap d = new HashMap();
String[] nameArray = JSONObject.getNames(obj);
if (nameArray != null) {
for (String name : JSONObject.getNames(obj)) {
Object o = obj.get(name);
if (o.getClass() == JSONArray.class) {
o = jsonListTranscribe((JSONArray) o);
}
else if (o.getClass() == JSONObject.class) {
o = jsonObjectTranscribe((JSONObject) o);
}
d.put(name, o);
}
}
return d;
}
/**
* Transcribes a JSONArray object into a Collection object.
*
* @param arr A {@link JSONArray} instance.
* @return A string representing the JSON serialization.
* @throws JSONException
*/
protected static Collection<?> jsonListTranscribe(JSONArray arr) throws JSONException
{
ArrayList l = new ArrayList();
for (int i = 0; i < arr.length(); ++i) {
Object o = arr.get(i);
if (o.getClass() == JSONArray.class) {
o = jsonListTranscribe((JSONArray) o);
}
else if (o.getClass() == JSONObject.class) {
o = jsonObjectTranscribe((JSONObject) o);
}
l.add(o);
}
return l;
}
}
| gpl-3.0 |
alexholehouse/SBMLIntegrator | libsbml-5.0.0/src/bindings/java/test/org/sbml/libsbml/test/annotation/TestDate_newSetters.java | 11342 | /*
* @file TestDate_newSetters.java
* @brief Date unit tests
*
* @author Akiya Jouraku (Java conversion)
* @author Sarah Keating
*
* $Id: TestDate_newSetters.java 11532 2010-07-22 17:36:30Z mhucka $
* $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/bindings/java/test/org/sbml/libsbml/test/annotation/TestDate_newSetters.java $
*
* ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
*
* DO NOT EDIT THIS FILE.
*
* This file was generated automatically by converting the file located at
* src/annotation/test/TestDate_newSetters.c
* using the conversion program dev/utilities/translateTests/translateTests.pl.
* Any changes made here will be lost the next time the file is regenerated.
*
* -----------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright 2005-2010 California Institute of Technology.
* Copyright 2002-2005 California Institute of Technology and
* Japan Science and Technology Corporation.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* -----------------------------------------------------------------------------
*/
package org.sbml.libsbml.test.annotation;
import org.sbml.libsbml.*;
import java.io.File;
import java.lang.AssertionError;
public class TestDate_newSetters {
static void assertTrue(boolean condition) throws AssertionError
{
if (condition == true)
{
return;
}
throw new AssertionError();
}
static void assertEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
return;
}
else if ( (a == null) || (b == null) )
{
throw new AssertionError();
}
else if (a.equals(b))
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
throw new AssertionError();
}
else if ( (a == null) || (b == null) )
{
return;
}
else if (a.equals(b))
{
throw new AssertionError();
}
}
static void assertEquals(boolean a, boolean b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(boolean a, boolean b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
static void assertEquals(int a, int b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(int a, int b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
public void test_Date_setDateAsString()
{
Date date = new Date(2007,10,23,14,15,16,1,3,0);
assertTrue( date != null );
int i = date.setDateAsString( "20081-12-30T12:15:45+02:00");
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue(date.getDateAsString().equals( "2007-10-23T14:15:16+03:00"));
i = date.setDateAsString( "200-12-30T12:15:45+02:00");
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue(date.getDateAsString().equals( "2007-10-23T14:15:16+03:00"));
i = date.setDateAsString("");
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue(date.getDateAsString().equals( "2000-01-01T00:00:00Z"));
i = date.setDateAsString( "2008-12-30T12:15:45+02:00");
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getYear() == 2008 );
assertTrue( date.getMonth() == 12 );
assertTrue( date.getDay() == 30 );
assertTrue( date.getHour() == 12 );
assertTrue( date.getMinute() == 15 );
assertTrue( date.getSecond() == 45 );
assertTrue( date.getSignOffset() == 1 );
assertTrue( date.getHoursOffset() == 2 );
assertTrue( date.getMinutesOffset() == 0 );
date = null;
}
public void test_Date_setDay()
{
Date date = new Date(2005,2,12,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setDay(29);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getDay() == 1 );
i = date.setDay(31);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getDay() == 1 );
i = date.setDay(15);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getDay() == 15 );
assertTrue(date.getDateAsString().equals( "2005-02-15T12:15:45+02:00"));
date = null;
}
public void test_Date_setHour()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setHour(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getHour() == 0 );
i = date.setHour(12121);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getHour() == 0 );
i = date.setHour(9);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getHour() == 9 );
assertTrue(date.getDateAsString().equals( "2005-12-30T09:15:45+02:00"));
date = null;
}
public void test_Date_setHoursOffset()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setHoursOffset(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getHoursOffset() == 0 );
i = date.setHoursOffset(11);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getHoursOffset() == 11 );
assertTrue(date.getDateAsString().equals( "2005-12-30T12:15:45+11:00"));
date = null;
}
public void test_Date_setMinute()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setMinute(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMinute() == 0 );
i = date.setMinute(12121);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMinute() == 0 );
i = date.setMinute(32);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getMinute() == 32 );
assertTrue(date.getDateAsString().equals( "2005-12-30T12:32:45+02:00"));
date = null;
}
public void test_Date_setMinutesOffset()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setMinutesOffset(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMinutesOffset() == 0 );
i = date.setMinutesOffset(60);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMinutesOffset() == 0 );
i = date.setMinutesOffset(45);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getMinutesOffset() == 45 );
assertTrue(date.getDateAsString().equals( "2005-12-30T12:15:45+02:45"));
date = null;
}
public void test_Date_setMonth()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setMonth(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMonth() == 1 );
i = date.setMonth(12121);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getMonth() == 1 );
i = date.setMonth(11);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getMonth() == 11 );
assertTrue(date.getDateAsString().equals( "2005-11-30T12:15:45+02:00"));
date = null;
}
public void test_Date_setSecond()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setSecond(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getSecond() == 0 );
i = date.setSecond(12121);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getSecond() == 0 );
i = date.setSecond(32);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getSecond() == 32 );
assertTrue(date.getDateAsString().equals( "2005-12-30T12:15:32+02:00"));
date = null;
}
public void test_Date_setYear()
{
Date date = new Date(2005,12,30,12,15,45,1,2,0);
assertTrue( date != null );
int i = date.setYear(434);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getYear() == 2000 );
i = date.setYear(12121);
assertTrue( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE );
assertTrue( date.getYear() == 2000 );
i = date.setYear(2008);
assertTrue( i == libsbml.LIBSBML_OPERATION_SUCCESS );
assertTrue( date.getYear() == 2008 );
assertTrue(date.getDateAsString().equals( "2008-12-30T12:15:45+02:00"));
date = null;
}
/**
* Loads the SWIG-generated libSBML Java module when this class is
* loaded, or reports a sensible diagnostic message about why it failed.
*/
static
{
String varname;
String shlibname;
if (System.getProperty("mrj.version") != null)
{
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
shlibname = "libsbmlj.jnilib and/or libsbml.dylib";
}
else
{
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
shlibname = "libsbmlj.so and/or libsbml.so";
}
try
{
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (SecurityException e)
{
e.printStackTrace();
System.err.println("Could not load the libSBML library files due to a"+
" security exception.\n");
System.exit(1);
}
catch (UnsatisfiedLinkError e)
{
e.printStackTrace();
System.err.println("Error: could not link with the libSBML library files."+
" It is likely\nyour " + varname +
" environment variable does not include the directories\n"+
"containing the " + shlibname + " library files.\n");
System.exit(1);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.err.println("Error: unable to load the file libsbmlj.jar."+
" It is likely\nyour -classpath option and CLASSPATH" +
" environment variable\n"+
"do not include the path to libsbmlj.jar.\n");
System.exit(1);
}
}
}
| gpl-3.0 |
atf4j/atf4j | atf4j-data/src/main/java/net/atf4j/data/ExpectedDataInterface.java | 131 |
package net.atf4j.data;
/**
* The Interface to the ExpectedData class.
*/
public interface ExpectedDataInterface {
}
| gpl-3.0 |
JayTea173/saiyancraft | SaiyanCraft/src/main/java/com/jaynopp/saiyancraft/input/KeyInputHandler.java | 1210 | package com.jaynopp.saiyancraft.input;
import com.jaynopp.saiyancraft.capabilities.saiyanbattler.DefaultSaiyanBattler;
import com.jaynopp.saiyancraft.gui.SaiyanPlayerStatusGui;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
public class KeyInputHandler {
@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) {
if(KeyBindings.openSaiyanGUI.isPressed()){
Minecraft.getMinecraft().displayGuiScreen(new SaiyanPlayerStatusGui());
System.out.println("You have " + DefaultSaiyanBattler.Get(Minecraft.getMinecraft().player).GetMoves().size() + " moves");
}
}
@SubscribeEvent
public void onMouseInput (InputEvent.MouseInputEvent event){
for (StatedKeyBinding i : StatedKeyBinding.registered){
boolean pressed = i.binding.isKeyDown();
if (pressed && !i.pressed)
i.eventHandler.OnDown();
if (!pressed && i.pressed)
i.eventHandler.OnUp();
i.pressed = pressed;
if (i.pressed)
i.eventHandler.OnPressed();
}
}
}
| gpl-3.0 |
qt-haiku/LibreOffice | scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java | 9601 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package com.sun.star.script.framework.io;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import com.sun.star.uno.XComponentContext;
import com.sun.star.ucb.XSimpleFileAccess;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.io.XTruncate;
import com.sun.star.script.framework.log.LogUtils;
import com.sun.star.script.framework.provider.PathUtils;
public class UCBStreamHandler extends URLStreamHandler {
public final static String separator = "/ucb/";
private XComponentContext m_xContext = null;
private XMultiComponentFactory m_xMultiComponentFactory = null;
private XSimpleFileAccess m_xSimpleFileAccess = null;
private HashMap<String,InputStream> m_jarStreamMap = new HashMap<String,InputStream>(12);
public static String m_ucbscheme;
public UCBStreamHandler( XComponentContext ctxt, String scheme, XSimpleFileAccess xSFA )
{
LogUtils.DEBUG( "UCBStreamHandler ctor, scheme = " + scheme );
this.m_xContext = ctxt;
UCBStreamHandler.m_ucbscheme = scheme;
this.m_xSimpleFileAccess = xSFA;
}
public void parseURL(URL url, String spec, int start, int limit) {
LogUtils.DEBUG("**XUCBStreamHandler, parseURL: " + url + " spec: " + spec + " start: " + start + " limit: " + limit );
String file = url.getFile();
if (file == null)
file = spec.substring(start, limit);
else
file += spec.substring(start, limit);
LogUtils.DEBUG("**For scheme = " + m_ucbscheme );
LogUtils.DEBUG("**Setting path = " + file );
setURL(url, m_ucbscheme, null, -1, null, null, file, null, null);
}
public URLConnection openConnection(URL u) throws IOException {
return new UCBConnection(u);
}
private class UCBConnection extends URLConnection {
public UCBConnection(URL url) {
super(url);
}
public void connect() {
}
public InputStream getInputStream() throws IOException {
LogUtils.DEBUG("UCBConnectionHandler GetInputStream on " + url );
String sUrl = url.toString();
if (sUrl.lastIndexOf(separator) == -1) {
LogUtils.DEBUG("getInputStream straight file load" );
return getFileStreamFromUCB(sUrl);
}
else {
String path = sUrl.substring(0, sUrl.lastIndexOf(separator) );
String file = sUrl.substring(
sUrl.lastIndexOf(separator) + separator.length());
LogUtils.DEBUG("getInputStream, load of file from another file eg. " + file + " from " + path );
return getUCBStream(file, path);
}
}
public OutputStream getOutputStream() throws IOException {
LogUtils.DEBUG("UCBConnectionHandler getOutputStream on " + url );
OutputStream os = null;
try
{
String sUrl = url.toString();
if ( !( sUrl.lastIndexOf(separator) == -1) ) {
String path = sUrl.substring(0, sUrl.lastIndexOf(separator));
String file = sUrl.substring(
sUrl.lastIndexOf(separator) + separator.length());
if ( m_xSimpleFileAccess.isReadOnly( path ) )
{
throw new java.io.IOException("File is read only");
}
LogUtils.DEBUG("getOutputStream, create o/p stream for file eg. " + path );
// we will only deal with simple file write
XOutputStream xos = m_xSimpleFileAccess.openFileWrite( path );
XTruncate xtrunc = UnoRuntime.queryInterface( XTruncate.class, xos );
if ( xtrunc != null )
{
xtrunc.truncate();
}
os = new XOutputStreamWrapper( xos );
}
if ( os == null )
{
throw new IOException("Failed to get OutputStream for " + sUrl );
}
}
catch ( com.sun.star.ucb.CommandAbortedException cae )
{
LogUtils.DEBUG("caught exception: " + cae.toString() + " getting writable stream from " + url );
throw new IOException( cae.toString() );
}
catch ( com.sun.star.uno.Exception e )
{
LogUtils.DEBUG("caught unknown exception: " + e.toString() + " getting writable stream from " + url );
throw new IOException( e.toString() );
}
return os;
}
}
private InputStream getUCBStream(String file, String path)
throws IOException
{
InputStream is = null;
InputStream result = null;
try {
if (path.endsWith(".jar")) {
is = m_jarStreamMap.get(path);
if (is == null) {
is = getFileStreamFromUCB(path);
m_jarStreamMap.put(path, is);
}
else {
try {
is.reset();
}
catch (IOException e) {
is.close();
is = getFileStreamFromUCB(path);
m_jarStreamMap.put(path, is);
}
}
result = getFileStreamFromJarStream(file, is);
}
else
{
String fileUrl = PathUtils.make_url(path,file);
result = getFileStreamFromUCB(fileUrl);
}
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException ioe) {
LogUtils.DEBUG("Caught exception closing stream: " +
ioe.getMessage());
}
}
}
return result;
}
private InputStream getFileStreamFromJarStream(String file, InputStream is)
throws IOException
{
ZipInputStream zis = null;
ZipEntry entry = null;
boolean found = false;
zis = new ZipInputStream(is);
while (zis.available() != 0) {
entry = zis.getNextEntry();
if (entry.getName().equals(file)) {
return zis;
}
}
return null;
}
private InputStream getFileStreamFromUCB(String path)
throws IOException
{
InputStream result = null;
XInputStream xInputStream = null;
try {
LogUtils.DEBUG("Trying to read from " + path );
xInputStream = m_xSimpleFileAccess.openFileRead(path);
LogUtils.DEBUG("sfa appeared to read file " );
byte[][] inputBytes = new byte[1][];
int ln = 0;
int sz = m_xSimpleFileAccess.getSize(path);
// TODO don't depend on result of available() or size()
// just read stream 'till complete
if ( sz == 0 )
{
if ( xInputStream.available() > 0 )
{
sz = xInputStream.available();
}
}
LogUtils.DEBUG("size of file " + path + " is " + sz );
LogUtils.DEBUG("available = " + xInputStream.available() );
inputBytes[0] = new byte[sz];
ln = xInputStream.readBytes(inputBytes, sz);
if (ln != sz) {
throw new IOException(
"Failed to read " + sz + " bytes from XInputStream");
}
result = new ByteArrayInputStream(inputBytes[0]);
}
catch (com.sun.star.io.IOException ioe) {
LogUtils.DEBUG("caught exception " + ioe );
throw new IOException(ioe.getMessage());
}
catch (com.sun.star.uno.Exception e) {
LogUtils.DEBUG("caught exception " + e );
throw new IOException(e.getMessage());
}
finally
{
if (xInputStream != null) {
try {
xInputStream.closeInput();
}
catch (Exception e2) {
LogUtils.DEBUG(
"Error closing XInputStream:" + e2.getMessage());
}
}
}
return result;
}
private String convertClassNameToFileName(String name) {
return name.replace('.', File.separatorChar) + ".class";
}
}
| gpl-3.0 |
cooked/NDT | sc.ndt.editor.fast.fst/src-gen/sc/ndt/editor/fast/fastfst/bEdgeDOF.java | 2184 | /**
*/
package sc.ndt.editor.fast.fastfst;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>bEdge DOF</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link sc.ndt.editor.fast.fastfst.bEdgeDOF#isValue <em>Value</em>}</li>
* <li>{@link sc.ndt.editor.fast.fastfst.bEdgeDOF#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see sc.ndt.editor.fast.fastfst.FastfstPackage#getbEdgeDOF()
* @model
* @generated
*/
public interface bEdgeDOF extends EObject
{
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(boolean)
* @see sc.ndt.editor.fast.fastfst.FastfstPackage#getbEdgeDOF_Value()
* @model
* @generated
*/
boolean isValue();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fastfst.bEdgeDOF#isValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #isValue()
* @generated
*/
void setValue(boolean value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see sc.ndt.editor.fast.fastfst.FastfstPackage#getbEdgeDOF_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fastfst.bEdgeDOF#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // bEdgeDOF
| gpl-3.0 |
nemecp4/termoserver | sensorOld/src/main/java/termoserver/TermoGraph.java | 3171 | package termoserver;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TermoGraph {
public static final String OVERALL_GRAPH = "overall_graph.png";
private SimpleDateFormat formater = new SimpleDateFormat("HH:mm:ss");
private int graphSize = 10;
@Autowired
private TermoModel model;
public File generateGraph(String name) {
Map<Long, Float> data = model.getData(name);
TimeSeries dataset = new TimeSeries("Temperature for " + name);
for (Long key : data.keySet()) {
Float value = data.get(key);
Second s = new Second(new Date(key));
try {
dataset.add(s, new Double(value));
} catch (SeriesException se) {
// probably already added
}
}
TimeSeriesCollection seriesCollection = new TimeSeriesCollection();
seriesCollection.addSeries(dataset);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
String.format("Teplota - %s", name), "Minutes",
"Temperature [C]", seriesCollection, false, false, false);
/* Step -3 : Write line chart to a file */
int width = 640; /* Width of the image */
int height = 480; /* Height of the image */
File file = new File(name + ".png");
try {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
public File generateGraph(GraphTiming timing) {
long limitMilis = Instant.now()
.minus(timing.getDuration(), timing.getUnit()).toEpochMilli();
List<String> names = model.getSensorNames();
TimeSeriesCollection seriesCollection = new TimeSeriesCollection();
for (String name : names) {
Map<Long, Float> data = model.getData(name);
TimeSeries dataset = new TimeSeries("Temperature for " + name);
for (Long key : data.keySet()) {
if (key > limitMilis) {
Float value = data.get(key);
Second s = new Second(new Date(key));
try {
dataset.add(s, new Double(value));
} catch (SeriesException se) {
// probably already added
}
}
}
seriesCollection.addSeries(dataset);
}
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Celkový přehled " + timing.getDuration() + " "
+ timing.getUnit(), "Čas", "Teplota [C]",
seriesCollection, true, true, false);
/* Step -3 : Write line chart to a file */
int width = 640; /* Width of the image */
int height = 480; /* Height of the image */
File file = new File(timing + OVERALL_GRAPH);
try {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
}
| gpl-3.0 |
sanke69/fr.xs.cms | fr.xs.cms.core/src/main/java/fr/xs/cms/services/ajax/user/UserServlet.java | 4098 | package fr.xs.cms.services.ajax.user;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.xs.cms.services.guest.beans.UserBean;
import fr.xs.jtk.tools.Debugger;
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 3593872938021901333L;
public static final String loginFormId = "form_login";
public static final String loginFormAction = "/login-servlet";
public static final String loginFormMethod = "get";
public static final String loginUsernameIn = "username";
public static final String loginPasswordIn = "password";
public static final String sessionAttribute = "user";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
UserBean user = new UserBean();
user.setLogin(request.getParameter(loginUsernameIn));
user.setPassword(request.getParameter(loginPasswordIn));
if( request.getSession(false) != null ) {
Debugger.error("A session is already opened !!!");
}
/* user = UserDAO.login(user);
if(trueuser.isRegistered()) {
/ ** /
response.sendRedirect("/?action=login_success");
/ * /
request.getSession(true).setAttribute(sessionAttribute, user);
request.setAttribute(sessionAttribute, user);
getServletContext().getRequestDispatcher("/?action=login_success").forward(request, response);
/ ** /
} else {
response.sendRedirect("/?action=login_failed");
}
*/ } catch (Throwable theException) {
System.out.println(theException);
}
}
/*
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("ListJeux", l);
String login = request.getParameter("login");
HttpSession session = request.getSession();
session.setAttribute("login", login);
getServletContext().getRequestDispatcher("/Liste.jsp").forward(request, response);
}
*/
public void doGet00(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
/* try {
UserBean user = new UserBean();
user.setUsername(request.getParameter("un"));
user.setPassword(request.getParameter("pw"));
user = UserDAO.login(user);
if(user.isRegistered()) {
request.getSession(true).setAttribute(sessionAttribute, user);
response.sendRedirect("/login/LoginWelcome.jsp");
} else {
response.sendRedirect("/login/LoginFailed.jsp");
}
} catch (Throwable theException) {
System.out.println(theException);
}
*/ }
/**
* Respond to a GET request for the content produced by
* this servlet.
*
* @param request The servlet request we are processing
* @param response The servlet response we are producing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doGet0(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>Pillo v0.1 - java</title>");
writer.println("</head>");
writer.println("<body bgcolor=0x0FA00FFF>");
writer.println("<center style='font-size: 500%'>");
writer.println("<h1>Pillo</h1>");
writer.println("<h4>... is incubating ...</h4>");
writer.println("<a href='index.jsp'> <img src='images/Pillo_Stade_2.png'> </a>");
writer.println("<h5>click on the egg to connect...</h5>");
writer.println("</center>");
writer.println("</body>");
writer.println("</html>");
}
}
| gpl-3.0 |
fauconnier/LaToe | src/de/tudarmstadt/ukp/wikipedia/parser/tutorial/TestFile.java | 14954 | /*******************************************************************************
* Copyright (c) 2010 Torsten Zesch.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* Torsten Zesch - initial API and implementation
******************************************************************************/
package de.tudarmstadt.ukp.wikipedia.parser.tutorial;
public class TestFile {
private static final String LF = "\n";
public static String getFileText() {
StringBuilder sb = new StringBuilder();
sb.append("'''Darmstadt''' is a city in the [[States of Germany|Bundesland]] (federal state) of [[Hesse]]n in [[Germany]]. As of 2005, its population was 139,000. The city is located in the southern part of the [[Frankfurt Rhine Main Area|Rhine Main Metropolitan Area]].");
sb.append(LF);
sb.append(LF);
sb.append("== History ==");
sb.append(LF);
sb.append("The name Darmstadt first appears towards the end of the [[11th century]], then ''Darmundestat''; Darmstadt was chartered as a city by the [[Holy Roman Emperor]] [[Louis IV, Holy Roman Emperor|Ludwig the Bavarian]] in 1330. The seat of the ruling [[Landgraf|landgraves]] (1567-1806) and thereafter (to 1918) to the [[Grand Duke of Hesse and by Rhine|Grand Dukes of Hesse]], the city grew in population during the [[19th century]] from little over 10,000 to 72,000 inhabitants. A polytechnical school, which later became a Technical University now known as [[Darmstadt University of Technology|TU Darmstadt]], was established in 1877. ");
sb.append(LF);
sb.append("In the beginning of the 20th Century Darmstadt was an important centre for the art movement of [[Art Nouveau|Jugendstil]], the German variant of [[Art Nouveau]]. Annual architectural competitions led to the building of many architectural treasures of this period. Also during this period, in [[1912]] the chemist [[Anton Kollisch]], working for the pharmaceutical company [[Merck]], first synthesised the chemical [[MDMA]] (ecstasy) in Darmstadt.");
sb.append(LF);
sb.append("Darmstadt's municipal area was extended in 1937 to include the neighbouring localities of Arheilgen [not Arheil''i''gen] and Eberstadt, and in 1938 the city was separated administratively from the surrounding district (''Kreis''). Its old city centre was largely destroyed in a [[Bombing of Darmstadt in World War II|British bombing raid]] of [[September 11]] [[1944]], which killed an estimated 12,300 inhabitants and rendered 66,000 homeless. Most of Darmstadt's 3000 [[Jew]]s were killed by the [[Nazism|Nazi]] regime between 1933 and 1945. ");
sb.append(LF);
sb.append("Darmstadt is home to many technology companies and research institutes, and has been promoting itself as a \"city of science\" since 1997. It is well known as the high-tech centre in the vicinity of [[Frankfurt International Airport|Frankfurt Airport]], with important activities in spacecraft operations, chemistry, pharmacy, information technology, biotechnology, telecommunications and mechatronics. The [[Darmstadt University of Technology|TU Darmstadt]] is one of the important technical institutes in Germany and is well known for its research and teaching in the Electrical, Mechanical and Civil Engineering disciplines.");
sb.append(LF);
sb.append(LF);
sb.append("== Institutions ==");
sb.append(LF);
sb.append("Darmstadt is the site of one of the leading German universities, the [[Darmstadt University of Technology]], renowned for its engineering departments and the [[Darmstadt University of Applied Sciences]]. Related institutes are the [[Gesellschaft für Schwerionenforschung]] (see also 'Trivia', below) and the four Institutes of the [[Fraunhofer Society]]. The European Space Operations Center ([[ESOC]]) of the [[European Space Agency]] is located in Darmstadt, as is [[EUMETSAT]], which operates [[meteorological]] [[satellite]]s. Darmstadt is a centre for the pharmaceutical and chemical industry, with [[Merck KGaA|Merck]], Röhm and Schenck RoTec (part of The Dürr Group) having their main plants and centres here.");
sb.append(LF);
sb.append("The [http://www.jazzinstitut.de Jazz-Institut Darmstadt] is Germany's largest publicly accessible [[Jazz]] archive.");
sb.append(LF);
sb.append("The [http://www.imd.darmstadt.de/ Internationales Musikinstitut Darmstadt], harboring one of the world's largest collections of [[post-war]] [[sheet music]], also hosts the biannual ''[[International Summer Courses for New Music|Internationale Ferienkurse für Neue Musik]]'', a summer school in [[contemporary classical music]] founded by [[Wolfgang Steinecke]]. A large number of avant-garde [[composer]]s have attended and given lectures there, including [[Olivier Messiaen]], [[Luciano Berio]], [[Milton Babbitt]], [[Pierre Boulez]], [[John Cage]], [[György Ligeti]], [[Iannis Xenakis]], [[Karlheinz Stockhausen]] and [[Mauricio Kagel]].");
sb.append(LF);
sb.append("The [http://www.deutscheakademie.de/ Deutsche Akademie für Sprache und Dichtung] (German Academy for Language and Poetry) provides writers and scholars with a place to research the German language. The Academy's annual ''Georg-Büchner-Preis'', named in memory of [[Georg Büchner]], is considered the most renowned literary award for writers of German language.");
sb.append(LF);
sb.append(LF);
sb.append("== Sons and Daughters of the City ==");
sb.append(LF);
sb.append("* Justus von Liebig, Chemist ");
sb.append(LF);
sb.append("* Georg Büchner, German Poet");
sb.append(LF);
sb.append("* [[Dr Walter Köbel]], German politician");
sb.append(LF);
sb.append("* [[August Anton Ullrich]], German industrialist (1865-1919)");
sb.append(LF);
sb.append("* [[Fabian Scheuermann]], World traveller");
sb.append(LF);
sb.append("* [[Björn Phau]], Tennis player");
sb.append(LF);
sb.append("* [[Friedrich August Kekulé von Stradonitz]], Organic Chemist");
sb.append(LF);
sb.append(LF);
sb.append("== Military ==");
sb.append(LF);
sb.append("There are still [[U.S. Army]] personnel stationed in the Darmstadt area. Just outside the Darmstadt centre is the U.S. Army Garrison Darmstadt on Cambrai-Fritsch Kaserne. The barracks was originally built in the 1930s as two separate German Army barracks (Cambrai Kaserne and Freiherr von Fritsch Kaserne). ");
sb.append(LF);
sb.append("It is possible to listen to the military entertainment radio for the American troops in the region. The station is called [[American Forces Network|AFN Europe]] and broadcasts from Frankfurt on FM 98.7 or AM 873.");
sb.append(LF);
sb.append("The base has already started deactivation and will be closed around 2008-2010, at that time AFN Europe will be moved to Mannheim.");
sb.append(LF);
sb.append(LF);
sb.append("== Trivia ==");
sb.append(LF);
sb.append("Literally translated, the German name \"Darmstadt\" means \"City of the intestine\". But that is just a coincidence, as the name derives from the medieval name \"darmundestat\". The Darm(bach) is a small creek running through the city.");
sb.append(LF);
sb.append("The [[chemical element]] [[Darmstadtium]] ([[atomic number]]: 110), first discovered at the [[Gesellschaft für Schwerionenforschung]] was named after the city in 2003, making Darmstadt only the sixth city with an element named after it (the other five cities are [[Ytterby]] in [[Sweden]] (four elements); [[Strontian]] in [[Scotland]]; [[Copenhagen]] in [[Denmark]] (whose latin name gives [[Hafnium]]); [[Berkeley, California]]; and [[Dubna]] in [[Russia]]). [[Meitnerium]] ([[atomic number]]: 109) (1982), [[Hassium]] ([[atomic number]]: 108) (1984) and [[Roentgenium]] ([[atomic number]]: 111) (1994) and [[Ununbium]] ([[atomic number]]: 112) (1996) were also synthesized in this facility.");
sb.append(LF);
sb.append("Darmstadt also happens to be one of the small number of cities worldwide which do not lie close to a river or coast.");
sb.append(LF);
sb.append("Darmstadt is the home of [[Software AG]], a software company.");
sb.append(LF);
sb.append("Frankenstein Castle, ''[http://de.wikipedia.org/wiki/Burg_Frankenstein_%28Bergstrasse%29 Burg Frankenstein]'' (in German), possibly Mary Shelley's inspiration for the title of her famous 1818 novel ''[[Frankenstein | Frankenstein; or, The Modern Prometheus]]'', is located nearby.");
sb.append(LF);
sb.append(LF);
sb.append("== Twinning ==");
sb.append(LF);
sb.append("Darmstadt is [[twinned]] with:");
sb.append(LF);
sb.append(LF);
sb.append("*{{flagicon|Netherlands}}[[Alkmaar]], [[Netherlands]]");
sb.append(LF);
sb.append("*{{flagicon|Italy}}[[Brescia]], [[Italy]]");
sb.append(LF);
sb.append("*{{flagicon|Turkey}}[[Bursa, Turkey|Bursa]], [[Turkey]]");
sb.append(LF);
sb.append("*{{flagicon|United Kingdom}}[[Chesterfield]], [[United Kingdom|UK]]");
sb.append(LF);
sb.append("*{{flagicon|Austria}}[[Graz]], [[Austria]]");
sb.append(LF);
sb.append("*{{flagicon|Latvia}}[[Liepaja]], [[Latvia]]");
sb.append(LF);
sb.append("*{{flagicon|Spain}}[[Logroño]], [[Spain]]");
sb.append(LF);
sb.append("*{{flagicon|Poland}}[[Płock]], [[Poland]]");
sb.append(LF);
sb.append("*{{flagicon|Hungary}}[[Szeged]], [[Hungary]]");
sb.append(LF);
sb.append("*{{flagicon|Norway}}[[Trondheim]], [[Norway]]");
sb.append(LF);
sb.append("*{{flagicon|France}}[[Troyes]], [[France]]");
sb.append(LF);
sb.append("*{{flagicon|Ukraine}}[[Uzhhorod]], [[Ukraine]]");
sb.append(LF);
sb.append("*{{flagicon|Switzerland}}[[Saanen]], [[Switzerland]]");
sb.append(LF);
sb.append(LF);
sb.append("==External links==");
sb.append(LF);
sb.append("{{commonscat|Darmstadt, Germany}}");
sb.append(LF);
sb.append("*[http://www.darmstadt.de/ Official site of the city of Darmstadt] (German, English)");
sb.append(LF);
sb.append("*[[wikitravel:Darmstadt|Darmstadt]] on [[wikitravel:Main Page|Wikitravel]]");
sb.append(LF);
sb.append("*[http://www.mathildenhoehe.info Mathildenhoehe]");
sb.append(LF);
sb.append("*[http://public-transport.net/bim/Darmstadt.htm Details of Trams and Buses used in Darmstadt]");
sb.append(LF);
sb.append("*[http://www.rmv.de/ Public Transport in Darmstadt - Maps, Timetables, Fares]");
sb.append(LF);
sb.append("*[http://sites-of-memory.de/main/location.html#darmstadt War memorials in Darmstadt]");
sb.append(LF);
sb.append("*[http://www.darmstadt.army.mil/ Webpage of the U.S. army in Darmstadt]");
sb.append(LF);
sb.append(LF);
sb.append("===Notable institutions===");
sb.append(LF);
sb.append("* [http://www.tu-darmstadt.de/index.en.html Darmstadt University of Technology]");
sb.append(LF);
sb.append("* [http://www.hochschule-darmstadt.de/engl/engl.htm University of Applied Sciences Darmstadt]");
sb.append(LF);
sb.append("* [http://www.igd.fraunhofer.de/ Fraunhofer Institute for Computer Graphics]");
sb.append(LF);
sb.append("* [http://www.sit.fraunhofer.de/ Fraunhofer Institute for Secure Information Technology]");
sb.append(LF);
sb.append("* [http://www.ipsi.fraunhofer.de/ Fraunhofer Institute for Integrated Publication and Information Systems]");
sb.append(LF);
sb.append("* [http://www.lbf.fhg.de/ Fraunhofer Institute for Structural Durability]");
sb.append(LF);
sb.append("* [http://www.deutscheakademie.de/ Deutsche Akademie für Sprache und Dichtung]");
sb.append(LF);
sb.append("* [http://www.gsi.de/ Gesellschaft für Schwerionenforschung]");
sb.append(LF);
sb.append("* [http://www.esa.int/SPECIALS/ESOC/ European Space Operations Centre] (ESOC)");
sb.append(LF);
sb.append("* [http://www.eumetsat.int/ European Organisation for the Exploitation of Meteorological Satellites (EUMETSAT)]");
sb.append(LF);
sb.append(LF);
sb.append("[[Category:Cities in Hesse]]");
sb.append(LF);
sb.append("[[Category:Merck]]");
sb.append(LF);
sb.append("[[ar:دارمشتادت]]");
sb.append(LF);
sb.append("[[an:Darmstadt]]");
sb.append(LF);
sb.append("[[bg:Дармщат]]");
sb.append(LF);
sb.append("[[ca:Darmstadt]]");
sb.append(LF);
sb.append("[[cs:Darmstadt]]");
sb.append(LF);
sb.append("[[da:Darmstadt]]");
sb.append(LF);
sb.append("[[de:Darmstadt]]");
sb.append(LF);
sb.append("[[et:Darmstadt]]");
sb.append(LF);
sb.append("[[el:Ντάρμστατ]]");
sb.append(LF);
sb.append("[[es:Darmstadt]]");
sb.append(LF);
sb.append("[[eo:Darmstadt]]");
sb.append(LF);
sb.append("[[fr:Darmstadt]]");
sb.append(LF);
sb.append("[[ko:다름슈타트]]");
sb.append(LF);
sb.append("[[id:Darmstadt]]");
sb.append(LF);
sb.append("[[it:Darmstadt]]");
sb.append(LF);
sb.append("[[la:Darmstadium]]");
sb.append(LF);
sb.append("[[hu:Darmstadt]]");
sb.append(LF);
sb.append("[[nl:Darmstadt]]");
sb.append(LF);
sb.append("[[ja:ダルムシュタット]]");
sb.append(LF);
sb.append("[[no:Darmstadt]]");
sb.append(LF);
sb.append("[[nds:Darmstadt]]");
sb.append(LF);
sb.append("[[pl:Darmstadt]]");
sb.append(LF);
sb.append("[[pt:Darmstadt]]");
sb.append(LF);
sb.append("[[ro:Darmstadt]]");
sb.append(LF);
sb.append("[[ru:Дармштадт]]");
sb.append(LF);
sb.append("[[simple:Darmstadt]]");
sb.append(LF);
sb.append("[[fi:Darmstadt]]");
sb.append(LF);
sb.append("[[sv:Darmstadt]]");
sb.append(LF);
sb.append("[[tr:Darmstadt]]");
sb.append(LF);
sb.append("[[vo:Darmstadt]]");
sb.append(LF);
sb.append("[[zh:达姆施塔特]]");
sb.append(LF);
return sb.toString();
}
}
| gpl-3.0 |
noodlewiz/xjavab | xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/xprint/internal/CreateContextRequest.java | 2718 | //
// DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!!
//
// Copyright (c) 2014 Vincent W. Chen.
//
// This file is part of XJavaB.
//
// XJavaB is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// XJavaB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with XJavaB. If not, see <http://www.gnu.org/licenses/>.
//
package com.noodlewiz.xjavab.ext.xprint.internal;
import java.nio.ByteBuffer;
import com.noodlewiz.xjavab.core.internal.Measurer;
import com.noodlewiz.xjavab.core.internal.Packer;
import com.noodlewiz.xjavab.core.internal.Util;
import com.noodlewiz.xjavab.core.internal.XRequest;
public class CreateContextRequest
implements XRequest
{
public final long contextId;
public final long printerNameLen;
public final long localeLen;
public final String printerName;
public final String locale;
public CreateContextRequest(final long contextId, final long printerNameLen, final long localeLen, final String printerName, final String locale) {
this.contextId = contextId;
this.printerNameLen = printerNameLen;
this.localeLen = localeLen;
this.printerName = printerName;
this.locale = locale;
}
@Override
public short getOpcode() {
return 2;
}
@Override
public boolean isExtension() {
return true;
}
@Override
public String getExtensionName() {
return "XpExtension";
}
@Override
public ByteBuffer pack() {
int __xjb_length = 4;
__xjb_length += Measurer.measureUInt();
__xjb_length += Measurer.measureUInt();
__xjb_length += Measurer.measureUInt();
__xjb_length += Measurer.measureString(this.printerName);
__xjb_length += Measurer.measureString(this.locale);
__xjb_length += Util.padding(__xjb_length);
final ByteBuffer __xjb_buf = ByteBuffer.allocate(__xjb_length);
__xjb_buf.position(4);
Packer.packUInt(__xjb_buf, this.contextId);
Packer.packUInt(__xjb_buf, this.printerNameLen);
Packer.packUInt(__xjb_buf, this.localeLen);
Packer.packString(__xjb_buf, this.printerName);
Packer.packString(__xjb_buf, this.locale);
return __xjb_buf;
}
}
| gpl-3.0 |
heikehuan/technical-notes | ===============技术笔记积累===========/studentinf/JavaSource/studentinf/servlet/StuinfoSelectServlet.java | 1024 | package studentinf.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StuinfoSelectServlet extends HttpServlet implements Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public StuinfoSelectServlet() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest arg0, HttpServletResponse arg1)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest arg0, HttpServletResponse arg1)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
} | gpl-3.0 |
resamsel/translatr | app/services/api/MessageApiService.java | 375 | package services.api;
import com.google.inject.ImplementedBy;
import criterias.MessageCriteria;
import dto.Message;
import java.util.UUID;
import services.api.impl.MessageApiServiceImpl;
/**
* @author resamsel
* @version 29 Jan 2017
*/
@ImplementedBy(MessageApiServiceImpl.class)
public interface MessageApiService extends ApiService<Message, UUID, MessageCriteria> {
}
| gpl-3.0 |
konradrenner/scjp | CodeBeispiele/src/main/java/at/arz/scjp/codebeispiele/konrad/thread/WaitingAndNotify.java | 3276 | /*
* Copyright (C) 2014 Konrad Renner
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.arz.scjp.codebeispiele.konrad.thread;
/**
* Ein Beispiel das wait und notify demonstiert. Diese Methoden machen nur in einem synchronized Block Sinn! Da es bei
* den Methoden um die Lock-Verwaltung von Threads geht!
*
* @author Konrad Renner
*/
public class WaitingAndNotify {
static final Monitor MONITOR = new Monitor();
public static void main(String[] args) {
new Max().start();
new Moritz().start();
}
}
class Monitor {
int zahl = 10;
boolean wegnehmen = true;
public synchronized void machWas() {
System.out.println("Starte mit Thread:" + Thread.currentThread().toString() + "; zahl:" + zahl);
for (int i = 0; i < 12; i++) {
System.out.println("Aktueller Thread:" + Thread.currentThread().toString() + "; zahl:" + zahl + "; i:" + i);
System.out.println("wegnehmen:" + wegnehmen);
if (wegnehmen) {
zahl--;
} else {
zahl++;
}
System.out.println("zahl:" + zahl);
if (zahl == 0) {
try {
wegnehmen = false;
System.out.println("" + Thread.currentThread().toString() + ": Ich muss warten");
// Der Thread wartet jetzt, bis er von einem anderen Thread mittels notify bzw. notifyAll
// "aufgeweckt" wird
wait();
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
}
} else if (zahl == 10) {
wegnehmen = true;
System.out.println("" + Thread.currentThread().toString() + ": Jetzt darf der andere wieder");
// Wuerde man hier das notifyAll oder notify nicht machen, wuerde der andere Thread "ewig" warten. Dh
// der andere Thread macht nicht von selbst weiter
// Unterschied notify und notifAll: Bei notify gibt die JVM genau 1 Thread bescheid das er weiter machen
// kann, es ist nicht garantiert, welcher Thread das ist und kann in bestimmten Situationen zu Deadlocks
// fuehren!
notifyAll();
break;
}
}
}
}
class Max
extends Thread {
@Override
public void run() {
WaitingAndNotify.MONITOR.machWas();
System.out.println(toString() + ": Habe meine Arbeit getan");
System.out.println(toString() + ": Shutdown gestartet");
System.out.println(toString() + ": Gute Nacht");
}
@Override
public String toString() {
return "I bin da Max";
}
}
class Moritz
extends Thread {
@Override
public void run() {
WaitingAndNotify.MONITOR.machWas();
System.out.println(toString() + ": Habe meine Arbeit getan");
System.out.println(toString() + ": Shutdown gestartet");
System.out.println(toString() + ": Gute Nacht");
}
@Override
public String toString() {
return "I bin da Moritz";
}
}
| gpl-3.0 |
zb2009/Practice-Mod | src/main/java/com/zb2009/practicemod/proxy/ServerProxy.java | 89 | package com.zb2009.practicemod.proxy;
public class ServerProxy extends CommonProxy {
}
| gpl-3.0 |
christiangda/pigiptools | src/main/java/com/github/christiangda/pig/geoip/GetCountryName.java | 3504 | /*
* GetCountryName.java
*
* Copyright (c) 2015 Christian González
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.christiangda.pig.geoip;
import com.github.christiangda.utils.geoip.GeoCoding;
import org.apache.pig.EvalFunc;
import org.apache.pig.FuncSpec;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GetCountryName extends EvalFunc<String> {
/** Value - {@value}, GeoCoding object to uses for get its methods.*/
private GeoCoding geo;
private HashMap<String, String> dbFilesPaths = new HashMap<String, String>();
/**
* Class constructor specifying the two MaxMind Database Files (IPV4 and IPV6)
*
* @param IPV4DBFilePath Path to the MaxMind GeoIP Database for IPV4
* @param IPV6DBFilePath Path to the MaxMind GeoIP Database for IPV6
*/
public GetCountryName(final String IPV4DBFilePath, final String IPV6DBFilePath) {
this.dbFilesPaths.put("ipv4", IPV4DBFilePath);
this.dbFilesPaths.put("ipv6", IPV6DBFilePath);
try {
this.geo = new GeoCoding(IPV4DBFilePath, IPV4DBFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String exec(Tuple input) throws IOException {
// validate input
if (input == null || input.size() == 0 || input.get(0) == null) {
return null;
}
// get the value of input
String strAddress = (String) input.get(0);
// Get geoip information
try {
String result = this.geo.getCountryName(strAddress);
// replace "--" and "N/A" to null, better for pig
if (result == null || result.equals("--") || result.equals("N/A")) {
return null;
} else {
return result;
}
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
@Override
public List<FuncSpec> getArgToFuncMapping() throws FrontendException {
List<FuncSpec> funcList = new ArrayList<FuncSpec>();
funcList.add(new FuncSpec(this.getClass().getName(), new Schema(new Schema.FieldSchema(null, DataType.CHARARRAY))));
return funcList;
}
@Override
public final List<String> getCacheFiles() {
List<String> cacheFiles = new ArrayList<String>();
//iterate over this.dbFilesPaths, to put file in cache
for (Map.Entry<String, String> entry : this.dbFilesPaths.entrySet()) {
cacheFiles.add(entry.getValue() + "#" + entry.getValue());
}
return cacheFiles;
}
} | gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_people/ETag_object.java | 539 | package tmp.generated_people;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class ETag_object extends GenASTNode {
public ETag_object(Token firstToken, Token lastToken) {
super(new Property[] {
}, firstToken, lastToken);
}
public ETag_object(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new ETag_object(cloneProperties(),firstToken,lastToken);
}
}
| gpl-3.0 |
eswaraj/android | JanSampark/src/com/next/eswaraj/models/Type.java | 163 | package com.next.eswaraj.models;
public enum Type {
LACK_IN_INFRA,
LACK_IN_MAIN,
LACK_OF_QUALITY_STAFF,
POOR_PRICING,
AWARENESS,
OTHERS
}
| gpl-3.0 |
transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/generated/java/com/rapid_i/repository/wsimport/GetFreeMemoryResponse.java | 2279 | /**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapid_i.repository.wsimport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getFreeMemoryResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getFreeMemoryResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getFreeMemoryResponse", propOrder = {
"_return"
})
public class GetFreeMemoryResponse {
@XmlElement(name = "return")
protected String _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturn(String value) {
this._return = value;
}
}
| gpl-3.0 |
craftercms/social | server/src/main/java/org/craftercms/social/util/serialization/SocialInjectValueFactory.java | 3588 | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.craftercms.social.util.serialization;
import java.util.Arrays;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.craftercms.commons.i10n.I10nLogger;
import org.craftercms.commons.jackson.mvc.annotations.InjectValueFactory;
import org.craftercms.profile.api.Profile;
import org.craftercms.social.domain.UGC;
import org.craftercms.social.exceptions.NotificationException;
import org.craftercms.social.security.SecurityActionNames;
import org.craftercms.social.security.SocialSecurityUtils;
import org.craftercms.social.services.notification.NotificationService;
import org.craftercms.social.util.LoggerFactory;
import org.craftercms.social.util.ProfileUtils;
import org.craftercms.social.util.profile.ProfileAggregator;
/**
*
*/
public class SocialInjectValueFactory implements InjectValueFactory {
protected ProfileAggregator profileAggregator;
protected NotificationService notificationService;
protected I10nLogger log = LoggerFactory.getLogger(SocialInjectValueFactory.class);
protected String ignoreAnonymousFlagRoles;
@Override
public <T> T getObjectFor(final Class<T> declaringClass, final Object basePropertyValue, final String
originalProperty, final Object object) {
if (UGC.class.isAssignableFrom(object.getClass())) {
if (declaringClass.equals(Profile.class)) {
final Profile profile = profileAggregator.getProfile((String)basePropertyValue);
if(((UGC)object).isAnonymousFlag() && !ignoreAnonymousFlag()){
anonymizeProfile((UGC)object);
return (T)ProfileUtils.getAnonymousProfile();
}else{
return (T)profile;
}
}
}
return null;
}
private boolean ignoreAnonymousFlag() {
final Profile currentUser = SocialSecurityUtils.getCurrentProfile();
if( currentUser==null || currentUser.getRoles().isEmpty() ||
currentUser.getUsername().equalsIgnoreCase(SocialSecurityUtils.ANONYMOUS)) {
return false;
}
return CollectionUtils.containsAny(currentUser.getRoles(), Arrays.asList(ignoreAnonymousFlagRoles.split(",")));
}
protected void anonymizeProfile(final UGC object) {
if(object.getCreatedBy().equals(object.getLastModifiedBy())){
object.setLastModifiedBy("");
}
object.setCreatedBy("");
}
public void setProfileAggregator(final ProfileAggregator profileAggregator) {
this.profileAggregator = profileAggregator;
}
public void setNotificationServiceImpl(NotificationService notificationService) {
this.notificationService = notificationService;
}
public void setIgnoreAnonymousFlagRoles(final String ignoreAnonymousFlagRoles) {
this.ignoreAnonymousFlagRoles = ignoreAnonymousFlagRoles;
}
}
| gpl-3.0 |
mrsistemasytecnologia/aplicaciones | WSGoSmartEJB/ejbModule/com/tour/ws/model/dto/CategoriaDTO.java | 1954 | package com.tour.ws.model.dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="CATEGORIA")
public class CategoriaDTO implements Serializable {
/**
* <b>UID</b>
*/
private static final long serialVersionUID = 7982289016659224410L;
@XmlElement(name = "ID")
private String idCategoria;
@XmlElement(name="COD_DESTINO")
private String codDestino;
@XmlElement(name="PORCENTAJE")
private String porcentajeAjuste;
@XmlElement(name="COD_PERFIL")
private String codPerfil;
@XmlElement(name="PERFIL")
private PerfilDTO genPerfil;
public CategoriaDTO() {
// TODO Auto-generated constructor stub
}
public String getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(String idCategoria) {
this.idCategoria = idCategoria;
}
public String getCodDestino() {
return codDestino;
}
public void setCodDestino(String codDestino) {
this.codDestino = codDestino;
}
public String getPorcentajeAjuste() {
return porcentajeAjuste;
}
public void setPorcentajeAjuste(String porcentajeAjuste) {
this.porcentajeAjuste = porcentajeAjuste;
}
public PerfilDTO getGenPerfil() {
return genPerfil;
}
public void setGenPerfil(PerfilDTO genPerfil) {
this.genPerfil = genPerfil;
}
public String getCodPerfil() {
return codPerfil;
}
public void setCodPerfil(String codPerfil) {
this.codPerfil = codPerfil;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CategoriaDTO [idCategoria=");
builder.append(idCategoria);
builder.append(", codDestino=");
builder.append(codDestino);
builder.append(", porcentajeAjuste=");
builder.append(porcentajeAjuste);
builder.append(", codPerfil=");
builder.append(codPerfil);
builder.append(", genPerfil=");
builder.append(genPerfil);
builder.append("]");
return builder.toString();
}
}
| gpl-3.0 |
vdsalex/Final-Year-Project | Euterpe/app/src/main/java/com/example/alex/rhymebot/Euterpe.java | 5746 | package com.example.alex.rhymebot;
import android.app.Application;
import android.content.Context;
import android.renderscript.ScriptGroup;
import com.example.alex.rhymebot.BotPackage.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Euterpe extends Application
{
@Override
public void onCreate()
{
File modeFile = new File(getFilesDir().getPath() + "/mode_file.txt");
File selectedTabFile = new File(getFilesDir().getPath() + "/selected_tab.txt");
File vocabFile = new File(getFilesDir().getPath() + "/vocabulary_i.txt");
File adjFile = new File(getFilesDir().getPath() + "/adjectives_i.txt");
File advFile = new File(getFilesDir().getPath() + "/adverbs_i.txt");
File nnsFile = new File(getFilesDir().getPath() + "/nouns_i.txt");
File vbsFile = new File(getFilesDir().getPath() + "/verbs_i.txt");
createFile(modeFile);
createFile(selectedTabFile);
createFile(new File(getFilesDir().getPath() + "/conversation_file.txt"));
createFile(new File(getFilesDir().getPath() + "/eminescu.txt"));
createFile(new File(getFilesDir().getPath() + "/bacovia.txt"));
createFile(new File(getFilesDir().getPath() + "/stanescu.txt"));
createFile(vocabFile);
populateVocabulary(vocabFile);
createFile(adjFile);
populateAdjectives(adjFile);
createFile(advFile);
populateAdverbs(advFile);
createFile(vbsFile);
populateVerbs(vbsFile);
createFile(nnsFile);
populateNouns(nnsFile);
try
{
if(modeFile.length() == 0)
{
FileOutputStream fileOutputStream = openFileOutput("mode_file.txt", Context.MODE_PRIVATE);
fileOutputStream.write('0');
}
} catch (IOException e)
{
e.printStackTrace();
}
try
{
if(selectedTabFile.length() == 0)
{
FileOutputStream fileOutputStream = openFileOutput("selected_tab.txt", Context.MODE_PRIVATE);
fileOutputStream.write('0');
}
} catch (IOException e)
{
e.printStackTrace();
}
super.onCreate();
}
private void createFile(File file)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void populateVocabulary(File vocabFile)
{
if(vocabFile.length() <= 1)
{
try
{
InputStream is = getAssets().open("vocabulary.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
FileOutputStream fos = openFileOutput("vocabulary_i.txt", Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void populateAdjectives(File adjFile)
{
if(adjFile.length() <= 1)
{
try
{
InputStream is = getAssets().open("adjectives.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
FileOutputStream fos = openFileOutput("adjectives_i.txt", Context.MODE_PRIVATE);
for(byte b: buffer)
{
fos.write(b);
}
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void populateNouns(File nnsFile)
{
if(nnsFile.length() <= 1)
{
try
{
InputStream is = getAssets().open("nouns.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
FileOutputStream fos = openFileOutput("nouns_i.txt", Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void populateVerbs(File vbsFile)
{
if(vbsFile.length() <= 1)
{
try
{
InputStream is = getAssets().open("verbs.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
FileOutputStream fos = openFileOutput("verbs_i.txt", Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void populateAdverbs(File advFile)
{
if(advFile.length() <= 1)
{
try
{
InputStream is = getAssets().open("adverbs.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
FileOutputStream fos = openFileOutput("adverbs_i.txt", Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/nianticproject/ingress/common/t/a.java | 2044 | package com.nianticproject.ingress.common.t;
import com.google.a.a.an;
import com.google.a.c.eq;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
final class a
{
private final ArrayList<f> a = eq.b(4);
private boolean b = c.a;
private int c;
private h d = new h();
private g e = new g();
a()
{
this.a.add(new f(c.b));
}
final void a()
{
if (!this.b)
{
this.c = (-1 + this.c);
return;
}
if (this.c > 0);
for (boolean bool = true; ; bool = false)
{
an.b(bool, "Zone stack underflow");
ArrayList localArrayList = this.a;
int i = this.c;
this.c = (i - 1);
f localf = (f)localArrayList.remove(i);
((f)this.a.get(this.c)).a(localf.a());
this.d.a(localf);
return;
}
}
final void a(b paramb)
{
this.c = (1 + this.c);
if (!this.b)
return;
f localf = new f(paramb);
this.a.add(localf);
}
final void b()
{
if (!this.b)
{
this.b = c.a;
return;
}
if (this.c == 0);
long l;
for (boolean bool = true; ; bool = false)
{
an.b(bool, "Updating counters while profiling active");
l = System.nanoTime() - 60000000000L;
while (true)
{
f localf1 = this.e.a(l);
if (localf1 == null)
break;
localf1.d();
}
}
while (true)
{
f localf2 = this.d.a(l);
if (localf2 == null)
break;
localf2.c();
this.e.a(localf2);
}
this.d.a();
Iterator localIterator = c.c().iterator();
while (localIterator.hasNext())
((b)localIterator.next()).g();
this.b = c.a;
}
final void b(b paramb)
{
if (this.b)
if (this.c <= 0)
break label30;
label30: for (boolean bool = true; ; bool = false)
{
an.b(bool);
a();
a(paramb);
return;
}
}
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.nianticproject.ingress.common.t.a
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
bushidowallet/bushido-java-core | src/test/java/com/bushidowallet/core/bitcoin/bip32/ECKeySignatureTest.java | 1418 | package com.bushidowallet.core.bitcoin.bip32;
import com.bushidowallet.core.TestResource;
import com.bushidowallet.core.crypto.util.ByteUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.security.Security;
import java.util.Arrays;
/**
* Created by Jesion on 2015-03-10.
*/
public class ECKeySignatureTest {
@BeforeClass
public static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
@Test
public void testSign() throws Exception {
JSONArray tests = new TestResource("eckeysignature.json").readObjectArray();
for (int i = 0; i < tests.length (); i++) {
JSONObject test = tests.getJSONObject(i);
String wifKey = test.getString("wif");
String message = test.getString("message");
String signature = test.getString("signature");
byte[] expectedSignature = ByteUtil.fromHex(signature);
ECKey key = ECKey.ECKeyParser.parse(wifKey);
byte[] sig = key.sign(message.getBytes());
System.out.println("Signature created: " + ByteUtil.toHex(sig));
Assert.assertTrue(Arrays.equals(expectedSignature, sig));
Assert.assertTrue(key.verify(message.getBytes(), sig));
}
}
}
| gpl-3.0 |
hellobingbing/MySinaProject | src/cn/com/sina/weka/cluster/MyKMeans.java | 2576 | package cn.com.sina.weka.cluster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import weka.clusterers.AbstractClusterer;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.SimpleKMeans;
import weka.core.Capabilities;
import weka.core.CapabilitiesHandler;
import weka.core.DistanceFunction;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
/**
* ʹÓÃK-Means¶ÔÐÂΞÛÀà
* @author sina
*
*/
public class MyKMeans {
public static void main(String[] args) {
// TODO Auto-generated method stub
//ÐÂÎÅÌØÕ÷Êý¾Ý·¾¶
String pathname = "." + File.separator + "cluster" + File.separator + "news.arff";
try {
getClusterResult(pathname);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* µ÷ÓÃweka½Ó¿Ú¶ÔÐÂÎÅÌØÕ÷ÏòÁ¿¾ÛÀ࣬Êä³ö¾ÛÀà½á¹û
* @param pathname Òª¾ÛÀàµÄÐÂÎÅÊý¾ÝµÄÎļþ·¾¶
* @throws Exception
*/
public static void getClusterResult(String pathname) throws Exception{
Instances instances = null;
SimpleKMeans KM = null;
//ĬÈÏÅ·¼¸ÀïµÃ¾àÀë
DistanceFunction disFun = null;
//¶ÁÈëÑù±¾Êý¾Ý
File file = new File(pathname);
ArffLoader loader = new ArffLoader();
loader.setFile(file);
instances = loader.getDataSet();
//ɾ³ýµÚÒ»¸öÊôÐÔ£¬ÓÉÓÚÆäÊÇÐÂÎÅid
instances.deleteAttributeAt(0);
//³õʼ»¯¾ÛÀàÆ÷,¼ÓÔØËã·¨
KM = new SimpleKMeans();
//ÉèÖòÎÊý
KM.setNumClusters(20);
KM.setSeed(10);
KM.buildClusterer(instances);
//´òÓ¡½á¹û
//System.out.println(KM.toString());
//»ñµÃÄ£ÐͲÎÊýÉèÖÃ
//for(String option : KM.getOptions()){
//System.out.print(option + " ");
//}
//System.out.println();
// the cluster to evaluate
ClusterEvaluation eval = new ClusterEvaluation();
// set the clusterer
eval.setClusterer(KM);
// the set of instances to cluster
eval.evaluateClusterer(instances);
// ÆÀ¼Û¾ÛÀà,´òÓ¡¾ÛÀà½á¹û
System.out.println(eval.clusterResultsToString());
// »ñµÃÿÌõ¼Ç¼ËùÊôµÄ¾Û´Ø ,µÃµ½Ò»¸ö¾ÛÀà½á¹ûµÄÊý×é
//double[] clusterResultForEach = eval.getClusterAssignments();
//
//int i = 0;
//Enumeration<Instance> enumeration = instances.enumerateInstances();
//while(enumeration.hasMoreElements()){
//System.out.print(enumeration.nextElement().toString());
//System.out.println("\t" + clusterResultForEach[i]);
//i++;
//}
}
}
| gpl-3.0 |
Hunternif/Dota2Items | src/hunternif/mc/dota2items/block/BlockCycloneContainer.java | 1571 | package hunternif.mc.dota2items.block;
import hunternif.mc.dota2items.tileentity.TileEntityCyclone;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
public class BlockCycloneContainer extends BlockContainer {
public BlockCycloneContainer(int id) {
super(id, Material.air);
setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 3.0F, 1.0F);
setBlockUnbreakable();
setResistance(6000000.0F);
}
//NOTE Some of these overrides may be unnecessary
@Override
public boolean getBlocksMovement(IBlockAccess par1iBlockAccess, int par2, int par3, int par4) {
return true;
}
@Override
public boolean isAirBlock(World world, int x, int y, int z) {
return true;
}
@Override
public boolean isBlockSolid(IBlockAccess par1iBlockAccess, int par2, int par3, int par4, int par5) {
return false;
}
@Override
public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side) {
return false;
}
@Override
public boolean shouldSideBeRendered(IBlockAccess par1iBlockAccess, int par2, int par3, int par4, int par5) {
return false;
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityCyclone();
}
public boolean isOpaqueCube() {
return false;
}
@Override
public void registerIcons(IconRegister iconRegister) {
}
}
| gpl-3.0 |
TheHortonMachine/hortonmachine | apps/src/main/java/org/hortonmachine/database/DatabaseController.java | 119810 | /*
* This file is part of HortonMachine (http://www.hortonmachine.org)
* (C) HydroloGIS - www.hydrologis.com
*
* The HortonMachine 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.hortonmachine.database;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.tree.TreePath;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame.Tool;
import org.h2.jdbc.JdbcBlob;
import org.h2.jdbc.JdbcSQLException;
import org.hortonmachine.HM;
import org.hortonmachine.database.tree.DatabaseTreeCellRenderer;
import org.hortonmachine.database.tree.DatabaseTreeModel;
import org.hortonmachine.database.tree.MultiLineTableCellRenderer;
import org.hortonmachine.dbs.compat.ADb;
import org.hortonmachine.dbs.compat.ASpatialDb;
import org.hortonmachine.dbs.compat.ConnectionData;
import org.hortonmachine.dbs.compat.EDb;
import org.hortonmachine.dbs.compat.objects.ColumnLevel;
import org.hortonmachine.dbs.compat.objects.DbLevel;
import org.hortonmachine.dbs.compat.objects.LeafLevel;
import org.hortonmachine.dbs.compat.objects.QueryResult;
import org.hortonmachine.dbs.compat.objects.TableLevel;
import org.hortonmachine.dbs.datatypes.ESpatialiteGeometryType;
import org.hortonmachine.dbs.log.Logger;
import org.hortonmachine.dbs.nosql.INosqlCollection;
import org.hortonmachine.dbs.nosql.INosqlDb;
import org.hortonmachine.dbs.nosql.INosqlDocument;
import org.hortonmachine.dbs.spatialite.SpatialiteCommonMethods;
import org.hortonmachine.dbs.spatialite.SpatialiteTableNames;
import org.hortonmachine.dbs.utils.CommonQueries;
import org.hortonmachine.dbs.utils.DbsUtilities;
import org.hortonmachine.gears.io.dbs.DbsHelper;
import org.hortonmachine.gears.io.vectorwriter.OmsVectorWriter;
import org.hortonmachine.gears.libs.modules.HMConstants;
import org.hortonmachine.gears.libs.modules.HMFileFilter;
import org.hortonmachine.gears.libs.monitor.IHMProgressMonitor;
import org.hortonmachine.gears.libs.monitor.LogProgressMonitor;
import org.hortonmachine.gears.spatialite.GTSpatialiteThreadsafeDb;
import org.hortonmachine.gears.utils.PreferencesHandler;
import org.hortonmachine.gears.utils.chart.CategoryHistogram;
import org.hortonmachine.gears.utils.chart.Scatter;
import org.hortonmachine.gears.utils.features.FeatureUtilities;
import org.hortonmachine.gears.utils.files.FileUtilities;
import org.hortonmachine.gears.utils.geometry.GeometryUtilities;
import org.hortonmachine.gui.console.LogConsoleController;
import org.hortonmachine.gui.utils.GuiBridgeHandler;
import org.hortonmachine.gui.utils.GuiUtilities;
import org.hortonmachine.gui.utils.GuiUtilities.IOnCloseListener;
import org.hortonmachine.gui.utils.HMMapframe;
import org.hortonmachine.gui.utils.ImageCache;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
/**
* The database view controller.
*
* @author Andrea Antonello (www.hydrologis.com)
*
*/
public abstract class DatabaseController extends DatabaseView implements IOnCloseListener {
private static final int SQL_ONSELECT_LIMIT = 100;
private static final int NOSQL_ONSELECT_LIMIT = 10;
private static final String THIS_ACTION_IS_AVAILABLE_ONLY_FOR_SQL_DATABASES = "This action is available only for SQL databases.";
public static final String THIS_ACTION_IS_AVAILABLE_ONLY_FOR_SPATIAL_DATABASES = "This action is available only for spatial databases.";
private static final String NO_SAVED_CONNECTIONS_AVAILABLE = "No saved connections available.";
private static final String HM_SAVED_QUERIES = "HM_SAVED_QUERIES";
private static final long serialVersionUID = 1L;
// private static final String SHAPEFILE_IMPORT = "import shapefile in selected table";
// private static final String SHAPEFILE_CCREATE_FROM_SCHEMA = "create table from shapefile
// schema";
// private static final String SHAPEFILE_TOOLTIP = "tools to deal with shapefiles";
// private static final String SHAPEFILE = "shapefile";
private static final String SQL_TEMPLATES_TOOLTIP = "create a query based on a template";
private static final String SQL_TEMPLATES = "sql templates";
private static final String SQL_HISTORY_TOOLTIP = "select queries from the history";
private static final String SQL_HISTORY = "sql history";
private static final String DISCONNECT_TOOLTIP = "disconnect from current database";
private static final String DISCONNECT = "disconnect";
// private static final String RUN_QUERY = "run query";
private static final String RUN_QUERY_TOOLTIP = "run the query in the SQL Editor";
private static final String RUN_QUERY_TO_FILE_TOOLTIP = "run the query in the SQL Editor and store result in file";
private static final String RUN_QUERY_TO_SHAPEFILE_TOOLTIP = "run the query in the SQL Editor and store result in a shapefile";
protected static final String VIEW_QUERY_TOOLTIP = "run spatial query and view the result in the geometry viewer";
// private static final String SQL_EDITOR = "SQL Editor";
private static final String CLEAR_SQL_EDITOR = "clear SQL editor";
// private static final String DATA_VIEWER = "Data viewer";
private static final String DATABASE_CONNECTIONS = "Database connection";
private static final String NEW = "new";
private static final String NEW_TOOLTIP = "create a new database";
private static final String CONNECT = "connect";
private static final String CONNECT_TOOLTIP = "connect to an existing database";
private static final String CONNECT_REMOTE = "remote";
private static final String CONNECT_REMOTE_TOOLTIP = "connect to a remote database";
private static final String DB_TREE_TITLE = "Database Connection";
protected GuiBridgeHandler guiBridge;
protected IHMProgressMonitor pm = new LogProgressMonitor();
protected ADb currentConnectedSqlDatabase;
protected INosqlDb currentConnectedNosqlDatabase;
protected DbLevel currentSelectedDb;
protected TableLevel currentSelectedTable;
protected ColumnLevel currentSelectedColumn;
protected LeafLevel currentSelectedLeaf;
private Dimension preferredToolbarButtonSize = new Dimension(120, 65);
private Dimension preferredSqleditorButtonSize = new Dimension(30, 30);
private List<String> oldSqlCommands = new ArrayList<String>();
protected SqlTemplatesAndActions sqlTemplatesAndActions;
private HMMapframe mapFrame;
private DatabaseTreeCellRenderer databaseTreeCellRenderer;
private JTextPane currentSqlEditorArea;
private JTextPane[] editorPanesArray;
private JTable[] dataTablesArray;
private JTable currentDataTable;
private DatabaseTreeView databaseTreeView;
private SqlEditorView sqlEditorView;
private DataTableView dataTableView;
public DatabaseController( GuiBridgeHandler guiBridge ) {
this.guiBridge = guiBridge;
setPreferredSize(new Dimension(1200, 900));
init();
}
@SuppressWarnings("serial")
private void init() {
databaseTreeView = new DatabaseTreeView();
_mainSplitPane.setLeftComponent(databaseTreeView);
sqlEditorView = new SqlEditorView();
dataTableView = new DataTableView();
JSplitPane rightSplitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sqlEditorView, dataTableView);
rightSplitPanel.setDividerLocation(0.3);
_mainSplitPane.setRightComponent(rightSplitPanel);
_mainSplitPane.setDividerLocation(0.3);
String[] oldSqlCommandsArray = PreferencesHandler.getPreference("HM_OLD_SQL_COMMANDS", new String[0]);
for( String oldSql : oldSqlCommandsArray ) {
oldSqlCommands.add(oldSql);
}
sqlEditorView._limitCountTextfield.setText("1000");
sqlEditorView._limitCountTextfield
.setToolTipText("1000 is default and used when no valid number is supplied. -1 means no limit.");
dataTableView._recordCountTextfield.setEditable(false);
sqlEditorView._sqlEditorAreaPanel.setLayout(new BorderLayout());
dataTableView._formatDatesPatternTextField.setText("date, ts, timestamp");
JTabbedPane tabbedDataViewerPane = new JTabbedPane();
JTabbedPane tabbedEditorPane = new JTabbedPane();
tabbedDataViewerPane.addChangeListener(e -> {
if (editorPanesArray != null && dataTablesArray != null) {
int selectedIndex = tabbedDataViewerPane.getSelectedIndex();
currentSqlEditorArea = editorPanesArray[selectedIndex];
currentDataTable = dataTablesArray[selectedIndex];
tabbedEditorPane.setSelectedIndex(selectedIndex);
}
});
tabbedEditorPane.addChangeListener(e -> {
if (editorPanesArray != null && dataTablesArray != null) {
int selectedIndex = tabbedEditorPane.getSelectedIndex();
currentSqlEditorArea = editorPanesArray[selectedIndex];
currentDataTable = dataTablesArray[selectedIndex];
tabbedDataViewerPane.setSelectedIndex(selectedIndex);
}
});
int tabCount = 5;
dataTablesArray = new JTable[tabCount];
for( int i = 0; i < tabCount; i++ ) {
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
tabbedDataViewerPane.addTab("Viewer " + (i + 1), panel1);
MultiLineTableCellRenderer wordWrapRenderer = new MultiLineTableCellRenderer();
JTable table = new JTable(){
public TableCellRenderer getCellRenderer( int row, int column ) {
if (currentConnectedNosqlDatabase != null) {
return wordWrapRenderer;
} else {
return super.getCellRenderer(row, column);
}
}
};
JScrollPane dataTablesScrollpane = new JScrollPane(table);
panel1.add(dataTablesScrollpane, BorderLayout.CENTER);
if (i == 0) {
currentDataTable = table;
}
dataTablesArray[i] = table;
addDataTableContextMenu(table);
}
editorPanesArray = new JTextPane[tabCount];
for( int i = 0; i < tabCount; i++ ) {
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
tabbedEditorPane.addTab("Editor " + (i + 1), panel1);
JTextPane sqlEditorArea = new JTextPane();
JScrollPane _sqlEditorAreaScrollpane = new JScrollPane(sqlEditorArea);
panel1.add(_sqlEditorAreaScrollpane, BorderLayout.CENTER);
SqlDocument doc = new SqlDocument();
sqlEditorArea.setDocument(doc);
if (i == 0) {
currentSqlEditorArea = sqlEditorArea;
}
addSqlAreaContextMenu(sqlEditorArea);
editorPanesArray[i] = sqlEditorArea;
}
sqlEditorView._sqlEditorAreaPanel.add(tabbedEditorPane, BorderLayout.CENTER);
dataTableView._dataViewerPanel.setLayout(new BorderLayout());
dataTableView._dataViewerPanel.add(tabbedDataViewerPane, BorderLayout.CENTER);
_newDbButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_newDbButton.setHorizontalTextPosition(SwingConstants.CENTER);
_newDbButton.setText(NEW);
_newDbButton.setToolTipText(NEW_TOOLTIP);
_newDbButton.setPreferredSize(preferredToolbarButtonSize);
_newDbButton.setIcon(ImageCache.getInstance().getImage(ImageCache.NEW_DATABASE));
_newDbButton.addActionListener(e -> {
JDialog f = new JDialog();
f.setModal(true);
NewDbController newDb = new NewDbController(f, guiBridge, false, null, null, null, null, false);
f.add(newDb, BorderLayout.CENTER);
f.setTitle("Create new database");
f.pack();
f.setIconImage(ImageCache.getInstance().getImage(ImageCache.NEW_DATABASE).getImage());
f.setLocationRelativeTo(_newDbButton);
f.setVisible(true);
f.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
if (newDb.isOk()) {
String dbPath = newDb.getDbPath();
String user = newDb.getDbUser();
String pwd = newDb.getDbPwd();
EDb dbType = newDb.getDbType();
createNewDatabase(dbType, dbPath, user, pwd);
}
});
_connectDbButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_connectDbButton.setHorizontalTextPosition(SwingConstants.CENTER);
_connectDbButton.setText(CONNECT);
_connectDbButton.setToolTipText(CONNECT_TOOLTIP);
_connectDbButton.setPreferredSize(preferredToolbarButtonSize);
_connectDbButton.setIcon(ImageCache.getInstance().getImage(ImageCache.CONNECT));
_connectDbButton.addActionListener(e -> {
JDialog f = new JDialog();
f.setModal(true);
String lastPath = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, "");
String lastUser = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, "sa");
String lastPwd = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, "");
NewDbController newDb = new NewDbController(f, guiBridge, true, lastPath, null, lastUser, lastPwd, true);
f.add(newDb, BorderLayout.CENTER);
f.setTitle("Open database");
f.pack();
f.setIconImage(ImageCache.getInstance().getImage(ImageCache.CONNECT).getImage());
f.setLocationRelativeTo(_connectDbButton);
f.setVisible(true);
f.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
if (newDb.isOk()) {
String dbPath = newDb.getDbPath();
String user = newDb.getDbUser();
String pwd = newDb.getDbPwd();
EDb dbType = newDb.getDbType();
boolean connectInRemote = newDb.connectInRemote();
if (connectInRemote) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, dbPath);
dbPath = "jdbc:h2:tcp://localhost:9092/" + dbPath;
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, pwd);
openRemoteDatabase(dbPath, user, pwd);
} else {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, dbPath);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, pwd);
openDatabase(dbType, dbPath, user, pwd);
}
}
});
_connectRemoteDbButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_connectRemoteDbButton.setHorizontalTextPosition(SwingConstants.CENTER);
_connectRemoteDbButton.setText(CONNECT_REMOTE);
_connectRemoteDbButton.setToolTipText(CONNECT_REMOTE_TOOLTIP);
_connectRemoteDbButton.setPreferredSize(preferredToolbarButtonSize);
_connectRemoteDbButton.setIcon(ImageCache.getInstance().getImage(ImageCache.CONNECT_REMOTE));
_connectRemoteDbButton.addActionListener(e -> {
JDialog f = new JDialog();
f.setModal(true);
String lastPath = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_URL,
"jdbc:h2:tcp://localhost:9092/absolute_dbpath");
String lastUser = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, "sa");
String lastPwd = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, "");
NewDbController newDb = new NewDbController(f, guiBridge, false, null, lastPath, lastUser, lastPwd, false);
f.add(newDb, BorderLayout.CENTER);
f.setTitle("Connect to remote database");
f.pack();
f.setIconImage(ImageCache.getInstance().getImage(ImageCache.CONNECT_REMOTE).getImage());
f.setLocationRelativeTo(_newDbButton);
f.setVisible(true);
f.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
if (newDb.isOk()) {
String dbPath = newDb.getDbPath();
String user = newDb.getDbUser();
String pwd = newDb.getDbPwd();
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, pwd);
openRemoteDatabase(dbPath, user, pwd);
}
});
_disconnectDbButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_disconnectDbButton.setHorizontalTextPosition(SwingConstants.CENTER);
_disconnectDbButton.setText(DISCONNECT);
_disconnectDbButton.setToolTipText(DISCONNECT_TOOLTIP);
_disconnectDbButton.setPreferredSize(preferredToolbarButtonSize);
_disconnectDbButton.setIcon(ImageCache.getInstance().getImage(ImageCache.DISCONNECT));
_disconnectDbButton.addActionListener(e -> {
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
});
_historyButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_historyButton.setHorizontalTextPosition(SwingConstants.CENTER);
_historyButton.setText(SQL_HISTORY);
_historyButton.setToolTipText(SQL_HISTORY_TOOLTIP);
_historyButton.setPreferredSize(preferredToolbarButtonSize);
_historyButton.setIcon(ImageCache.getInstance().getImage(ImageCache.HISTORY_DB));
_historyButton.addActionListener(e -> {
try {
if (oldSqlCommands.size() == 0) {
JOptionPane.showMessageDialog(this, "No history available.");
return;
}
String[] sqlHistory = oldSqlCommands.toArray(new String[0]);
String selected = GuiUtilities.showComboDialog(this, "HISTORY", "", sqlHistory, null);
if (selected != null) {
addTextToQueryEditor(selected);
}
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
});
_templatesButton.setVerticalTextPosition(SwingConstants.BOTTOM);
_templatesButton.setHorizontalTextPosition(SwingConstants.CENTER);
_templatesButton.setText(SQL_TEMPLATES);
_templatesButton.setToolTipText(SQL_TEMPLATES_TOOLTIP);
_templatesButton.setPreferredSize(preferredToolbarButtonSize);
_templatesButton.setIcon(ImageCache.getInstance().getImage(ImageCache.TEMPLATE));
_templatesButton.addActionListener(e -> {
try {
if (currentConnectedSqlDatabase == null) {
GuiUtilities.showWarningMessage(this, THIS_ACTION_IS_AVAILABLE_ONLY_FOR_SQL_DATABASES);
return;
}
LinkedHashMap<String, String> templatesMap = CommonQueries.getTemplatesMap(currentConnectedSqlDatabase.getType());
String[] sqlTemplates = templatesMap.keySet().toArray(new String[0]);
String selected = GuiUtilities.showComboDialog(this, "TEMPLATES", "", sqlTemplates, null);
if (selected != null) {
String sql = templatesMap.get(selected);
addTextToQueryEditor(sql);
}
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
});
addComponentListener(new ComponentListener(){
public void componentShown( ComponentEvent e ) {
}
public void componentResized( ComponentEvent e ) {
}
public void componentMoved( ComponentEvent e ) {
}
public void componentHidden( ComponentEvent e ) {
onClose();
}
});
try {
databaseTreeView._databaseTreeView.setMinimumSize(new Dimension(300, 200));
addJtreeDragNDrop();
addJtreeContextMenu();
setRightTreeRenderer();
databaseTreeView._databaseTree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged( TreeSelectionEvent evt ) {
TreePath[] paths = evt.getPaths();
currentSelectedDb = null;
currentSelectedTable = null;
currentSelectedColumn = null;
currentSelectedLeaf = null;
if (paths.length > 0) {
Object selectedItem = paths[0].getLastPathComponent();
if (selectedItem instanceof DbLevel) {
currentSelectedDb = (DbLevel) selectedItem;
} else if (selectedItem instanceof ColumnLevel) {
currentSelectedColumn = (ColumnLevel) selectedItem;
} else if (selectedItem instanceof TableLevel) {
currentSelectedTable = (TableLevel) selectedItem;
try {
QueryResult queryResult = null;
if (currentConnectedSqlDatabase != null) {
if (currentConnectedSqlDatabase instanceof ASpatialDb) {
queryResult = ((ASpatialDb) currentConnectedSqlDatabase).getTableRecordsMapIn(
currentSelectedTable.tableName, null, SQL_ONSELECT_LIMIT, -1, null);
} else {
queryResult = currentConnectedSqlDatabase.getTableRecordsMapFromRawSql(
"select * from " + currentSelectedTable.tableName, SQL_ONSELECT_LIMIT);
}
} else if (currentConnectedNosqlDatabase != null) {
INosqlCollection collection = currentConnectedNosqlDatabase
.getCollection(currentSelectedTable.tableName);
List<INosqlDocument> result = collection.find(null, NOSQL_ONSELECT_LIMIT);
queryResult = nosqlToQueryResult(result);
}
loadDataViewer(queryResult);
} catch (Exception e) {
Logger.INSTANCE.insertError("", "ERROR", e);
}
} else if (selectedItem instanceof LeafLevel) {
currentSelectedLeaf = (LeafLevel) selectedItem;
} else {
currentSelectedTable = null;
currentDataTable.setModel(new DefaultTableModel());
}
}
}
});
databaseTreeView._databaseTree.setVisible(false);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error", e1);
}
layoutTree(null, false);
sqlEditorView._runQueryButton.setIcon(ImageCache.getInstance().getImage(ImageCache.RUN));
sqlEditorView._runQueryButton.setToolTipText(RUN_QUERY_TOOLTIP);
sqlEditorView._runQueryButton.setText("");
sqlEditorView._runQueryButton.setPreferredSize(preferredSqleditorButtonSize);
sqlEditorView._runQueryButton.addActionListener(e -> {
String sqlText = currentSqlEditorArea.getText().trim();
if (sqlText.length() == 0) {
return;
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
boolean hadErrors = false;
try {
logConsole.beginProcess("Run query");
hadErrors = runQuery(sqlText, pm);
} catch (Exception ex) {
pm.errorMessage(ex.getLocalizedMessage());
hadErrors = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadErrors) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->run query").start();
});
sqlEditorView._runQueryAndStoreButton.setIcon(ImageCache.getInstance().getImage(ImageCache.RUN_TO_FILE));
sqlEditorView._runQueryAndStoreButton.setToolTipText(RUN_QUERY_TO_FILE_TOOLTIP);
sqlEditorView._runQueryAndStoreButton.setText("");
sqlEditorView._runQueryAndStoreButton.setPreferredSize(preferredSqleditorButtonSize);
sqlEditorView._runQueryAndStoreButton.addActionListener(e -> {
File selectedFile = null;
String sqlText = currentSqlEditorArea.getText().trim();
if (sqlText.length() > 0) {
if (isSelectOrPragma(sqlText)) {
File[] saveFiles = guiBridge.showSaveFileDialog("Select file to save to", PreferencesHandler.getLastFile(),
null);
if (saveFiles != null && saveFiles.length > 0) {
try {
PreferencesHandler.setLastPath(saveFiles[0].getAbsolutePath());
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
} else {
return;
}
selectedFile = saveFiles[0];
} else {
JOptionPane.showMessageDialog(this, "Writing to files is allowed only for SELECT statements and PRAGMAs.",
"WARNING", JOptionPane.WARNING_MESSAGE, null);
return;
}
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
final File f_selectedFile = selectedFile;
new Thread(() -> {
boolean hadErrors = false;
try {
if (f_selectedFile != null) {
logConsole.beginProcess("Run query");
hadErrors = runQueryToFile(sqlText, f_selectedFile, pm);
}
} catch (Exception ex) {
pm.errorMessage(ex.getLocalizedMessage());
hadErrors = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadErrors) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->run query to file").start();
});
sqlEditorView._runQueryAndStoreShapefileButton.setIcon(ImageCache.getInstance().getImage(ImageCache.RUN_TO_SHAPEFILE));
sqlEditorView._runQueryAndStoreShapefileButton.setToolTipText(RUN_QUERY_TO_SHAPEFILE_TOOLTIP);
sqlEditorView._runQueryAndStoreShapefileButton.setText("");
sqlEditorView._runQueryAndStoreShapefileButton.setPreferredSize(preferredSqleditorButtonSize);
sqlEditorView._runQueryAndStoreShapefileButton.addActionListener(e -> {
if (!(currentConnectedSqlDatabase instanceof ASpatialDb)) {
GuiUtilities.showWarningMessage(this, THIS_ACTION_IS_AVAILABLE_ONLY_FOR_SPATIAL_DATABASES);
return;
}
File selectedFile = null;
String sqlText = currentSqlEditorArea.getText().trim();
if (sqlText.length() > 0) {
if (sqlText.toLowerCase().startsWith("select")) {
File[] saveFiles = guiBridge.showSaveFileDialog("Select shapefile to save to",
PreferencesHandler.getLastFile(), HMConstants.vectorFileFilter);
if (saveFiles != null && saveFiles.length > 0) {
try {
PreferencesHandler.setLastPath(saveFiles[0].getAbsolutePath());
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
} else {
return;
}
selectedFile = saveFiles[0];
} else {
JOptionPane.showMessageDialog(this, "Writing to shapefile is allowed only for SELECT statements.", "WARNING",
JOptionPane.WARNING_MESSAGE, null);
return;
}
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
final File f_selectedFile = selectedFile;
new Thread(() -> {
boolean hadErrors = false;
try {
if (f_selectedFile != null) {
logConsole.beginProcess("Run query");
hadErrors = runQueryToShapefile(sqlText, f_selectedFile, pm);
}
} catch (Exception ex) {
pm.errorMessage(ex.getLocalizedMessage());
hadErrors = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadErrors) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->run query to shapefile").start();
});
setViewQueryButton(sqlEditorView._viewQueryButton, preferredSqleditorButtonSize, currentSqlEditorArea);
sqlEditorView._clearSqlEditorbutton.setIcon(ImageCache.getInstance().getImage(ImageCache.TRASH));
sqlEditorView._clearSqlEditorbutton.setToolTipText(CLEAR_SQL_EDITOR);
sqlEditorView._clearSqlEditorbutton.setText("");
sqlEditorView._clearSqlEditorbutton.setPreferredSize(preferredSqleditorButtonSize);
sqlEditorView._clearSqlEditorbutton.addActionListener(e -> {
currentSqlEditorArea.setText("");
});
}
protected abstract void setViewQueryButton( JButton _viewQueryButton, Dimension preferredButtonSize,
JTextPane sqlEditorArea );
@SuppressWarnings("serial")
private void addJtreeDragNDrop() {
databaseTreeView._databaseTree.setDragEnabled(true);
databaseTreeView._databaseTree.setTransferHandler(new TransferHandler(null){
public int getSourceActions( JComponent c ) {
return COPY;
}
protected Transferable createTransferable( JComponent c ) {
if (c instanceof JTree) {
if (currentSelectedColumn != null) {
return new StringSelection(currentSelectedColumn.columnName);
} else if (currentSelectedTable != null) {
return new StringSelection(currentSelectedTable.tableName);
}
}
return new StringSelection("");
}
});
}
@SuppressWarnings({"serial", "unchecked"})
private void addSqlAreaContextMenu( JTextPane sqlEditorArea ) {
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.setBorder(new BevelBorder(BevelBorder.RAISED));
popupMenu.addPopupMenuListener(new PopupMenuListener(){
@Override
public void popupMenuWillBecomeVisible( PopupMenuEvent e ) {
AbstractAction loadAction = new AbstractAction("Load saved query"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedQueries = PreferencesHandler.getPreference(HM_SAVED_QUERIES, new byte[0]);
List<SqlData> sqlDataList;
if (savedQueries.length == 0) {
sqlDataList = new ArrayList<>();
} else {
sqlDataList = (List<SqlData>) SqlTemplatesAndActions.convertFromBytes(savedQueries);
}
Set<String> checkSet = new TreeSet<>();
sqlDataList.removeIf(sd -> sd.name == null || !checkSet.add(sd.name));
if (sqlDataList.size() == 0) {
GuiUtilities.showWarningMessage(DatabaseController.this, null, "No saved queries available.");
} else {
sqlDataList.sort(( sd1, sd2 ) -> sd1.name.compareTo(sd2.name));
Map<String, SqlData> collect = sqlDataList.stream()
.collect(Collectors.toMap(c -> c.name, Function.identity()));
List<String> names = sqlDataList.stream().map(sd -> sd.name).collect(Collectors.toList());
String selected = GuiUtilities.showComboDialog(DatabaseController.this, "Select Query",
"Select the query to load", names.toArray(new String[0]), null);
if (selected != null && selected.length() > 0) {
SqlData sqlData = collect.get(selected);
if (sqlData != null) {
addTextToQueryEditor(sqlData.sql);
}
}
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
AbstractAction saveAction = new AbstractAction("Save current query"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedQueries = PreferencesHandler.getPreference(HM_SAVED_QUERIES, new byte[0]);
List<SqlData> sqlDataList = new ArrayList<>();
if (savedQueries.length != 0) {
sqlDataList = (List<SqlData>) SqlTemplatesAndActions.convertFromBytes(savedQueries);
}
String sql = currentSqlEditorArea.getText();
String newName = GuiUtilities.showInputDialog(DatabaseController.this,
"Enter a name for the saved query",
"query " + new DateTime().toString(HMConstants.dateTimeFormatterYYYYMMDDHHMMSS));
if (newName == null || newName.trim().length() == 0) {
return;
}
sqlDataList.removeIf(sd -> sd.name == newName);
SqlData sd = new SqlData();
sd.name = newName;
sd.sql = sql;
sqlDataList.add(sd);
byte[] bytesToSave = SqlTemplatesAndActions.convertObjectToBytes(sqlDataList);
PreferencesHandler.setPreference(HM_SAVED_QUERIES, bytesToSave);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
}
};
AbstractAction removeAction = new AbstractAction("Remove a query from saved"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedQueries = PreferencesHandler.getPreference(HM_SAVED_QUERIES, new byte[0]);
List<SqlData> sqlDataList = (List<SqlData>) SqlTemplatesAndActions.convertFromBytes(savedQueries);
Set<String> checkSet = new TreeSet<>();
sqlDataList.removeIf(sd -> sd.name == null || !checkSet.add(sd.name));
if (sqlDataList.size() == 0) {
GuiUtilities.showWarningMessage(DatabaseController.this, null, "No saved queries available.");
} else {
sqlDataList.sort(( sd1, sd2 ) -> sd1.name.compareTo(sd2.name));
List<String> names = sqlDataList.stream().map(sd -> sd.name).collect(Collectors.toList());
String selected = GuiUtilities.showComboDialog(DatabaseController.this, "Select Query",
"Select the query to remove", names.toArray(new String[0]), null);
if (selected != null && selected.length() > 0) {
sqlDataList.removeIf(sd -> {
if (sd.name == null)
return true;
return sd.name.equals(selected);
});
byte[] bytesToSave = SqlTemplatesAndActions.convertObjectToBytes(sqlDataList);
PreferencesHandler.setPreference(HM_SAVED_QUERIES, bytesToSave);
}
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
AbstractAction exportAction = new AbstractAction("Export saved queries"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedQueries = PreferencesHandler.getPreference(HM_SAVED_QUERIES, new byte[0]);
List<SqlData> sqlDataList = (List<SqlData>) SqlTemplatesAndActions.convertFromBytes(savedQueries);
JSONArray queriesArray = new JSONArray();
for( SqlData sqlData : sqlDataList ) {
JSONObject item = new JSONObject();
item.put(sqlData.name, sqlData.sql);
queriesArray.put(item);
}
String jsonString = queriesArray.toString(2);
File[] files = guiBridge.showSaveFileDialog("Select queries json to create",
PreferencesHandler.getLastFile(), new HMFileFilter("JSON Files", new String[]{"json"}));
if (files != null && files.length > 0) {
String absolutePath = files[0].getAbsolutePath();
PreferencesHandler.setLastPath(absolutePath);
FileUtilities.writeFile(jsonString, files[0]);
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
AbstractAction importAction = new AbstractAction("Import saved queries"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
File[] files = guiBridge.showOpenFileDialog("Select queries json to import",
PreferencesHandler.getLastFile(), new HMFileFilter("JSON Files", new String[]{"json"}));
if (files != null && files.length > 0) {
String absolutePath = files[0].getAbsolutePath();
PreferencesHandler.setLastPath(absolutePath);
byte[] savedQueries = PreferencesHandler.getPreference(HM_SAVED_QUERIES, new byte[0]);
List<SqlData> sqlDataList = new ArrayList<>();
if (savedQueries.length != 0) {
sqlDataList = (List<SqlData>) SqlTemplatesAndActions.convertFromBytes(savedQueries);
}
String json = FileUtilities.readFile(files[0]);
JSONArray queriesArray = new JSONArray(json);
for( int i = 0; i < queriesArray.length(); i++ ) {
JSONObject jsonObject = queriesArray.getJSONObject(i);
String[] names = JSONObject.getNames(jsonObject);
for( String name : names ) {
boolean hasAlready = sqlDataList.stream().anyMatch(sd -> sd.name.equals(name));
if (!hasAlready) {
SqlData newSqlData = new SqlData();
newSqlData.name = name;
newSqlData.sql = jsonObject.getString(name);
sqlDataList.add(newSqlData);
}
}
}
byte[] bytesToSave = SqlTemplatesAndActions.convertObjectToBytes(sqlDataList);
PreferencesHandler.setPreference(HM_SAVED_QUERIES, bytesToSave);
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
JMenuItem item = new JMenuItem(saveAction);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
item = new JMenuItem(loadAction);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
item = new JMenuItem(removeAction);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
popupMenu.addSeparator();
item = new JMenuItem(exportAction);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
item = new JMenuItem(importAction);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
}
@Override
public void popupMenuWillBecomeInvisible( PopupMenuEvent e ) {
popupMenu.removeAll();
}
@Override
public void popupMenuCanceled( PopupMenuEvent e ) {
popupMenu.removeAll();
}
});
sqlEditorArea.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked( MouseEvent e ) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = databaseTreeView._databaseTree.getClosestRowForLocation(e.getX(), e.getY());
databaseTreeView._databaseTree.setSelectionRow(row);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
private void addJtreeContextMenu() {
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.setBorder(new BevelBorder(BevelBorder.RAISED));
popupMenu.addPopupMenuListener(new PopupMenuListener(){
@Override
public void popupMenuWillBecomeVisible( PopupMenuEvent e ) {
if (currentSelectedTable != null) {
List<Action> tableActions = makeTableAction(currentSelectedTable);
for( Action action : tableActions ) {
if (action != null) {
JMenuItem item = new JMenuItem(action);
popupMenu.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
} else {
popupMenu.add(new JSeparator());
}
}
} else if (currentSelectedDb != null) {
List<Action> tableActions = makeDatabaseAction(currentSelectedDb);
for( Action action : tableActions ) {
if (action != null) {
JMenuItem item = new JMenuItem(action);
popupMenu.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
} else {
popupMenu.add(new JSeparator());
}
}
} else if (currentSelectedColumn != null) {
List<Action> columnActions = makeColumnActions(currentSelectedColumn);
for( Action action : columnActions ) {
if (action != null) {
JMenuItem item = new JMenuItem(action);
popupMenu.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
} else {
popupMenu.add(new JSeparator());
}
}
} else if (currentSelectedLeaf != null) {
List<Action> columnActions = makeLeafActions(currentSelectedLeaf);
for( Action action : columnActions ) {
if (action != null) {
JMenuItem item = new JMenuItem(action);
popupMenu.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
} else {
popupMenu.add(new JSeparator());
}
}
}
}
@Override
public void popupMenuWillBecomeInvisible( PopupMenuEvent e ) {
popupMenu.removeAll();
}
@Override
public void popupMenuCanceled( PopupMenuEvent e ) {
popupMenu.removeAll();
}
});
databaseTreeView._databaseTree.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked( MouseEvent e ) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = databaseTreeView._databaseTree.getClosestRowForLocation(e.getX(), e.getY());
databaseTreeView._databaseTree.setSelectionRow(row);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
addConnectButtonContextMenu();
}
@SuppressWarnings({"unchecked", "serial"})
private void addConnectButtonContextMenu() {
JPopupMenu popupMenuConnectButton = new JPopupMenu();
popupMenuConnectButton.setBorder(new BevelBorder(BevelBorder.RAISED));
popupMenuConnectButton.addPopupMenuListener(new PopupMenuListener(){
@Override
public void popupMenuWillBecomeVisible( PopupMenuEvent e ) {
AbstractAction loadConnectionAction = new AbstractAction("Load from saved Connection"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedDbs = PreferencesHandler.getPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES,
new byte[0]);
List<ConnectionData> connectionDataList;
if (savedDbs.length > 0) {
connectionDataList = (List<ConnectionData>) SqlTemplatesAndActions.convertFromBytes(savedDbs);
} else {
connectionDataList = new ArrayList<>();
}
connectionDataList.removeIf(c -> c.connectionLabel == null);
if (connectionDataList.size() == 0) {
GuiUtilities.showWarningMessage(DatabaseController.this, null, NO_SAVED_CONNECTIONS_AVAILABLE);
} else {
connectionDataList.sort(( c1, c2 ) -> c1.connectionLabel.compareTo(c2.connectionLabel));
Map<String, ConnectionData> collect = connectionDataList.stream().distinct()
.collect(Collectors.toMap(c -> c.connectionLabel, Function.identity()));
List<String> labels = connectionDataList.stream().map(c -> c.connectionLabel)
.collect(Collectors.toList());
String selected = GuiUtilities.showComboDialog(DatabaseController.this, "Select Connection",
"Select the connection to use", labels.toArray(new String[0]), null);
if (selected != null && selected.length() > 0) {
ConnectionData connectionData = collect.get(selected);
if (connectionData != null) {
openDatabase(connectionData, true);
}
}
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
AbstractAction removeAction = new AbstractAction("Remove from saved Connection"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedDbs = PreferencesHandler.getPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES,
new byte[0]);
List<ConnectionData> connectionDataList = (List<ConnectionData>) SqlTemplatesAndActions
.convertFromBytes(savedDbs);
connectionDataList.removeIf(c -> c.connectionLabel == null);
if (connectionDataList.size() == 0) {
GuiUtilities.showWarningMessage(DatabaseController.this, null, NO_SAVED_CONNECTIONS_AVAILABLE);
} else {
connectionDataList.sort(( c1, c2 ) -> c1.connectionLabel.compareTo(c2.connectionLabel));
List<String> labels = connectionDataList.stream().map(c -> c.connectionLabel)
.collect(Collectors.toList());
String selected = GuiUtilities.showComboDialog(DatabaseController.this, "Select Connection",
"Select the connection to remove", labels.toArray(new String[0]), null);
if (selected != null && selected.length() > 0) {
connectionDataList.removeIf(cd -> {
if (cd.connectionLabel == null)
return true;
return cd.connectionLabel.equals(selected);
});
byte[] bytesToSave = SqlTemplatesAndActions.convertObjectToBytes(connectionDataList);
PreferencesHandler.setPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES, bytesToSave);
}
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
AbstractAction exportAction = new AbstractAction("Export saved connections"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
byte[] savedDbs = PreferencesHandler.getPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES,
new byte[0]);
if (savedDbs.length == 0) {
GuiUtilities.showWarningMessage(DatabaseController.this, null, NO_SAVED_CONNECTIONS_AVAILABLE);
} else {
List<ConnectionData> connectionDataList = (List<ConnectionData>) SqlTemplatesAndActions
.convertFromBytes(savedDbs);
if (connectionDataList.size() > 0) {
JSONArray queriesArray = new JSONArray();
for( ConnectionData connData : connectionDataList ) {
if (connData.connectionLabel != null && connData.connectionLabel.length() != 0) {
JSONObject item = new JSONObject();
item.put("type", connData.dbType);
item.put("label", connData.connectionLabel);
item.put("url", connData.connectionUrl);
item.put("user", connData.user);
item.put("pwd", connData.password);
queriesArray.put(item);
}
}
String jsonString = queriesArray.toString(2);
File[] files = guiBridge.showSaveFileDialog("Select connections json to create",
PreferencesHandler.getLastFile(),
new HMFileFilter("JSON Files", new String[]{"json"}));
if (files != null && files.length > 0) {
String absolutePath = files[0].getAbsolutePath();
PreferencesHandler.setLastPath(absolutePath);
FileUtilities.writeFile(jsonString, files[0]);
}
} else {
GuiUtilities.showWarningMessage(DatabaseController.this, null,
NO_SAVED_CONNECTIONS_AVAILABLE);
}
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
Logger.INSTANCE.insertError("", "ERROR", e1);
}
}
};
AbstractAction importAction = new AbstractAction("Import saved connections"){
@Override
public void actionPerformed( ActionEvent e ) {
try {
File[] files = guiBridge.showOpenFileDialog("Select connections json to import",
PreferencesHandler.getLastFile(), new HMFileFilter("JSON Files", new String[]{"json"}));
if (files != null && files.length > 0) {
String absolutePath = files[0].getAbsolutePath();
PreferencesHandler.setLastPath(absolutePath);
byte[] savedConnections = PreferencesHandler
.getPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES, new byte[0]);
List<ConnectionData> connectionsDataList = new ArrayList<>();
if (savedConnections.length != 0) {
connectionsDataList = (List<ConnectionData>) SqlTemplatesAndActions
.convertFromBytes(savedConnections);
}
String json = FileUtilities.readFile(files[0]);
JSONArray queriesArray = new JSONArray(json);
for( int i = 0; i < queriesArray.length(); i++ ) {
JSONObject jsonObject = queriesArray.getJSONObject(i);
if (jsonObject.has("label")) {
String label = jsonObject.getString("label");
boolean hasAlready = connectionsDataList.stream().anyMatch(sd -> sd != null
&& sd.connectionLabel != null && sd.connectionLabel.equals(label));
if (!hasAlready) {
ConnectionData newConnectionData = new ConnectionData();
newConnectionData.dbType = jsonObject.getInt("type");
newConnectionData.connectionLabel = label;
newConnectionData.connectionUrl = jsonObject.getString("url");
newConnectionData.user = jsonObject.getString("user");
newConnectionData.password = jsonObject.getString("pwd");
connectionsDataList.add(newConnectionData);
}
}
}
byte[] bytesToSave = SqlTemplatesAndActions.convertObjectToBytes(connectionsDataList);
PreferencesHandler.setPreference(SqlTemplatesAndActions.HM_SAVED_DATABASES, bytesToSave);
}
} catch (Exception e1) {
GuiUtilities.showErrorMessage(DatabaseController.this, e1.getMessage());
}
}
};
JMenuItem item = new JMenuItem(loadConnectionAction);
popupMenuConnectButton.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
item = new JMenuItem(removeAction);
popupMenuConnectButton.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenuConnectButton.addSeparator();
item = new JMenuItem(exportAction);
popupMenuConnectButton.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
item = new JMenuItem(importAction);
popupMenuConnectButton.add(item);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
@Override
public void popupMenuWillBecomeInvisible( PopupMenuEvent e ) {
popupMenuConnectButton.removeAll();
}
@Override
public void popupMenuCanceled( PopupMenuEvent e ) {
popupMenuConnectButton.removeAll();
}
});
_connectDbButton.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked( MouseEvent e ) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = databaseTreeView._databaseTree.getClosestRowForLocation(e.getX(), e.getY());
databaseTreeView._databaseTree.setSelectionRow(row);
popupMenuConnectButton.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
private void addDataTableContextMenu( JTable table ) {
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.setBorder(new BevelBorder(BevelBorder.RAISED));
popupMenu.addPopupMenuListener(new PopupMenuListener(){
@Override
public void popupMenuWillBecomeVisible( PopupMenuEvent e ) {
int[] selectedRows = table.getSelectedRows();
int[] selectedCols = table.getSelectedColumns();
boolean isGeom = false;
boolean isBinary = false;
boolean proposeChart = false;
ESpatialiteGeometryType geomType = null;
if (selectedCols.length == 1 && selectedRows.length > 0) {
// check content
Object valueObj = table.getValueAt(selectedRows[0], selectedCols[0]);
if (valueObj instanceof byte[] || valueObj instanceof JdbcBlob) {
isBinary = true;
}
String valueAt = valueObj.toString();
String checkString = valueAt.split("\\(")[0].trim();
checkString = removeSrid(checkString);
if (ESpatialiteGeometryType.isGeometryName(checkString)) {
isGeom = true;
geomType = ESpatialiteGeometryType.forName(checkString);
}
}
if (selectedCols.length > 1 && selectedRows.length > 1) {
proposeChart = true;
}
JMenuItem item = new JMenuItem(new AbstractAction("Copy cells content"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
table.getTransferHandler().exportToClipboard(table, clipboard, TransferHandler.COPY);
}
});
item.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item);
if (isBinary) {
JMenuItem item1 = new JMenuItem(new AbstractAction("View as image"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
for( int r : selectedRows ) {
Object valueObj = table.getValueAt(r, selectedCols[0]);
byte[] bytes = null;
if (valueObj instanceof JdbcBlob) {
JdbcBlob blob = (JdbcBlob) valueObj;
try {
bytes = blob.getBytes(0, (int) blob.length());
} catch (SQLException e1) {
Logger.INSTANCE.e("error reading image bytes", e1);
continue;
}
} else if (valueObj instanceof byte[]) {
bytes = (byte[]) valueObj;
}
if (bytes != null) {
try {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
GuiUtilities.showImage(popupMenu, valueObj.toString(), image);
} catch (IOException e1) {
GuiUtilities.showWarningMessage(popupMenu, "Not an image.");
break;
}
}
}
}
});
item1.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item1);
JMenuItem itemToString = new JMenuItem(new AbstractAction("View as string"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
for( int r : selectedRows ) {
Object valueObj = table.getValueAt(r, selectedCols[0]);
byte[] bytes = null;
if (valueObj instanceof JdbcBlob) {
JdbcBlob blob = (JdbcBlob) valueObj;
try {
bytes = blob.getBytes(0, (int) blob.length());
} catch (SQLException e1) {
Logger.INSTANCE.e("error reading image bytes", e1);
continue;
}
} else if (valueObj instanceof byte[]) {
bytes = (byte[]) valueObj;
}
if (bytes != null) {
String string = new String(bytes);
JTextArea tArea = new JTextArea(string, 10, 20);
JPanel p = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane(tArea);
p.add(scroll, BorderLayout.CENTER);
tArea.setLineWrap(true);
GuiUtilities.openDialogWithPanel(p, "Cell as string", new Dimension(600, 500), false);
}
}
}
});
itemToString.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(itemToString);
}
if (proposeChart) {
JMenuItem item1 = new JMenuItem(new AbstractAction("Chart values"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
try {
int chartsCount = selectedCols.length - 1;
String xLabel = table.getColumnName(selectedCols[0]);
Scatter scatterChart = null;
CategoryHistogram categoryHistogram = null;
for( int i = 0; i < chartsCount; i++ ) {
Object tmpX = table.getValueAt(0, selectedCols[0]);
boolean doCat = true;
if (tmpX instanceof Number) {
doCat = false;
}
Object tmpY = table.getValueAt(0, selectedCols[i + 1]);
if (!(tmpY instanceof Number)) {
break;
}
if (doCat) {
if (categoryHistogram == null) {
String[] xStr = new String[selectedRows.length];
double[] y = new double[selectedRows.length];
for( int r : selectedRows ) {
Object xObj = table.getValueAt(r, selectedCols[0]);
Object yObj = table.getValueAt(r, selectedCols[i + 1]);
xStr[r] = xObj.toString();
y[r] = ((Number) yObj).doubleValue();
}
categoryHistogram = new CategoryHistogram(xStr, y);
}
} else {
if (scatterChart == null) {
scatterChart = new Scatter("");
List<Boolean> showLines = new ArrayList<Boolean>();
for( int j = 0; j < chartsCount; j++ ) {
showLines.add(true);
}
scatterChart.setShowLines(showLines);
scatterChart.setXLabel(xLabel);
scatterChart.setYLabel("");
}
double[] x = new double[selectedRows.length];
double[] y = new double[selectedRows.length];
String seriesName = table.getColumnName(selectedCols[i + 1]);
for( int r : selectedRows ) {
Object xObj = table.getValueAt(r, selectedCols[0]);
Object yObj = table.getValueAt(r, selectedCols[i + 1]);
x[r] = ((Number) xObj).doubleValue();
y[r] = ((Number) yObj).doubleValue();
}
scatterChart.addSeries(seriesName, x, y);
}
}
Dimension dimension = new Dimension(800, 600);
if (scatterChart != null) {
JFreeChart chart = scatterChart.getChart();
ChartPanel chartPanel = new ChartPanel(chart, true);
chartPanel.setPreferredSize(dimension);
JPanel p = new JPanel(new BorderLayout());
p.add(chartPanel, BorderLayout.CENTER);
GuiUtilities.openDialogWithPanel(p, "Chart from cells", dimension, false);
} else if (categoryHistogram != null) {
JFreeChart chart = categoryHistogram.getChart();
ChartPanel chartPanel = new ChartPanel(chart, true);
chartPanel.setPreferredSize(dimension);
JPanel p = new JPanel(new BorderLayout());
p.add(chartPanel, BorderLayout.CENTER);
GuiUtilities.openDialogWithPanel(p, "Chart from cells", dimension, false);
} else {
GuiUtilities.showWarningMessage(popupMenu, "Charting of selected data not possible.");
}
} catch (Exception ex) {
Logger.INSTANCE.insertError("", "ERROR", ex);
}
}
});
item1.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item1);
}
if (isGeom) {
JMenuItem item1 = new JMenuItem(new AbstractAction("View geometry"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
WKTReader wktReader = new WKTReader();
List<Geometry> geomsList = new ArrayList<>();
for( int r : selectedRows ) {
try {
String valueAt = table.getValueAt(r, selectedCols[0]).toString();
valueAt = removeSrid(valueAt);
Geometry geometry = wktReader.read(valueAt);
if (geometry instanceof GeometryCollection) {
int numGeometries = geometry.getNumGeometries();
for( int j = 0; j < numGeometries; j++ ) {
Geometry geometryN = geometry.getGeometryN(j);
geomsList.add(geometryN);
}
} else {
geomsList.add(geometry);
}
} catch (ParseException e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
}
if (geomsList.size() > 0) {
List<SimpleFeatureCollection> fcs = FeatureUtilities.featureCollectionsFromGeometry(null,
geomsList.toArray(new Geometry[0]));
showInMapFrame(false, fcs.toArray(new SimpleFeatureCollection[0]), null);
}
}
});
item1.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item1);
JMenuItem item2 = new JMenuItem(new AbstractAction("Plot geometry"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
WKTReader wktReader = new WKTReader();
List<Geometry> geomsList = new ArrayList<>();
for( int r : selectedRows ) {
try {
String valueAt = table.getValueAt(r, selectedCols[0]).toString();
valueAt = removeSrid(valueAt);
Geometry geometry = wktReader.read(valueAt);
if (geometry instanceof GeometryCollection) {
int numGeometries = geometry.getNumGeometries();
for( int j = 0; j < numGeometries; j++ ) {
Geometry geometryN = geometry.getGeometryN(j);
geomsList.add(geometryN);
}
} else {
geomsList.add(geometry);
}
} catch (ParseException e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
}
if (geomsList.size() > 0) {
HM.plotJtsGeometries(null, geomsList);
}
}
});
item2.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item2);
if (geomType != null && !geomType.isPoint()) {
JMenuItem item3 = new JMenuItem(new AbstractAction("View geometry with directions hint"){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed( ActionEvent e ) {
WKTReader wktReader = new WKTReader();
List<Geometry> geomsList = new ArrayList<>();
for( int r : selectedRows ) {
try {
String valueAt = table.getValueAt(r, selectedCols[0]).toString();
valueAt = removeSrid(valueAt);
Geometry geometry = wktReader.read(valueAt);
if (geometry instanceof GeometryCollection) {
int numGeometries = geometry.getNumGeometries();
for( int j = 0; j < numGeometries; j++ ) {
Geometry geometryN = geometry.getGeometryN(j);
List<Polygon> simpleDirectionArrows = GeometryUtilities
.createSimpleDirectionArrow(geometryN);
geomsList.add(geometryN);
geomsList.addAll(simpleDirectionArrows);
}
} else {
List<Polygon> simpleDirectionArrows = GeometryUtilities
.createSimpleDirectionArrow(geometry);
geomsList.add(geometry);
geomsList.addAll(simpleDirectionArrows);
}
} catch (ParseException e1) {
Logger.INSTANCE.insertError("", "ERROR", e1);
}
}
if (geomsList.size() > 0) {
List<SimpleFeatureCollection> fcs = FeatureUtilities.featureCollectionsFromGeometry(null,
geomsList.toArray(new Geometry[0]));
showInMapFrame(false, fcs.toArray(new SimpleFeatureCollection[0]), null);
}
}
});
item3.setHorizontalTextPosition(JMenuItem.RIGHT);
popupMenu.add(item3);
}
}
}
private String removeSrid( String valueAt ) {
if (valueAt.startsWith("SRID=")) {
valueAt = valueAt.split(";")[1];
}
return valueAt;
}
@Override
public void popupMenuWillBecomeInvisible( PopupMenuEvent e ) {
popupMenu.removeAll();
}
@Override
public void popupMenuCanceled( PopupMenuEvent e ) {
popupMenu.removeAll();
}
});
table.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked( MouseEvent e ) {
if (SwingUtilities.isRightMouseButton(e)) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
protected void loadDataViewer( QueryResult queryResult ) {
if (queryResult == null) {
currentDataTable.setModel(new DefaultTableModel());
return;
}
boolean doDates = dataTableView._formatDatesCheckbox.isSelected();
String[] patternSplit = dataTableView._formatDatesPatternTextField.getText().split(",");
List<String> patternsList = new ArrayList<String>();
for( String pattern : patternSplit ) {
pattern = pattern.trim();
if (pattern.length() > 0) {
patternsList.add(pattern.toLowerCase());
}
}
String[] names = queryResult.names.toArray(new String[0]);
List<Object[]> data = queryResult.data;
Object[][] values = new Object[queryResult.data.size()][];
int index = 0;
for( Object[] objects : data ) {
values[index++] = objects;
for( int i = 0; i < objects.length; i++ ) {
String fieldName = names[i];
if (objects[i] instanceof Date) {
Date date = (Date) objects[i];
String formatted = DbsUtilities.dbDateFormatter.format(date);
objects[i] = formatted;
} else if (doDates && patternsList.contains(fieldName.toLowerCase())) {
if (objects[i] instanceof Number) {
Number num = (Number) objects[i];
long longValue = num.longValue();
if (longValue == 0) {
objects[i] = "";
} else {
Date newDate = new Date(longValue);
String formatted = DbsUtilities.dbDateFormatter.format(newDate);
objects[i] = formatted;
}
}
} else if(objects[i] == null) {
objects[i] = "NULL";
}
}
}
currentDataTable.setModel(new DefaultTableModel(values, names));
currentDataTable.setCellSelectionEnabled(true);
if (currentConnectedNosqlDatabase != null) {
currentDataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
} else if (currentConnectedSqlDatabase != null) {
currentDataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
for( int column = 0; column < currentDataTable.getColumnCount(); column++ ) {
TableColumn tableColumn = currentDataTable.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for( int row = 0; row < currentDataTable.getRowCount(); row++ ) {
TableCellRenderer cellRenderer = currentDataTable.getCellRenderer(row, column);
Component c = currentDataTable.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + currentDataTable.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
if (preferredWidth >= maxWidth) {
preferredWidth = maxWidth;
break;
}
}
if (preferredWidth < 50) {
preferredWidth = 50;
}
if (preferredWidth > 300) {
preferredWidth = 300;
}
tableColumn.setPreferredWidth(preferredWidth);
}
dataTableView._recordCountTextfield.setText(values.length + " in " + millisToTimeString(queryResult.queryTimeMillis));
}
private void layoutTree( DbLevel dbLevel, boolean expandNodes ) {
toggleButtonsEnabling(dbLevel != null);
String title = "";
if (dbLevel != null) {
databaseTreeView._databaseTree.setVisible(true);
// title = dbLevel.dbName;
if (currentConnectedSqlDatabase != null) {
title = currentConnectedSqlDatabase.getDatabasePath();
} else if (currentConnectedNosqlDatabase != null) {
title = currentConnectedNosqlDatabase.getDbEngineUrl();
}
} else {
dbLevel = new DbLevel();
databaseTreeView._databaseTree.setVisible(false);
title = DATABASE_CONNECTIONS;
}
setDbTreeTitle(title);
DatabaseTreeModel model = new DatabaseTreeModel();
model.setRoot(dbLevel);
databaseTreeView._databaseTree.setModel(model);
if (expandNodes) {
databaseTreeView._databaseTree.expandRow(0);
databaseTreeView._databaseTree.expandRow(1);
}
// expandAllNodes(_databaseTree, 0, 2);
}
private void toggleButtonsEnabling( boolean enable ) {
sqlEditorView._runQueryButton.setEnabled(enable);
sqlEditorView._runQueryAndStoreButton.setEnabled(enable);
sqlEditorView._runQueryAndStoreShapefileButton.setEnabled(enable);
_templatesButton.setEnabled(enable);
_historyButton.setEnabled(enable);
sqlEditorView._clearSqlEditorbutton.setEnabled(enable);
sqlEditorView._viewQueryButton.setEnabled(enable);
dataTableView._recordCountTextfield.setText("");
currentSqlEditorArea.setText("");
currentSqlEditorArea.setEditable(enable);
}
// private void expandAllNodes( JTree tree, int startingIndex, int rowCount ) {
// for( int i = startingIndex; i < rowCount; ++i ) {
// tree.expandRow(i);
// }
//
// if (tree.getRowCount() != rowCount) {
// expandAllNodes(tree, rowCount, tree.getRowCount());
// }
// }
public JComponent asJComponent() {
return this;
}
public void onClose() {
if (currentConnectedSqlDatabase != null) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_SPATIALITE_LAST_FILE,
currentConnectedSqlDatabase.getDatabasePath());
}
try {
closeCurrentDb(false);
} catch (Exception e) {
Logger.INSTANCE.insertError("", "Error", e);
}
}
protected void createNewDatabase( EDb dbType, String dbfilePath, String user, String pwd ) {
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error closing the database...", e1);
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
logConsole.beginProcess("Create new database");
boolean hadError = false;
try {
if (dbType == EDb.SPATIALITE) {
currentConnectedSqlDatabase = new GTSpatialiteThreadsafeDb();
} else {
currentConnectedSqlDatabase = dbType.getSpatialDb();
}
currentConnectedSqlDatabase.setCredentials(user, pwd);
currentConnectedSqlDatabase.open(dbfilePath);
if (currentConnectedSqlDatabase instanceof ASpatialDb) {
((ASpatialDb) currentConnectedSqlDatabase).initSpatialMetadata(null);
}
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedSqlDatabase.getType());
setRightTreeRenderer();
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
layoutTree(dbLevel, false);
} catch (Exception e) {
currentConnectedSqlDatabase = null;
Logger.INSTANCE.insertError("", "Error connecting to the database...", e);
hadError = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadError) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->create new database").start();
}
private void setRightTreeRenderer() {
if (currentConnectedSqlDatabase != null) {
databaseTreeCellRenderer = new DatabaseTreeCellRenderer(currentConnectedSqlDatabase);
} else if (currentConnectedNosqlDatabase != null) {
databaseTreeCellRenderer = new DatabaseTreeCellRenderer(currentConnectedNosqlDatabase);
}
databaseTreeView._databaseTree.setCellRenderer(databaseTreeCellRenderer);
}
protected void setDbTreeTitle( String title ) {
Border databaseTreeViewBorder = databaseTreeView._databaseTreeView.getBorder();
if (databaseTreeViewBorder instanceof TitledBorder) {
TitledBorder tBorder = (TitledBorder) databaseTreeViewBorder;
tBorder.setTitle(title);
databaseTreeView._databaseTreeView.repaint();
databaseTreeView._databaseTreeView.invalidate();
}
}
protected void openDatabase( EDb dbType, String dbfilePath, String user, String pwd ) {
if (dbfilePath == null && dbType == null) {
return;
}
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error closing the database...", e1);
}
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
new Thread(() -> {
logConsole.beginProcess("Open database");
boolean hadError = false;
try {
DbLevel dbLevel = null;
String dbPath;
if (!dbType.isNosql()) {
if (dbType == EDb.SPATIALITE) {
if (SpatialiteCommonMethods.isSqliteFile(new File(dbfilePath))) {
currentConnectedSqlDatabase = new GTSpatialiteThreadsafeDb();
} else {
guiBridge.messageDialog("The selected file is not a Spatialite database.", "WARNING",
JOptionPane.WARNING_MESSAGE);
return;
}
} else {
currentConnectedSqlDatabase = dbType.getSpatialDb();
}
currentConnectedSqlDatabase.setCredentials(user, pwd);
try {
currentConnectedSqlDatabase.open(dbfilePath);
} catch (JdbcSQLException e) {
String message = e.getMessage();
if (message.contains("Wrong user name or password")) {
guiBridge.messageDialog("Wrong user name or password.", "ERROR", JOptionPane.ERROR_MESSAGE);
currentConnectedSqlDatabase = null;
return;
}
if (message.contains("Database may be already in use")) {
guiBridge.messageDialog("Database may be already in use. Close all connections or use server mode.",
"ERROR", JOptionPane.ERROR_MESSAGE);
currentConnectedSqlDatabase = null;
return;
}
} catch (Exception e) {
Logger.INSTANCE.insertError("", "ERROR", e);
hadError = true;
}
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedSqlDatabase.getType());
dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
dbPath = currentConnectedSqlDatabase.getDatabasePath();
} else {
currentConnectedNosqlDatabase = dbType.getNosqlDb();
currentConnectedNosqlDatabase.setCredentials(user, pwd);
currentConnectedNosqlDatabase.open(dbfilePath);
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedNosqlDatabase.getType());
dbPath = currentConnectedNosqlDatabase.getDbEngineUrl();
dbLevel = gatherDatabaseLevels(currentConnectedNosqlDatabase);
}
setRightTreeRenderer();
layoutTree(dbLevel, true);
setDbTreeTitle(dbPath);
} catch (Exception e) {
currentConnectedSqlDatabase = null;
currentConnectedNosqlDatabase = null;
Logger.INSTANCE.insertError("", "Error connecting to the database...", e);
hadError = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadError) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->open database").start();
}
protected void openRemoteDatabase( String urlString, String user, String pwd ) {
try {
closeCurrentDb(true);
} catch (Exception e1) {
Logger.INSTANCE.insertError("", "Error closing the database...", e1);
}
EDb type = null;
if (urlString.trim().startsWith(EDb.H2GIS.getJdbcPrefix())) {
type = EDb.H2GIS;
} else if (urlString.trim().startsWith(EDb.POSTGIS.getJdbcPrefix())) {
type = EDb.POSTGIS;
} else if (urlString.trim().startsWith(EDb.MONGODB.getJdbcPrefix())) {
type = EDb.MONGODB;
}
if (type == null) {
guiBridge.messageDialog("Only H2GIS, MongoDb and Postgis databases are supported in remote connection.", "ERROR",
JOptionPane.WARNING_MESSAGE);
return;
}
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_URL, urlString);
urlString = urlString.replaceFirst(type.getJdbcPrefix(), "");
final LogConsoleController logConsole = new LogConsoleController(null);
pm = logConsole.getProgressMonitor();
Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
JFrame window = guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
EDb _type = type;
String _urlString = urlString;
new Thread(() -> {
logConsole.beginProcess("Open database");
boolean hadError = false;
try {
if (!_type.isNosql()) {
if (_type.isSpatial()) {
currentConnectedSqlDatabase = _type.getSpatialDb();
} else {
currentConnectedSqlDatabase = _type.getDb();
}
currentConnectedSqlDatabase.setCredentials(user, pwd);
currentConnectedSqlDatabase.open(_urlString);
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedSqlDatabase.getType());
setRightTreeRenderer();
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
layoutTree(dbLevel, true);
setDbTreeTitle(currentConnectedSqlDatabase.getDatabasePath());
} else {
currentConnectedNosqlDatabase = _type.getNosqlDb();
currentConnectedNosqlDatabase.setCredentials(user, pwd);
currentConnectedNosqlDatabase.open(_urlString);
sqlTemplatesAndActions = new SqlTemplatesAndActions(currentConnectedNosqlDatabase.getType());
setRightTreeRenderer();
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedNosqlDatabase);
layoutTree(dbLevel, true);
setDbTreeTitle(currentConnectedNosqlDatabase.getDbEngineUrl());
}
} catch (Exception e) {
currentConnectedSqlDatabase = null;
currentConnectedNosqlDatabase = null;
Logger.INSTANCE.insertError("", "Error connecting to the database...", e);
hadError = true;
} finally {
logConsole.finishProcess();
logConsole.stopLogging();
Logger.INSTANCE.resetStreams();
if (!hadError) {
logConsole.setVisible(false);
window.dispose();
}
}
}, "DatabaseController->open remote database").start();
}
protected void openDatabase( ConnectionData connectionData, boolean openDialog ) {
EDb type = EDb.forCode(connectionData.dbType);
if (type.supportsDesktop()) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, connectionData.connectionUrl);
} else if (type.supportsServerMode()) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_URL,
type.getJdbcPrefix() + connectionData.connectionUrl);
}
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, connectionData.user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, connectionData.password);
if (openDialog) {
// open dialog on that to allow for simple changes
JDialog f = new JDialog();
f.setModal(true);
String lastPath = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, "");
String lastUser = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, "sa");
String lastPwd = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, "");
String lastUrl = PreferencesHandler.getPreference(DatabaseGuiUtils.HM_JDBC_LAST_URL, "");
NewDbController newDb = new NewDbController(f, guiBridge, true, lastPath, lastUrl, lastUser, lastPwd, true);
f.add(newDb, BorderLayout.CENTER);
f.setTitle("Open database");
f.pack();
f.setIconImage(ImageCache.getInstance().getImage(ImageCache.CONNECT).getImage());
f.setLocationRelativeTo(_connectDbButton);
f.setVisible(true);
f.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
if (newDb.isOk()) {
String dbPath = newDb.getDbPath();
String user = newDb.getDbUser();
String pwd = newDb.getDbPwd();
EDb dbType = EDb.forCode(connectionData.dbType);
boolean connectInRemote = newDb.connectInRemote();
if (connectInRemote) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, dbPath);
dbPath = "jdbc:h2:tcp://localhost:9092/" + dbPath;
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, pwd);
openRemoteDatabase(dbPath, user, pwd);
} else {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_USER, user);
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_PWD, pwd);
if (dbPath.toLowerCase().contains("jdbc")) {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_JDBC_LAST_URL, dbPath);
openRemoteDatabase(dbPath, user, pwd);
} else {
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_LOCAL_LAST_FILE, dbPath);
openDatabase(dbType, dbPath, user, pwd);
}
}
}
} else {
openDatabase(type, connectionData.connectionUrl, connectionData.user, connectionData.password);
}
}
protected DbLevel gatherDatabaseLevels( ADb db ) throws Exception {
DbLevel currentDbLevel = DbLevel.getDbLevel(db, SpatialiteTableNames.ALL_TYPES_LIST.toArray(new String[0]));
return currentDbLevel;
}
protected DbLevel gatherDatabaseLevels( INosqlDb db ) throws Exception {
DbLevel currentDbLevel = DbLevel.getDbLevel(db, SpatialiteTableNames.ALL_TYPES_LIST.toArray(new String[0]));
return currentDbLevel;
}
protected void closeCurrentDb( boolean manually ) throws Exception {
setDbTreeTitle(DB_TREE_TITLE);
layoutTree(null, false);
loadDataViewer(null);
if (currentConnectedSqlDatabase != null) {
currentConnectedSqlDatabase.close();
currentConnectedSqlDatabase = null;
} else if (currentConnectedNosqlDatabase != null) {
currentConnectedNosqlDatabase.close();
currentConnectedNosqlDatabase = null;
}
dataTableView._recordCountTextfield.setText("");
if (manually)
PreferencesHandler.setPreference(DatabaseGuiUtils.HM_SPATIALITE_LAST_FILE, (String) null);
}
protected boolean runQuery( String sqlText, IHMProgressMonitor pm ) {
if (pm == null) {
pm = this.pm;
}
boolean hasError = false;
int limit = getLimit();
if (currentConnectedSqlDatabase != null && sqlText.length() > 0) {
try {
String[] split = sqlText.split("\n");
StringBuilder sb = new StringBuilder();
for( String string : split ) {
if (string.trim().startsWith("--")) {
continue;
}
sb.append(string).append("\n");
}
sqlText = sb.toString();
int maxLength = 100;
String queryForLog;
if (sqlText.length() > maxLength) {
queryForLog = sqlText.substring(0, maxLength) + "...";
} else {
queryForLog = sqlText;
}
pm.beginTask("Run query: " + queryForLog, IHMProgressMonitor.UNKNOWN);
if (sqlText.contains(";")) {
String trim = sqlText.replaceAll("\n", " ").trim();
String[] querySplit = trim.split(";");
if (querySplit.length > 1) {
pm.message("Runnng in multi query mode, since a semicolon has been found.");
for( String sql : querySplit ) {
if (isSelectOrPragma(sql)) {
QueryResult queryResult = currentConnectedSqlDatabase.getTableRecordsMapFromRawSql(sql, limit);
loadDataViewer(queryResult);
// TODO } else if (sql.toLowerCase().startsWith("copy ")) {
// EDb type = currentConnectedDatabase.getType();
// if (type == EDb.POSTGIS
// || type == EDb.POSTGRES) {
// currentConnectedDatabase.execOnConnection(connection -> {
//// try (IHMStatement stmt = connection.createStatement()) {
//// return stmt.executeUpdate(sql);
//// }
// Connection originalConnection = ((HMConnection)connection).getOriginalConnection();
// if (originalConnection instanceof PgConnection) {
// PgConnection pgConnection = (PgConnection) originalConnection;
//
// CopyManager copyManager = new CopyManager(pgConnection);
//// copyManager.copyIn(sqlText);
// }
// return "";
// });
// }
} else {
long start = System.currentTimeMillis();
int resultCode = currentConnectedSqlDatabase.executeInsertUpdateDeleteSql(sql);
QueryResult dummyQueryResult = new QueryResult();
long end = System.currentTimeMillis();
dummyQueryResult.queryTimeMillis = end - start;
dummyQueryResult.names.add(
"Result = " + resultCode + " in " + millisToTimeString(dummyQueryResult.queryTimeMillis));
// loadDataViewer(dummyQueryResult);
}
// addQueryToHistoryCombo(sql);
}
if (!hasError && sqlEditorView._refreshTreeAfterQueryCheckbox.isSelected()) {
try {
refreshDatabaseTree();
} catch (SQLException e) {
Logger.INSTANCE.insertError("", "error", e);
}
}
return hasError;
}
}
if (isSelectOrPragma(sqlText)) {
QueryResult queryResult = currentConnectedSqlDatabase.getTableRecordsMapFromRawSql(sqlText, limit);
loadDataViewer(queryResult);
int size = queryResult.data.size();
String msg = "Records: " + size;
if (size == limit) {
msg += " (table output limited to " + limit + " records)";
}
pm.message(msg);
} else {
int resultCode = currentConnectedSqlDatabase.executeInsertUpdateDeleteSql(sqlText);
QueryResult dummyQueryResult = new QueryResult();
dummyQueryResult.names.add("Result = " + resultCode);
loadDataViewer(dummyQueryResult);
}
addQueryToHistoryCombo(sqlText);
} catch (Exception e1) {
String localizedMessage = e1.getLocalizedMessage();
hasError = true;
pm.errorMessage("An error occurred: " + localizedMessage);
} finally {
pm.done();
}
} else if (currentConnectedNosqlDatabase != null && sqlText.length() > 0) {
if (currentSelectedTable != null) {
INosqlCollection collection = currentConnectedNosqlDatabase.getCollection(currentSelectedTable.tableName);
if (collection != null) {
List<INosqlDocument> docs = collection.find(sqlText, limit);
QueryResult nosqlToQueryResult = nosqlToQueryResult(docs);
loadDataViewer(nosqlToQueryResult);
}
}
}
if (!hasError && sqlEditorView._refreshTreeAfterQueryCheckbox.isSelected()) {
try {
refreshDatabaseTree();
} catch (Exception e) {
Logger.INSTANCE.insertError("", "error", e);
}
}
return hasError;
}
private String millisToTimeString( long queryTimeMillis ) {
if (queryTimeMillis < 1000) {
return queryTimeMillis + " milliseconds";
} else if (queryTimeMillis < 1000 * 60) {
return queryTimeMillis / 1000 + " seconds";
} else if (queryTimeMillis < 1000 * 60 * 60) {
return queryTimeMillis / 1000 / 60 + " minutes";
} else {
return queryTimeMillis / 1000 / 60 / 60 + " hours";
}
}
protected int getLimit() {
int limit;
limit = 1000;
try {
String limitText = sqlEditorView._limitCountTextfield.getText();
limit = Integer.parseInt(limitText);
} catch (Exception e) {
// reset
sqlEditorView._limitCountTextfield.setText("1000");
}
return limit;
}
private QueryResult nosqlToQueryResult( List<INosqlDocument> result ) {
QueryResult queryResult;
queryResult = new QueryResult();
queryResult.names.add("Document");
for( INosqlDocument iNosqlDocument : result ) {
String json = iNosqlDocument.toJson();
queryResult.data.add(new Object[]{json});
}
return queryResult;
}
protected boolean isSelectOrPragma( String sqlText ) {
sqlText = sqlText.trim();
return sqlText.toLowerCase().startsWith("select") || sqlText.toLowerCase().startsWith("pragma")
|| sqlText.toLowerCase().startsWith("explain");
}
protected boolean runQueryToFile( String sqlText, File selectedFile, IHMProgressMonitor pm ) {
boolean hasError = false;
if (currentConnectedSqlDatabase != null && sqlText.length() > 0) {
try {
pm.beginTask("Run query: " + sqlText + "\ninto file: " + selectedFile, IHMProgressMonitor.UNKNOWN);
currentConnectedSqlDatabase.runRawSqlToCsv(sqlText, selectedFile, true, ";");
addQueryToHistoryCombo(sqlText);
} catch (Exception e1) {
String localizedMessage = e1.getLocalizedMessage();
hasError = true;
pm.errorMessage("An error occurred: " + localizedMessage);
} finally {
pm.done();
}
}
return hasError;
}
protected boolean runQueryToShapefile( String sqlText, File selectedFile, IHMProgressMonitor pm ) {
boolean hasError = false;
if (sqlText.trim().length() == 0) {
return false;
}
try {
pm.beginTask("Run query: " + sqlText + "\ninto shapefile: " + selectedFile, IHMProgressMonitor.UNKNOWN);
DefaultFeatureCollection fc = DbsHelper.runRawSqlToFeatureCollection(null, (ASpatialDb) currentConnectedSqlDatabase,
sqlText, null);
OmsVectorWriter.writeVector(selectedFile.getAbsolutePath(), fc);
addQueryToHistoryCombo(sqlText);
} catch (Exception e1) {
String localizedMessage = e1.getLocalizedMessage();
hasError = true;
pm.errorMessage("An error occurred: " + localizedMessage);
} finally {
pm.done();
}
return hasError;
}
protected void addTextToQueryEditor( String newText ) {
String text = currentSqlEditorArea.getText();
if (text.trim().length() != 0) {
text += "\n";
}
text += newText;
currentSqlEditorArea.setText(text);
}
protected void addQueryToHistoryCombo( String sqlText ) {
if (oldSqlCommands.contains(sqlText)) {
oldSqlCommands.remove(sqlText);
}
oldSqlCommands.add(0, sqlText);
if (oldSqlCommands.size() > 20) {
oldSqlCommands.remove(20);
}
PreferencesHandler.setPreference("HM_OLD_SQL_COMMANDS", oldSqlCommands.toArray(new String[0]));
}
protected abstract List<Action> makeLeafActions( final LeafLevel selectedLeaf );
protected abstract List<Action> makeColumnActions( final ColumnLevel selectedColumn );
protected abstract List<Action> makeDatabaseAction( final DbLevel dbLevel );
protected abstract List<Action> makeTableAction( final TableLevel selectedTable );
protected void refreshDatabaseTree() throws Exception {
if (currentConnectedSqlDatabase != null) {
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedSqlDatabase);
setDbTreeTitle(currentConnectedSqlDatabase.getDatabasePath());
layoutTree(dbLevel, true);
} else if (currentConnectedNosqlDatabase != null) {
DbLevel dbLevel = gatherDatabaseLevels(currentConnectedNosqlDatabase);
setDbTreeTitle(currentConnectedNosqlDatabase.getDbEngineUrl());
layoutTree(dbLevel, true);
}
}
protected void showInMapFrame( boolean withLayers, SimpleFeatureCollection[] fcs, Style[] styles ) {
if (mapFrame == null || !mapFrame.isVisible()) {
Class<DatabaseController> class1 = DatabaseController.class;
ImageIcon icon = new ImageIcon(class1.getResource("/org/hortonmachine/images/hm150.png"));
mapFrame = new HMMapframe("Geometries Viewer");
mapFrame.setIconImage(icon.getImage());
mapFrame.enableToolBar(true);
mapFrame.enableStatusBar(false);
mapFrame.enableLayerTable(withLayers);
mapFrame.enableTool(Tool.PAN, Tool.ZOOM, Tool.RESET);
mapFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
if (withLayers) {
mapFrame.setSize(900, 600);
} else {
mapFrame.setSize(600, 600);
}
mapFrame.setVisible(true);
}
ReferencedEnvelope renv = null;
for( int i = 0; i < fcs.length; i++ ) {
SimpleFeatureCollection fc = fcs[i];
if (styles != null) {
mapFrame.addLayer(fc, styles[i]);
} else {
mapFrame.addLayer(fc);
}
ReferencedEnvelope bounds = fc.getBounds();
if (renv == null) {
renv = bounds;
} else {
renv.expandToInclude(bounds);
}
}
mapFrame.getMapPane().setDisplayArea(renv);
}
@Override
public boolean canCloseWithoutPrompt() {
return currentConnectedSqlDatabase == null && currentConnectedNosqlDatabase == null;
}
}
| gpl-3.0 |
juacom99/hermes-client | src/com/hermes/gui/renderers/UserRenderer.java | 7682 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hermes.gui.renderers;
import com.hermes.common.HUser;
import com.hermes.common.constants.HAdminLevel;
import com.hermes.gui.Panel;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
/**
*
* @author joaquin
*/
public class UserRenderer extends javax.swing.JPanel implements ListCellRenderer<HUser>
{
/**
* Creates new form UserRenderer
*/
public UserRenderer()
{
initComponents();
}
/**
* 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()
{
LAvatar = new javax.swing.JLabel();
LUsername = new javax.swing.JLabel();
LPersonalMessage = new javax.swing.JLabel();
LASL = new javax.swing.JLabel();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 1, 5, 1));
LAvatar.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
LUsername.setFont(new java.awt.Font("SansSerif", 1, 12)); // NOI18N
LUsername.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
LUsername.setMaximumSize(new java.awt.Dimension(10, 21));
LUsername.setMinimumSize(new java.awt.Dimension(10, 21));
LUsername.setPreferredSize(new java.awt.Dimension(10, 21));
LPersonalMessage.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
LPersonalMessage.setForeground(new java.awt.Color(102, 102, 102));
LPersonalMessage.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
LPersonalMessage.setMaximumSize(new java.awt.Dimension(2, 21));
LPersonalMessage.setMinimumSize(new java.awt.Dimension(2, 21));
LPersonalMessage.setPreferredSize(new java.awt.Dimension(2, 21));
LASL.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
LASL.setForeground(new java.awt.Color(102, 102, 102));
LASL.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
LASL.setMaximumSize(new java.awt.Dimension(2, 21));
LASL.setMinimumSize(new java.awt.Dimension(2, 21));
LASL.setPreferredSize(new java.awt.Dimension(2, 21));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
.addGap(10, 10, 10))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LASL, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(LPersonalMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(10, 10, 10))))
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(LUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(LASL, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(LPersonalMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(LAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel LASL;
private javax.swing.JLabel LAvatar;
private javax.swing.JLabel LPersonalMessage;
private javax.swing.JLabel LUsername;
private javax.swing.Box.Filler filler1;
// End of variables declaration//GEN-END:variables
@Override
public Component getListCellRendererComponent(JList<? extends HUser> list, HUser value, int index, boolean isSelected, boolean cellHasFocus)
{
if (isSelected)
{
setBackground(new Color(224, 227, 206));
setForeground(list.getSelectionForeground());
}
else
{
setBackground(new Color(248, 248, 248));
}
if (value.getAvatar() != null)
{
LAvatar.setIcon(value.getAvatar());
}
else
{
LAvatar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/hermes/resources/images/noAvatar.png")));
}
if (value.getLevel() == HAdminLevel.Moderator)
{
LUsername.setForeground(Color.BLUE);
}
else if (value.getLevel() == HAdminLevel.Administratior)
{
LUsername.setForeground(new Color(0, 128, 0));
}
else if (value.getLevel() == HAdminLevel.Host)
{
LUsername.setForeground(Color.RED);
}
else
{
LUsername.setForeground(Color.BLACK);
}
LUsername.setText(value.getUsername());
LUsername.validate();
LPersonalMessage.setText(value.getPersonalMessage());
String asl = value.getAge() + " - " + value.getGender() + " - ";
if (value.getRegion()==null || value.getRegion().trim().equals(""))
{
asl += value.getCountry();
}
else
{
asl += value.getRegion().trim() + ", " + value.getCountry().toString().trim();
}
LASL.setText(asl);
return this;
}
}
| gpl-3.0 |
wizjany/craftbook | src/main/java/com/sk89q/craftbook/circuits/gates/world/miscellaneous/WirelessTransmitter.java | 3639 | // $Id$
/*
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com>
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not,
* see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.craftbook.circuits.gates.world.miscellaneous;
import org.bukkit.Server;
import com.sk89q.craftbook.ChangedSign;
import com.sk89q.craftbook.LocalPlayer;
import com.sk89q.craftbook.circuits.ic.AbstractIC;
import com.sk89q.craftbook.circuits.ic.AbstractICFactory;
import com.sk89q.craftbook.circuits.ic.ChipState;
import com.sk89q.craftbook.circuits.ic.IC;
import com.sk89q.craftbook.circuits.ic.ICFactory;
import com.sk89q.craftbook.circuits.ic.ICVerificationException;
import com.sk89q.craftbook.util.HistoryHashMap;
import com.sk89q.util.yaml.YAMLProcessor;
public class WirelessTransmitter extends AbstractIC {
protected static final HistoryHashMap<String, Boolean> memory = new HistoryHashMap<String, Boolean>(100);
protected String band;
public WirelessTransmitter(Server server, ChangedSign sign, ICFactory factory) {
super(server, sign, factory);
}
@Override
public void load() {
band = getSign().getLine(2);
if (!getLine(3).trim().isEmpty())
band = band + getSign().getLine(3);
}
@Override
public String getTitle() {
return "Wireless Transmitter";
}
@Override
public String getSignTitle() {
return "TRANSMITTER";
}
@Override
public void trigger(ChipState chip) {
setValue(band, chip.getInput(0));
chip.setOutput(0, chip.getInput(0));
}
public static Boolean getValue(String band) {
return memory.get(band);
}
public static void setValue(String band, boolean val) {
memory.put(band, val);
}
public static class Factory extends AbstractICFactory {
public boolean requirename;
public Factory(Server server) {
super(server);
}
@Override
public IC create(ChangedSign sign) {
return new WirelessTransmitter(getServer(), sign, this);
}
@Override
public String getShortDescription() {
return "Transmits wireless signal to wireless recievers.";
}
@Override
public String[] getLineHelp() {
String[] lines = new String[] {"wireless band", "user"};
return lines;
}
@Override
public void checkPlayer(ChangedSign sign, LocalPlayer player) throws ICVerificationException {
if (requirename) sign.setLine(3, player.getName());
else if (!sign.getLine(3).isEmpty()) sign.setLine(3, player.getName());
}
@Override
public void addConfiguration(YAMLProcessor config, String path) {
requirename = config.getBoolean(path + "per-player", false);
}
@Override
public boolean needsConfiguration() {
return true;
}
}
} | gpl-3.0 |
SpeckiJ/dao-series-api | sos-integration/src/main/java/org/n52/series/db/da/sos/SOSHibernateSessionHolder.java | 4089 | /*
* Copyright (C) 2015-2017 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.series.db.da.sos;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.hibernate.Session;
import org.n52.series.db.HibernateSessionStore;
import org.n52.sos.ds.hibernate.HibernateSessionHolder;
import org.n52.sos.ds.hibernate.SessionFactoryProvider;
import org.n52.sos.ogc.ows.OwsExceptionReport;
import org.n52.sos.service.Configurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SOSHibernateSessionHolder implements HibernateSessionStore {
private static final Logger LOGGER = LoggerFactory.getLogger(SOSHibernateSessionHolder.class);
private static final String DATASOURCE_PROPERTIES = "/datasource.properties";
private static SessionFactoryProvider provider;
private HibernateSessionHolder sessionHolder;
public static HibernateSessionHolder createSessionHolder() {
if (Configurator.getInstance() == null) {
try (InputStream inputStream = SOSHibernateSessionHolder.class.getResourceAsStream(DATASOURCE_PROPERTIES)) {
LOGGER.debug("SOS Configurator not present, trying to load DB config from '{}'", DATASOURCE_PROPERTIES);
if (inputStream == null) {
LOGGER.error("DB config '{}' is missing!", DATASOURCE_PROPERTIES);
throwNewDatabaseConnectionException();
}
Properties connectionProviderConfig = new Properties();
connectionProviderConfig.load(inputStream);
provider = new SessionFactoryProvider();
provider.initialize(connectionProviderConfig);
return new HibernateSessionHolder(provider);
} catch (IOException e) {
LOGGER.error("Could not establish database connection. Check '{}'", DATASOURCE_PROPERTIES, e);
throwNewDatabaseConnectionException();
}
}
return new HibernateSessionHolder();
}
private static void throwNewDatabaseConnectionException() {
throw new RuntimeException("Could not establish database connection.");
}
@Override
public void returnSession(Session session) {
sessionHolder.returnSession(session);
}
@Override
public Session getSession() {
if (sessionHolder == null) {
sessionHolder = createSessionHolder();
}
try {
return sessionHolder.getSession();
} catch (OwsExceptionReport e) {
throw new IllegalStateException("Could not get hibernate session.", e);
}
}
@Override
public void shutdown() {
LOGGER.info("shutdown '{}'", getClass().getSimpleName());
if (provider != null) {
provider.cleanup();
}
}
}
| gpl-3.0 |
kontext-e/jqassistant | plugin/common/src/main/java/com/buschmais/jqassistant/plugin/common/impl/scanner/DefaultUriScannerPlugin.java | 1497 | package com.buschmais.jqassistant.plugin.common.impl.scanner;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.buschmais.jqassistant.core.scanner.api.Scanner;
import com.buschmais.jqassistant.core.scanner.api.Scope;
import com.buschmais.jqassistant.core.store.api.model.Descriptor;
import com.buschmais.jqassistant.plugin.common.api.scanner.AbstractResourceScannerPlugin;
/**
* Scanner plugin which handles URIs with defined default schemas as input.
*/
public class DefaultUriScannerPlugin extends AbstractResourceScannerPlugin<URI, Descriptor> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUriScannerPlugin.class);
private Set<String> schemes;
@Override
public void initialize() {
schemes = new HashSet<>();
schemes.add("file");
schemes.add("http");
schemes.add("https");
schemes.add("ftp");
}
@Override
public boolean accepts(URI item, String path, Scope scope) throws IOException {
String scheme = item.getScheme().toLowerCase();
return schemes.contains(scheme);
}
@Override
public Descriptor scan(final URI item, String path, Scope scope, Scanner scanner) throws IOException {
URL url = item.toURL();
LOGGER.debug("Scanning url '{}'.", url.toString());
return scanner.scan(url, path, scope);
}
}
| gpl-3.0 |
Perpanb0/FilmDemo | src/dp/ws/popcorntime/config/VPN.java | 327 | package dp.ws.popcorntime.config;
public class VPN {
public String host;
public int port;
public String user;
public String pass;
public VPN() {
this("", 0, "", "");
}
public VPN(String host, int port, String user, String pass) {
this.host = host;
this.port = port;
this.user = user;
this.pass = pass;
}
} | gpl-3.0 |
johnalexandergreene/Geom_Kisrhombille | app/docGraphics/DG_KGridDefinitionOnAPlaneWithParamsLabelled.java | 13522 | package org.fleen.geom_Kisrhombille.app.docGraphics;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.fleen.geom_2D.DPoint;
import org.fleen.geom_2D.GD;
import org.fleen.geom_Kisrhombille.KGrid;
import org.fleen.geom_Kisrhombille.KPoint;
/*
* 3 examples of KGrids defined in the plane
* use a square image 512x512
* render 1 at a time by commenting out the param constants
*/
public class DG_KGridDefinitionOnAPlaneWithParamsLabelled extends DocGraphics{
/*
* ################################
* GRID AND GRAPHICS PARAMS
* ################################
*/
//========
//GRID #1
private static final double
originx=0,originy=0;
private static final double
NORTH=0,
FISH=1.0;
private static final boolean
TWIST=true;
private static final double
IMAGEXOFFSET=0,
IMAGEYOFFSET=0;
private static final int
CGRIDLABELSOFFSETXX=-250,
CGRIDLABELSOFFSETXY=12,
CGRIDLABELSOFFSETYX=-12,
CGRIDLABELSOFFSETYY=220;
private static final int
ORIGINLABELOFFSETX=-24,
ORIGINLABELOFFSETY=26;
private static final int
NORTHLABELOFFSETX=8,
NORTHLABELOFFSETY=20;
private static final
String NORTHLABELTEXT="north=0";
private static final KPoint
FISHPOINT0=new KPoint(1,0,-1,3),
FISHPOINT1=new KPoint(1,0,-1,4);
private static final int
FISHLABELOFFSETX=-37,
FISHLABELOFFSETY=40;
private static final double
TWISTARCRADIUS=1.5,
TWISTARCSTART=GD.PI*0.7,
TWISTARCEND=GD.PI*1.6;
private static final String
TWISTLABELTEXT="twist=clockwise";
private static final int
TWISTLABELOFFSETX=-160,
TWISTLABELOFFSETY=1;
private static final double
NORTHSHAFTOFFSET=0.5;
//========
//GRID #2
// private static final double
// originx=2,originy=3;
// private static final double
// NORTH=GD.PI/8,
// FISH=1.23;
// private static final boolean
// TWIST=true;
// private static final double
// IMAGEXOFFSET=-3,
// IMAGEYOFFSET=-3;
// private static final int
// CGRIDLABELSOFFSETXX=-32,
// CGRIDLABELSOFFSETXY=12,
// CGRIDLABELSOFFSETYX=-12,
// CGRIDLABELSOFFSETYY=40;
// private static final int
// ORIGINLABELOFFSETX=-24,
// ORIGINLABELOFFSETY=26;
// private static final int
// NORTHLABELOFFSETX=-2,
// NORTHLABELOFFSETY=35;
// private static final
// String NORTHLABELTEXT="north=\u03c0/8";
// private static final KVertex
// FISHPOINT0=new KVertex(0,0,0,4),
// FISHPOINT1=new KVertex(1,1,0,1);
// private static final int
// FISHLABELOFFSETX=18,
// FISHLABELOFFSETY=20;
// private static final double
// TWISTARCRADIUS=1.5,
// TWISTARCSTART=GD.PI*0.7,
// TWISTARCEND=GD.PI*1.8;
// private static final String
// TWISTLABELTEXT="twist=clockwise";
// private static final int
// TWISTLABELOFFSETX=-120,
// TWISTLABELOFFSETY=-19;
// private static final double
// NORTHSHAFTOFFSET=0.5;
//========
//GRID #3
// private static final double
// originx=4,originy=-3;
// private static final double
// NORTH=7*GD.PI/4,
// FISH=1.7;
// private static final boolean
// TWIST=false;
// private static final double
// IMAGEXOFFSET=-3.5,
// IMAGEYOFFSET=3;
// private static final int
// CGRIDLABELSOFFSETXX=40,
// CGRIDLABELSOFFSETXY=12,
// CGRIDLABELSOFFSETYX=-12,
// CGRIDLABELSOFFSETYY=44;
// private static final int
// ORIGINLABELOFFSETX=-144,
// ORIGINLABELOFFSETY=26;
// private static final int
// NORTHLABELOFFSETX=-122,
// NORTHLABELOFFSETY=-32;
// private static final
// String NORTHLABELTEXT="north=7\u03c0/4";
// private static final KVertex
// FISHPOINT0=new KVertex(0,0,0,5),
// FISHPOINT1=new KVertex(1,0,-1,2);
// private static final int
// FISHLABELOFFSETX=-55,
// FISHLABELOFFSETY=40;
// private static final double
// TWISTARCRADIUS=1.5,
// TWISTARCSTART=GD.PI*2.1,
// TWISTARCEND=GD.PI*1.1;
// private static final String
// TWISTLABELTEXT="twist=counterclockwise";
// private static final int
// TWISTLABELOFFSETX=-52,
// TWISTLABELOFFSETY=-22;
// private static final double
// NORTHSHAFTOFFSET=0.5;
/*
* ################################
* DO GRAPHICS
* ################################
*/
//arrow
private static final double
SHAFTLENGTH=0.6,
HEADLENGTH=0.5,
HEADSPAN=0.25;
void doGraphics(){
//init kgrid
KGrid g=new KGrid(originx,originy,NORTH,TWIST,FISH);
//init image, more or less center on the diagram
initImage(IMAGEWIDTH1,IMAGEHEIGHT1,IMAGESCALE3,WHITE);
AffineTransform t=graphics.getTransform();
t.translate(IMAGEXOFFSET,IMAGEYOFFSET);
graphics.setTransform(t);
//render everything
renderCGrid();
renderKGrid(g);
renderOrigin(g);
renderNorth(g);
renderFish(g);
renderTwist(g);}
/*
* ################################
* CGRID
* just x and y axes, and little labels
* ################################
*/
private void renderCGrid(){
graphics.setStroke(createStroke(STROKETHICKNESS1));
graphics.setPaint(YELLOW);
graphics.drawLine(-100,0,100,0);
graphics.drawLine(0,-100,0,100);
renderCGridLabels();}
private void renderCGridLabels(){
AffineTransform graphicstransform=graphics.getTransform();
double[] p={0,0};
graphicstransform.transform(p,0,p,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(YELLOW);
graphics.setFont(new Font("Sans",Font.PLAIN,12));
graphics.drawString("x",(float)(p[0]+CGRIDLABELSOFFSETXX),(float)(p[1]+CGRIDLABELSOFFSETXY));
graphics.drawString("y",(float)(p[0]+CGRIDLABELSOFFSETYX),(float)(p[1]+CGRIDLABELSOFFSETYY));
graphics.setTransform(graphicstransform);}
/*
* ################################
* KGRID
* ################################
*/
private void renderKGrid(KGrid g){
Set<KPoint> gp=renderKGrid(g,8,STROKETHICKNESS0,GREY6);
for(KPoint p:gp)
renderKGridPoint(g,p);}
Set<KPoint> renderKGrid(KGrid grid,int range,double thickness,Color color){
Set<KPoint> points=new HashSet<KPoint>();
Set<KPoint> v0s=getV0s(range);
for(KPoint p:v0s){
points.addAll(Arrays.asList(getClockKPoints(p)));
strokeClock(grid,p,thickness,color);}
return points;}
void strokeClock(KGrid grid,KPoint v,double thickness,Color color){
KPoint[] cp=getClockKPoints(v);
int j;
for(int i=1;i<cp.length;i++){
j=i+1;
if(j==cp.length)j=1;
strokeSeg(grid,cp[i],cp[j],thickness,color);
strokeSeg(grid,cp[0],cp[i],thickness,color);}}
void strokeSeg(KGrid grid,KPoint v0,KPoint v1,double thickness,Color color){
DPoint
p0=new DPoint(grid.getPoint2D(v0)),
p1=new DPoint(grid.getPoint2D(v1));
strokeSeg(p0,p1,thickness,color);}
private void renderKGridPoint(KGrid grid,KPoint p){
DPoint dp=new DPoint(grid.getPoint2D(p));
renderPoint(dp,DOTSPAN0,GREY4);
AffineTransform graphicstransform=graphics.getTransform();
double[] pt={dp.x,dp.y};
graphicstransform.transform(pt,0,pt,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(GREY3);
graphics.setFont(new Font("Sans",Font.PLAIN,10));
String s=p.getAnt()+" "+p.getBat();
graphics.drawString(s,(float)(pt[0]+4),(float)(pt[1]-15));
s=p.getCat()+" "+p.getDog();
graphics.drawString(s,(float)(pt[0]+4),(float)(pt[1]-3));;
graphics.setTransform(graphicstransform);}
/*
* ################################
* ORIGIN
* ################################
*/
private void renderOrigin(KGrid grid){
KPoint origin=new KPoint(0,0,0,0);
DPoint p=new DPoint(grid.getPoint2D(origin));
renderPoint(p,DOTSPAN1,RED);
AffineTransform graphicstransform=graphics.getTransform();
double[] pt={p.x,p.y};
graphicstransform.transform(pt,0,pt,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(RED);
graphics.setFont(new Font("Sans",Font.PLAIN,18));
String s="origin=("+p.x+","+p.y+")";
graphics.drawString(s,(float)(pt[0]+ORIGINLABELOFFSETX),(float)(pt[1]+ORIGINLABELOFFSETY));
graphics.setTransform(graphicstransform);}
/*
* ################################
* TWIST
* ################################
*/
private static final double SEGARCINCREMENT=GD.PI/24;
DPoint pend=null;
double dend;
private void renderTwist(KGrid g){
DPoint p=new DPoint(g.getPoint2D(new KPoint(0,0,0,0)));
renderTwistArc(p,TWISTARCRADIUS,TWISTARCSTART,TWISTARCEND);
renderTwistArcArrowhead();
renderTwistLabel(TWISTLABELTEXT);}
private void renderTwistLabel(String text){
AffineTransform graphicstransform=graphics.getTransform();
double[] pt={pend.x,pend.y};
graphicstransform.transform(pt,0,pt,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(PURPLE);
graphics.setFont(new Font("Sans",Font.PLAIN,18));
graphics.drawString(text,(float)(pt[0]+TWISTLABELOFFSETX),(float)(pt[1]+TWISTLABELOFFSETY));
graphics.setTransform(graphicstransform);}
private void renderTwistArc(DPoint center,double radius,double start,double end){
Path2D path=new Path2D.Double();
double arclength=Math.abs(GD.getAngle_2Directions(start,end));
int segcount=(int)(arclength/SEGARCINCREMENT)+1;
double d=start;
double[] p=GD.getPoint_PointDirectionInterval(center.x,center.y,d,radius);
List<DPoint> points=new ArrayList<DPoint>();
points.add(new DPoint(p));
path.moveTo(p[0],p[1]);
for(int i=0;i<segcount;i++){
d=GD.normalizeDirection(d+SEGARCINCREMENT);
p=GD.getPoint_PointDirectionInterval(center.x,center.y,d,radius);
points.add(new DPoint(p));
path.lineTo(p[0],p[1]);}
//
graphics.setPaint(PURPLE);
graphics.setStroke(createStroke(STROKETHICKNESS2));
graphics.draw(path);
//
if(TWIST){
pend=points.get(points.size()-1);
dend=points.get(points.size()-2).getDirection(pend);
}else{
pend=points.get(0);
dend=points.get(1).getDirection(pend);}}
private void renderTwistArcArrowhead(){
double
dleft=GD.normalizeDirection(dend-GD.PI/2),
dright=GD.normalizeDirection(dend+GD.PI/2);
DPoint
pleft=pend.getPoint(dleft,HEADSPAN/2),
pright=pend.getPoint(dright,HEADSPAN/2),
ptip=pend.getPoint(dend,HEADLENGTH);
Path2D path=new Path2D.Double();
path.moveTo(pleft.x,pleft.y);
path.lineTo(ptip.x,ptip.y);
path.lineTo(pright.x,pright.y);
path.closePath();
graphics.setPaint(PURPLE);
graphics.fill(path);}
/*
* ################################
* FISH
* ################################
*/
private void renderFish(KGrid g){
DPoint
p0d=new DPoint(g.getPoint2D(FISHPOINT0)),
p1d=new DPoint(g.getPoint2D(FISHPOINT1));
strokeSeg(p0d,p1d,STROKETHICKNESS2,GREEN);
renderPoint(p0d,DOTSPAN1,GREEN);
renderPoint(p1d,DOTSPAN1,GREEN);
renderFishLabel(p0d,"fish="+FISH);}
private void renderFishLabel(DPoint p,String labeltext){
AffineTransform graphicstransform=graphics.getTransform();
double[] pt={p.x,p.y};
graphicstransform.transform(pt,0,pt,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(GREEN);
graphics.setFont(new Font("Sans",Font.PLAIN,18));
graphics.drawString(labeltext,(float)(pt[0]+FISHLABELOFFSETX),(float)(pt[1]+FISHLABELOFFSETY));
graphics.setTransform(graphicstransform);}
/*
* ################################
* NORTH
* ################################
*/
private void renderNorth(KGrid grid){
KPoint
p0=new KPoint(0,0,0,0),
p1=new KPoint(0,0,0,2);
DPoint
p0d=new DPoint(grid.getPoint2D(p0)),
p1d=new DPoint(grid.getPoint2D(p1));
double dir=p0d.getDirection(p1d);
DPoint
a0=p0d.getPoint(dir,NORTHSHAFTOFFSET),
a1=a0.getPoint(dir,SHAFTLENGTH);
renderNorthArrow(a0,a1);
renderNorthLabel(a1);}
private void renderNorthArrow(DPoint p0,DPoint p1){
strokeSeg(p0,p1,STROKETHICKNESS2,BLUE);
double
d=p0.getDirection(p1),
dleft=GD.normalizeDirection(d-GD.PI/2),
dright=GD.normalizeDirection(d+GD.PI/2);
DPoint
pleft=p1.getPoint(dleft,HEADSPAN/2),
pright=p1.getPoint(dright,HEADSPAN/2),
pend=p1.getPoint(d,HEADLENGTH);
Path2D path=new Path2D.Double();
path.moveTo(pleft.x,pleft.y);
path.lineTo(pend.x,pend.y);
path.lineTo(pright.x,pright.y);
path.closePath();
graphics.setPaint(BLUE);
graphics.fill(path);}
private void renderNorthLabel(DPoint p){
AffineTransform graphicstransform=graphics.getTransform();
double[] pt={p.x,p.y};
graphicstransform.transform(pt,0,pt,0,1);
graphics.setTransform(new AffineTransform());
graphics.setPaint(BLUE);
graphics.setFont(new Font("Sans",Font.PLAIN,18));
graphics.drawString(NORTHLABELTEXT,(float)(pt[0]+NORTHLABELOFFSETX),(float)(pt[1]+NORTHLABELOFFSETY));
graphics.setTransform(graphicstransform);}
/*
* ################################
* ################################
* ################################
*/
public static final void main(String[] a){
new DG_KGridDefinitionOnAPlaneWithParamsLabelled();}
}
| gpl-3.0 |
TUD-IfC/WebGen-WPS | src/ch/unizh/geo/webgen/model/ConstrainedFeature.java | 2639 | package ch.unizh.geo.webgen.model;
import java.io.Serializable;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jump.feature.AttributeType;
import com.vividsolutions.jump.feature.BasicFeature;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureSchema;
import com.vividsolutions.jump.feature.FeatureUtil;
public class ConstrainedFeature extends BasicFeature implements Serializable {
static final long serialVersionUID = 12345;
Constraint constraint;
int uid;
public ConstrainedFeature(FeatureSchema fs) {
super(fs);
}
public ConstrainedFeature(Feature feat) {
super(feat.getSchema());
this.setAttributes(feat.getAttributes());
this.setGeometry(feat.getGeometry());
constraint = new Constraint(this);
}
public ConstrainedFeature(Geometry geom) {
super(makeGeometrySchema());
this.setGeometry(geom);
constraint = new Constraint(this);
}
public ConstrainedFeature(Feature feat, boolean deepclone) {
super((FeatureSchema)feat.getSchema().clone());
if(deepclone) {
FeatureUtil.copyAttributes(feat.clone(true), this);
constraint = new Constraint(this);
}
else {
this.setAttributes(feat.getAttributes());
this.setGeometry(feat.getGeometry());
constraint = new Constraint(this);
}
}
private static FeatureSchema makeGeometrySchema() {
FeatureSchema fs = new FeatureSchema();
fs.addAttribute("GEOMETRY", AttributeType.GEOMETRY);
return fs;
}
//constraint functionalities
public void setConstraint(Constraint c) {
this.constraint = c;
}
public void initConstraint() {
constraint = new Constraint(this);
}
public Constraint getConstraint() {
return this.constraint;
}
public void setUID(int uid) {
this.uid = uid;
}
public int getUID() {
return uid;
}
//for compatibility with old constraint attributes (must be removed soon)
public Object getAttribute(String name) {
if(name.equals("constraint")) return constraint;
else return super.getAttribute(name);
}
public void setAttribute(String name, Object attrib) {
if(name.equals("constraint") && (attrib instanceof Constraint))
constraint = (Constraint)attrib;
else super.setAttribute(name, attrib);
}
public ConstrainedFeature clone() {
ConstrainedFeature tfeat = new ConstrainedFeature(((Feature)this).clone(true));
try {
tfeat.setUID(this.uid);
tfeat.constraint = (Constraint)this.constraint.clone();
}
catch(Exception e) {
tfeat.initConstraint();
}
return tfeat;
}
}
| gpl-3.0 |
wangxdouc/ouc-java-course | Code/Mid-project-refs/music.client/src/main/java/ouc/cs/course/java/httpclient/FileDownloader.java | 2682 | package ouc.cs.course.java.httpclient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public class FileDownloader {
private static final int SUCCESS = 200;
public static void downloadMusicFile(String url, String fileMd5, String targetPath) {
downloadMusicFile(url, fileMd5, targetPath, null);
}
public static void downloadMusicFile(String url, String fileMd5, String targetPath, String fileName) {
HttpClient client = new HttpClient();
GetMethod get = null;
FileOutputStream output = null;
String filename = null;
try {
get = new GetMethod(url + "?md5=" + fileMd5);
int i = client.executeMethod(get);
if (SUCCESS == i) {
if (fileName == null) {
filename = java.net.URLDecoder
.decode(get.getResponseHeader("Content-Disposition").getValue().substring(21), "UTF-8");
System.out.println("[The file name getting from HTTP HEADER] " + filename);
} else {
filename = fileName;
}
File storeFile = new File(targetPath + "/" + filename);
output = new FileOutputStream(storeFile);
output.write(get.getResponseBody());
} else {
System.out.println("DownLoad file failed with error code: " + i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
}
}
public static void downloadMusicSheetPicture(String url, String musicSheetUuid, String targetPath) {
HttpClient client = new HttpClient();
GetMethod get = null;
FileOutputStream output = null;
String filename = null;
try {
get = new GetMethod(url + "?uuid=" + musicSheetUuid);
int i = client.executeMethod(get);
if (SUCCESS == i) {
filename = java.net.URLDecoder
.decode(get.getResponseHeader("Content-Disposition").getValue().substring(21), "UTF-8");
System.out.println("[The file name getting from HTTP HEADER] " + filename);
File storeFile = new File(targetPath + "/" + filename);
output = new FileOutputStream(storeFile);
output.write(get.getResponseBody());
} else {
System.out.println("DownLoad file failed with error code: " + i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
}
}
}
| gpl-3.0 |
m1ckr1sk/voting_booth | booth/src/main/java/uk/co/mickrisk/VoterValidator.java | 2634 | package uk.co.mickrisk;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
@Component
public class VoterValidator {
protected Logger logger = Logger.getLogger(VoterValidator.class.getName());
private RestOperations restTemplate;
private DiscoveryClient discoveryClient;
@Autowired
public VoterValidator(RestOperations restTemplate, DiscoveryClient discoveryClient) {
this.restTemplate = restTemplate;
this.discoveryClient = discoveryClient;
}
public String getVoterServiceUrl() throws InterruptedException {
List<ServiceInstance> serviceInstances = null;
long time = System.currentTimeMillis();
long timeout = time + 60000;
while (System.currentTimeMillis() < timeout) {
serviceInstances = discoveryClient.getInstances("voting-voter");
if (serviceInstances != null && serviceInstances.size() > 0) {
logger.info("voting-voter Url:" + serviceInstances.get(0).getUri());
return serviceInstances.get(0).getUri().toString();
}
Thread.sleep(1000);
}
return "";
}
public Boolean validateVoter(long voterId) {
String url = "";
try {
url = getVoterServiceUrl();
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
ResponseEntity<List<Voter>> exchange = this.restTemplate.exchange(url + "/voterservice/voters", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Voter>>() {
}, (Object) "mstine");
Boolean foundVoter = false;
List<Voter> voters = exchange.getBody();
for (Voter voter : voters) {
if (voter.getVoterId() == voterId && !voter.getHasVoted()) {
foundVoter = true;
}
}
return foundVoter;
}
public Boolean registerVote(long voterId) {
String url = "";
try {
url = getVoterServiceUrl();
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
HttpEntity<String> request = new HttpEntity<>(new String());
String response =
restTemplate.postForObject(url + "/voterservice/voter/cast/" + voterId, request, String.class);
logger.info(response);
return true;
}
}
| gpl-3.0 |
ReunionDev/reunion | jreunion/src/main/java/org/reunionemu/jreunion/model/quests/restrictions/LevelRestrictionImpl.java | 1099 | package org.reunionemu.jreunion.model.quests.restrictions;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.reunionemu.jreunion.game.Player;
import org.reunionemu.jreunion.model.quests.RestrictionImpl;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
@XmlType(name = "level")
public class LevelRestrictionImpl extends RestrictionImpl implements
LevelRestriction {
@XmlAttribute(required = false)
@XmlSchemaType(name = "positiveInteger")
protected Integer min;
@XmlAttribute(required = false)
@XmlSchemaType(name = "positiveInteger")
protected Integer max;
@Override
public Integer getMax() {
return max;
}
@Override
public Integer getMin() {
return min;
}
@Override
public boolean isAllowed(Player player) {
Integer max = getMax();
int level = player.getLevel();
if (max != null && max < level) {
return false;
}
Integer min = getMin();
if (min != null && min > level) {
return false;
}
return true;
}
}
| gpl-3.0 |
interstar/art-toys-version-1 | src/art-toys/library/IObservingController.java | 100 | package arttoys.core;
public interface IObservingController extends IBusUser {
void scanBus();
}
| gpl-3.0 |
tvesalainen/parsers | sql/src/main/java/org/vesalainen/parsers/sql/Range.java | 2233 | /*
* Copyright (C) 2012 Timo Vesalainen
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.parsers.sql;
import java.util.Comparator;
/**
* @author Timo Vesalainen
*/
public class Range<C>
{
Comparator<C> comparator;
private C lower;
private C upper;
public Range(Comparator<C> comparator)
{
this.comparator = comparator;
}
public Range(Comparator<C> comparator, C lower, C upper)
{
this.comparator = comparator;
this.lower = lower;
this.upper = upper;
}
public void narrow(C lower, C upper)
{
if (this.lower == null || comparator.compare(this.lower, lower) < 0)
{
this.lower = lower;
}
if (this.upper == null || comparator.compare(this.upper, upper) > 0)
{
this.upper = upper;
}
}
public void lower(C lower)
{
if (this.lower == null || comparator.compare(this.lower, lower) < 0)
{
this.lower = lower;
}
}
public void upper(C upper)
{
if (this.upper == null || comparator.compare(this.upper, upper) > 0)
{
this.upper = upper;
}
}
public void exact(C item)
{
this.lower = item;
this.upper = item;
}
public boolean inRange(C item)
{
return (this.lower == null || comparator.compare(this.lower, item) <= 0) &&
(this.upper == null || comparator.compare(this.upper, item) >= 0);
}
public boolean isSingle()
{
return this.lower != null && this.lower.equals(this.upper);
}
}
| gpl-3.0 |
emanueleforestieri/PSW-Generator | src/PSWGen.java | 382 |
/**
* @author Emanuele Forestieri
* @version 0.2.0 [15/05/2016]
*/
public class PSWGen {
public static void main(String[] args) {
if(args.length<1) {
System.err.println("[!] You must enter at least one string");
System.exit(1);
}
System.out.print("[+] Password: ");
for(byte i = 0; i < args.length; i++) {
new Generator(args[i]).start();
}
}
}
| gpl-3.0 |
Blaxcraft/RPGGame | src/us/mcsw/rpg/attack/Attack.java | 955 | package us.mcsw.rpg.attack;
import java.awt.Graphics2D;
import us.mcsw.rpg.damage.Damage;
import us.mcsw.rpg.entity.EntityDamageable;
import us.mcsw.rpg.entity.EntityLeveled;
import us.mcsw.rpg.entity.EntityPlayer;
import us.mcsw.rpg.util.Vector2d;
public abstract class Attack {
public static AttackSweep SWEEP = new AttackSweep();
public static AttackShoot SHOOT = new AttackShoot();
Damage damage;
int ticks;
public Attack(Damage damage, int ticks) {
this.damage = damage;
this.ticks = ticks;
}
public Damage getDamage(int level) {
return damage.scale(level);
}
public int getTicks() {
return ticks;
}
public void doDamageTo(EntityLeveled a, EntityDamageable d) {
d.damage(a, getDamage(a.getLevel()));
}
public abstract void doAttack(EntityPlayer pl, Vector2d dir);
public abstract void renderAttack(int[] pixels, Graphics2D g, EntityPlayer pl, double stage, Vector2d dir);
}
| gpl-3.0 |
naousse/urerp | src/main/java/com/urservices/urerp/validator/FonctionValidation.java | 1295 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.urservices.urerp.validator;
import com.urservices.urerp.entities.Fonction;
import com.urservices.urerp.metier.IFonctionEJBMetierLocal;
import java.text.MessageFormat;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
*
* @author samuel
*/
@FacesValidator(value = "fonctionValidator")
public class FonctionValidation implements Validator{
@EJB
private IFonctionEJBMetierLocal iFonctionEJBMetierLocal;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Fonction fonction = iFonctionEJBMetierLocal.findByLibelle(value.toString());
if (fonction != null) {
String message = MessageFormat.format("{0} existe déjà", value.toString());
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
throw new ValidatorException(facesMessage);
}
}
}
| gpl-3.0 |
lonerlin/ardublock | src/main/java/com/ardublock/translator/block/nhedu/RFID_ReadCardBlock.java | 1217 | package com.ardublock.translator.block.nhedu;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.TranslatorBlock;
import com.ardublock.translator.block.exception.BlockException;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
/**
* Created by Administrator on 2017/7/20.
*/
public class RFID_ReadCardBlock extends TranslatorBlock {
public RFID_ReadCardBlock(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) {
super(blockId, translator, codePrefix, codeSuffix, label);
}
@Override
public String toCode() throws SocketNullException, SubroutineNotDeclaredException, BlockException {
String SectionIndex;
String BlockIndex;
TranslatorBlock translatorBlock=this.getRequiredTranslatorBlockAtSocket(0);
SectionIndex=translatorBlock.toCode();
translatorBlock=this.getRequiredTranslatorBlockAtSocket(1);
BlockIndex=translatorBlock.toCode();
String ret="nhedu_RFID.readCard(" + SectionIndex +"," + BlockIndex +")";
return codePrefix+ ret+ codeSuffix;
}
}
| gpl-3.0 |
InfWGospodarce/projekt | transporter-server/src/org/pwr/transporter/entity/sales/Request.java | 4483 | package org.pwr.transporter.entity.sales;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.pwr.transporter.entity.NamesForHibernate;
import org.pwr.transporter.entity.article.Article;
import org.pwr.transporter.entity.base.Address;
import org.pwr.transporter.entity.base.GenericDocument;
import org.pwr.transporter.entity.enums.documents.OrderType;
/**
* <pre>
* Sales request document from client.
* </pre>
* <hr/>
*
* @author W.S.
* @version 0.0.3
*/
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = NamesForHibernate.REQUEST_DOCUMENT)
@PrimaryKeyJoinColumn(name = NamesForHibernate.GENERIC_DOCUMENT_ID)
public class Request extends GenericDocument {
/** */
private static final long serialVersionUID = -5323409176872050200L;
public Request() {
rows = new ArrayList<RequestRow>();
}
// *******************************************************************************************************************************
// ****** FIELDS
// *******************************************************************************************************************************
@Column(name = "no_taxable_amount", nullable = false)
private BigDecimal noTaxableAmount;
@Column(name = "tax_amount", nullable = false)
private BigDecimal taxAmount;
// mamy juz delivery addres wiec to raczej odpada
// @Column(name = "AdrReceiver")
// private String AdrReceiver;
@OneToOne
private Address targetAddress;
@Transient
private String transportServicetypeId;
@Transient
private String targetAddressId;
@Column(name = "order_type")
private OrderType orderType;
@Transient
private String orderTypeValue;
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "request", cascade = CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
private List<RequestRow> rows;
// *******************************************************************************************************************************
// ****** GETTERS AND SETTERS
// *******************************************************************************************************************************
public List<RequestRow> getRows() {
return this.rows;
}
public void setRows(List<RequestRow> rows) {
this.rows = rows;
}
public BigDecimal getNoTaxableAmount() {
return this.noTaxableAmount;
}
public void setNoTaxableAmount(BigDecimal noTaxableAmount) {
this.noTaxableAmount = noTaxableAmount;
}
public BigDecimal getTaxAmount() {
return this.taxAmount;
}
public void setTaxAmount(BigDecimal taxAmount) {
this.taxAmount = taxAmount;
}
public Address getTargetAddress() {
return targetAddress;
}
public void setTargetAddress(Address targetAddress) {
this.targetAddress = targetAddress;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTargetAddressId() {
return this.targetAddressId;
}
public void setTargetAddressId(String targetAddressId) {
this.targetAddressId = targetAddressId;
}
public OrderType getOrderType() {
return this.orderType;
}
public void setOrderType(OrderType orderType) {
this.orderType = orderType;
}
public String getOrderTypeValue() {
return this.orderTypeValue;
}
public void setOrderTypeValue(String orderTypeValue) {
this.orderTypeValue = orderTypeValue;
}
public String getTransportServicetypeId() {
return transportServicetypeId;
}
public void setTransportServicetypeId(String transportServicetypeId) {
this.transportServicetypeId = transportServicetypeId;
}
}
| gpl-3.0 |
mikesligo/visGrid | ie.tcd.gmf.visGrid.diagram/src/visGrid/diagram/edit/parts/LoadEditPart.java | 61079 | package visGrid.diagram.edit.parts;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.draw2d.FlowLayout;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.XYLayoutEditPolicy;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.lite.svg.SVGFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;
/**
* @generated
*/
public class LoadEditPart extends ShapeNodeEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 2005;
/**
* @generated
*/
protected IFigure contentPane;
/**
* @generated
*/
protected IFigure primaryShape;
/**
* @generated
*/
public LoadEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new visGrid.diagram.edit.policies.LoadItemSemanticEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
}
/**
* @generated
*/
protected LayoutEditPolicy createLayoutEditPolicy() {
XYLayoutEditPolicy lep = new XYLayoutEditPolicy() {
protected EditPolicy createChildEditPolicy(EditPart child) {
EditPolicy result = super.createChildEditPolicy(child);
if (result == null) {
return new ResizableShapeEditPolicy();
}
return result;
}
};
return lep;
}
/**
* @generated
*/
protected IFigure createNodeShape() {
return primaryShape = new LoadFigure();
}
/**
* @generated
*/
public LoadFigure getPrimaryShape() {
return (LoadFigure) primaryShape;
}
/**
* @generated
*/
protected boolean addFixedChild(EditPart childEditPart) {
if (childEditPart instanceof visGrid.diagram.edit.parts.LoadNameEditPart) {
((visGrid.diagram.edit.parts.LoadNameEditPart) childEditPart)
.setLabel(getPrimaryShape().getFigureLoadNameFigure());
return true;
}
return false;
}
/**
* @generated
*/
protected boolean removeFixedChild(EditPart childEditPart) {
if (childEditPart instanceof visGrid.diagram.edit.parts.LoadNameEditPart) {
return true;
}
return false;
}
/**
* @generated
*/
protected void addChildVisual(EditPart childEditPart, int index) {
if (addFixedChild(childEditPart)) {
return;
}
super.addChildVisual(childEditPart, -1);
}
/**
* @generated
*/
protected void removeChildVisual(EditPart childEditPart) {
if (removeFixedChild(childEditPart)) {
return;
}
super.removeChildVisual(childEditPart);
}
/**
* @generated
*/
protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {
return getContentPane();
}
/**
* @generated
*/
protected NodeFigure createNodePlate() {
DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40);
return result;
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated
*/
protected NodeFigure createNodeFigure() {
NodeFigure figure = createNodePlate();
figure.setLayoutManager(new StackLayout());
IFigure shape = createNodeShape();
figure.add(shape);
contentPane = setupContentPane(shape);
return figure;
}
/**
* Default implementation treats passed figure as content pane.
* Respects layout one may have set for generated figure.
* @param nodeShape instance of generated figure class
* @generated
*/
protected IFigure setupContentPane(IFigure nodeShape) {
if (nodeShape.getLayoutManager() == null) {
nodeShape.setLayoutManager(new FreeformLayout() {
public Object getConstraint(IFigure figure) {
Object result = constraints.get(figure);
if (result == null) {
result = new Rectangle(0, 0, -1, -1);
}
return result;
}
});
}
return nodeShape; // use nodeShape itself as contentPane
}
/**
* @generated
*/
public IFigure getContentPane() {
if (contentPane != null) {
return contentPane;
}
return super.getContentPane();
}
/**
* @generated
*/
protected void setForegroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setForegroundColor(color);
}
}
/**
* @generated
*/
protected void setBackgroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setBackgroundColor(color);
}
}
/**
* @generated
*/
protected void setLineWidth(int width) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineWidth(width);
}
}
/**
* @generated
*/
protected void setLineType(int style) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineStyle(style);
}
}
/**
* @generated
*/
public EditPart getPrimaryChildEditPart() {
return getChildBySemanticHint(visGrid.diagram.part.VisGridVisualIDRegistry
.getType(visGrid.diagram.edit.parts.LoadNameEditPart.VISUAL_ID));
}
/**
* @generated
*/
public List<IElementType> getMARelTypesOnSource() {
ArrayList<IElementType> types = new ArrayList<IElementType>(2);
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
return types;
}
/**
* @generated
*/
public List<IElementType> getMARelTypesOnSourceAndTarget(
IGraphicalEditPart targetEditPart) {
LinkedList<IElementType> types = new LinkedList<IElementType>();
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_meterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ClimateEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.DryerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Underground_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CapbankEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.HistogramEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RelayEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.BatteryEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.NodeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Overhead_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.HouseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Transformer_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Volt_var_controlEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Regulator_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Energy_storageEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Csv_readerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LoadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MultizoneEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RefrigeratorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Series_reactorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.AuctionEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LinkEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.InverterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PqloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlayerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SubstationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MicroturbineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_nodeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.TransformerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlugloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Controller2EditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ClotheswasherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.StubauctionEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RectifierEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Power_electronicsEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Line_spacingEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MotorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.House_aEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ControllerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Underground_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Line_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.OccupantloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.EvchargerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Overhead_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.OfficeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.WaterheaterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Dc_dc_converterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.DishwasherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RecorderEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SwitchEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CommEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SolarEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.VoltdumpEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.FreezerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Diesel_dgEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MeterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ShaperEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MicrowaveEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlcEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Fault_checkEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_line_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.FuseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.BilldumpEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Frequency_genEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LightsEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Residential_enduseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CollectorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RestorationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ZIPloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RegulatorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.WeatherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RangeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.GeneratorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CapacitorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Windturb_dgEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_meterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ClimateEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.DryerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Underground_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CapbankEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.HistogramEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RelayEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.BatteryEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.NodeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Overhead_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.HouseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Transformer_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Volt_var_controlEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Regulator_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Energy_storageEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Csv_readerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LoadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MultizoneEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RefrigeratorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Series_reactorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.AuctionEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LinkEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.InverterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PqloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlayerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SubstationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MicroturbineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_nodeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.TransformerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlugloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Controller2EditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ClotheswasherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.StubauctionEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RectifierEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Power_electronicsEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Line_spacingEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MotorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.House_aEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ControllerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Underground_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Line_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.OccupantloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.EvchargerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Overhead_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.OfficeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.WaterheaterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Dc_dc_converterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_lineEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.DishwasherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RecorderEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SwitchEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CommEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.SolarEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.VoltdumpEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.FreezerEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Diesel_dgEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MeterEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ShaperEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_line_conductorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.MicrowaveEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.PlcEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Fault_checkEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Triplex_line_configurationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.FuseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.BilldumpEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Frequency_genEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.LightsEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Residential_enduseEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CollectorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RestorationEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.ZIPloadEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RegulatorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.WeatherEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.RangeEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.GeneratorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.CapacitorEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
if (targetEditPart instanceof visGrid.diagram.edit.parts.Windturb_dgEditPart) {
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
}
return types;
}
/**
* @generated
*/
public List<IElementType> getMATypesForTarget(IElementType relationshipType) {
LinkedList<IElementType> types = new LinkedList<IElementType>();
if (relationshipType == visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001) {
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_meter_2050);
types.add(visGrid.diagram.providers.VisGridElementTypes.Climate_2059);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dryer_2052);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_conductor_2026);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capbank_2024);
types.add(visGrid.diagram.providers.VisGridElementTypes.Histogram_2069);
types.add(visGrid.diagram.providers.VisGridElementTypes.Relay_2017);
types.add(visGrid.diagram.providers.VisGridElementTypes.Battery_2002);
types.add(visGrid.diagram.providers.VisGridElementTypes.Node_2054);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_conductor_2039);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_2016);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_configuration_2007);
types.add(visGrid.diagram.providers.VisGridElementTypes.Volt_var_control_2022);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_configuration_2009);
types.add(visGrid.diagram.providers.VisGridElementTypes.Energy_storage_2076);
types.add(visGrid.diagram.providers.VisGridElementTypes.Csv_reader_2033);
types.add(visGrid.diagram.providers.VisGridElementTypes.Load_2005);
types.add(visGrid.diagram.providers.VisGridElementTypes.Multizone_2066);
types.add(visGrid.diagram.providers.VisGridElementTypes.Refrigerator_2020);
types.add(visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032);
types.add(visGrid.diagram.providers.VisGridElementTypes.Auction_2047);
types.add(visGrid.diagram.providers.VisGridElementTypes.Link_2004);
types.add(visGrid.diagram.providers.VisGridElementTypes.Inverter_2058);
types.add(visGrid.diagram.providers.VisGridElementTypes.Pqload_2006);
types.add(visGrid.diagram.providers.VisGridElementTypes.Player_2015);
types.add(visGrid.diagram.providers.VisGridElementTypes.Substation_2067);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microturbine_2038);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_node_2042);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_2001);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plugload_2019);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller2_2029);
types.add(visGrid.diagram.providers.VisGridElementTypes.Clotheswasher_2063);
types.add(visGrid.diagram.providers.VisGridElementTypes.Stubauction_2048);
types.add(visGrid.diagram.providers.VisGridElementTypes.Rectifier_2075);
types.add(visGrid.diagram.providers.VisGridElementTypes.Power_electronics_2061);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_spacing_2025);
types.add(visGrid.diagram.providers.VisGridElementTypes.Motor_2065);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_a_2008);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller_2040);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_2041);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_configuration_2053);
types.add(visGrid.diagram.providers.VisGridElementTypes.Occupantload_2037);
types.add(visGrid.diagram.providers.VisGridElementTypes.Evcharger_2012);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_2036);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_2034);
types.add(visGrid.diagram.providers.VisGridElementTypes.Office_2060);
types.add(visGrid.diagram.providers.VisGridElementTypes.Waterheater_2062);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dc_dc_converter_2068);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_2027);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dishwasher_2010);
types.add(visGrid.diagram.providers.VisGridElementTypes.Recorder_2046);
types.add(visGrid.diagram.providers.VisGridElementTypes.Switch_2071);
types.add(visGrid.diagram.providers.VisGridElementTypes.Comm_2074);
types.add(visGrid.diagram.providers.VisGridElementTypes.Solar_2051);
types.add(visGrid.diagram.providers.VisGridElementTypes.Voltdump_2023);
types.add(visGrid.diagram.providers.VisGridElementTypes.Freezer_2014);
types.add(visGrid.diagram.providers.VisGridElementTypes.Diesel_dg_2077);
types.add(visGrid.diagram.providers.VisGridElementTypes.Meter_2049);
types.add(visGrid.diagram.providers.VisGridElementTypes.Shaper_2003);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_conductor_2064);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microwave_2018);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plc_2073);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fault_check_2028);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_configuration_2030);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fuse_2057);
types.add(visGrid.diagram.providers.VisGridElementTypes.Billdump_2070);
types.add(visGrid.diagram.providers.VisGridElementTypes.Frequency_gen_2035);
types.add(visGrid.diagram.providers.VisGridElementTypes.Lights_2056);
types.add(visGrid.diagram.providers.VisGridElementTypes.Residential_enduse_2011);
types.add(visGrid.diagram.providers.VisGridElementTypes.Collector_2021);
types.add(visGrid.diagram.providers.VisGridElementTypes.Restoration_2013);
types.add(visGrid.diagram.providers.VisGridElementTypes.ZIPload_2055);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_2031);
types.add(visGrid.diagram.providers.VisGridElementTypes.Weather_2044);
types.add(visGrid.diagram.providers.VisGridElementTypes.Range_2043);
types.add(visGrid.diagram.providers.VisGridElementTypes.Generator_2072);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capacitor_2045);
types.add(visGrid.diagram.providers.VisGridElementTypes.Windturb_dg_2078);
} else if (relationshipType == visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002) {
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_meter_2050);
types.add(visGrid.diagram.providers.VisGridElementTypes.Climate_2059);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dryer_2052);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_conductor_2026);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capbank_2024);
types.add(visGrid.diagram.providers.VisGridElementTypes.Histogram_2069);
types.add(visGrid.diagram.providers.VisGridElementTypes.Relay_2017);
types.add(visGrid.diagram.providers.VisGridElementTypes.Battery_2002);
types.add(visGrid.diagram.providers.VisGridElementTypes.Node_2054);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_conductor_2039);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_2016);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_configuration_2007);
types.add(visGrid.diagram.providers.VisGridElementTypes.Volt_var_control_2022);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_configuration_2009);
types.add(visGrid.diagram.providers.VisGridElementTypes.Energy_storage_2076);
types.add(visGrid.diagram.providers.VisGridElementTypes.Csv_reader_2033);
types.add(visGrid.diagram.providers.VisGridElementTypes.Load_2005);
types.add(visGrid.diagram.providers.VisGridElementTypes.Multizone_2066);
types.add(visGrid.diagram.providers.VisGridElementTypes.Refrigerator_2020);
types.add(visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032);
types.add(visGrid.diagram.providers.VisGridElementTypes.Auction_2047);
types.add(visGrid.diagram.providers.VisGridElementTypes.Link_2004);
types.add(visGrid.diagram.providers.VisGridElementTypes.Inverter_2058);
types.add(visGrid.diagram.providers.VisGridElementTypes.Pqload_2006);
types.add(visGrid.diagram.providers.VisGridElementTypes.Player_2015);
types.add(visGrid.diagram.providers.VisGridElementTypes.Substation_2067);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microturbine_2038);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_node_2042);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_2001);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plugload_2019);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller2_2029);
types.add(visGrid.diagram.providers.VisGridElementTypes.Clotheswasher_2063);
types.add(visGrid.diagram.providers.VisGridElementTypes.Stubauction_2048);
types.add(visGrid.diagram.providers.VisGridElementTypes.Rectifier_2075);
types.add(visGrid.diagram.providers.VisGridElementTypes.Power_electronics_2061);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_spacing_2025);
types.add(visGrid.diagram.providers.VisGridElementTypes.Motor_2065);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_a_2008);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller_2040);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_2041);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_configuration_2053);
types.add(visGrid.diagram.providers.VisGridElementTypes.Occupantload_2037);
types.add(visGrid.diagram.providers.VisGridElementTypes.Evcharger_2012);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_2036);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_2034);
types.add(visGrid.diagram.providers.VisGridElementTypes.Office_2060);
types.add(visGrid.diagram.providers.VisGridElementTypes.Waterheater_2062);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dc_dc_converter_2068);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_2027);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dishwasher_2010);
types.add(visGrid.diagram.providers.VisGridElementTypes.Recorder_2046);
types.add(visGrid.diagram.providers.VisGridElementTypes.Switch_2071);
types.add(visGrid.diagram.providers.VisGridElementTypes.Comm_2074);
types.add(visGrid.diagram.providers.VisGridElementTypes.Solar_2051);
types.add(visGrid.diagram.providers.VisGridElementTypes.Voltdump_2023);
types.add(visGrid.diagram.providers.VisGridElementTypes.Freezer_2014);
types.add(visGrid.diagram.providers.VisGridElementTypes.Diesel_dg_2077);
types.add(visGrid.diagram.providers.VisGridElementTypes.Meter_2049);
types.add(visGrid.diagram.providers.VisGridElementTypes.Shaper_2003);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_conductor_2064);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microwave_2018);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plc_2073);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fault_check_2028);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_configuration_2030);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fuse_2057);
types.add(visGrid.diagram.providers.VisGridElementTypes.Billdump_2070);
types.add(visGrid.diagram.providers.VisGridElementTypes.Frequency_gen_2035);
types.add(visGrid.diagram.providers.VisGridElementTypes.Lights_2056);
types.add(visGrid.diagram.providers.VisGridElementTypes.Residential_enduse_2011);
types.add(visGrid.diagram.providers.VisGridElementTypes.Collector_2021);
types.add(visGrid.diagram.providers.VisGridElementTypes.Restoration_2013);
types.add(visGrid.diagram.providers.VisGridElementTypes.ZIPload_2055);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_2031);
types.add(visGrid.diagram.providers.VisGridElementTypes.Weather_2044);
types.add(visGrid.diagram.providers.VisGridElementTypes.Range_2043);
types.add(visGrid.diagram.providers.VisGridElementTypes.Generator_2072);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capacitor_2045);
types.add(visGrid.diagram.providers.VisGridElementTypes.Windturb_dg_2078);
}
return types;
}
/**
* @generated
*/
public List<IElementType> getMARelTypesOnTarget() {
ArrayList<IElementType> types = new ArrayList<IElementType>(2);
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001);
types.add(visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002);
return types;
}
/**
* @generated
*/
public List<IElementType> getMATypesForSource(IElementType relationshipType) {
LinkedList<IElementType> types = new LinkedList<IElementType>();
if (relationshipType == visGrid.diagram.providers.VisGridElementTypes.ConnectionParent_4001) {
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_meter_2050);
types.add(visGrid.diagram.providers.VisGridElementTypes.Climate_2059);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dryer_2052);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_conductor_2026);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capbank_2024);
types.add(visGrid.diagram.providers.VisGridElementTypes.Histogram_2069);
types.add(visGrid.diagram.providers.VisGridElementTypes.Relay_2017);
types.add(visGrid.diagram.providers.VisGridElementTypes.Battery_2002);
types.add(visGrid.diagram.providers.VisGridElementTypes.Node_2054);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_conductor_2039);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_2016);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_configuration_2007);
types.add(visGrid.diagram.providers.VisGridElementTypes.Volt_var_control_2022);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_configuration_2009);
types.add(visGrid.diagram.providers.VisGridElementTypes.Energy_storage_2076);
types.add(visGrid.diagram.providers.VisGridElementTypes.Csv_reader_2033);
types.add(visGrid.diagram.providers.VisGridElementTypes.Load_2005);
types.add(visGrid.diagram.providers.VisGridElementTypes.Multizone_2066);
types.add(visGrid.diagram.providers.VisGridElementTypes.Refrigerator_2020);
types.add(visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032);
types.add(visGrid.diagram.providers.VisGridElementTypes.Auction_2047);
types.add(visGrid.diagram.providers.VisGridElementTypes.Link_2004);
types.add(visGrid.diagram.providers.VisGridElementTypes.Inverter_2058);
types.add(visGrid.diagram.providers.VisGridElementTypes.Pqload_2006);
types.add(visGrid.diagram.providers.VisGridElementTypes.Player_2015);
types.add(visGrid.diagram.providers.VisGridElementTypes.Substation_2067);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microturbine_2038);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_node_2042);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_2001);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plugload_2019);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller2_2029);
types.add(visGrid.diagram.providers.VisGridElementTypes.Clotheswasher_2063);
types.add(visGrid.diagram.providers.VisGridElementTypes.Stubauction_2048);
types.add(visGrid.diagram.providers.VisGridElementTypes.Rectifier_2075);
types.add(visGrid.diagram.providers.VisGridElementTypes.Power_electronics_2061);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_spacing_2025);
types.add(visGrid.diagram.providers.VisGridElementTypes.Motor_2065);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_a_2008);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller_2040);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_2041);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_configuration_2053);
types.add(visGrid.diagram.providers.VisGridElementTypes.Occupantload_2037);
types.add(visGrid.diagram.providers.VisGridElementTypes.Evcharger_2012);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_2036);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_2034);
types.add(visGrid.diagram.providers.VisGridElementTypes.Office_2060);
types.add(visGrid.diagram.providers.VisGridElementTypes.Waterheater_2062);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dc_dc_converter_2068);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_2027);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dishwasher_2010);
types.add(visGrid.diagram.providers.VisGridElementTypes.Recorder_2046);
types.add(visGrid.diagram.providers.VisGridElementTypes.Switch_2071);
types.add(visGrid.diagram.providers.VisGridElementTypes.Comm_2074);
types.add(visGrid.diagram.providers.VisGridElementTypes.Solar_2051);
types.add(visGrid.diagram.providers.VisGridElementTypes.Voltdump_2023);
types.add(visGrid.diagram.providers.VisGridElementTypes.Freezer_2014);
types.add(visGrid.diagram.providers.VisGridElementTypes.Diesel_dg_2077);
types.add(visGrid.diagram.providers.VisGridElementTypes.Meter_2049);
types.add(visGrid.diagram.providers.VisGridElementTypes.Shaper_2003);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_conductor_2064);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microwave_2018);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plc_2073);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fault_check_2028);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_configuration_2030);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fuse_2057);
types.add(visGrid.diagram.providers.VisGridElementTypes.Billdump_2070);
types.add(visGrid.diagram.providers.VisGridElementTypes.Frequency_gen_2035);
types.add(visGrid.diagram.providers.VisGridElementTypes.Lights_2056);
types.add(visGrid.diagram.providers.VisGridElementTypes.Residential_enduse_2011);
types.add(visGrid.diagram.providers.VisGridElementTypes.Collector_2021);
types.add(visGrid.diagram.providers.VisGridElementTypes.Restoration_2013);
types.add(visGrid.diagram.providers.VisGridElementTypes.ZIPload_2055);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_2031);
types.add(visGrid.diagram.providers.VisGridElementTypes.Weather_2044);
types.add(visGrid.diagram.providers.VisGridElementTypes.Range_2043);
types.add(visGrid.diagram.providers.VisGridElementTypes.Generator_2072);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capacitor_2045);
types.add(visGrid.diagram.providers.VisGridElementTypes.Windturb_dg_2078);
} else if (relationshipType == visGrid.diagram.providers.VisGridElementTypes.ConnectionConnections_4002) {
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_meter_2050);
types.add(visGrid.diagram.providers.VisGridElementTypes.Climate_2059);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dryer_2052);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_conductor_2026);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capbank_2024);
types.add(visGrid.diagram.providers.VisGridElementTypes.Histogram_2069);
types.add(visGrid.diagram.providers.VisGridElementTypes.Relay_2017);
types.add(visGrid.diagram.providers.VisGridElementTypes.Battery_2002);
types.add(visGrid.diagram.providers.VisGridElementTypes.Node_2054);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_conductor_2039);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_2016);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_configuration_2007);
types.add(visGrid.diagram.providers.VisGridElementTypes.Volt_var_control_2022);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_configuration_2009);
types.add(visGrid.diagram.providers.VisGridElementTypes.Energy_storage_2076);
types.add(visGrid.diagram.providers.VisGridElementTypes.Csv_reader_2033);
types.add(visGrid.diagram.providers.VisGridElementTypes.Load_2005);
types.add(visGrid.diagram.providers.VisGridElementTypes.Multizone_2066);
types.add(visGrid.diagram.providers.VisGridElementTypes.Refrigerator_2020);
types.add(visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032);
types.add(visGrid.diagram.providers.VisGridElementTypes.Auction_2047);
types.add(visGrid.diagram.providers.VisGridElementTypes.Link_2004);
types.add(visGrid.diagram.providers.VisGridElementTypes.Inverter_2058);
types.add(visGrid.diagram.providers.VisGridElementTypes.Pqload_2006);
types.add(visGrid.diagram.providers.VisGridElementTypes.Player_2015);
types.add(visGrid.diagram.providers.VisGridElementTypes.Substation_2067);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microturbine_2038);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_node_2042);
types.add(visGrid.diagram.providers.VisGridElementTypes.Transformer_2001);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plugload_2019);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller2_2029);
types.add(visGrid.diagram.providers.VisGridElementTypes.Clotheswasher_2063);
types.add(visGrid.diagram.providers.VisGridElementTypes.Stubauction_2048);
types.add(visGrid.diagram.providers.VisGridElementTypes.Rectifier_2075);
types.add(visGrid.diagram.providers.VisGridElementTypes.Power_electronics_2061);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_spacing_2025);
types.add(visGrid.diagram.providers.VisGridElementTypes.Motor_2065);
types.add(visGrid.diagram.providers.VisGridElementTypes.House_a_2008);
types.add(visGrid.diagram.providers.VisGridElementTypes.Controller_2040);
types.add(visGrid.diagram.providers.VisGridElementTypes.Underground_line_2041);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_configuration_2053);
types.add(visGrid.diagram.providers.VisGridElementTypes.Occupantload_2037);
types.add(visGrid.diagram.providers.VisGridElementTypes.Evcharger_2012);
types.add(visGrid.diagram.providers.VisGridElementTypes.Overhead_line_2036);
types.add(visGrid.diagram.providers.VisGridElementTypes.Line_2034);
types.add(visGrid.diagram.providers.VisGridElementTypes.Office_2060);
types.add(visGrid.diagram.providers.VisGridElementTypes.Waterheater_2062);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dc_dc_converter_2068);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_2027);
types.add(visGrid.diagram.providers.VisGridElementTypes.Dishwasher_2010);
types.add(visGrid.diagram.providers.VisGridElementTypes.Recorder_2046);
types.add(visGrid.diagram.providers.VisGridElementTypes.Switch_2071);
types.add(visGrid.diagram.providers.VisGridElementTypes.Comm_2074);
types.add(visGrid.diagram.providers.VisGridElementTypes.Solar_2051);
types.add(visGrid.diagram.providers.VisGridElementTypes.Voltdump_2023);
types.add(visGrid.diagram.providers.VisGridElementTypes.Freezer_2014);
types.add(visGrid.diagram.providers.VisGridElementTypes.Diesel_dg_2077);
types.add(visGrid.diagram.providers.VisGridElementTypes.Meter_2049);
types.add(visGrid.diagram.providers.VisGridElementTypes.Shaper_2003);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_conductor_2064);
types.add(visGrid.diagram.providers.VisGridElementTypes.Microwave_2018);
types.add(visGrid.diagram.providers.VisGridElementTypes.Plc_2073);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fault_check_2028);
types.add(visGrid.diagram.providers.VisGridElementTypes.Triplex_line_configuration_2030);
types.add(visGrid.diagram.providers.VisGridElementTypes.Fuse_2057);
types.add(visGrid.diagram.providers.VisGridElementTypes.Billdump_2070);
types.add(visGrid.diagram.providers.VisGridElementTypes.Frequency_gen_2035);
types.add(visGrid.diagram.providers.VisGridElementTypes.Lights_2056);
types.add(visGrid.diagram.providers.VisGridElementTypes.Residential_enduse_2011);
types.add(visGrid.diagram.providers.VisGridElementTypes.Collector_2021);
types.add(visGrid.diagram.providers.VisGridElementTypes.Restoration_2013);
types.add(visGrid.diagram.providers.VisGridElementTypes.ZIPload_2055);
types.add(visGrid.diagram.providers.VisGridElementTypes.Regulator_2031);
types.add(visGrid.diagram.providers.VisGridElementTypes.Weather_2044);
types.add(visGrid.diagram.providers.VisGridElementTypes.Range_2043);
types.add(visGrid.diagram.providers.VisGridElementTypes.Generator_2072);
types.add(visGrid.diagram.providers.VisGridElementTypes.Capacitor_2045);
types.add(visGrid.diagram.providers.VisGridElementTypes.Windturb_dg_2078);
}
return types;
}
/**
* @generated
*/
public class LoadFigure extends RectangleFigure {
/**
* @generated
*/
private RectangleFigure fFigureOuterRect;
/**
* @generated
*/
private WrappingLabel fFigureLoadNameFigure;
/**
* @generated
*/
public LoadFigure() {
this.setLayoutManager(new XYLayout());
this.setFill(false);
this.setOutline(false);
createContents();
}
/**
* @generated
*/
private void createContents() {
RectangleFigure innerSVG0 = new RectangleFigure();
innerSVG0.setOutline(false);
this.add(innerSVG0, new Rectangle(getMapMode().DPtoLP(45),
getMapMode().DPtoLP(0), getMapMode().DPtoLP(60),
getMapMode().DPtoLP(60)));
innerSVG0.setLayoutManager(new XYLayout());
SVGFigure loadFigureSVG1 = new SVGFigure();
File tempFile = new File("visGridImages/load.svg");
loadFigureSVG1.setURI(tempFile.toURI().toString());
innerSVG0.add(loadFigureSVG1, new Rectangle(0, 0, getMapMode()
.DPtoLP(60), getMapMode().DPtoLP(60)));
RectangleFigure inner0 = new RectangleFigure();
inner0.setFill(false);
inner0.setOutline(false);
inner0.setLineWidth(0);
this.add(
inner0,
new Rectangle(getMapMode().DPtoLP(0), getMapMode().DPtoLP(
60), getMapMode().DPtoLP(150), getMapMode().DPtoLP(
20)));
FlowLayout layoutInner0 = new FlowLayout();
layoutInner0.setStretchMinorAxis(false);
layoutInner0.setMinorAlignment(FlowLayout.ALIGN_LEFTTOP);
layoutInner0.setMajorAlignment(FlowLayout.ALIGN_LEFTTOP);
layoutInner0.setMajorSpacing(5);
layoutInner0.setMinorSpacing(5);
layoutInner0.setHorizontal(true);
inner0.setLayoutManager(layoutInner0);
fFigureLoadNameFigure = new WrappingLabel();
fFigureLoadNameFigure.setText("<...>");
inner0.add(fFigureLoadNameFigure);
FlowLayout layoutFFigureLoadNameFigure = new FlowLayout();
layoutFFigureLoadNameFigure.setStretchMinorAxis(false);
layoutFFigureLoadNameFigure
.setMinorAlignment(FlowLayout.ALIGN_LEFTTOP);
layoutFFigureLoadNameFigure
.setMajorAlignment(FlowLayout.ALIGN_LEFTTOP);
layoutFFigureLoadNameFigure.setMajorSpacing(5);
layoutFFigureLoadNameFigure.setMinorSpacing(5);
layoutFFigureLoadNameFigure.setHorizontal(true);
fFigureLoadNameFigure.setLayoutManager(layoutFFigureLoadNameFigure);
}
/**
* @generated
*/
public RectangleFigure getFigureOuterRect() {
return fFigureOuterRect;
}
/**
* @generated
*/
public WrappingLabel getFigureLoadNameFigure() {
return fFigureLoadNameFigure;
}
}
}
| gpl-3.0 |
shadowmage45/AncientWarfare | AncientWarfare/src/shadowmage/ancient_warfare/client/gui/info/GuiResearchBook.java | 19725 | /**
Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513)
This software is distributed under the terms of the GNU General Public License.
Please see COPYING for precise license information.
This file is part of Ancient Warfare.
Ancient Warfare 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 3 of the License, or
(at your option) any later version.
Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>.
*/
package shadowmage.ancient_warfare.client.gui.info;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.ShapedRecipes;
import shadowmage.ancient_warfare.client.gui.GuiContainerAdvanced;
import shadowmage.ancient_warfare.client.gui.elements.GuiButtonSimple;
import shadowmage.ancient_warfare.client.gui.elements.GuiElement;
import shadowmage.ancient_warfare.client.gui.elements.GuiItemStack;
import shadowmage.ancient_warfare.client.gui.elements.GuiScrollableArea;
import shadowmage.ancient_warfare.client.gui.elements.GuiString;
import shadowmage.ancient_warfare.client.gui.elements.GuiTab;
import shadowmage.ancient_warfare.client.gui.elements.GuiTextInputLine;
import shadowmage.ancient_warfare.client.gui.elements.IGuiElement;
import shadowmage.ancient_warfare.client.render.RenderTools;
import shadowmage.ancient_warfare.common.config.Config;
import shadowmage.ancient_warfare.common.container.ContainerDummy;
import shadowmage.ancient_warfare.common.crafting.AWCraftingManager;
import shadowmage.ancient_warfare.common.crafting.RecipeSorterAZ;
import shadowmage.ancient_warfare.common.crafting.RecipeSorterTextFilter;
import shadowmage.ancient_warfare.common.crafting.RecipeType;
import shadowmage.ancient_warfare.common.crafting.ResourceListRecipe;
import shadowmage.ancient_warfare.common.research.IResearchGoal;
import shadowmage.ancient_warfare.common.research.ResearchGoal;
import shadowmage.ancient_warfare.common.tracker.ResearchTracker;
import shadowmage.ancient_warfare.common.tracker.TeamTracker;
import shadowmage.ancient_warfare.common.tracker.entry.PlayerEntry;
import shadowmage.ancient_warfare.common.vehicles.IVehicleType;
import shadowmage.ancient_warfare.common.vehicles.types.VehicleType;
public class GuiResearchBook extends GuiContainerAdvanced
{
GuiTab activeTab = null;
HashSet<GuiTab> tabs = new HashSet<GuiTab>();
PlayerEntry entry;
RecipeSorterAZ sorterAZ = new RecipeSorterAZ();
RecipeSorterTextFilter sorterFilter = new RecipeSorterTextFilter();
GuiTextInputLine searchBox;
GuiScrollableArea area;
int buttonWidth = 256 - 24 - 10;
HashMap<GuiButtonSimple, ResourceListRecipe> recipes = new HashMap<GuiButtonSimple, ResourceListRecipe>();
GuiTab mainTab;
GuiTab vehicleTab;
GuiTab ammoTab;
GuiTab npcTab;
GuiTab civicTab;
GuiTab miscTab;
GuiTab researchTab;
GuiTab structuresTab;
GuiTab craftingTab;
EnumSet recipeTypes = null;
/**
* @param container
*/
public GuiResearchBook(EntityPlayer player)
{
super(new ContainerDummy());
this.entry = ResearchTracker.instance().getClientEntry();
this.shouldCloseOnVanillaKeys = true;
}
@Override
public int getXSize()
{
return 256;
}
@Override
public int getYSize()
{
return 240;
}
@Override
protected void renderBackgroundImage(String tex)
{
if(tex!=null)
{
RenderTools.drawQuadedTexture(guiLeft, guiTop+21, this.xSize, this.ySize-42, 256, 240, tex, 0, 0);
}
}
@Override
public String getGuiBackGroundTexture()
{
return Config.texturePath+"gui/guiBackgroundLarge.png";
}
@Override
public void renderExtraBackGround(int mouseX, int mouseY, float partialTime)
{
}
@Override
public void updateScreenContents()
{
area.updateGuiPos(guiLeft, guiTop);
}
@Override
public void onElementActivated(IGuiElement element)
{
if(this.tabs.contains(element))
{
GuiTab selected = (GuiTab) element;
for(GuiTab tab : this.tabs)
{
tab.enabled = false;
}
selected.enabled = true;
this.activeTab = selected;
this.forceUpdate = true;
this.searchBox.selected = false;
}
if(this.activeTab==this.mainTab)
{
/**
* need basic stats on front info page, ++ descriptions of what they other tabs are for
*/
}
else if(this.activeTab==this.vehicleTab)
{
if(this.recipes.containsKey(element))
{
this.handleRecipeClick(element);
}
}
else if(this.activeTab==this.ammoTab)
{
if(this.recipes.containsKey(element))
{
this.handleRecipeClick(element);
}
}
else if(this.activeTab==this.npcTab)
{
if(this.recipes.containsKey(element))
{
this.handleRecipeClick(element);
}
}
else if(this.activeTab==this.civicTab)
{
if(this.recipes.containsKey(element))
{
this.handleRecipeClick(element);
}
}
else if(this.activeTab==this.researchTab)
{
if(this.recipes.containsKey(element))
{
this.handleRecipeClick(element);
}
}
else if(this.activeTab==this.craftingTab)
{
}
else if(this.activeTab==this.structuresTab)
{
}
else if(this.activeTab==this.miscTab)
{
}
}
@Override
public void setupControls()
{
GuiTab tab = this.addGuiTab(1000, 3, 0, 50, 24, "Info");
this.activeTab = tab;
this.tabs.add(tab);
this.mainTab = tab;
tab = this.addGuiTab(1001, 3+50, 0, 50, 24, "Vehicles");
tab.enabled = false;
this.tabs.add(tab);
this.vehicleTab = tab;
tab = this.addGuiTab(1002, 3+50+50, 0, 50, 24, "Ammo");
tab.enabled = false;
this.tabs.add(tab);
this.ammoTab = tab;
tab = this.addGuiTab(1003, 3+50+50+50, 0, 50, 24, "Npcs");
tab.enabled = false;
this.tabs.add(tab);
this.npcTab = tab;
tab = this.addGuiTab(1004, 3+50+50+50+50, 0, 50, 24, "Civics");
tab.enabled = false;
this.tabs.add(tab);
this.civicTab = tab;
int y = this.getYSize()-24;
tab = this.addGuiTab(1005, 3, y, 60, 24, "Research");
tab.enabled = false;
tab.inverted = true;
this.tabs.add(tab);
this.researchTab = tab;
tab = this.addGuiTab(1006, 3+60, y, 60, 24, "Crafting");
tab.enabled = false;
tab.inverted = true;
this.tabs.add(tab);
this.craftingTab = tab;
tab = this.addGuiTab(1007, 3+60+60, y, 80, 24, "Structures");
tab.enabled = false;
tab.inverted = true;
this.tabs.add(tab);
this.structuresTab = tab;
tab = this.addGuiTab(1008, 3+60+60+80, y, 50, 24, "Misc");
tab.enabled = false;
tab.inverted = true;
this.tabs.add(tab);
this.miscTab = tab;
this.searchBox = (GuiTextInputLine) new GuiTextInputLine(2, this, 240, 12, 30, "").updateRenderPos(5, 28);
searchBox.selected = false;
int w = 256-10;
int h = 240 - 42 - 10 - 20;
int x = 5;
y = 21+5+20;
this.area = new GuiScrollableArea(0, this, x, y, w, h, 0);
this.forceUpdate = true;
}
@Override
public void updateControls()
{
this.guiElements.clear();
this.area.elements.clear();
this.recipeTypes = null;
for(GuiTab tab : this.tabs)
{
this.guiElements.put(tab.getElementNumber(), tab);
}
for(Integer i : this.guiElements.keySet())
{
this.guiElements.get(i).updateGuiPos(guiLeft, guiTop);
}
if(this.activeTab==this.mainTab)
{
this.addMainInfo();
}
else if(this.activeTab==this.vehicleTab)
{
this.recipeTypes = EnumSet.of(RecipeType.VEHICLE, RecipeType.VEHICLE_MISC);
this.guiElements.put(1, searchBox);
this.handleSearchBoxUpdate(recipeTypes);
}
else if(this.activeTab==this.ammoTab)
{
this.recipeTypes = EnumSet.of(RecipeType.AMMO, RecipeType.AMMO_MISC);
this.guiElements.put(1, searchBox);
this.handleSearchBoxUpdate(recipeTypes);
}
else if(this.activeTab==this.npcTab)
{
this.recipeTypes = EnumSet.of(RecipeType.NPC, RecipeType.NPC_MISC);
this.guiElements.put(1, searchBox);
this.handleSearchBoxUpdate(recipeTypes);
}
else if(this.activeTab==this.civicTab)
{
this.recipeTypes = EnumSet.of(RecipeType.CIVIC, RecipeType.CIVIC_MISC);
this.guiElements.put(1, searchBox);
this.handleSearchBoxUpdate(recipeTypes);
}
else if(this.activeTab==this.researchTab)
{
/**
* hmm...might need sub-tabs/buttons for known/unknown
*/
this.recipeTypes = EnumSet.of(RecipeType.RESEARCH);
this.guiElements.put(1, searchBox);
this.handleSearchBoxUpdate(recipeTypes);
}
else if(this.activeTab==this.craftingTab)
{
this.addCraftingInfo();//mostly done..or done..w/e
}
else if(this.activeTab==this.structuresTab)
{
this.addStructureInfo();
}
else if(this.activeTab==this.miscTab)
{
this.addMiscInfo();
}
for(Integer i : this.guiElements.keySet())
{
this.guiElements.get(i).updateGuiPos(guiLeft, guiTop);
}
}
protected void addMiscInfo()
{
this.guiElements.put(0, area);
int y = 0;
int elementNum = 0;
List<String> displayText = new ArrayList<String>();
displayText.add("Misc Tips and Info");
displayText.add("");
displayText.add("1.) Always keep your NPCs fed, and protected. Hungry NPCs won't work very hard!");
displayText.add("2.) More coming soon!");
displayText = RenderTools.getFormattedLines(displayText, 220);
GuiString string;
for(String line : displayText)
{
string = new GuiString(elementNum, area, 240, 10, line);
string.updateRenderPos(0, y);
y+=10;
elementNum++;
area.elements.add(string);
}
area.updateTotalHeight(y);
}
protected void addMainInfo()
{
this.guiElements.put(0, area);
int y = 0;
int elementNum = 0;
List<String> displayText = new ArrayList<String>();
displayText.add("Welcome to Ancient Warfare.");
displayText.add("");
displayText.add("Current Team: " + TeamTracker.instance().getTeamForPlayer(player));
displayText.add("Players on Team: " +TeamTracker.instance().getTeamEntryFor(player).members.size());
displayText.add("Known Research: "+entry.getKnownResearch().size());
displayText.add("Unkown Research: "+entry.getUnknwonResearch().size());
displayText.add("");
displayText.add("To begin research, place a research book (that is bound to you) into a research table.");
displayText.add("");
displayText.add("To begin crafting, place a research book (that is bound to you) into the book slot of a crafting table.");
displayText.add("");
displayText.add("Recipes for Vehicles, NPCs, Civics, and Ammo may be viewed by opening the corresponding tab. All research goals" +
" may be viewed by clicking on the Research Tab.");
displayText.add("");
displayText.add("Crafting instructions are available in the Crafing tab.");
displayText.add("Structure processing instructions are available in the Structures tab.");
displayText = RenderTools.getFormattedLines(displayText, 220);
GuiString string;
for(String line : displayText)
{
string = new GuiString(elementNum, area, 240, 10, line);
string.updateRenderPos(0, y);
y+=10;
elementNum++;
area.elements.add(string);
}
area.updateTotalHeight(y);
}
protected void addStructureInfo()
{
this.guiElements.put(0, area);
int y = 0;
int elementNum = 0;
List<String> displayText = new ArrayList<String>();
String text = "Structure crafting in Ancient Warfare is accomplished at the Drafting Station. " +
"This station allows for the production of structure creation items for any structures flagged" +
" as being available in survival-mode.";
displayText.add(text);
text = "";
displayText.add(text);
text = "In order to begin production of a structure, select if from the selection list, and click the" +
" start button on the crafting/progress page. The structure will then be 'locked in' and may not be" +
" changed except through the use of the 'Clear' button (which will discard any used materials--so" +
" use with caution).";
displayText.add(text);
text = "";
displayText.add(text);
text = "Once a structure item has been produced, you must select an appropriate site for its construction. In" +
" survival mode, the chosen site must be 100% clear of any existing blocks or obstructions in order to proceed" +
" with placement. Once you have placed the building site, you will need workers in order to construct the building" +
" for you. Currently Miner type NPCs are the only type that can construct buildings.";
displayText.add(text);
displayText = RenderTools.getFormattedLines(displayText, 220);
GuiString string;
for(String line : displayText)
{
string = new GuiString(elementNum, area, 240, 10, line);
string.updateRenderPos(0, y);
y+=10;
elementNum++;
area.elements.add(string);
}
area.updateTotalHeight(y);
}
protected void addCraftingInfo()
{
this.guiElements.put(0, area);
int y = 0;
int elementNum = 0;
List<String> displayText = new ArrayList<String>();
String text = "Crafting in Ancient Warfare is accomplished at one of five crafting" +
" stations. These stations each have specific types of recipes that may be crafted" +
" corresponding with the station type. Crafting stations are available for Vehicles," +
" Npcs, Civics, Ammunitions, and Structures.";
displayText.add(text);
text = "";
displayText.add(text);
text = "All crafting stations aside from the Structure station require that a Research Book" +
" be present in the Upper-Left slot (The research book slot). The recipes available at" +
" any particular station are dependant upon the research book that is slotted (and whether" +
" or not creative mode is enabled).";
displayText.add(text);
text = "";
displayText.add(text);
text = "Crafting stations need workers in order to make progress. Any time a player is interacting" +
" with a crafting station this counts as a full-time worker. NPC Craftsman may also be designated" +
" to work at crafting stations so that items may be crafted without a player present. (Config option" +
" available to disable worker requirements)";
displayText.add(text);
text = "";
displayText.add(text);
text = "All Crafting Station recipes are available in the normal Crafting Bench (as well as the Civic" +
" crafting station). The recipes are as follows: ";
displayText.add(text);
text = "";
displayText.add(text);
displayText = RenderTools.getFormattedLines(displayText, 220);
GuiString string;
for(String line : displayText)
{
string = new GuiString(elementNum, area, 240, 10, line);
string.updateRenderPos(0, y);
y+=10;
elementNum++;
area.elements.add(string);
}
GuiItemStack stack;
ItemStack recipeStack;
for(ShapedRecipes recipe : AWCraftingManager.vanillaRecipeList)
{
int sy = 0;
int sx = 0;
string = new GuiString(elementNum, area, 220, 10, recipe.getRecipeOutput().getDisplayName());
string.updateRenderPos(0, y);
area.elements.add(string);
y+=10;
elementNum++;
for(int i = 0; i < 9; i++)
{
if(i<recipe.recipeItems.length)
{
recipeStack = recipe.recipeItems[i];
}
else
{
recipeStack = null;
}
stack = new GuiItemStack(elementNum, area);
stack.renderSlotBackground = true;
stack.setItemStack(recipeStack);
stack.updateRenderPos(sx * 18, y);
area.elements.add(stack);
sx++;
elementNum++;
if(sx>=3)
{
sx= 0;
sy++;
y+=18;
}
}
stack = new GuiItemStack(elementNum, area);
stack.updateRenderPos(4*18, y-36);
stack.setItemStack(recipe.getRecipeOutput());
stack.renderSlotBackground = true;
area.elements.add(stack);
y+=10;
elementNum++;
}
area.updateTotalHeight(y);
}
protected void handleSearchBoxUpdate(EnumSet<RecipeType> recipeTypes)
{
this.guiElements.put(0, area);
String text = this.searchBox.getText();
this.recipes.clear();
this.area.elements.clear();
this.sorterFilter.setFilterText(text);
PlayerEntry entry = ResearchTracker.instance().getClientEntry();
if(recipeTypes!=null)
{
this.addRecipeButtons(AWCraftingManager.instance().getRecipesContaining(entry, text, recipeTypes, true), sorterFilter);
}
}
protected void addRecipeButtons(List<ResourceListRecipe> recipes, Comparator sorter)
{
this.guiElements.put(0, area);
Collections.sort(recipes, sorter);
area.updateTotalHeight(recipes.size()*18);
GuiButtonSimple button;
int x = 0;
int y = 0;
ArrayList<String> tooltip = new ArrayList<String>();
tooltip.add("Hold (shift) while clicking to");
tooltip.add("view detailed recipe information");
int num = 100;
for(ResourceListRecipe recipe : recipes)
{
button = new GuiButtonSimple(num, area, buttonWidth, 16, recipe.getLocalizedDisplayName());
button.updateRenderPos(x, y);
button.setTooltip(tooltip);
area.addGuiElement(button);
this.recipes.put(button, recipe);
y+=18;
num++;
}
}
@Override
protected void keyTyped(char par1, int par2)
{
for(Integer i : this.guiElements.keySet())
{
GuiElement el = this.guiElements.get(i);
el.onKeyTyped(par1, par2);
}
if(!this.searchBox.selected)
{
super.keyTyped(par1, par2);
}
else
{
this.handleSearchBoxUpdate(this.recipeTypes);
}
}
protected void handleRecipeClick(IGuiElement element)
{
ResourceListRecipe recipe = recipes.get(element);
if(recipe.type==RecipeType.RESEARCH)
{
this.handleResearchDetailsClick(recipe);
}
else if(recipe.type==RecipeType.VEHICLE)
{
this.handleVehicleDetailsClick(recipe);
}
else
{
this.handleRecipeDetailsClick(recipe);
}
}
protected void handleRecipeDetailsClick(ResourceListRecipe recipe)
{
mc.displayGuiScreen(new GuiRecipeDetails(this, recipe));
}
protected void handleResearchDetailsClick(ResourceListRecipe recipe)
{
int id = recipe.getResult().getItemDamage();
IResearchGoal goal = ResearchGoal.getGoalByID(id);
mc.displayGuiScreen(new GuiResearchGoal(this, goal));
}
protected void handleVehicleDetailsClick(ResourceListRecipe recipe)
{
int type = recipe.getResult().getItemDamage();
int lev = recipe.getResult().getTagCompound().getCompoundTag("AWVehSpawner").getInteger("lev");
IVehicleType t = VehicleType.getVehicleType(type);
mc.displayGuiScreen(new GuiVehicleDetails(this, recipe, t, lev));
}
}
| gpl-3.0 |
cattool/CAT_Dev_Version | src/ca/usask/ocd/ldap/LdapConnection.java | 31954 | /*****************************************************************************
* Copyright 2012, 2013 University of Saskatchewan
*
* This file is part of the Curriculum Alignment Tool (CAT).
*
* CAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
*(at your option) any later version.
*
* CAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CAT. If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************************/
package ca.usask.ocd.ldap;
//import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.io.IOException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.log4j.Logger;
public class LdapConnection
{
// private static Logger logger = Logger.getLogger( LdapConnection.class );
private static LdapConnection singleton;
private static boolean connectionError;
/** the reference to the connection info stored in the context */
private static DirContext ctx;
private static Properties env;
final static String ldapServerName = "ldap.usask.ca";
static String nsid = "abv641";
private int retries = 0;
static long start=0;
private static Logger logger = Logger.getLogger( LdapConnection.class );
public static LdapConnection instance() throws Exception
{
if(singleton == null)
{
singleton = new LdapConnection();
singleton.initConnection();
}
return singleton;
}
public LdapConnection()
{
if(singleton==null)
{
logger.info("In LdapConnection contructor, should only happen when tomcat or context is restarted.");
retries=0;
connectionError=true;
java.util.ResourceBundle bundle =java.util.ResourceBundle.getBundle("ldapuser");
String ldapuser=bundle.getString("user");
String ldappass=bundle.getString("password");
String ldapServerName=bundle.getString("serverName");
//for testing, use the ldapuserid for the memberOf query as well (comment next line to disable)
//nsid=ldapuser;
// set up environment to access the server
env = new Properties();
String connDN = "uid="+ldapuser+",ou=nsids,ou=people,dc=usask,dc=ca";
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
env.put( Context.PROVIDER_URL, "ldaps://"+ldapServerName);//+":636/");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put( Context.SECURITY_PRINCIPAL, connDN );
env.put( Context.SECURITY_CREDENTIALS, ldappass );
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put("com.sun.jndi.ldap.read.timeout", "10000");
env.put("com.sun.jndi.ldap.connect.timeout","5000");
logger.debug("Singleton is null, initConnection!");
try
{
initConnection();
logger.debug("initConnection complete!");
}
catch(Exception e)
{
logger.fatal("LDAP connection failure (tried 5 times)");
}
}
else
logger.debug("Singleton not null, no need to init Connection");
}
public boolean hasErrors()
{
return connectionError;
}
/** sets up the connection to the ldap server
* Any Exceptions that occur are logged using log4j */
public void initConnection() throws Exception
{
try
{
// obtain initial directory context using the environment
ctx = new InitialDirContext( env );
connectionError=false;
}
catch(javax.naming.CommunicationException e)
{
logger.error("Oops, creating ldap connection problem",e);
}
catch(Exception e)
{
boolean retry=false;
if(e instanceof NoInitialContextException )
{
singleton=new LdapConnection();
retry=true;
}
logger.error("Oops, creating ldap connection problem",e);
String message=e.getMessage();
//connection has gone away!
if(message.startsWith("LDAP response read timed out"))
{
retry=true;
}
if(retry)
{
//try to reconnect
connectionError=true;
try{Thread.sleep(500);}catch(Exception te){}
retries++;
logger.error("LDAP Connection error, trying again");
if(retries<5)
{
try
{
initConnection();
}
catch(Exception ee)
{
logger.fatal("LDAP connection failure (tried 5 times)");
}
}
else
{
retries=0;
logger.error("unresolveable error!",e);
throw new Exception("UNABLE TO CONNECT TO LDAP SERVER");
}
}
}
}
/** closes open connection, should really only be used from a stand alone app, or from finalize
* any Exceptions are logged using log4j*/
public void closeConnection()
{
try
{
ctx.close();
logger.debug("Closing ldap connection!");
}
catch(javax.naming.CommunicationException e)
{
logger.error("Oops, closing ldap connection problem",e);
}
catch (NamingException e)
{
logger.error("Oops, closing ldap connection problem",e);
}
catch(NullPointerException e)
{
logger.error("Oops, closing ldap connection problem",e);
}
}
public ArrayList<String> getTeachingGroups(String user) throws Exception
{
ArrayList<String> groups=new ArrayList<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
String[] attrIDs = {"memberOf"};
constraints.setReturningAttributes(attrIDs);
//you can also limit search results to a specified number
//constraints.setCountLimit(10);
String searchStringGroups="ou=people,dc=usask,dc=ca";
String searchStringData="(&(objectClass=eduPerson)(uid="+user+"))";
groups=this.runQuery(attrIDs, searchStringGroups,searchStringData,null);
ArrayList<String> toReturn = new ArrayList<String>();
if(groups!=null)
{
for(int i=0;i<groups.size();i++)
{
String value=groups.get(i);
if(value.contains("ou=classLeaders"))
{
String[] valueSets = value.split(",");
for(int j = 0; j< valueSets.length; j++)
{
if(valueSets[j].startsWith("cn="))
{
String courseOfferingInfo = valueSets[j].split("=")[1];
int leaderIndex = courseOfferingInfo.indexOf("_leaders");
if(leaderIndex > 0)
{
String offeringString = courseOfferingInfo.substring(0, leaderIndex);
if(startsWithTerm(offeringString))
{
toReturn.add(offeringString);
}
}
}
}
}
}
}
return toReturn;
}
private boolean startsWithTerm(String s)
{
try
{
String term = s.substring(0,6);
Integer.parseInt(term);
return true;
}
catch(Exception e)
{
//either the start wasn't a number or the string was too short. Either way, it didn't start with the term
}
return false;
}
public static void main( String[] args ) throws Exception
{
start=System.currentTimeMillis();
LdapConnection ldap=new LdapConnection();
TreeMap<String,String> data = ldap.getUserData("dfv574");
for(String key : data.keySet())
{
System.out.println(key +" = " + data.get(key));
}
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
List<String> grouplist = ldap.getDirectDeptEmployees("University Learning Centre");
for(String group:grouplist)
{
System.out.println(group);
}
/* List<TreeMap<String,String>> list = ldap.getUserData(grouplist);
for(TreeMap<String,String> data:list)
{
for(String key : data.keySet())
{
System.out.println(key+" : "+data.get(key));
}
System.out.println("+++++++++");
}*/
for(String group:grouplist)
{
List<String> depts = ldap.getUserDepartments(group);
for(String dept:depts)
{
System.out.println(dept);
}
System.out.println("+++++++++");
}
/* List<TreeMap<String,String>> results = ldap.searchForUserWithSurname("reer");
for(TreeMap<String,String> res : results)
{
for(String key : res.keySet())
{
System.out.println(key+" : "+res.get(key));
}
System.out.println("+++++++++");
}*/
/*List<String> grouplist = ldap.getUserGroups("abv641");
for(String group:grouplist)
{
System.out.println(group);
}*/
/*
List<String> leaders = ldap.getGroupMembers("201201_ETAD_470_02_leaders");
for(String group:leaders)
{
System.out.println(group);
}
*/
/* Collection<String> groups=ldap.getGroupsContaining("biol");
System.out.println("\n\n\nResults:");
for(String group:groups)
{
System.out.println(group);
}
// BIOL
// Biology
// student_major_biol
Map<String,String> data=ldap.getUsersInGroup("Biology");
System.out.println("\n\n\nResults:");
for(String group:data.keySet())
{
System.out.println(group);
}
*/
//logger.debug("time taken (including creating a connection) ="+(System.currentTimeMillis()-start));
ldap.closeConnection();
}
public List<TreeMap<String,String>> searchForUserWithSurname(String name) throws Exception
{
List<TreeMap<String,String>> valuesList=new ArrayList<TreeMap<String,String>>();
String[] attributesToReturn = {"cn","givenName","sn","uid"}; // this changed for guest accounts. Everyone has at least one mail attribute, though it may be different from abc123@mail.usask.ca, which is the uofsofficialemailaddress
SearchControls constraints = new SearchControls();
constraints.setReturningAttributes(attributesToReturn);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
NamingEnumeration<SearchResult> results = this.executeSearch("ou=people,dc=usask,dc=ca","(&(objectClass=eduPerson)(sn=*"+name+"*))", constraints);
if(results != null)
{
while (results.hasMore())
{
TreeMap<String,String> values=new TreeMap<String,String>();
SearchResult sr = (SearchResult)results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
/* print each attribute */
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
/* print each value */
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
{
Object temp = (Object)vals.nextElement();
if(temp instanceof String)
{
values.put(attrId, (String)temp);
}
}
}
}
valuesList.add(values);
}
results.close();
}
else
{
System.out.println("Did not find an person with account "+ nsid);
}
return valuesList;
}
public TreeMap<String,String> getUserData(String nsid) throws Exception
{
TreeMap<String,String> values=new TreeMap<String,String>();
//the assumption is made that sn and givenName exist. If these values have a different name,
// please use a translation where the values are placed in the treemap
String[] attributesToReturn = {"sn", "givenName","initials","uofsStudentNumber","cn"};
SearchControls constraints = new SearchControls();
constraints.setReturningAttributes(attributesToReturn);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
String ouGroupString = "ou=guests";
if (isNsidType(nsid))
{
ouGroupString = "ou=nsids";
}
NamingEnumeration<SearchResult> results = this.executeSearch(ouGroupString + ",ou=people,dc=usask,dc=ca","(uid="+nsid+")", constraints);
if(results != null)
{
while (results.hasMore())
{
SearchResult sr = (SearchResult)results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
/* print each attribute */
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
/* print each value */
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
{
Object temp = (Object)vals.nextElement();
if(temp instanceof String)
{
//put attrId key and temp value in treemap.
/*
if (attrId.equals("your first name key"))
values.put("givenName",(String)temp);
else if (attrId.equals("your last name key"))
values.put("sn",(String)temp);
*/
values.put(attrId, (String)temp);
}
}
}
}
}
results.close();
}
else
{
System.out.println("Did not find an person with account "+ nsid);
}
return values;
}
public TreeMap<String,TreeMap<String,String>> getUserData(List<String> nsids) throws Exception
{
StringBuilder nsidString = new StringBuilder("(|");
for(String nsid: nsids)
{
nsidString.append("(uid=");
nsidString.append(nsid);
nsidString.append(")");
}
nsidString.append(")");
TreeMap<String,TreeMap<String,String>> valuesMap=new TreeMap<String,TreeMap<String,String>>();
String[] attributesToReturn = {"uid","sn", "givenName","initials","uofsStudentNumber","cn"};
SearchControls constraints = new SearchControls();
constraints.setReturningAttributes(attributesToReturn);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
NamingEnumeration<SearchResult> results = this.executeSearch("ou=people,dc=usask,dc=ca","(&(objectClass=eduPerson)"+nsidString.toString()+")", constraints);
if(results != null)
{
while (results.hasMore())
{
TreeMap<String,String> values=new TreeMap<String,String>();
SearchResult sr = (SearchResult)results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
/* print each attribute */
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
/* print each value */
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
{
Object temp = (Object)vals.nextElement();
if(temp instanceof String)
{
values.put(attrId, (String)temp);
}
}
}
valuesMap.put(values.get("uid"),values);
}
}
results.close();
}
else
{
System.out.println("Did not find an person with account "+ nsid);
}
return valuesMap;
}
public Map<String,String> getUsersInGroup(String groupName) throws Exception
{
Map<String,String> users = new TreeMap<String,String>();
SearchControls constraints = new SearchControls();
String[] emailAttr = {"displayName"}; // this changed for guest accounts. Everyone has at least one mail attribute, though it may be different from abc123@mail.usask.ca, which is the uofsofficialemailaddress
constraints.setReturningAttributes(emailAttr);
constraints.setCountLimit(500L);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
StringBuilder builder = new StringBuilder();
builder.append("(&(objectClass=eduPerson)");
builder.append("(uofsGroupName=");
builder.append(groupName);
builder.append("))");
NamingEnumeration<SearchResult> answer = this.executeSearch("ou=people,dc=usask,dc=ca", builder.toString(), constraints);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMoreElements();) {
Attribute attr = (Attribute) ae.next();
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements();) {
Object temp = (Object) vals.nextElement(); // just grab the first email address
if (temp instanceof String)
{
String value = (String) temp;
String name = sr.getName();
String nsid = name.split("=")[1].split(",")[0];
users.put(value, nsid);
}
}
}
}
}
return users;
}
public List<String> getDirectDeptEmployees(String dept) throws Exception
{
String[] attrIDs = {"member"};
List<String> groups=this.runQuery(attrIDs, "ou=direct,ou=staff,ou=employeeDepartments,ou=groups,dc=usask,dc=ca","(&(objectClass=groupOfNames)(uofsEmployeeDepartmentLong="+dept+"))","uid=");
List<String> toReturn = new ArrayList<String>();
for(String x : groups)
{
System.out.println(x);
int uidLocation = x.indexOf("uid=");
String value = x.substring(uidLocation, x.indexOf(",",uidLocation)).split("=")[1];
toReturn.add(value);
}
return toReturn;
}
public List<String> getGroupMembers(String group) throws Exception
{
String[] attrIDs = {"member"};
List<String> groups=this.runQuery(attrIDs, "ou=groups,dc=usask,dc=ca","(&(objectClass=groupOfNames)(cn="+group+"))","uid=");
List<String> toReturn = new ArrayList<String>();
for(String x : groups)
{
int uidLocation = x.indexOf("uid=");
String value = x.substring(uidLocation, x.indexOf(",",uidLocation)).split("=")[1];
toReturn.add(value);
}
return toReturn;
}
public ArrayList<String> getUserDepartments(String user) throws Exception
{
logger.error("Retrieving groups for "+user);
ArrayList<String> groups=new ArrayList<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
String[] attrIDs = {"uofsEmployeeDepartmentLong"};
constraints.setReturningAttributes(attrIDs);
//you can also limit search results to a specified number
//constraints.setCountLimit(10);
String searchStringGroups="ou=people,dc=usask,dc=ca";
String searchStringData="(&(objectClass=eduPerson)(uid="+user+"))";
groups=this.runQuery(attrIDs, searchStringGroups,searchStringData,null);
logger.error("done retrieving groups for "+user);
return groups;
}
public ArrayList<String> getUserGroups(String user) throws Exception
{
logger.error("Retrieving groups for "+user);
ArrayList<String> groups=new ArrayList<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//this limits the list of attributes that the LDAP query will return
//NOTE: operational attributes like MemberOf only appear if requested specifically
//String[] attrIDs = {"uofsEmployeeDepartmentLong"};
//constraints.setReturningAttributes(attrIDs);
//you can also limit search results to a specified number
//constraints.setCountLimit(10);
String searchStringGroups="dc=usask,dc=ca";
String searchStringData="(&(objectClass=eduPerson)(uid="+user+"))";
NamingEnumeration<SearchResult> results = this.executeSearch(searchStringGroups,searchStringData, constraints);
if(results != null)
{
while (results.hasMore())
{
SearchResult sr = (SearchResult)results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
/* print each attribute */
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
/* print each value */
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
{
Object temp = (Object)vals.nextElement();
if(temp instanceof String)
{
// values.put(attrId, (String)temp);
System.out.println(attrId +" = "+ temp );
}
}
}
}
}
results.close();
}
else
{
System.out.println("Did not find an person with account "+ nsid);
}
System.out.println("done retrieving groups for "+user);
return groups;
}
/** retrieves all the roles matching search criteria
*
* @param term if included, the role must match term
* @param name if included, role-names returned must contain the name
* @param exact if true, only exact name matches are included. Since the term is also part of the name, it makes no sense to search for a term, a name and set exact to true.
* @return All groups matching given search-criteria
* @throws NamingException
* @throws CommunicationException
* @throws NullPointerException
*/
public ArrayList<String> getGroupsMatchingSearch(String term,String name,boolean exact) throws Exception
{
ArrayList<String> groups=new ArrayList<String>();
String[] attrIDs = {"cn"};
String searchStringGroups="ou=groups,dc=usask,dc=ca";
String searchStringData=null;
if(term!=null)
searchStringData="(&(objectClass=groupOfNames)(cn="+term+"*))";
if(name !=null)
{
if(!exact)
name="*"+name+"*";
if(searchStringData==null)
searchStringData="(&(objectClass=groupOfNames)(cn="+name+"))";
else
searchStringData="(&"+searchStringData+"(cn="+name+"))";
}
logger.info("Running LDAP query:["+searchStringGroups+"] ssd=["+searchStringData+"]");
groups=this.runQuery(attrIDs, searchStringGroups, searchStringData, null);
return groups;
}
/**Method does very little other than handle the retry if the connection has gone away.
*
* @param g groups to be returned
* @param c conditions
* @param s search conditions
* @return speaks for itself.
* @throws Exception
*/
public NamingEnumeration<SearchResult> executeSearch(String g,String c, SearchControls s) throws Exception
{
NamingEnumeration<SearchResult> results =null;
try
{
results=ctx.search(g,c, s);
return results;
}
catch (Exception ne)
{
boolean retry=false;
if(ne instanceof NoInitialContextException )
{
logger.error("LDAP Connection: NoInitialContextException ");
retry=true;
}
else if(ne instanceof IOException )
{
logger.error("LDAP Connection: IOException ");
retry=true;
}
else if(ne instanceof CommunicationException )
{
logger.error("LDAP Connection: CommunicationException ");
retry=true;
}
else
{
String message=ne.getMessage();
//connection has gone away!
if(message.startsWith("LDAP response read timed out")|| message.startsWith("Connection reset"))
{
logger.error("LDAP Connection: LDAP response read timed out or Connection Reset");
retry=true;
}
else
{
logger.error("LDAP Connection, other kind of error!", ne);
}
}
if(retry)
{
//try to reconnect
connectionError=true;
initConnection();
if(!hasErrors())
{//there are no errors, but if it was already attempted and I still got
//an exception, don't bother trying again.
retries++;
if(retries>3)
{
throw new Exception("Unable to retrieve groups from ULDAP, tried it 3 times.");
}
else
{
return executeSearch(g,c,s);
}
}
}
throw ne;
}
}
/**
* method queries uldap for either membership groups or groups matching conditions
* @param attributesToReturn which field in the result-set do we want back
* @param groups which groups should be used to determine search-domain
* @param conditions search-criteria
* @param filter any values that the returned
* @return
*/
public ArrayList<String> runQuery(String[] attributesToReturn, String groups,String conditions, String filter ) throws Exception
{
ArrayList<String> toReturn=new ArrayList<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(attributesToReturn);
constraints.setCountLimit(1000);
NamingEnumeration<SearchResult> results=executeSearch(groups,conditions,constraints);
try
{
if(results != null)
{
while (results.hasMore())
{
SearchResult sr = results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
/* print each attribute */
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
/* print each value */
for (Enumeration<?> vals = (Enumeration<?>)attr.getAll(); vals.hasMoreElements(); )
{
Object temp = vals.nextElement();
if(temp instanceof String)
{
String x = (String)temp;
if(filter!=null)
{
if(x!=null && x.contains(filter))
toReturn.add(x);
}
else
toReturn.add(x);
}
}
}
}
}
results.close();
retries=0;
}
}
catch(NamingException e)
{
String message=e.getMessage();
if(message.contains("Sizelimit Exceeded"))
throw new Exception("Your search-criteria are too broad, more than 1000 entries were returned");
throw new Exception("Something went horribly wrong while attempting to read the ULDAP results");
}
//if(toReturn!=null)
// logger.info("Number of groups returned : "+toReturn.size());
return toReturn;
}
public void finalize()
{
this.closeConnection();
}
public Collection<String> getDepartmentsContaining(String text) throws Exception
{
TreeMap<String,String> groups=new TreeMap<String,String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {"uofsEmployeeDepartmentLong"};
constraints.setReturningAttributes(attrIDs);
constraints.setCountLimit(1000);
NamingEnumeration<SearchResult> results =this.executeSearch("dc=usask,dc=ca","(uofsEmployeeDepartmentLong=*"+text+"*)", constraints);
text = text.toLowerCase();
if(results != null)
{
while (results.hasMore())
{
SearchResult sr = results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
for (Enumeration<?> vals = (Enumeration<?>)attr.getAll(); vals.hasMoreElements(); )
{
Object temp = vals.nextElement();
if(temp!= null && temp instanceof String)
{
String x = (String)temp;
String key = x.toLowerCase();
if(!groups.containsKey(key))
{
if(key.contains(text))
{
groups.put(key,x);
}
}
}
}
}
}
}
results.close();
}
return groups.values();
}
public Collection<String> getGroupsContaining(String text) throws Exception
{
TreeMap<String,String> groups=new TreeMap<String,String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//String[] attrIDs = {"uofsGroupName"};
//constraints.setReturningAttributes(attrIDs);
constraints.setCountLimit(1000);
NamingEnumeration<SearchResult> results =this.executeSearch("ou=groups,dc=usask,dc=ca","(&(objectCLass=groupOfNames)(uofsGroupName=*"+text+"*))", constraints);
text = text.toLowerCase();
if(results != null)
{
while (results.hasMore())
{
SearchResult sr = results.next();
Attributes attrs = sr.getAttributes();
if (attrs != null)
{
for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();)
{
Attribute attr = (Attribute)ae.next();
for (Enumeration<?> vals = (Enumeration<?>)attr.getAll(); vals.hasMoreElements(); )
{
Object temp = vals.nextElement();
if(temp!= null && temp instanceof String)
{
String x = (String)temp;
String key = x.toLowerCase();
// System.out.println("uofsGroupName = "+x);
if(!groups.containsKey(key))
{
if(key.contains(text))
{
groups.put(key,x);
}
}
}
}
}
}
}
results.close();
}
return groups.values();
}
// if you want to get email addresses for users, you can pass in their "group": uid=cfh928,ou=blah,etc
public HashMap<String, List<String>> getUsersAndEmailsInGroups(List<String> userids) throws Exception
{
if (userids.isEmpty()) {
return new HashMap<String, List<String>>();
}
HashMap<String, List<String>> usersAndEmails = new HashMap<String, List<String>>();
SearchControls constraints = new SearchControls();
String[] emailAttr = {"mail"}; // this changed for guest accounts. Everyone has at least one mail attribute, though it may be different from abc123@mail.usask.ca, which is the uofsofficialemailaddress
constraints.setReturningAttributes(emailAttr);
constraints.setCountLimit(500L);
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
StringBuilder builder = new StringBuilder();
builder.append("(&(objectClass=eduPerson)");
builder.append("(|");
for (String userid : userids)
{
builder.append("(uid=");
builder.append(userid);
builder.append(")");
}
builder.append(")"); // close the |
builder.append(")"); // close the &
NamingEnumeration<SearchResult> answer = this.executeSearch("ou=people,dc=usask,dc=ca", builder.toString(), constraints);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMoreElements();) {
Attribute attr = (Attribute) ae.next();
for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements();) {
Object temp = (Object) vals.nextElement(); // just grab the first email address
if (temp instanceof String) {
String value = (String) temp;
String name = sr.getName();
String userid = name.substring(name.indexOf("=")+1, name.indexOf(","));
List<String> existingList = usersAndEmails.get(userid);
if(existingList == null)
{
existingList = new ArrayList<String>();
}
if(!existingList.contains(value))
{
existingList.add(value);
usersAndEmails.put(userid,existingList);
}
}
}
}
}
}
return usersAndEmails;
}
private boolean isNsidType(String s)
{
if(s == null)
return false;
s = s.trim().toLowerCase();
if (s.length() != 6)
return false;
for(int i= 0 ; i < 3; i++)
{
if(s.charAt(i) < 'a' || s.charAt(i) > 'z')
return false;
}
try
{
Integer.parseInt(s.substring(3,6));
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
}
| gpl-3.0 |
Pwn9/PwnFilter | Core/src/main/java/com/pwn9/filter/minecraft/util/ColoredString.java | 12524 | /*
* PwnFilter - Chat and user-input filter with the power of Regex
* Copyright (C) 2016 Pwn9.com / Sage905 <sage905@takeflight.ca>
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package com.pwn9.filter.minecraft.util;
import com.pwn9.filter.engine.api.EnhancedString;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This object is used to provide a mechanism for running regex match and replacements on a string that may
* have Color Codes and formats (eg: &5&k) embedded in it.
* NOTE: By default, this object works on the ampersand (&) character, but this can be specified in the constructor.
* Any valid format code will be removed from the string for matching purposes.
* <p>
* Example String:
* raw:
* The quick &4brown fox &1&kj&2u&3m&4p&5e&6d over&7 the lazy &ldog.
* plain:
* The quick brown fox jumped over the lazy dog
* codes:
* {,,,,,,,,,,&4,,,,,,,,,&1&k,&2,&3,&4,&5,&6,,,,,&7,,,,,,,,,&l,,,}
* <p>
* The codes array maps codes to the character following it. In the example above, plain[10] = 'b', codes[10] = "&4"
* <p>
* In any string modification action, the codes will be updated to reflect the new string.
*
* @author Sage905
* @version $Id: $Id
*/
public final class ColoredString implements EnhancedString {
//todo recreate this class to filter {@link TextComponents}
private final String[] codes; // The String array containing the color / formatting codes
private final char[] plain; // the plain text
private final static String COLOR_CODES = "0123456789AaBbCcDdEeFfKkLlMmNnOoRrx";
private final char CR = '\r';
private final char LF = '\n';
private final static String FORMAT_PREFIXES = "§&";
/**
* <p>Constructor for ColoredString.</p>
*
* @param s a {@link java.lang.String} object.
*/
public ColoredString(String s) {
char[] raw = s.toCharArray();
char[] tmpPlain = new char[raw.length];
String[] tmpCodes = new String[raw.length + 1];
int textpos = 0;
for (int i = 0; i < raw.length; i++) {
if (i != raw.length - 1 && FORMAT_PREFIXES.indexOf(raw[i]) > -1
&& COLOR_CODES.indexOf(raw[i + 1]) > -1) {
if (tmpCodes[textpos] == null) {
tmpCodes[textpos] = new String(raw, i, 2);
} else {
tmpCodes[textpos] += new String(raw, i, 2);
}
i++; // Move past the code character.
} else if (raw[i] == CR || raw[i] == LF) {
tmpCodes[textpos] = new String(raw, i, 1);
// Now insert a tab in its place
tmpPlain[textpos] = ' ';
textpos++;
} else {
tmpPlain[textpos] = raw[i];
textpos++;
}
}
plain = Arrays.copyOf(tmpPlain, textpos);
// Copy one more code than the plain string
// so we can capture any trailing format codes.
codes = Arrays.copyOf(tmpCodes, textpos + 1);
}
/**
* <p>Constructor for ColoredString.</p>
*
* @param plain an array of char.
* @param codes an array of {@link java.lang.String} objects.
*/
private ColoredString(char[] plain, String[] codes) {
this.plain = Arrays.copyOf(plain, plain.length);
this.codes = Arrays.copyOf(codes, plain.length + 1);
}
/* CharSequence methods */
/**
* <p>length.</p>
*
* @return a int.
*/
public int length() {
return plain.length;
}
/**
* {@inheritDoc}
*/
public char charAt(int i) {
return plain[i];
}
/**
* {@inheritDoc}
*/
public CharSequence subSequence(int i, int j) {
return new String(Arrays.copyOfRange(plain, i, j));
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
public String toString() {
return new String(plain);
}
// Return a string with color codes interleaved.
/**
* Reassemble a colord string by inserting codes found in the array before the
* character in that spot. If the code is a CR/LF, discard the temporary
* space character, and replace it with the correct code.
*
* @return a {@link java.lang.String} object.
*/
String getColoredString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < plain.length; i++) {
if (codes[i] != null) {
if (codes[i].indexOf(CR) > -1 || codes[i].indexOf(LF) > -1) {
sb.append(codes[i]);
} else {
sb.append(codes[i]).append(plain[i]);
}
} else {
sb.append(plain[i]);
}
}
// Check to see if there is a code at the end of the text
// If so, append it to the end of the string.
if (codes[codes.length - 1] != null)
sb.append(codes[codes.length - 1]);
return sb.toString();
}
// Return the char array with the code information.
/**
* <p>getCodeArray.</p>
*
* @return an array of {@link java.lang.String} objects.
*/
String[] getCodeArray() {
return codes;
}
/**
* Replace all occurrences of Regex pattern with replacement String.
* If the replacement string has codes embedded, separate them and
* add them to the code array.
* <p>
* This is a tricky bit of code. We will copy the last code before
* a replacement and prepend it to the next code of the current text.
* If the current text is done, we'll prepend the last code at the end
* of the replacement text to the last code of the final string.
* Example:
* Test &1foo
* replace foo with bar:
* Test &1bar
* replace bar with baz&2:
* Test &1baz&2
* replace baz with nothing:
* Test &1&2
*
* @param p Regex Pattern
* @param rText Replacement Text
* @return a {@link ColoredString} object.
*/
@Override
public ColoredString replaceText(Pattern p, String rText) {
Matcher m = p.matcher(new String(plain));
ColoredString replacement = new ColoredString(rText);
// Start with an empty set of arrays. These will be incrementally added
// to, as we replace each match.
char[] lastMatchText = new char[0];
String[] lastMatchCodes = new String[1];
int currentPosition = 0;
while (m.find()) {
int mStart = m.start();
int mEnd = m.end();
int lastMatchTextLength = lastMatchText.length;
int middleLen = mStart - currentPosition;
int newLength = lastMatchTextLength + middleLen + replacement.length();
char[] currentText = new char[newLength];
String[] currentCodes = new String[newLength + 1];
// Copy all of the text up to the end of the last match.
System.arraycopy(lastMatchText, 0, currentText, 0, lastMatchTextLength);
// Copy any text between the end of the last match and the start
// of this match.
System.arraycopy(plain, currentPosition, currentText, lastMatchTextLength, middleLen);
// Append replacement text in place of current text.
System.arraycopy(replacement.plain, 0, currentText, lastMatchTextLength + middleLen, replacement.length());
/*
Now, copy the format codes. If there are "trailing" format codes
from the previous match, prepend them to the codes for the next character.
*/
// First, the codes up to the end of the last match, including any trailing codes.
System.arraycopy(lastMatchCodes, 0, currentCodes, 0, lastMatchTextLength + 1);
// Append the first code to the trailing code.
currentCodes[lastMatchTextLength] = mergeCodes(currentCodes[lastMatchTextLength], codes[currentPosition]);
// Copy the codes from between the last match and this one.
System.arraycopy(codes, currentPosition + 1, currentCodes, lastMatchTextLength + 1, middleLen);
// Append the first replacement code to the trailing code.
currentCodes[lastMatchTextLength + middleLen] = mergeCodes(currentCodes[lastMatchTextLength + middleLen], replacement.codes[0]);
// Copy the codes from the replacement text.
if (replacement.codes.length > 1)
System.arraycopy(replacement.codes, 1, currentCodes, lastMatchTextLength + 1 + middleLen, replacement.length());
currentPosition = mEnd; // Set the position in the original string to the end of the match
lastMatchText = currentText;
lastMatchCodes = currentCodes;
}
char[] tempText = new char[lastMatchText.length + plain.length - currentPosition];
String[] tempCodes = new String[lastMatchText.length + plain.length - currentPosition + 1];
// Copy the text we've processed in previous matches.
System.arraycopy(lastMatchText, 0, tempText, 0, lastMatchText.length);
// ... and copy the formats
System.arraycopy(lastMatchCodes, 0, tempCodes, 0, lastMatchText.length);
// Copy the original text from the end of the last match to the end
// of the string.
System.arraycopy(plain, currentPosition, tempText, lastMatchText.length, plain.length - currentPosition);
// Merge the codes from the end of the last segment and the beginning of this one
tempCodes[lastMatchText.length] = mergeCodes(lastMatchCodes[lastMatchText.length], codes[currentPosition]);
// Copy the remaining codes (not the first one, it was already appended),
// as well as the trailing code.
System.arraycopy(codes, currentPosition + 1, tempCodes, lastMatchText.length + 1, plain.length - currentPosition);
return new ColoredString(tempText, tempCodes);
}
public ColoredString patternToLower(Pattern p) {
char[] modified = plain.clone();
Matcher m = p.matcher(new String(plain));
while (m.find()) {
for (int i = m.start(); i < m.end(); i++) {
modified[i] = Character.toLowerCase(modified[i]);
}
}
return new ColoredString(modified, codes);
}
public ColoredString patternToUpper(Pattern p) {
char[] modified = plain.clone();
Matcher m = p.matcher(new String(plain));
while (m.find()) {
for (int i = m.start(); i < m.end(); i++) {
modified[i] = Character.toUpperCase(modified[i]);
}
}
return new ColoredString(modified, codes);
}
/**
* Returns a concatenation of two strings, a + b. If a or b are null, they
* are converted to an empty string. If both a and b are null, returns null.
*
* @param a First string to concatenate
* @param b Second string to concatenate
* @return Concatenation of a and b, or null if they are both null.
*/
private String mergeCodes(String a, String b) {
String result = (a == null) ? "" : a;
if (b != null) {
result += b;
}
return (result.isEmpty()) ? null : result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ColoredString) {
return ((ColoredString) obj).getColoredString().equals(getColoredString());
} else {
return getColoredString().equals(obj);
}
}
@Override
public String getRaw() {
return getColoredString();
}
}
| gpl-3.0 |
dsudaez/sootp2 | src/main/java/ar/edu/unju/fi/soo/model/dao/VehicleDAO.java | 145 | package ar.edu.unju.fi.soo.model.dao;
import ar.edu.unju.fi.soo.model.Vehicle;
public interface VehicleDAO extends BaseDAO<Vehicle, Long> {
}
| gpl-3.0 |
curiosag/ftc | RSyntaxTextArea/src/main/java/org/fife/ui/rtextarea/ConfigurableCaret.java | 20058 | /*
* 12/21/2004
*
* ConfigurableCaret.java - The caret used by RTextArea.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rtextarea;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.folding.FoldManager;
/**
* The caret used by {@link RTextArea}. This caret has all of the properties
* that <code>javax.swing.text.DefaultCaret</code> does, as well as adding the
* following niceties:
*
* <ul>
* <li>This caret can render itself many different ways; see the
* {@link #setStyle(CaretStyle)} method and {@link CaretStyle} for
* more information.</li>
* <li>On Microsoft Windows and other operating systems that do not
* support system selection (i.e., selecting text, then pasting
* via the middle mouse button), clicking the middle mouse button
* will cause a regular paste operation to occur. On systems
* that support system selection (i.e., all UNIX variants),
* the middle mouse button will behave normally.</li>
* </ul>
*
* @author Robert Futrell
* @version 0.6
*/
public class ConfigurableCaret extends DefaultCaret {
/**
* Action used to select a word on a double click.
*/
static private transient Action selectWord = null;
/**
* Action used to select a line on a triple click.
*/
static private transient Action selectLine = null;
/**
* holds last MouseEvent which caused the word selection
*/
private transient MouseEvent selectedWordEvent = null;
/**
* Used for fastest-possible retrieval of the character at the
* caret's position in the document.
*/
private transient Segment seg;
/**
* Whether the caret is a vertical line, a horizontal line, or a block.
*/
private CaretStyle style;
/**
* The selection painter. By default this paints selections with the
* text area's selection color.
*/
private ChangeableHighlightPainter selectionPainter;
private boolean alwaysVisible;
/**
* Creates the caret using {@link CaretStyle#THICK_VERTICAL_LINE_STYLE}.
*/
public ConfigurableCaret() {
this(CaretStyle.THICK_VERTICAL_LINE_STYLE);
}
/**
* Constructs a new <code>ConfigurableCaret</code>.
*
* @param style The style to use when painting the caret. If this is
* invalid, then {@link CaretStyle#THICK_VERTICAL_LINE_STYLE} is
* used.
*/
public ConfigurableCaret(CaretStyle style) {
seg = new Segment();
setStyle(style);
selectionPainter = new ChangeableHighlightPainter();
}
/**
* Adjusts the caret location based on the MouseEvent.
*/
private void adjustCaret(MouseEvent e) {
if ((e.getModifiers()&ActionEvent.SHIFT_MASK)!=0 && getDot()!=-1)
moveCaret(e);
else
positionCaret(e);
}
/**
* Adjusts the focus, if necessary.
*
* @param inWindow if true indicates requestFocusInWindow should be used
*/
private void adjustFocus(boolean inWindow) {
RTextArea textArea = getTextArea();
if ((textArea != null) && textArea.isEnabled() &&
textArea.isRequestFocusEnabled()) {
if (inWindow)
textArea.requestFocusInWindow();
else
textArea.requestFocus();
}
}
/**
* Overridden to damage the correct width of the caret, since this caret
* can be different sizes.
*
* @param r The current location of the caret.
*/
@Override
protected synchronized void damage(Rectangle r) {
if (r != null) {
validateWidth(r); // Check for "0" or "1" caret width
x = r.x - 1;
y = r.y;
width = r.width + 4;
height = r.height;
repaint();
}
}
/**
* Called when the UI is being removed from the
* interface of a JTextComponent. This is used to
* unregister any listeners that were attached.
*
* @param c The text component. If this is not an
* <code>RTextArea</code>, an <code>Exception</code>
* will be thrown.
* @see Caret#deinstall
*/
@Override
public void deinstall(JTextComponent c) {
if (!(c instanceof RTextArea))
throw new IllegalArgumentException(
"c must be instance of RTextArea");
super.deinstall(c);
c.setNavigationFilter(null);
}
/**
* Gets the text editor component that this caret is bound to.
*
* @return The <code>RTextArea</code>.
*/
protected RTextArea getTextArea() {
return (RTextArea)getComponent();
}
/**
* Returns whether this caret's selection uses rounded edges.
*
* @return Whether this caret's edges are rounded.
* @see #setRoundedSelectionEdges
*/
public boolean getRoundedSelectionEdges() {
return ((ChangeableHighlightPainter)getSelectionPainter()).
getRoundedEdges();
}
/**
* Gets the painter for the Highlighter. This is overridden to return
* our custom selection painter.
*
* @return The painter.
*/
@Override
protected Highlighter.HighlightPainter getSelectionPainter() {
return selectionPainter;
}
/**
* Gets the current style of this caret.
*
* @return The caret's style.
* @see #setStyle(CaretStyle)
*/
public CaretStyle getStyle() {
return style;
}
/**
* Installs this caret on a text component.
*
* @param c The text component. If this is not an {@link RTextArea},
* an <code>Exception</code> will be thrown.
* @see Caret#install
*/
@Override
public void install(JTextComponent c) {
if (!(c instanceof RTextArea))
throw new IllegalArgumentException(
"c must be instance of RTextArea");
super.install(c);
c.setNavigationFilter(new FoldAwareNavigationFilter());
}
/**
* Returns whether this caret is always visible (as opposed to
* blinking, or not visible when the editor's window is not focused).
* This can be used by popup windows that want the caret's location
* to still be visible for contextual purposes while they are displayed.
*
* @return Whether this caret is always visible.
* @see #setAlwaysVisible(boolean)
*/
public boolean isAlwaysVisible() {
return alwaysVisible;
}
/**
* Called when the mouse is clicked. If the click was generated from
* button1, a double click selects a word, and a triple click the
* current line.
*
* @param e the mouse event
* @see MouseListener#mouseClicked
*/
@Override
public void mouseClicked(MouseEvent e) {
if (! e.isConsumed()) {
RTextArea textArea = getTextArea();
int nclicks = e.getClickCount();
if (SwingUtilities.isLeftMouseButton(e)) {
if (nclicks>2) {
nclicks %= 2; // Alternate selecting word/line.
switch (nclicks) {
case 0:
selectWord(e);
selectedWordEvent = null;
break;
case 1:
Action a = null;
ActionMap map = textArea.getActionMap();
if (map != null)
a = map.get(RTextAreaEditorKit.selectLineAction);
if (a == null) {
if (selectLine == null) {
selectLine = new RTextAreaEditorKit.SelectLineAction();
}
a = selectLine;
}
a.actionPerformed(new ActionEvent(textArea,
ActionEvent.ACTION_PERFORMED,
null, e.getWhen(), e.getModifiers()));
}
}
}
else if (SwingUtilities.isMiddleMouseButton(e)) {
if (nclicks == 1 && textArea.isEditable() && textArea.isEnabled()) {
// Paste the system selection, if it exists (e.g., on UNIX
// platforms, the user can select text, the middle-mouse click
// to paste it; this doesn't work on Windows). If the system
// doesn't support system selection, just do a normal paste.
JTextComponent c = (JTextComponent) e.getSource();
if (c != null) {
try {
Toolkit tk = c.getToolkit();
Clipboard buffer = tk.getSystemSelection();
// If the system supports system selections, (e.g. UNIX),
// try to do it.
if (buffer != null) {
adjustCaret(e);
TransferHandler th = c.getTransferHandler();
if (th != null) {
Transferable trans = buffer.getContents(null);
if (trans != null)
th.importData(c, trans);
}
adjustFocus(true);
}
// If the system doesn't support system selections
// (e.g. Windows), just do a normal paste.
else {
textArea.paste();
}
} catch (HeadlessException he) {
// do nothing... there is no system clipboard
}
} // if (c!=null)
} // if (nclicks == 1 && component.isEditable() && component.isEnabled())
} // else if (SwingUtilities.isMiddleMouseButton(e))
} // if (!c.isConsumed())
}
/**
* Overridden to also focus the text component on right mouse clicks.
*
* @param e The mouse event.
*/
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if (!e.isConsumed() && SwingUtilities.isRightMouseButton(e)) {
JTextComponent c = getComponent();
if (c!=null && c.isEnabled() && c.isRequestFocusEnabled()) {
c.requestFocusInWindow();
}
}
}
/**
* Paints the cursor.
*
* @param g The graphics context in which to paint.
*/
@Override
public void paint(Graphics g) {
// If the cursor is currently visible...
if (isVisible() || alwaysVisible) {
try {
RTextArea textArea = getTextArea();
g.setColor(textArea.getCaretColor());
TextUI mapper = textArea.getUI();
Rectangle r = mapper.modelToView(textArea, getDot());
// "Correct" the value of rect.width (takes into
// account caret being at EOL (and thus rect.width==1),
// etc.
// We do this even for LINE_STYLE because
// if they change from that caret to block/underline,
// the first time they do so width==1, so it will take
// one caret flash to paint correctly (wider). If we
// do this every time, then it's painted correctly the
// first blink.
validateWidth(r);
// This condition is most commonly hit when code folding is
// enabled and the user collapses a fold above the caret
// position. If our cached x/y/w/h aren't updated, this caret
// appears to stop blinking because the wrong line range gets
// damaged. This check keeps us in sync.
if (width>0 && height>0 &&
!contains(r.x, r.y, r.width, r.height)) {
Rectangle clip = g.getClipBounds();
if (clip != null && !clip.contains(this)) {
// Clip doesn't contain the old location, force it
// to be repainted lest we leave a caret around.
repaint();
}
// This will potentially cause a repaint of something
// we're already repainting, but without changing the
// semantics of damage we can't really get around this.
damage(r);
}
// Need to subtract 2 from height, otherwise
// the caret will expand too far vertically.
r.height -= 2;
switch (style) {
// Draw a big rectangle, and xor the foreground color.
case BLOCK_STYLE:
Color textAreaBg = textArea.getBackground();
if (textAreaBg==null) {
textAreaBg = Color.white;
}
g.setXORMode(textAreaBg);
// fills x==r.x to x==(r.x+(r.width)-1), inclusive.
g.fillRect(r.x,r.y, r.width,r.height);
break;
// Draw a rectangular border.
case BLOCK_BORDER_STYLE:
// fills x==r.x to x==(r.x+(r.width-1)), inclusive.
g.drawRect(r.x,r.y, r.width-1,r.height);
break;
// Draw an "underline" below the current position.
case UNDERLINE_STYLE:
textAreaBg = textArea.getBackground();
if (textAreaBg==null) {
textAreaBg = Color.white;
}
g.setXORMode(textAreaBg);
int y = r.y + r.height;
g.drawLine(r.x,y, r.x+r.width-1,y);
break;
// Draw a vertical line.
default:
case VERTICAL_LINE_STYLE:
g.drawLine(r.x,r.y, r.x,r.y+r.height);
break;
// A thicker vertical line.
case THICK_VERTICAL_LINE_STYLE:
g.drawLine(r.x,r.y, r.x,r.y+r.height);
r.x++;
g.drawLine(r.x,r.y, r.x,r.y+r.height);
break;
} // End of switch (style).
} catch (BadLocationException ble) {
ble.printStackTrace();
}
} // End of if (isVisible()).
}
/**
* Selects word based on the MouseEvent
*/
private void selectWord(MouseEvent e) {
if (selectedWordEvent != null
&& selectedWordEvent.getX() == e.getX()
&& selectedWordEvent.getY() == e.getY()) {
// We've already the done selection for this.
return;
}
Action a = null;
RTextArea textArea = getTextArea();
ActionMap map = textArea.getActionMap();
if (map != null) {
a = map.get(RTextAreaEditorKit.selectWordAction);
}
if (a == null) {
if (selectWord == null) {
selectWord = new RTextAreaEditorKit.SelectWordAction();
}
a = selectWord;
}
a.actionPerformed(new ActionEvent(textArea,
ActionEvent.ACTION_PERFORMED,
null, e.getWhen(), e.getModifiers()));
selectedWordEvent = e;
}
/**
* Toggles whether this caret should always be visible (as opposed to
* blinking, or not visible when the editor's window is not focused).
* This can be used by popup windows that want the caret's location
* to still be visible for contextual purposes while they are displayed.
*
* @param alwaysVisible Whether this caret should always be visible.
* @see #isAlwaysVisible()
*/
public void setAlwaysVisible(boolean alwaysVisible) {
if (alwaysVisible != this.alwaysVisible) {
this.alwaysVisible = alwaysVisible;
if (!isVisible()) {
// Force painting of caret since super class's "flasher" timer
// won't fire when the window doesn't have focus
repaint();
}
}
}
/**
* Sets whether this caret's selection should have rounded edges.
*
* @param rounded Whether it should have rounded edges.
* @see #getRoundedSelectionEdges()
*/
public void setRoundedSelectionEdges(boolean rounded) {
((ChangeableHighlightPainter)getSelectionPainter()).
setRoundedEdges(rounded);
}
/**
* Overridden to always render the selection, even when the text component
* loses focus.
*
* @param visible Whether the selection should be visible. This parameter
* is ignored.
*/
@Override
public void setSelectionVisible(boolean visible) {
super.setSelectionVisible(true);
}
/**
* Sets the style used when painting the caret.
*
* @param style The style to use. This should not be <code>null</code>.
* @see #getStyle()
*/
public void setStyle(CaretStyle style) {
if (style==null) {
style = CaretStyle.THICK_VERTICAL_LINE_STYLE;
}
if (style!=this.style) {
this.style = style;
repaint();
}
}
/**
* Helper function used by the block and underline carets to ensure the
* width of the painted caret is valid. This is done for the following
* reasons:
*
* <ul>
* <li>The <code>View</code> classes in the javax.swing.text package
* always return a width of "1" when <code>modelToView</code> is
* called. We'll be needing the actual width.</li>
* <li>Even in smart views, such as <code>RSyntaxTextArea</code>'s
* <code>SyntaxView</code> and <code>WrappedSyntaxView</code> that
* return the width of the current character, if the caret is at the
* end of a line for example, the width returned from
* <code>modelToView</code> will be 0 (as the width of unprintable
* characters such as '\n' is calculated as 0). In this case, we'll
* use a default width value.</li>
* </ul>
*
* @param rect The rectangle returned by the current
* <code>View</code>'s <code>modelToView</code>
* method for the caret position.
*/
private void validateWidth(Rectangle rect) {
// If the width value > 1, we assume the View is
// a "smart" view that returned the proper width.
// So only worry about this stuff if width <= 1.
if (rect!=null && rect.width<=1) {
// The width is either 1 (most likely, we're using a "dumb" view
// like those in javax.swing.text) or 0 (most likely, we're using
// a "smart" view like org.fife.ui.rsyntaxtextarea.SyntaxView,
// we're at the end of a line, and the width of '\n' is being
// computed as 0).
try {
// Try to get a width for the character at the caret
// position. We use the text area's font instead of g's
// because g's may vary in an RSyntaxTextArea.
RTextArea textArea = getTextArea();
textArea.getDocument().getText(getDot(),1, seg);
Font font = textArea.getFont();
FontMetrics fm = textArea.getFontMetrics(font);
rect.width = fm.charWidth(seg.array[seg.offset]);
// This width being returned 0 likely means that it is an
// unprintable character (which is almost 100% to be a
// newline char, i.e., we're at the end of a line). So,
// just use the width of a space.
if (rect.width==0) {
rect.width = fm.charWidth(' ');
}
} catch (BadLocationException ble) {
// This shouldn't ever happen.
ble.printStackTrace();
rect.width = 8;
}
} // End of if (rect!=null && rect.width<=1).
}
/**
* Keeps the caret out of folded regions in edge cases where it doesn't
* happen automatically, for example, when the caret moves automatically in
* response to Document.insert() and Document.remove() calls. Most keyboard
* shortcuts already take folding into account, as do viewToModel() and
* modelToView(), so this filter usually does not do anything.<p>
*
* Common cases: backspacing to visible line of collapsed region.
*/
private class FoldAwareNavigationFilter extends NavigationFilter {
@Override
public void setDot(FilterBypass fb, int dot, Position.Bias bias) {
RTextArea textArea = getTextArea();
if (textArea instanceof RSyntaxTextArea) {
RSyntaxTextArea rsta = (RSyntaxTextArea)getTextArea();
if (rsta.isCodeFoldingEnabled()) {
int lastDot = getDot();
FoldManager fm = rsta.getFoldManager();
int line = 0;
try {
line = textArea.getLineOfOffset(dot);
} catch (Exception e) {
e.printStackTrace();
}
if (fm.isLineHidden(line)) {
//System.out.println("filterBypass: avoiding hidden line");
try {
if (dot>lastDot) { // Moving to further line
int lineCount = textArea.getLineCount();
while (++line<lineCount &&
fm.isLineHidden(line));
if (line<lineCount) {
dot = textArea.getLineStartOffset(line);
}
else { // No lower lines visible
UIManager.getLookAndFeel().
provideErrorFeedback(textArea);
return;
}
}
else if (dot<lastDot) { // Moving to earlier line
while (--line>=0 && fm.isLineHidden(line));
if (line>=0) {
dot = textArea.getLineEndOffset(line) - 1;
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
super.setDot(fb, dot, bias);
}
@Override
public void moveDot(FilterBypass fb, int dot, Position.Bias bias) {
super.moveDot(fb, dot, bias);
}
}
} | gpl-3.0 |
apruden/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/keystore/presenter/commands/ImportKeyPairCommand.java | 2571 | /*
* Copyright (c) 2013 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.keystore.presenter.commands;
import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory;
import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback;
import org.obiba.opal.web.model.client.opal.KeyForm;
import org.obiba.opal.web.model.client.opal.KeyType;
import edu.umd.cs.findbugs.annotations.Nullable;
import static com.google.gwt.http.client.Response.SC_BAD_REQUEST;
import static com.google.gwt.http.client.Response.SC_CREATED;
import static com.google.gwt.http.client.Response.SC_INTERNAL_SERVER_ERROR;
import static com.google.gwt.http.client.Response.SC_OK;
public class ImportKeyPairCommand extends AbstractKeystoreCommand {
private String publicKey;
private String privateKey;
private KeyType keyType;
@Override
public void execute(@Nullable ResponseCodeCallback success, @Nullable ResponseCodeCallback failure) {
KeyForm keyForm = KeyForm.create();
keyForm.setAlias(alias);
keyForm.setKeyType(keyType);
keyForm.setPrivateImport(privateKey);
keyForm.setPublicImport(publicKey);
if(update) {
ResourceRequestBuilderFactory.newBuilder() //
.forResource(url) //
.withResourceBody(KeyForm.stringify(keyForm)) //
.withCallback(SC_OK, success).withCallback(failure, SC_BAD_REQUEST, SC_INTERNAL_SERVER_ERROR).put().send();
} else {
ResourceRequestBuilderFactory.newBuilder() //
.forResource(url) //
.withResourceBody(KeyForm.stringify(keyForm)) //
.withCallback(SC_CREATED, success).withCallback(failure, SC_BAD_REQUEST, SC_INTERNAL_SERVER_ERROR).post()
.send();
}
}
public static class Builder extends AbstractKeystoreCommand.Builder<Builder, ImportKeyPairCommand> {
private Builder() {
command = new ImportKeyPairCommand();
}
public static Builder newBuilder() {
return new Builder();
}
public Builder setPublicKey(String value) {
command.publicKey = value;
return this;
}
public Builder setKeyType(KeyType value) {
command.keyType = value;
return this;
}
public Builder setPrivateKey(String value) {
command.privateKey = value;
return this;
}
}
}
| gpl-3.0 |
pdudits/supergenpass-android | src/edu/mit/mobile/android/utils/ProviderUtils.java | 2033 | package edu.mit.mobile.android.utils;
/*
* Copyright (C) 2010-2011 MIT Mobile Experience Lab
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.text.TextUtils;
public class ProviderUtils {
/**
* Adds extra where clauses
* @param where
* @param extraWhere
* @return
*/
public static String addExtraWhere(String where, String ... extraWhere){
final String extraWhereJoined = "(" + TextUtils.join(") AND (", Arrays.asList(extraWhere))
+ ")";
return extraWhereJoined + (where != null && where.length() > 0 ? " AND ("+where+")":"");
}
/**
* Adds in extra arguments to a where query. You'll have to put in the appropriate
* @param whereArgs the original whereArgs passed in from the query. Can be null.
* @param extraArgs Extra arguments needed for the query.
* @return
*/
public static String[] addExtraWhereArgs(String[] whereArgs, String...extraArgs){
final List<String> whereArgs2 = new ArrayList<String>();
if (whereArgs != null){
whereArgs2.addAll(Arrays.asList(whereArgs));
}
whereArgs2.addAll(0, Arrays.asList(extraArgs));
return whereArgs2.toArray(new String[]{});
}
}
| gpl-3.0 |
aginsun/The-Betweenlands-Reboot | betweenlands/items/SwampTalisman.java | 1586 | package betweenlands.items;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import betweenlands.entities.mobs.EntityDarkDruid;
import betweenlands.lib.ModInfo;
import betweenlands.lib.Names;
public class SwampTalisman extends Item {
public SwampTalisman(int id) {
super(id);
this.setCreativeTab(CreativeTabs.tabMisc);
this.setUnlocalizedName(Names.swampTalisman_unlocalizedName);
this.setMaxStackSize(64);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister icon) {
itemIcon = icon.registerIcon(ModInfo.ID.toLowerCase() + ":" + Names.swampTalisman_unlocalizedName);
}
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player)
{
/*
Entity entity = EntityList.createEntityByName("entity.instance.darkDruid.name", world);
world.spawnEntityInWorld(entity);
entity.setPosition(player.posX, player.posY, player.posZ);
*/
/*EntityDarkDruid entitychicken = new EntityDarkDruid(world);
entitychicken.setPosition(player.posX, player.posY, player.posZ);
world.spawnEntityInWorld(entitychicken); */
return itemstack;
}
}
| gpl-3.0 |
meek0/mica2 | mica-search/src/main/java/org/obiba/mica/taxonomy/TaxonomyIndexer.java | 4413 | /*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.mica.taxonomy;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.obiba.mica.micaConfig.event.OpalTaxonomiesUpdatedEvent;
import org.obiba.mica.micaConfig.event.TaxonomiesUpdatedEvent;
import org.obiba.mica.micaConfig.service.TaxonomyService;
import org.obiba.mica.spi.search.Indexer;
import org.obiba.mica.spi.search.TaxonomyTarget;
import org.obiba.opal.core.domain.taxonomy.Taxonomy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class TaxonomyIndexer {
private static final Logger log = LoggerFactory.getLogger(TaxonomyIndexer.class);
@Inject
private TaxonomyService taxonomyService;
@Inject
private Indexer indexer;
@Async
@Subscribe
public void opalTaxonomiesUpdatedEvent(OpalTaxonomiesUpdatedEvent event) {
log.info("Reindex all opal taxonomies");
index(
TaxonomyTarget.VARIABLE,
event.extractOpalTaxonomies()
.stream()
.filter(t -> taxonomyService.metaTaxonomyContains(t.getName()))
.collect(Collectors.toList()));
}
@Async
@Subscribe
public void taxonomiesUpdated(TaxonomiesUpdatedEvent event) {
// reindex all taxonomies if target is TAXONOMY or there is no target
if ((event.getTaxonomyTarget() == null && event.getTaxonomyName() == null) || event.getTaxonomyTarget() == TaxonomyTarget.TAXONOMY) {
log.info("All taxonomies were updated");
if(indexer.hasIndex(Indexer.TAXONOMY_INDEX)) indexer.dropIndex(Indexer.TAXONOMY_INDEX);
index(TaxonomyTarget.VARIABLE,
ImmutableList.<Taxonomy>builder().addAll(taxonomyService.getOpalTaxonomies().stream() //
.filter(t -> taxonomyService.metaTaxonomyContains(t.getName())).collect(Collectors.toList())) //
.add(taxonomyService.getVariableTaxonomy()) //
.build());
index(TaxonomyTarget.STUDY, Lists.newArrayList(taxonomyService.getStudyTaxonomy()));
index(TaxonomyTarget.DATASET, Lists.newArrayList(taxonomyService.getDatasetTaxonomy()));
index(TaxonomyTarget.NETWORK, Lists.newArrayList(taxonomyService.getNetworkTaxonomy()));
} else {
Map.Entry<String, String> termQuery = ImmutablePair.of("taxonomyName", event.getTaxonomyName());
indexer.delete(Indexer.TAXONOMY_INDEX, new String[] {Indexer.TAXONOMY_TYPE, Indexer.TAXONOMY_VOCABULARY_TYPE, Indexer.TAXONOMY_TERM_TYPE}, termQuery);
switch (event.getTaxonomyTarget()) {
case STUDY:
log.info("Study taxonomies were updated");
index(TaxonomyTarget.STUDY, Lists.newArrayList(taxonomyService.getStudyTaxonomy()));
break;
case NETWORK:
log.info("Network taxonomies were updated");
index(TaxonomyTarget.NETWORK, Lists.newArrayList(taxonomyService.getNetworkTaxonomy()));
break;
case DATASET:
log.info("Dataset taxonomies were updated");
index(TaxonomyTarget.DATASET, Lists.newArrayList(taxonomyService.getDatasetTaxonomy()));
break;
case VARIABLE:
log.info("Variable taxonomies were updated");
index(TaxonomyTarget.VARIABLE, Lists.newArrayList(taxonomyService.getVariableTaxonomy()));
break;
}
}
}
private void index(TaxonomyTarget target, List<Taxonomy> taxonomies) {
taxonomies.forEach(taxo -> {
indexer.index(Indexer.TAXONOMY_INDEX, new TaxonomyIndexable(target, taxo));
if(taxo.hasVocabularies()) taxo.getVocabularies().forEach(voc -> {
indexer.index(Indexer.TAXONOMY_INDEX, new TaxonomyVocabularyIndexable(target, taxo, voc));
if(voc.hasTerms()) voc.getTerms().forEach(
term -> indexer.index(Indexer.TAXONOMY_INDEX, new TaxonomyTermIndexable(target, taxo, voc, term)));
});
});
}
}
| gpl-3.0 |
OOP-Team-11/RoadsAndBoats | src/main/game/view/NavigationBar.java | 5205 | package game.view;
import game.view.utilities.Assets;
import javafx.scene.canvas.Canvas;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
public class NavigationBar {
private AnchorPane anchorPane;
private ViewHandler viewHandler;
private ImageView mainViewButton;
private ImageView transportViewButton;
private ImageView researchViewButton;
private ImageView wonderViewButton;
private ImageView saveLoadButton;
private ImageView optionsViewButton;
private Assets assets;
private Canvas canvas;
public NavigationBar(ViewHandler viewHandler){
setViewHandler(viewHandler);
initializeAnchorPane();
loadAssets();
setupNavigationBar();
setUpEventHandlers();
}
private void setViewHandler(ViewHandler viewHandler){
this.viewHandler = viewHandler;
}
private void initializeAnchorPane(){
this.anchorPane = new AnchorPane();
}
private void loadAssets(){
this.assets = Assets.getInstance();
}
public AnchorPane getAnchorPaneReference(){
return this.anchorPane;
}
private void setUpEventHandlers(){
// jump to main View
this.mainViewButton.setOnMouseClicked(event ->{
viewHandler.jumpToMainView();
});
// jump to transportView
this.transportViewButton.setOnMouseClicked(event ->{
viewHandler.jumpToTransportView();
});
// jump to research view
this.researchViewButton.setOnMouseClicked(event ->{
viewHandler.jumpToResearchView();
});
// jump to model.wonder view
this.wonderViewButton.setOnMouseClicked( event ->{
viewHandler.jumptToWonderView();
});
// jump to saveLoad view
this.saveLoadButton.setOnMouseClicked(event ->{
viewHandler.jumpToSaveLoadView();
});
// jump to transport view
this.transportViewButton.setOnMouseClicked(event ->{
viewHandler.jumpToTransportView();
});
// jump to options view
this.optionsViewButton.setOnMouseClicked(event ->{
viewHandler.jumpToOptionsView();
});
}
private void setupNavigationBar(){
this.mainViewButton = new ImageView();
this.transportViewButton = new ImageView();
this.researchViewButton = new ImageView();
this.wonderViewButton = new ImageView();
this.saveLoadButton = new ImageView();
this.optionsViewButton = new ImageView();
this.canvas = new Canvas(80,800);
this.canvas.getGraphicsContext2D().setFill(Color.TEAL);
this.canvas.getGraphicsContext2D().fillRect(0,0,80,800);
// TODO replace images, make them look like icons or something
this.mainViewButton.setImage(assets.NAVIGATION_BAR_1);
this.transportViewButton.setImage(assets.NAVIGATION_BAR_2);
this.researchViewButton.setImage(assets.NAVIGATION_BAR_3);
this.wonderViewButton.setImage(assets.NAVIGATION_BAR_4);
this.saveLoadButton.setImage(assets.NAVIGATION_BAR_5);
this.optionsViewButton.setImage(assets.NAVIGATION_BAR_6);
this.mainViewButton.setFitHeight(55);
this.mainViewButton.setFitWidth(55);
this.transportViewButton.setFitWidth(55);
this.transportViewButton.setFitHeight(55);
this.researchViewButton.setFitHeight(55);
this.researchViewButton.setFitWidth(55);
this.wonderViewButton.setFitHeight(55);
this.wonderViewButton.setFitWidth(55);
this.saveLoadButton.setFitHeight(55);
this.saveLoadButton.setFitWidth(55);
this.optionsViewButton.setFitWidth(55);
this.optionsViewButton.setFitHeight(55);
this.anchorPane.setPrefWidth(80);
this.anchorPane.setMaxWidth(80);
this.anchorPane.setMinWidth(80);
this.anchorPane.setPrefHeight(800);
this.anchorPane.setMaxHeight(800);
this.anchorPane.getChildren().add(canvas);
this.anchorPane.getChildren().add(mainViewButton);
this.anchorPane.setTopAnchor(mainViewButton,50.0);
this.anchorPane.setLeftAnchor(mainViewButton,12.5);
this.anchorPane.getChildren().add(transportViewButton);
this.anchorPane.setTopAnchor(transportViewButton,175.0);
this.anchorPane.setLeftAnchor(transportViewButton,15.0);
this.anchorPane.getChildren().add(researchViewButton);
this.anchorPane.setTopAnchor(researchViewButton,300.0);
this.anchorPane.setLeftAnchor(researchViewButton,12.5);
this.anchorPane.getChildren().add(wonderViewButton);
this.anchorPane.setTopAnchor(wonderViewButton,425.0);
this.anchorPane.setLeftAnchor(wonderViewButton,12.5);
this.anchorPane.getChildren().add(saveLoadButton);
this.anchorPane.setTopAnchor(saveLoadButton,550.0);
this.anchorPane.setLeftAnchor(saveLoadButton,12.5);
this.anchorPane.getChildren().add(optionsViewButton);
this.anchorPane.setTopAnchor(optionsViewButton,675.0);
this.anchorPane.setLeftAnchor(optionsViewButton, 12.5);
}
}
| gpl-3.0 |
TUD-IfC/WebGen-WPS | src/ch/unizh/geo/webgen/client/jump/KnowledgeBaseVisualisationPanel.java | 4722 | package ch.unizh.geo.webgen.client.jump;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import ch.unizh.geo.webgen.model.Constraint;
import com.vividsolutions.jump.feature.Feature;
public class KnowledgeBaseVisualisationPanel extends JPanel {
static final long serialVersionUID = 12345;
List fclist;
String[] names = {"Min Size","Edge Length","Min Dist","Local Width","Diff Pos","Diff EdgeCount","Diff WidthLen","Diff Orientation"};
//Color[] colors = {Color.CYAN, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.WHITE, Color.YELLOW};
double[] average;
public Line2D[][] lines;
//public int selectedpos = -1;
public ArrayList<Integer> selectedposs = new ArrayList<Integer>();
public int actstate = 0;
public int laststate = 0;
public KnowledgeBaseVisualisationPanel(double constraintOperatorPriority[][][][]) {
super();
// this.fclist = fclist;
//laststate = ((Constraint)((Feature)fclist.get(0)).getAttribute("constraint")).getHistorySize()-1;
//actstate = laststate;
this.setBackground(Color.BLACK);
//lines = new Line2D[fclist.size()][7];
//this.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setBackground(Color.WHITE);
g2d.setPaint(Color.YELLOW);
//g2d.setPaint(Color.BLACK);
int xpos, ywpos;
for(int i=1; i<=8; i++) {
xpos = (i*100)-60;
g2d.drawString(names[i-1], xpos-5, 40);
g2d.drawLine(xpos,50,xpos,450);
for(int j=0; j<=10; j++) {
ywpos = (j*40)+50;
g2d.drawLine(xpos-2,ywpos,xpos+2,ywpos);
}
}
g2d.drawString("1.0", 18, 53);
g2d.drawString("0.5", 18, 253);
g2d.drawString("0.0", 18, 453);
//draw history navigation
g2d.setPaint(Color.WHITE);
g2d.drawString("State: ", 325, 480);
g2d.drawRect(370, 470, 12, 12);
g2d.drawString("-", 375, 480);
g2d.drawString(actstate+"", 400, 480);
g2d.drawRect(420, 470, 12, 12);
g2d.drawString("+", 423, 480);
//draw values:
average = new double[8];
int xposA, xposB, yposA, yposB;
double[] tvalues;
String tmessage = "";
g2d.setStroke(new BasicStroke(1));
for(int i=0; i<fclist.size(); i++) {
Constraint wgc = (Constraint)((Feature)fclist.get(i)).getAttribute("constraint");
//tvalues = wgc.getHistoryLast();
tvalues = wgc.getStateFromHistory(actstate);
tmessage = wgc.getStateMessageFromHistory(actstate);
//if(selectedpos == i) g2d.setStroke(new BasicStroke(4));
if(selectedposs.contains(new Integer(i))) g2d.setStroke(new BasicStroke(4));
g2d.setPaint(new Color(((int)(Math.random()*100)+150),((int)(Math.random()*100)+150),((int)(Math.random()*100)+150)));
for(int j=0; j<tvalues.length-1; j++) {
xposA = ((j+1)*100)-60;
yposA = 450 - ((int)(tvalues[j]*400));
xposB = ((j+2)*100)-60;
yposB = 450 - ((int)(tvalues[j+1]*400));
lines[i][j] = new Line2D.Double(xposA,yposA,xposB,yposB);;
g2d.draw(lines[i][j]);
//g2d.drawLine(xposA,yposA,xposB,yposB);
average[j] += tvalues[j];
}
average[tvalues.length-1] += tvalues[tvalues.length-1];
//if(selectedpos == i) g2d.setStroke(new BasicStroke(1));
g2d.setStroke(new BasicStroke(1));
}
//display wgc message
g2d.drawString(tmessage, 450, 480);
//display average
g2d.setPaint(Color.RED);
g2d.setStroke(new BasicStroke(4));
average[0] = average[0] / fclist.size();
for(int i=0; i<average.length-1; i++) {
average[i+1] = average[i+1] / fclist.size();
xposA = ((i+1)*100)-60;
yposA = 450 - ((int)(average[i]*400));
xposB = ((i+2)*100)-60;
yposB = 450 - ((int)(average[i+1]*400));
g2d.drawLine(xposA,yposA,xposB,yposB);
}
//System.out.println("drawing finished!");
}
// super.paintComponent clears offscreen pixmap,
// since we're using double buffering by default.
protected void clear(Graphics g) {
super.paintComponent(g);
}
// for saving image as png
public RenderedImage getImage() {
BufferedImage total = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D gi = total.createGraphics();
this.paintComponent(gi);
return total;
}
}
| gpl-3.0 |
PSilling/rh-massages | dropwizard-api/src/main/java/cz/redhat/resources/ClientResource.java | 7886 | /*
Copyright (C) 2017 Petr Silling
<p>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 3 of the
License, or (at your option) any later version.
<p>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.
<p>You should have received a copy of the GNU General Public License along with this program. If
not, see <http://www.gnu.org/licenses/>.
*/
package cz.redhat.resources;
import cz.redhat.auth.User;
import cz.redhat.configuration.MailClient;
import cz.redhat.core.Client;
import cz.redhat.core.Massage;
import cz.redhat.db.ClientDao;
import cz.redhat.db.MassageDao;
import cz.redhat.websockets.OperationType;
import cz.redhat.websockets.WebSocketResource;
import io.dropwizard.auth.Auth;
import io.dropwizard.hibernate.UnitOfWork;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Client resource class.
*
* @author psilling
* @since 1.2.1
*/
@Path("/clients")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ClientResource {
private final MassageDao massageDao; // Massage data access object
private final ClientDao clientDao; // Client data access object
private final MailClient mailClient; // Mailing client
/**
* Constructor.
*
* @param massageDao {@link MassageDao} to work with
* @param clientDao {@link ClientDao} to work with
* @param mailClient {@link MailClient} to use for messaging
*/
public ClientResource(MassageDao massageDao, ClientDao clientDao, MailClient mailClient) {
this.massageDao = massageDao;
this.clientDao = clientDao;
this.mailClient = mailClient;
}
/**
* GETs all {@link Client}s that can be found.
*
* @return {@link List} of all {@link Client}s
*/
@GET
@PermitAll
@UnitOfWork
public List<Client> fetch() {
return clientDao.findAll();
}
/**
* GETs all {@link Client}s that are registered as masseurs.
*
* @return {@link List} of all masseur {@link Client}s
*/
@GET
@Path("/masseuses")
@PermitAll
@UnitOfWork
public List<Client> getMasseurs() {
return clientDao.findAllMasseurs();
}
/**
* GETs all {@link Client}s that are registered as normal users (non-masseurs).
*
* @return {@link List} of all non-masseur {@link Client}s
*/
@GET
@Path("/users")
@PermitAll
@UnitOfWork
public List<Client> getNonMasseurs() {
return clientDao.findAllNonMasseurs();
}
/**
* Updates a {@link Client} to an updated value.
*
* @param client updated {@link Client}
* @param user authenticated {@link User}
* @return on update {@link Response}
* @throws WebApplicationException if the {@link Client} could not be found or {@link User}
* tries to change other {@link Client}s without administrator
* rights
*/
@PUT
@PermitAll
@UnitOfWork
public Response update(@NotNull @Valid Client client, @Auth User user) {
if (client.getSub() == null) {
client.setSub(user.getSubject());
}
Client daoClient = clientDao.findBySub(client.getSub());
if (!user.isAdmin() && !user.getSubject().equals(client.getSub())) {
throw new WebApplicationException(Status.FORBIDDEN);
}
if (daoClient == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
if (!user.isAdmin()) {
client.setMasseur(user.isMasseur());
}
// Update only if a change is detected.
if (!daoClient.equals(client)) {
clientDao.update(client);
WebSocketResource.informSubscribed("Client", OperationType.CHANGE, client);
return Response.ok(client).build();
} else {
return Response.noContent().build();
}
}
/**
* Deletes a {@link Client} given by the subject. All massages assigned to that client are freed
* before the deletion or, if the client is a masseur, those massages are automatically removed.
*
* @param sub {@link Client} subject
* @return on delete {@link Response}
* @throws WebApplicationException if the subject could not be found
*/
@DELETE
@Path("/{sub}")
@RolesAllowed("admin")
@UnitOfWork
public Response delete(@PathParam("sub") String sub) {
Client daoClient = clientDao.findBySub(sub);
if (daoClient == null) {
throw new WebApplicationException(Status.NOT_FOUND);
}
List<Massage> clientMassages;
if (daoClient.isMasseur()) {
clientMassages = massageDao.findAllByMasseuse(daoClient);
for (Massage daoMassage : clientMassages) {
Client emailingClient = daoMassage.getEmailingClient(null);
massageDao.delete(daoMassage);
WebSocketResource.informSubscribed("Massage", OperationType.REMOVE, daoMassage);
// Send an e-mail to subscribed Users if they are set as Clients of the removed Massages.
if (emailingClient != null) {
Map<String, String> arguments = new HashMap<>();
arguments.put("MASSAGE", daoMassage.getEmailRepresentation());
mailClient.sendEmail(
emailingClient.getEmail(), "Massage Cancelled", "massageRemoved.html", arguments
);
}
}
} else {
clientMassages = massageDao.findAllByClient(daoClient);
massageDao.clearClient(clientMassages);
}
clientDao.delete(daoClient);
WebSocketResource.informSubscribed("Client", OperationType.REMOVE, daoClient);
// Send an e-mail to the removed User. This e-mail will be sent regardless of subscription.
mailClient.sendEmail(
daoClient.getEmail(), "Account Removed", "accountRemoved.html", null
);
return Response.noContent().build();
}
/**
* GETs local information of a {@link Client} (currently only his subscription value). For new
* {@link User}s creates their {@link Client} representation while returning {@link User}s get
* their {@link Client} representation updated if a change is detected.
*
* @param user authenticated {@link User}
* @return true if subscribed, false otherwise
* @throws WebApplicationException if the {@link Client} could not be found after creation
*/
@GET
@Path("/retrieve-info")
@PermitAll
@UnitOfWork
public boolean retrieveInfo(@Auth User user) {
Client daoClient = clientDao.findBySub(user.getSubject());
Client client =
new Client(user.getSubject(), user.getEmail(), user.getFirstName(), user.getSurname(),
user.isMasseur(), daoClient == null || daoClient.isSubscribed());
// Create a new Client the User doesn't have its Client representation instance.
if (daoClient == null) {
clientDao.create(client);
WebSocketResource.informSubscribed("Client", OperationType.ADD, client);
if (clientDao.findBySub(user.getSubject()) == null) {
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
} else if (!daoClient.equals(client)) {
clientDao.update(client);
WebSocketResource.informSubscribed("Client", OperationType.CHANGE, client);
}
return client.isSubscribed();
}
}
| gpl-3.0 |
acdh-oeaw/vlo-curation | vlo-importer/src/main/java/eu/clarin/cmdi/vlo/importer/FacetConceptMapping.java | 9059 | package eu.clarin.cmdi.vlo.importer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Corresponds to the facet concepts file.
*
* This class holds the mapping of facet name -> facetConcepts/patterns A
* facetConcept is a ISOcat conceptLink e.g.:
* http://www.isocat.org/datcat/DC-2544 the conceptLink will be analysed and
* translated into a valid Xpath expression to extract data out of the metadata.
* Valid xpath expression e.g. /c:CMD/c:Header/c:MdSelfLink/text(), the 'c'
* namespace will be mapped to http://www.clarin.eu/cmd/ in the parser. A
* pattern is an xpath expression used directly on the metadata. Use patterns
* only when a conceptLink does not suffice.
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "facetConcepts")
public class FacetConceptMapping {
private final static Logger LOG = LoggerFactory.getLogger(FacetConceptMapping.class);
@XmlElement(name = "facetConcept")
private List<FacetConcept> facetConcepts;
public List<FacetConcept> getFacetConcepts() {
return facetConcepts;
}
public void setFacetConcepts(List<FacetConcept> facetConcepts) {
this.facetConcepts = facetConcepts;
}
public Map<String, FacetConcept> getFacetConceptMap() {
Map<String, FacetConcept> facetConceptMap = new HashMap<String, FacetConcept>();
for (FacetConcept facet : getFacetConcepts()) {
facetConceptMap.put(facet.getName(), facet);
}
return facetConceptMap;
}
public void check() {
for (FacetConcept facetConcept : getFacetConcepts()) {
if (facetConcept.hasAcceptableContext() && facetConcept.hasRejectableContext()) {
AcceptableContext acceptableContext = facetConcept.getAcceptableContext();
RejectableContext rejectableContext = facetConcept.getRejectableContext();
if (acceptableContext.includeAny() && rejectableContext.includeAny()) {
LOG.error("Error: any context is both acceptable and rejectable for facet '" + facetConcept.getName() + "'");
}
if (acceptableContext.includeEmpty() && rejectableContext.includeEmpty()) {
LOG.error("Error: empty context is both acceptable and rejectable for facet '" + facetConcept.getName() + "'");
}
}
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "facetConcept")
public static class FacetConcept {
@XmlAttribute
private String name;
/**
* Values will be stored lowercase by default, set isCaseInsensitive to
* true if you want to keep the case of the value
*/
@XmlAttribute
private boolean isCaseInsensitive = false;
/**
* By default multiple values that are found for a matching pattern will
* be stored. For some facets this leads to too much values with little
* value for instance for "subject". Set allowMultipleValues to false
* will only store the first found value.
*/
@XmlAttribute
private boolean allowMultipleValues = true;
@XmlAttribute
private String description = "";
@XmlAttribute
private String definition = "";
@XmlElement(name = "concept")
private List<String> concepts = new ArrayList<String>();
@XmlElement(name = "acceptableContext")
private AcceptableContext acceptableContext;
@XmlElement(name = "rejectableContext")
private RejectableContext rejectableContext;
@XmlElement(name = "pattern")
private List<String> patterns = new ArrayList<String>();
@XmlElement(name = "blacklistPattern")
private List<String> blacklistPatterns = new ArrayList<String>();
@XmlElement(name = "derivedFacet")
private List<String> derivedFacets = new ArrayList<String>();
public void setConcepts(List<String> concepts) {
this.concepts = concepts;
}
public List<String> getConcepts() {
return concepts;
}
public void setAccebtableContext(AcceptableContext context) {
this.acceptableContext = context;
}
public AcceptableContext getAcceptableContext() {
return acceptableContext;
}
public boolean hasAcceptableContext() {
return (acceptableContext != null);
}
public void setRejectableContext(RejectableContext context) {
this.rejectableContext = context;
}
public RejectableContext getRejectableContext() {
return rejectableContext;
}
public boolean hasRejectableContext() {
return (rejectableContext != null);
}
public boolean hasContext() {
return (hasAcceptableContext() || hasRejectableContext());
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCaseInsensitive(boolean isCaseInsensitive) {
this.isCaseInsensitive = isCaseInsensitive;
}
public boolean isCaseInsensitive() {
return isCaseInsensitive;
}
public void setAllowMultipleValues(boolean allowMultipleValues) {
this.allowMultipleValues = allowMultipleValues;
}
public boolean isAllowMultipleValues() {
return allowMultipleValues;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public String getDefinition() {
return this.definition;
}
public void setPatterns(List<String> patterns) {
this.patterns = patterns;
}
public List<String> getPatterns() {
return patterns;
}
public void setBlacklistPatterns(List<String> blacklistPatterns) {
this.blacklistPatterns = blacklistPatterns;
}
public List<String> getBlacklistPatterns() {
return blacklistPatterns;
}
public List<String> getDerivedFacets() {
return derivedFacets;
}
public void setDerivedFacets(List<String> derivedFacets) {
this.derivedFacets = derivedFacets;
}
@Override
public String toString() {
return "name=" + name + ", patterns=" + patterns + ", concepts=" + concepts;
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "acceptableContext")
public static class AcceptableContext {
@XmlAttribute
private boolean includeAny = false;
@XmlAttribute
private boolean includeEmpty = true;
@XmlElement(name = "concept")
private List<String> concepts = new ArrayList<String>();
public void setConcepts(List<String> concepts) {
this.concepts = concepts;
}
public List<String> getConcepts() {
return concepts;
}
public void setIncludeAny(boolean includeAny) {
this.includeAny = includeAny;
}
public boolean includeAny() {
return includeAny;
}
public void setIncludeEmpty(boolean includeEmpty) {
this.includeEmpty = includeEmpty;
}
public boolean includeEmpty() {
return includeEmpty;
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "rejectableContext")
public static class RejectableContext {
@XmlAttribute
private boolean includeAny = true;
@XmlAttribute
private boolean includeEmpty = false;
@XmlElement(name = "concept")
private List<String> concepts = new ArrayList<String>();
public void setConcepts(List<String> concepts) {
this.concepts = concepts;
}
public List<String> getConcepts() {
return concepts;
}
public void setIncludeAny(boolean includeAny) {
this.includeAny = includeAny;
}
public boolean includeAny() {
return includeAny;
}
public void setIncludeEmpty(boolean includeEmpty) {
this.includeEmpty = includeEmpty;
}
public boolean includeEmpty() {
return includeEmpty;
}
}
}
| gpl-3.0 |
pr0stik/AndroidDev | Lesson7_LayoutProp/app/src/androidTest/java/com/example/foxy/lesson7_layoutprop/ExampleInstrumentedTest.java | 774 | package com.example.foxy.lesson7_layoutprop;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.foxy.lesson7_layoutprop", appContext.getPackageName());
}
}
| gpl-3.0 |
redsoftbiz/executequery | src/org/underworldlabs/swing/MoveJListItemsStrategy.java | 2352 | /*
* MoveJListItemsStrategy.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* 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 3
* of the License, or 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, see <http://www.gnu.org/licenses/>.
*
*/
package org.underworldlabs.swing;
import javax.swing.*;
/**
* @author Takis Diakoumis
*/
public class MoveJListItemsStrategy {
private final JList list;
private static final int MOVE_DOWN = 1;
private static final int MOVE_UP = -1;
public MoveJListItemsStrategy(JList list) {
if (!(list.getModel() instanceof DefaultListModel)) {
throw new IllegalArgumentException(
"Model in specified list must be an instance of DefaultListModel");
}
this.list = list;
}
public void moveSelectionDown() {
if (noSelection() || lastElementSelected()) {
return;
}
moveSelection(MOVE_DOWN);
}
public void moveSelectionUp() {
if (noSelection() || firstElementSelected()) {
return;
}
moveSelection(MOVE_UP);
}
private void moveSelection(int increment) {
int index = list.getSelectedIndex();
Object element = list.getSelectedValue();
DefaultListModel model = modelFromList();
model.remove(index);
model.add(index + increment, element);
list.setSelectedIndex(index + increment);
}
private DefaultListModel modelFromList() {
return (DefaultListModel) list.getModel();
}
private boolean firstElementSelected() {
return (list.getSelectedIndex() == 0);
}
private boolean lastElementSelected() {
return (modelFromList().lastElement() == list.getSelectedValue());
}
private boolean noSelection() {
return list.isSelectionEmpty();
}
}
| gpl-3.0 |
widgetrefinery/wallpaper-refinery | src/main/java/org/widgetrefinery/wallpaper/common/Model.java | 9207 | /*
* Copyright (C) 2012 Widget Refinery
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.widgetrefinery.wallpaper.common;
import org.widgetrefinery.util.BadUserInputException;
import org.widgetrefinery.util.event.EventBus;
import org.widgetrefinery.wallpaper.event.SetInputFileEvent;
import org.widgetrefinery.wallpaper.event.SetThumbnailsPerRowEvent;
import org.widgetrefinery.wallpaper.event.SetWorkingDirectoryEvent;
import org.widgetrefinery.wallpaper.os.OSSupport;
import org.widgetrefinery.wallpaper.os.OSUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Manages the settings used throughout the application.
*
* @since 4/11/12 9:57 PM
*/
public class Model {
private final EventBus eventBus;
private File workingDirectory;
private File inputFile;
private File outputFile;
private int thumbnailsPerRow;
private boolean configOS;
private boolean refreshOS;
/**
* Creates a new instance with the working directory set to the current directory.
*
* @param eventBus event bus to fire events on
*/
public Model(final EventBus eventBus) {
this(eventBus, new File(System.getProperty("user.dir")));
}
/**
* Creates a new instance with a specific working directory.
*
* @param eventBus event bus to fire events on
* @param workingDirectory initial working directory
*/
public Model(final EventBus eventBus, final File workingDirectory) {
this.eventBus = eventBus;
setWorkingDirectory(workingDirectory);
setThumbnailsPerRow(4);
}
/**
* Get the working directory. The gui will search this directory for
* images to preview.
*
* @return working directory
*/
public File getWorkingDirectory() {
return this.workingDirectory;
}
/**
* Set the working directory to a new location. If the working directory is
* a file, it will be used as the input file while the parent directory
* will be used as the actual working directory. Otherwise the working
* directory will be used as is and the input file will be set to null.
*
* @param workingDirectory new working directory
*/
public void setWorkingDirectory(final File workingDirectory) {
boolean fireEvent;
if (null != workingDirectory && workingDirectory.isFile()) {
File parent = workingDirectory.getParentFile();
fireEvent = shouldFireEvent(parent, this.workingDirectory);
this.workingDirectory = parent;
setInputFile(workingDirectory);
} else {
fireEvent = shouldFireEvent(workingDirectory, this.workingDirectory);
this.workingDirectory = workingDirectory;
setInputFile(null);
}
if (fireEvent) {
this.eventBus.fireEvent(new SetWorkingDirectoryEvent(this.workingDirectory));
}
}
/**
* Get the input file. This is the image that will be used to generate the
* wallpaper.
*
* @return input file
*/
public File getInputFile() {
return this.inputFile;
}
/**
* Set the input file to a new value.
*
* @param inputFile new input file
*/
public void setInputFile(final File inputFile) {
boolean fireEvent = shouldFireEvent(inputFile, this.inputFile);
this.inputFile = inputFile;
if (fireEvent) {
this.eventBus.fireEvent(new SetInputFileEvent(this.inputFile));
}
}
/**
* Get the output file. This is the file that the resulting wallpaper will
* be saved to.
*
* @return output file
*/
public File getOutputFile() {
return this.outputFile;
}
/**
* Set the output file to a new value.
*
* @param outputFile new output file
*/
public void setOutputFile(final File outputFile) {
this.outputFile = outputFile;
}
/**
* Get the minimum number of thumbnails to display per row.
*
* @return min thumbnails per row
*/
public int getMinThumbnailsPerRow() {
return 2;
}
/**
* Get the maximum number of thumbnails to display per row.
*
* @return max thumbnails per row
*/
public int getMaxThumbnailsPerRow() {
return 8;
}
/**
* Get the number of thumbnails to display per row.
*
* @return thumbnails per row
*/
public int getThumbnailsPerRow() {
return this.thumbnailsPerRow;
}
/**
* Set the number of preview thumbnails to display per row.
*
* @param thumbnailsPerRow thumbnails per row
*/
public void setThumbnailsPerRow(int thumbnailsPerRow) {
thumbnailsPerRow = Math.max(getMinThumbnailsPerRow(), thumbnailsPerRow);
thumbnailsPerRow = Math.min(getMaxThumbnailsPerRow(), thumbnailsPerRow);
boolean fireEvent = shouldFireEvent(thumbnailsPerRow, this.thumbnailsPerRow);
this.thumbnailsPerRow = thumbnailsPerRow;
if (fireEvent) {
this.eventBus.fireEvent(new SetThumbnailsPerRowEvent(thumbnailsPerRow));
}
}
/**
* Determine if the application should configure the OS to use the output
* file as the wallpaper. When set, {@link #process(boolean)} will call
* {@link org.widgetrefinery.wallpaper.os.OSSupport#updateWallpaperSettings(java.io.File)}.
*
* @return true if the application should configure the OS
*/
public boolean isConfigOS() {
return this.configOS;
}
/**
* Set whether the application should configure the OS.
*
* @param configOS boolean flag
*/
public void setConfigOS(final boolean configOS) {
this.configOS = configOS;
}
/**
* Determine if the application should notify the OS to reload its
* wallpaper. When set, {@link #process(boolean)} will call
* {@link org.widgetrefinery.wallpaper.os.OSSupport#reloadWallpaperSettings()}.
*
* @return true if the application should notify the OS
*/
public boolean isRefreshOS() {
return this.refreshOS;
}
/**
* Set whether the application should notify the OS to reload its
* wallpaper.
*
* @param refreshOS boolean flag
*/
public void setRefreshOS(final boolean refreshOS) {
this.refreshOS = refreshOS;
}
protected boolean shouldFireEvent(Object v1, Object v2) {
if (null != v1) {
return !v1.equals(v2);
} else {
return null != v2;
}
}
/**
* Generate a new wallpaper image and update the OS as configured.
*
* @param overwrite whether or not to overwrite the output file
* @throws BadUserInputException if there is a problem with the user-supplied parameters
* @throws IOException if an IO error occurred
* @throws InterruptedException if the operation was interrupted
*/
public void process(final boolean overwrite) throws BadUserInputException, IOException, InterruptedException {
File input = getInputFile();
if (null == input) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_NO_INPUT);
}
if (!input.exists()) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_INPUT_DOES_NOT_EXIST, input);
}
File output = getOutputFile();
if (null == output) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_NO_OUTPUT);
}
if (input.equals(output)) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_SAME_INPUT_OUTPUT, output);
}
if (output.exists() && !overwrite) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_OUTPUT_EXISTS, output);
}
ImageUtil imageUtil = new ImageUtil();
BufferedImage image = imageUtil.formatImage(input);
if (null == image) {
throw new BadUserInputException(WallpaperTranslationKey.PROCESS_ERROR_BAD_INPUT, input);
}
imageUtil.saveImage(image, output);
OSSupport osSupport = OSUtil.getOSSupport();
if (null != osSupport) {
if (isConfigOS()) {
osSupport.updateWallpaperSettings(output);
}
if (isRefreshOS()) {
osSupport.reloadWallpaperSettings();
}
}
}
}
| gpl-3.0 |
iterate-ch/cyberduck | core/src/main/java/ch/cyberduck/core/io/IOResumeException.java | 943 | package ch.cyberduck.core.io;
/*
* Copyright (c) 2007 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* dkocher@cyberduck.ch
*/
import java.io.IOException;
public class IOResumeException extends IOException {
private static final long serialVersionUID = -312412837701506092L;
public IOResumeException(String s) {
super(s);
}
}
| gpl-3.0 |
erfanoabdi/BatteryModPercentage | app/src/main/java/ir/erfanabdi/batterymodpercentage/EffEnhancer.java | 7759 | package ir.erfanabdi.batterymodpercentage;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.FileObserver;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by erfanabdi on 8/15/17.
*/
public class EffEnhancer extends AppCompatActivity {
Switch eff_on;
EditText soc_stop, soc_start;
TextView textViewStart, textViewStop, effstatus;
Button setButton;
Context context;
public interface FileObserverListener {
void onFileUpdated(String path);
void onFileAttributesChanged(String path);
}
private FileObserver mFileObserver;
private List<FileObserverListener> mFileObserverListeners;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enhancer);
context = this;
eff_on = (Switch) findViewById(R.id.eff_on);
soc_stop = (EditText) findViewById(R.id.eff_stop);
soc_start = (EditText) findViewById(R.id.eff_start);
textViewStart = (TextView) findViewById(R.id.textViewStart);
textViewStop = (TextView) findViewById(R.id.textViewStop);
effstatus = (TextView) findViewById(R.id.effstatus);
setButton = (Button) findViewById(R.id.eff_set);
String[] perms = new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE };
List<String> reqPerms = new ArrayList<>();
for (String perm : perms) {
if (context.checkSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
reqPerms.add(perm);
}
}
if (!reqPerms.isEmpty())
requestPermissions(reqPerms.toArray(new String[]{}), 0);
boolean eff_on_pref = false;
String soc_stop_pref = "80";
String soc_start_pref = "79";
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
WorldReadablePrefs prefs;
mFileObserverListeners = new ArrayList<>();
prefs = new WorldReadablePrefs(context, "EffEnhc");
mFileObserverListeners.add(prefs);
registerFileObserver();
fixFolderPermissionsAsync();
eff_on_pref = prefs.getBoolean("eff_on", false);
soc_stop_pref = prefs.getString("soc_stop", "80");
soc_start_pref = prefs.getString("soc_start", "79");
}
else
{
SharedPreferences prefs = getSharedPreferences("EffEnhc", MODE_WORLD_READABLE);
eff_on_pref = prefs.getBoolean("eff_on", false);
soc_stop_pref = prefs.getString("soc_stop", "80");
soc_start_pref = prefs.getString("soc_start", "79");
}
eff_on.setChecked(eff_on_pref);
soc_start.setText(soc_start_pref);
soc_stop.setText(soc_stop_pref);
setall(eff_on_pref);
setButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String start, stop;
start = soc_start.getText().toString().trim();
stop = soc_stop.getText().toString().trim();
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
WorldReadablePrefs prefs = new WorldReadablePrefs(context, "EffEnhc");
prefs.edit().putString("soc_stop", stop).commit();
prefs.edit().putString("soc_start", start).commit();
fixFolderPermissionsAsync();
} else {
SharedPreferences prefs = getSharedPreferences("EffEnhc", MODE_WORLD_READABLE);
prefs.edit().putString("soc_stop", stop).commit();
prefs.edit().putString("soc_start", start).commit();
}
Toast t = Toast.makeText(context, "Efficiency Mode Values Changed, just reset Efficiency mode", Toast.LENGTH_SHORT);
t.show();
}
});
eff_on.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
WorldReadablePrefs prefs = new WorldReadablePrefs(context, "EffEnhc");
prefs.edit().putBoolean("eff_on", isChecked).commit();
} else {
SharedPreferences prefs = getSharedPreferences("EffEnhc", MODE_WORLD_READABLE);
prefs.edit().putBoolean("eff_on", isChecked).commit();
}
setall(isChecked);
}
});
}
private void setall(boolean what){
soc_stop.setEnabled(what);
soc_start.setEnabled(what);
textViewStart.setEnabled(what);
textViewStop.setEnabled(what);
setButton.setEnabled(what);
}
public void fixFolderPermissionsAsync() {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
// main dir
File pkgFolder = context.getDataDir();
if (pkgFolder.exists()) {
pkgFolder.setExecutable(true, false);
pkgFolder.setReadable(true, false);
}
// cache dir
File cacheFolder = context.getCacheDir();
if (cacheFolder.exists()) {
cacheFolder.setExecutable(true, false);
cacheFolder.setReadable(true, false);
}
// files dir
File filesFolder = context.getFilesDir();
if (filesFolder.exists()) {
filesFolder.setExecutable(true, false);
filesFolder.setReadable(true, false);
for (File f : filesFolder.listFiles()) {
f.setExecutable(true, false);
f.setReadable(true, false);
}
}
// app picker
File appPickerFolder = new File(context.getFilesDir() + "/app_picker");
if (appPickerFolder.exists()) {
appPickerFolder.setExecutable(true, false);
appPickerFolder.setReadable(true, false);
for (File f : appPickerFolder.listFiles()) {
f.setExecutable(true, false);
f.setReadable(true, false);
}
}
}
});
}
private void registerFileObserver() {
mFileObserver = new FileObserver(context.getDataDir() + "/shared_prefs",
FileObserver.ATTRIB | FileObserver.CLOSE_WRITE) {
@Override
public void onEvent(int event, String path) {
for (FileObserverListener l : mFileObserverListeners) {
if ((event & FileObserver.ATTRIB) != 0)
l.onFileAttributesChanged(path);
if ((event & FileObserver.CLOSE_WRITE) != 0)
l.onFileUpdated(path);
}
}
};
mFileObserver.startWatching();
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java | 2060 | package com.baeldung.jaxws.server.repository;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jaxws.server.bottomup.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.server.bottomup.exception.EmployeeNotFound;
import com.baeldung.jaxws.server.bottomup.model.Employee;
public class EmployeeRepositoryImpl implements EmployeeRepository {
private List<Employee> employeeList;
public EmployeeRepositoryImpl() {
employeeList = new ArrayList<>();
employeeList.add(new Employee(1, "Jane"));
employeeList.add(new Employee(2, "Jack"));
employeeList.add(new Employee(3, "George"));
}
public List<Employee> getAllEmployees() {
return employeeList;
}
public Employee getEmployee(int id) throws EmployeeNotFound {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
return emp;
}
}
throw new EmployeeNotFound();
}
public Employee updateEmployee(int id, String name) throws EmployeeNotFound {
for (Employee employee1 : employeeList) {
if (employee1.getId() == id) {
employee1.setId(id);
employee1.setFirstName(name);
return employee1;
}
}
throw new EmployeeNotFound();
}
public boolean deleteEmployee(int id) throws EmployeeNotFound {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
employeeList.remove(emp);
return true;
}
}
throw new EmployeeNotFound();
}
public Employee addEmployee(int id, String name) throws EmployeeAlreadyExists {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
throw new EmployeeAlreadyExists();
}
}
Employee employee = new Employee(id, name);
employeeList.add(employee);
return employee;
}
public int count() {
return employeeList.size();
}
}
| gpl-3.0 |
brianhsu/MaidroidPlurk | src/main/java/idv/brianhsu/maidroid/billing/IabHelper.java | 44333 | /* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package idv.brianhsu.maidroid.billing;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* Provides convenience methods for in-app billing. You can create one instance of this
* class for your application and use it to process in-app billing operations.
* It provides synchronous (blocking) and asynchronous (non-blocking) methods for
* many common in-app billing operations, as well as automatic signature
* verification.
*
* After instantiating, you must perform setup in order to start using the object.
* To perform setup, call the {@link #startSetup} method and provide a listener;
* that listener will be notified when setup is complete, after which (and not before)
* you may call other methods.
*
* After setup is complete, you will typically want to request an inventory of owned
* items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync}
* and related methods.
*
* When you are done with this object, don't forget to call {@link #dispose}
* to ensure proper cleanup. This object holds a binding to the in-app billing
* service, which will leak unless you dispose of it correctly. If you created
* the object on an Activity's onCreate method, then the recommended
* place to dispose of it is the Activity's onDestroy method.
*
* A note about threading: When using this object from a background thread, you may
* call the blocking versions of methods; when using from a UI thread, call
* only the asynchronous versions and handle the results via callbacks.
* Also, notice that you can only call one asynchronous operation at a time;
* attempting to start a second asynchronous operation while the first one
* has not yet completed will result in an exception being thrown.
*
* @author Bruno Oliveira (Google)
*
*/
public class IabHelper {
// Is debug logging enabled?
boolean mDebugLog = false;
String mDebugTag = "IabHelper";
// Is setup done?
boolean mSetupDone = false;
// Has this object been disposed of? (If so, we should ignore callbacks, etc)
boolean mDisposed = false;
// Are subscriptions supported?
boolean mSubscriptionsSupported = false;
// Is an asynchronous operation in progress?
// (only one at a time can be in progress)
boolean mAsyncInProgress = false;
// (for logging/debugging)
// if mAsyncInProgress == true, what asynchronous operation is in progress?
String mAsyncOperation = "";
// Context we were passed during initialization
Context mContext;
// Connection to the service
IInAppBillingService mService;
ServiceConnection mServiceConn;
// The request code used to launch purchase flow
int mRequestCode;
// The item type of the current purchase flow
String mPurchasingItemType;
// Public key for verifying signature, in base64 encoding
String mSignatureBase64 = null;
// Billing response codes
public static final int BILLING_RESPONSE_RESULT_OK = 0;
public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1;
public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4;
public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5;
public static final int BILLING_RESPONSE_RESULT_ERROR = 6;
public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8;
// IAB Helper error codes
public static final int IABHELPER_ERROR_BASE = -1000;
public static final int IABHELPER_REMOTE_EXCEPTION = -1001;
public static final int IABHELPER_BAD_RESPONSE = -1002;
public static final int IABHELPER_VERIFICATION_FAILED = -1003;
public static final int IABHELPER_SEND_INTENT_FAILED = -1004;
public static final int IABHELPER_USER_CANCELLED = -1005;
public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006;
public static final int IABHELPER_MISSING_TOKEN = -1007;
public static final int IABHELPER_UNKNOWN_ERROR = -1008;
public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009;
public static final int IABHELPER_INVALID_CONSUMPTION = -1010;
// Keys for the responses from InAppBillingService
public static final String RESPONSE_CODE = "RESPONSE_CODE";
public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST";
public static final String RESPONSE_BUY_INTENT = "BUY_INTENT";
public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA";
public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE";
public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST";
public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST";
public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN";
// Item types
public static final String ITEM_TYPE_INAPP = "inapp";
public static final String ITEM_TYPE_SUBS = "subs";
// some fields on the getSkuDetails response bundle
public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST";
public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST";
/**
* Creates an instance. After creation, it will not yet be ready to use. You must perform
* setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not
* block and is safe to call from a UI thread.
*
* @param ctx Your application or Activity context. Needed to bind to the in-app billing service.
* @param base64PublicKey Your application's public key, encoded in base64.
* This is used for verification of purchase signatures. You can find your app's base64-encoded
* public key in your application's page on Google Play Developer Console. Note that this
* is NOT your "developer public key".
*/
public IabHelper(Context ctx, String base64PublicKey) {
mContext = ctx.getApplicationContext();
mSignatureBase64 = base64PublicKey;
logDebug("IAB helper created.");
}
/**
* Enables or disable debug logging through LogCat.
*/
public void enableDebugLogging(boolean enable, String tag) {
checkNotDisposed();
mDebugLog = enable;
mDebugTag = tag;
}
public void enableDebugLogging(boolean enable) {
checkNotDisposed();
mDebugLog = enable;
}
/**
* Callback for setup process. This listener's {@link #onIabSetupFinished} method is called
* when the setup process is complete.
*/
public interface OnIabSetupFinishedListener {
/**
* Called to notify that setup is complete.
*
* @param result The result of the setup process.
*/
public void onIabSetupFinished(IabResult result);
}
/**
* Starts the setup process. This will start up the setup process asynchronously.
* You will be notified through the listener when the setup process is complete.
* This method is safe to call from a UI thread.
*
* @param listener The listener to notify when the setup process is complete.
*/
public void startSetup(final OnIabSetupFinishedListener listener) {
// If already set up, can't do it again.
checkNotDisposed();
if (mSetupDone) throw new IllegalStateException("IAB helper is already set up.");
// Connection to IAB service
logDebug("Starting in-app billing setup.");
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
logDebug("Billing service disconnected.");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (mDisposed) return;
logDebug("Billing service connected.");
mService = IInAppBillingService.Stub.asInterface(service);
String packageName = mContext.getPackageName();
try {
logDebug("Checking for in-app billing 3 support.");
// check for in-app billing v3 support
int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
if (response != BILLING_RESPONSE_RESULT_OK) {
if (listener != null) listener.onIabSetupFinished(new IabResult(response,
"Error checking for billing v3 support."));
// if in-app purchases aren't supported, neither are subscriptions.
mSubscriptionsSupported = false;
return;
}
logDebug("In-app billing version 3 supported for " + packageName);
// check for v3 subscriptions support
response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Subscriptions AVAILABLE.");
mSubscriptionsSupported = true;
}
else {
logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
}
mSetupDone = true;
}
catch (RemoteException e) {
if (listener != null) {
listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION,
"RemoteException while setting up in-app billing."));
}
e.printStackTrace();
return;
}
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
}
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
}
/**
* Dispose of object, releasing resources. It's very important to call this
* method when you are done with this object. It will release any resources
* used by it such as service connections. Naturally, once the object is
* disposed of, it can't be used again.
*/
public void dispose() {
logDebug("Disposing.");
mSetupDone = false;
if (mServiceConn != null) {
logDebug("Unbinding from service.");
if (mContext != null) mContext.unbindService(mServiceConn);
}
mDisposed = true;
mContext = null;
mServiceConn = null;
mService = null;
mPurchaseListener = null;
}
private void checkNotDisposed() {
if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
}
/** Returns whether subscriptions are supported. */
public boolean subscriptionsSupported() {
checkNotDisposed();
return mSubscriptionsSupported;
}
/**
* Callback that notifies when a purchase is finished.
*/
public interface OnIabPurchaseFinishedListener {
/**
* Called to notify that an in-app purchase finished. If the purchase was successful,
* then the sku parameter specifies which item was purchased. If the purchase failed,
* the sku and extraData parameters may or may not be null, depending on how far the purchase
* process went.
*
* @param result The result of the purchase.
* @param info The purchase information (null if purchase failed)
*/
public void onIabPurchaseFinished(IabResult result, Purchase info);
}
// The listener registered on launchPurchaseFlow, which we have to call back when
// the purchase finishes
OnIabPurchaseFinishedListener mPurchaseListener;
public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) {
launchPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData);
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener) {
launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData);
}
/**
* Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase,
* which will involve bringing up the Google Play screen. The calling activity will be paused while
* the user interacts with Google Play, and the result will be delivered via the activity's
* {@link android.app.Activity#onActivityResult} method, at which point you must call
* this object's {@link #handleActivityResult} method to continue the purchase flow. This method
* MUST be called from the UI thread of the Activity.
*
* @param act The calling activity.
* @param sku The sku of the item to purchase.
* @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
* @param requestCode A request code (to differentiate from other responses --
* as in {@link android.app.Activity#startActivityForResult}).
* @param listener The listener to notify when the purchase process finishes
* @param extraData Extra data (developer payload), which will be returned with the purchase data
* when the purchase completes. This extra data will be permanently bound to that purchase
* and will always be returned when the purchase is queried.
*/
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
checkNotDisposed();
checkSetupDone("launchPurchaseFlow");
flagStartAsync("launchPurchaseFlow");
IabResult result;
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE,
"Subscriptions are not available.");
flagEndAsync();
if (listener != null) listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null) listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(),
requestCode, new Intent(),
Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
}
catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null) listener.onIabPurchaseFinished(result, null);
}
catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null) listener.onIabPurchaseFinished(result, null);
}
}
/**
* Handles an activity result that's part of the purchase flow in in-app billing. If you
* are calling {@link #launchPurchaseFlow}, then you must call this method from your
* Activity's {@link android.app.Activity@onActivityResult} method. This method
* MUST be called from the UI thread of the Activity.
*
* @param requestCode The requestCode as you received it.
* @param resultCode The resultCode as you received it.
* @param data The data (Intent) as you received it.
* @return Returns true if the result was related to a purchase flow and was handled;
* false if the result was not related to a purchase, in which case you should
* handle it normally.
*/
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
IabResult result;
if (requestCode != mRequestCode) return false;
checkNotDisposed();
checkSetupDone("handleActivityResult");
// end of async purchase operation that started on launchPurchaseFlow
flagEndAsync();
if (data == null) {
logError("Null data in IAB activity result.");
result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
int responseCode = getResponseCodeFromIntent(data);
String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);
if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successful resultcode from purchase activity.");
logDebug("Purchase data: " + purchaseData);
logDebug("Data signature: " + dataSignature);
logDebug("Extras: " + data.getExtras());
logDebug("Expected item type: " + mPurchasingItemType);
if (purchaseData == null || dataSignature == null) {
logError("BUG: either purchaseData or dataSignature is null.");
logDebug("Extras: " + data.getExtras().toString());
result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
Purchase purchase = null;
try {
purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
String sku = purchase.getSku();
// Verify signature
if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
logError("Purchase signature verification FAILED for sku " + sku);
result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku);
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase);
return true;
}
logDebug("Purchase signature successfully verified.");
}
catch (JSONException e) {
logError("Failed to parse purchase data.");
e.printStackTrace();
result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase);
}
}
else if (resultCode == Activity.RESULT_OK) {
// result code was OK, but in-app billing response was not OK.
logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
if (mPurchaseListener != null) {
result = new IabResult(responseCode, "Problem purchashing item.");
mPurchaseListener.onIabPurchaseFinished(result, null);
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
}
else {
logError("Purchase failed. Result code: " + Integer.toString(resultCode)
+ ". Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
}
return true;
}
public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException {
return queryInventory(querySkuDetails, moreSkus, null);
}
/**
* Queries the inventory. This will query all owned items from the server, as well as
* information on additional skus, if specified. This method may block or take long to execute.
* Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}.
*
* @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well
* as purchase information.
* @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @throws IabException if a problem occurs while refreshing the inventory.
*/
public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus,
List<String> moreSubsSkus) throws IabException {
checkNotDisposed();
checkSetupDone("queryInventory");
try {
Inventory inv = new Inventory();
int r = queryPurchases(inv, ITEM_TYPE_INAPP);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned items).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
}
}
// if subscriptions are supported, then also query for subscriptions
if (mSubscriptionsSupported) {
r = queryPurchases(inv, ITEM_TYPE_SUBS);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned subscriptions).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
}
}
}
return inv;
}
catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
}
catch (JSONException e) {
throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e);
}
}
/**
* Listener that notifies when an inventory query operation completes.
*/
public interface QueryInventoryFinishedListener {
/**
* Called to notify that an inventory query operation completed.
*
* @param result The result of the operation.
* @param inv The inventory.
*/
public void onQueryInventoryFinished(IabResult result, Inventory inv);
}
/**
* Asynchronous wrapper for inventory query. This will perform an inventory
* query as described in {@link #queryInventory}, but will do so asynchronously
* and call back the specified listener upon completion. This method is safe to
* call from a UI thread.
*
* @param querySkuDetails as in {@link #queryInventory}
* @param moreSkus as in {@link #queryInventory}
* @param listener The listener to notify when the refresh operation completes.
*/
public void queryInventoryAsync(final boolean querySkuDetails,
final List<String> moreSkus,
final QueryInventoryFinishedListener listener) {
final Handler handler = new Handler();
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
}
})).start();
}
public void queryInventoryAsync(QueryInventoryFinishedListener listener) {
queryInventoryAsync(true, null, listener);
}
public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) {
queryInventoryAsync(querySkuDetails, null, listener);
}
/**
* Consumes a given in-app product. Consuming can only be done on an item
* that's owned, and as a result of consumption, the user will no longer own it.
* This method may block or take long to return. Do not call from the UI thread.
* For that, see {@link #consumeAsync}.
*
* @param itemInfo The PurchaseInfo that represents the item to consume.
* @throws IabException if there is a problem during consumption.
*/
void consume(Purchase itemInfo) throws IabException {
checkNotDisposed();
checkSetupDone("consume");
if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) {
throw new IabException(IABHELPER_INVALID_CONSUMPTION,
"Items of type '" + itemInfo.mItemType + "' can't be consumed.");
}
try {
String token = itemInfo.getToken();
String sku = itemInfo.getSku();
if (token == null || token.equals("")) {
logError("Can't consume "+ sku + ". No token.");
throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: "
+ sku + " " + itemInfo);
}
logDebug("Consuming sku: " + sku + ", token: " + token);
int response = mService.consumePurchase(3, mContext.getPackageName(), token);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successfully consumed sku: " + sku);
}
else {
logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response));
throw new IabException(response, "Error consuming sku " + sku);
}
}
catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e);
}
}
/**
* Callback that notifies when a consumption operation finishes.
*/
public interface OnConsumeFinishedListener {
/**
* Called to notify that a consumption has finished.
*
* @param purchase The purchase that was (or was to be) consumed.
* @param result The result of the consumption operation.
*/
public void onConsumeFinished(Purchase purchase, IabResult result);
}
/**
* Callback that notifies when a multi-item consumption operation finishes.
*/
public interface OnConsumeMultiFinishedListener {
/**
* Called to notify that a consumption of multiple items has finished.
*
* @param purchases The purchases that were (or were to be) consumed.
* @param results The results of each consumption operation, corresponding to each
* sku.
*/
public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results);
}
/**
* Asynchronous wrapper to item consumption. Works like {@link #consume}, but
* performs the consumption in the background and notifies completion through
* the provided listener. This method is safe to call from a UI thread.
*
* @param purchase The purchase to be consumed.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
List<Purchase> purchases = new ArrayList<Purchase>();
purchases.add(purchase);
consumeAsyncInternal(purchases, listener, null);
}
/**
* Same as {@link consumeAsync}, but for multiple items at once.
* @param purchases The list of PurchaseInfo objects representing the purchases to consume.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
consumeAsyncInternal(purchases, null, listener);
}
/**
* Returns a human-readable description for the given response code.
*
* @param code The response code
* @return A human-readable string explaining the result code.
* It also includes the result code numerically.
*/
public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" +
"3:Billing Unavailable/4:Item unavailable/" +
"5:Developer Error/6:Error/7:Item Already Owned/" +
"8:Item not owned").split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" +
"-1002:Bad response received/" +
"-1003:Purchase signature verification failed/" +
"-1004:Send intent failed/" +
"-1005:User cancelled/" +
"-1006:Unknown purchase response/" +
"-1007:Missing token/" +
"-1008:Unknown error/" +
"-1009:Subscriptions not available/" +
"-1010:Invalid consumption attempt").split("/");
if (code <= IABHELPER_ERROR_BASE) {
int index = IABHELPER_ERROR_BASE - code;
if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index];
else return String.valueOf(code) + ":Unknown IAB Helper Error";
}
else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown";
else
return iab_msgs[code];
}
// Checks that setup was done; if not, throws an exception.
void checkSetupDone(String operation) {
if (!mSetupDone) {
logError("Illegal state for operation (" + operation + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation);
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromBundle(Bundle b) {
Object o = b.get(RESPONSE_CODE);
if (o == null) {
logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
}
else if (o instanceof Integer) return ((Integer)o).intValue();
else if (o instanceof Long) return (int)((Long)o).longValue();
else {
logError("Unexpected type for bundle response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromIntent(Intent i) {
Object o = i.getExtras().get(RESPONSE_CODE);
if (o == null) {
logError("Intent with no response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
}
else if (o instanceof Integer) return ((Integer)o).intValue();
else if (o instanceof Long) return (int)((Long)o).longValue();
else {
logError("Unexpected type for intent response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName());
}
}
void flagStartAsync(String operation) {
if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" +
operation + ") because another async operation(" + mAsyncOperation + ") is in progress.");
mAsyncOperation = operation;
mAsyncInProgress = true;
logDebug("Starting async operation: " + operation);
}
void flagEndAsync() {
logDebug("Ending async operation: " + mAsyncOperation);
mAsyncOperation = "";
mAsyncInProgress = false;
}
int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
// Query purchases
logDebug("Querying owned items, item type: " + itemType);
logDebug("Package name: " + mContext.getPackageName());
boolean verificationFailed = false;
String continueToken = null;
do {
logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(),
itemType, continueToken);
int response = getResponseCodeFromBundle(ownedItems);
logDebug("Owned items response: " + String.valueOf(response));
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getPurchases() failed: " + getResponseDesc(response));
return response;
}
if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) {
logError("Bundle returned from getPurchases() doesn't contain required fields.");
return IABHELPER_BAD_RESPONSE;
}
ArrayList<String> ownedSkus = ownedItems.getStringArrayList(
RESPONSE_INAPP_ITEM_LIST);
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList(
RESPONSE_INAPP_PURCHASE_DATA_LIST);
ArrayList<String> signatureList = ownedItems.getStringArrayList(
RESPONSE_INAPP_SIGNATURE_LIST);
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
String signature = signatureList.get(i);
String sku = ownedSkus.get(i);
if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) {
logDebug("Sku is owned: " + sku);
Purchase purchase = new Purchase(itemType, purchaseData, signature);
if (TextUtils.isEmpty(purchase.getToken())) {
logWarn("BUG: empty/null token!");
logDebug("Purchase data: " + purchaseData);
}
// Record ownership and token
inv.addPurchase(purchase);
}
else {
logWarn("Purchase signature verification **FAILED**. Not adding item.");
logDebug(" Purchase data: " + purchaseData);
logDebug(" Signature: " + signature);
verificationFailed = true;
}
}
continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN);
logDebug("Continuation token: " + continueToken);
} while (!TextUtils.isEmpty(continueToken));
return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK;
}
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
throws RemoteException, JSONException {
logDebug("Querying SKU details.");
ArrayList<String> skuList = new ArrayList<String>();
skuList.addAll(inv.getAllOwnedSkus(itemType));
if (moreSkus != null) {
for (String sku : moreSkus) {
if (!skuList.contains(sku)) {
skuList.add(sku);
}
}
}
if (skuList.size() == 0) {
logDebug("queryPrices: nothing to do because there are no SKUs.");
return BILLING_RESPONSE_RESULT_OK;
}
Bundle querySkus = new Bundle();
querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);
Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(),
itemType, querySkus);
if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
int response = getResponseCodeFromBundle(skuDetails);
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getSkuDetails() failed: " + getResponseDesc(response));
return response;
}
else {
logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
return IABHELPER_BAD_RESPONSE;
}
}
ArrayList<String> responseList = skuDetails.getStringArrayList(
RESPONSE_GET_SKU_DETAILS_LIST);
for (String thisResponse : responseList) {
SkuDetails d = new SkuDetails(itemType, thisResponse);
logDebug("Got sku details: " + d);
inv.addSkuDetails(d);
}
return BILLING_RESPONSE_RESULT_OK;
}
void consumeAsyncInternal(final List<Purchase> purchases,
final OnConsumeFinishedListener singleListener,
final OnConsumeMultiFinishedListener multiListener) {
final Handler handler = new Handler();
flagStartAsync("consume");
(new Thread(new Runnable() {
public void run() {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
}
catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (!mDisposed && singleListener != null) {
handler.post(new Runnable() {
public void run() {
singleListener.onConsumeFinished(purchases.get(0), results.get(0));
}
});
}
if (!mDisposed && multiListener != null) {
handler.post(new Runnable() {
public void run() {
multiListener.onConsumeMultiFinished(purchases, results);
}
});
}
}
})).start();
}
void logDebug(String msg) {
if (mDebugLog) Log.d(mDebugTag, msg);
}
void logError(String msg) {
Log.e(mDebugTag, "In-app billing error: " + msg);
}
void logWarn(String msg) {
Log.w(mDebugTag, "In-app billing warning: " + msg);
}
}
| gpl-3.0 |
drdrej/android-drafts-core | app/build/generated/source/buildConfig/androidTest/debug/com/touchableheroes/drafts/core/test/BuildConfig.java | 479 | /**
* Automatically generated file. DO NOT MODIFY
*/
package com.touchableheroes.drafts.core.test;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.touchableheroes.drafts.core.test";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| gpl-3.0 |
gamerforEA/EventHelper | src/main/java/com/gamerforea/eventhelper/cause/ICauseStackManager.java | 119 | package com.gamerforea.eventhelper.cause;
public interface ICauseStackManager
{
ICauseStackFrame pushCauseFrame();
}
| gpl-3.0 |
disappearTesting/workspace | JAVA/src/Examples/Circle.java | 1416 | package Examples;
/** Ïðîãðàììà-ìîäåëü îêðóæíîñòè íà êîîðäèíàòíîé ïëîñêîñòè.
* Ñîçäàííàÿ îêðóæíîñòü äîëæíà âûâîäèòüñÿ íà ýêðàí,
* ïåðåìåùàòüñÿ è ìàñøòàáèðîâàòüñÿ.
* @author hookie
* @version 1.0
*/
// Îòäåëüíûé íîâûé êëàññ
class myCircle {
// Ñâîéñòâà êëàññà
public double x; // Àáñöèññà öåíòðà
public double y; // Îðäèíàòà öåíòðà
public double r; // Ðàäèóñ îêðóæíîñòè
// Ìåòîä. Âûâîäèò íà ýêðàí ïàðàìåòðû îêðóæíîñòè
public void printCircle() {
System.out.println("Îêðóæíîñòü ñ öåòíîì ("+x+";"+y+") è ðàäèóñîì "+r);
}
// Ìåòîä. Ïåðåìåùåíèå îêðóæíîñòè, ñìåùåíèå öåòíðà îêðóæíîñòè
public void moveCircle(double a, double b) {
x = x + a;
y = y + b;
}
// Ìåòîä. Ìàñøòàáèðîâàíèå îêðóæíîñòè, ñ ïîìîùüþ êîýôèöèåíòà k
public void zoomCircle(double k) {
r = r * k;
}
}
//Îñíîâíîé êëàññ
public class Circle {
public static void main(String[] args) {
// Ñîçäàåì îáüåêò (îêðóæíîñòü) êëàññà Circle.
// Ðàäèóñ - 0.0, öåíòð â (0.0;0.0), - çíà÷åíèÿ ïî óìîë÷àíèþ
Circle o1 = new Circle();
// Âûâîä íà ýêðàí ïàðàìåòðîâ îêðóæíîñòè
o1.printCircle();
// Ìåíÿåì àáñöèññó öåíòðà
o1.x = 10;
// Ìåíÿåì ðàäèóñ
o1.r = 25;
// Âûâîä íà ýêðàí îáíîâëåííûõ ïàðàìåòðîâ îêðóæíîñòè
o1.printCircle();
// Ñîçäàíèå äðóãîãî îáüåêòà (îêðóæíîñòè) ýòîãî æå êëàññà
Circle o2 = new Circle();
o2.r = 3.14;
o2.zoomCircle(2.5);
o2.printCircle(); // Îêðóæíîñòü ñ öåíòðîì (0.0;0.0) è ðàäèóñîì 7.85
}
} | gpl-3.0 |