repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
crosslink/xowa
dev/400_xowa/src_490_xnde/gplx/xowa/Xop_xnde_wkr__include_basic_tst.java
4080
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012 gnosygnu@gmail.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 gplx.xowa; import gplx.*; import org.junit.*; public class Xop_xnde_wkr__include_basic_tst { private Xop_fxt fxt = new Xop_fxt(); @Before public void init() {fxt.Reset();} @Test public void Tmpl_includeonly() {fxt.Test_parse_tmpl_str_test("a<includeonly>b</includeonly>c" , "{{test}}", "abc");} @Test public void Tmpl_noinclude() {fxt.Test_parse_tmpl_str_test("a<noinclude>b</noinclude>c" , "{{test}}", "ac");} @Test public void Tmpl_onlyinclude() {fxt.Test_parse_tmpl_str_test("a<onlyinclude>b</onlyinclude>c" , "{{test}}", "b");} @Test public void Tmpl_onlyinclude_nest() {fxt.Test_parse_tmpl_str_test("{{#ifeq:y|y|a<onlyinclude>b</onlyinclude>c|n}}" , "{{test}}", "b");} // PURPOSE: check that onlyinclude handles (a) inside {{#if}} function (old engine did not); and (b) that abc are correctly added together @Test public void Tmpl_onlyinclude_page() {// PURPOSE: handle scenario similar to {{FA Number}} where # of articles is buried in page between onlyinclude tags; added noinclude as additional stress test fxt.Init_page_create("Transclude_1", "<noinclude>a<onlyinclude>b</onlyinclude>c</noinclude>d"); fxt.Test_parse_tmpl_str_test("{{:Transclude_1}}" , "{{test}}", "b"); } @Test public void Tmpl_onlyinclude_page2() { // PURPOSE: handle scenario similar to PS3 wherein onlyinclude was being skipped (somewhat correctly) but following text (<pre>) was also included fxt.Init_page_create("Transclude_2", "a<onlyinclude>b<includeonly>c</includeonly>d</onlyinclude>e<pre>f</pre>g"); fxt.Test_parse_tmpl_str_test("{{:Transclude_2}}" , "{{test}}", "bcd"); } @Test public void Tmpl_noinclude_unmatched() { // PURPOSE.fix: ignore unmatched </noinclude>; EX:fi.w:Sergio_Leone; DATE:2014-05-02 fxt.Test_parse_tmpl_str_test("{{{1|</noinclude>}}}", "{{test|a}}", "a"); // was "{{{test|" } @Test public void Wiki_includeonly() {fxt.Test_parse_page_all_str("a<includeonly>b</includeonly>c" , "ac");} @Test public void Wiki_noinclude() {fxt.Test_parse_page_all_str("a<noinclude>b</noinclude>c" , "abc");} @Test public void Wiki_onlyinclude() {fxt.Test_parse_page_all_str("a<onlyinclude>b</onlyinclude>c" , "abc");} @Test public void Wiki_oi_io() {fxt.Test_parse_page_all_str("a<onlyinclude>b<includeonly>c</includeonly>d</onlyinclude>e" , "abde");} @Test public void Wiki_oi_io_tblw() { fxt.Test_parse_page_all_str(String_.Concat_lines_nl_skip_last ( "<onlyinclude>" , "{|" , "|-" , "|a<includeonly>" , "|}</includeonly></onlyinclude>" , "|-" , "|b" , "|}" ), String_.Concat_lines_nl_skip_last ( "<table>" , " <tr>" , " <td>a" , " </td>" , " </tr>" , " <tr>" , " <td>b" , " </td>" , " </tr>" , "</table>" , "" )); } } /* <includeonly>-({{{1}}}={{{1}}}round-5)-({{{1}}}={{{1}}}round-4)-({{{1}}}={{{1}}}round-3)-({{{1}}}={{{1}}}round-2)-({{{1}}}={{{1}}}round-1)</includeonly><noinclude> {{pp-template}}Called by {{lt|precision/0}}</noinclude> ==includeonly== main: a<includeonly>b</includeonly>c<br/> tmpl: {{mwo_include_only|a|b|c}} ==noinclude== main: a<noinclude>b</noinclude>c<br/> tmpl: {{mwo_no_include|a|b|c}} ==onlyinclude== main: a<onlyinclude>b</onlyinclude>c<br/> tmpl: {{mwo_only_include|a|b|c}} */
agpl-3.0
fredericletellier/udacity-capstone
app/src/main/java/com/fredericletellier/foodinspector/data/source/remote/CountryCategoryRemoteDataSource.java
4316
/* * Food Inspector - Choose well to eat better * Copyright (C) 2016 Frédéric Letellier * * 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.fredericletellier.foodinspector.data.source.remote; import android.support.annotation.NonNull; import android.util.Log; import com.fredericletellier.foodinspector.data.CountryCategory; import com.fredericletellier.foodinspector.data.Search; import com.fredericletellier.foodinspector.data.source.CountryCategoryDataSource; import com.fredericletellier.foodinspector.data.source.remote.API.CountryCategoryNotExistException; import com.fredericletellier.foodinspector.data.source.remote.API.OpenFoodFactsAPIClient; import com.fredericletellier.foodinspector.data.source.remote.API.ServerUnreachableException; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.google.common.base.Preconditions.checkNotNull; public class CountryCategoryRemoteDataSource implements CountryCategoryDataSource { private static final String TAG = CountryCategoryRemoteDataSource.class.getName(); private static CountryCategoryRemoteDataSource INSTANCE; // Prevent direct instantiation. private CountryCategoryRemoteDataSource() { } public static CountryCategoryRemoteDataSource getInstance() { if (INSTANCE == null) { INSTANCE = new CountryCategoryRemoteDataSource(); } return INSTANCE; } /** * Gets the sumOfProducts from remote data source to complete CountryCategory data * <p/> * Note: {@link GetCountryCategoryCallback#onError(Throwable)} is fired if remote data sources fail to * get the data (HTTP error, IOException, IllegalStateException, ...) */ @Override public void getCountryCategory(@NonNull final String categoryKey, @NonNull final String countryKey, @NonNull final GetCountryCategoryCallback getCountryCategoryCallback) { checkNotNull(categoryKey); checkNotNull(countryKey); checkNotNull(getCountryCategoryCallback); OpenFoodFactsAPIClient openFoodFactsAPIClient = new OpenFoodFactsAPIClient(OpenFoodFactsAPIClient.ENDPOINT_SEARCH); Call<Search> call = openFoodFactsAPIClient.getCountryCategory(categoryKey, countryKey); call.enqueue(new Callback<Search>() { @Override public void onResponse(Call<Search> call, Response<Search> response) { if (!response.isSuccessful() || response.body() == null) { ServerUnreachableException e = new ServerUnreachableException(); Log.w(TAG, e); getCountryCategoryCallback.onError(e); return; } Search search = response.body(); if (search.getCount() == 0) { CountryCategoryNotExistException e = new CountryCategoryNotExistException(); Log.w(TAG, e); getCountryCategoryCallback.onError(e); return; } int sumOfProducts = search.getCount(); CountryCategory countryCategory = new CountryCategory(categoryKey, countryKey, sumOfProducts); getCountryCategoryCallback.onCountryCategoryLoaded(countryCategory); } @Override public void onFailure(Call<Search> call, Throwable t) { ServerUnreachableException e = new ServerUnreachableException(); Log.w(TAG, e); getCountryCategoryCallback.onError(e); } }); } }
agpl-3.0
Haakon-Lotveit/SmallObjects
src/main/java/no/smalltypes/telephone/norway/NorwegianLandlineNumber.java
3269
package no.smalltypes.telephone.norway; import java.util.regex.Matcher; import java.util.regex.Pattern; import no.smalltypes.telephone.IllegalPhoneNumberException; public final class NorwegianLandlineNumber extends NorwegianPhoneNumber { private static final Pattern pattern = Pattern.compile("(\\d{2})(\\d{2})(\\d{2})(\\d{2})"); private NorwegianLandlineNumber(String terseNumber, String localPrettyPrintedNumber) { super(terseNumber, localPrettyPrintedNumber); } /** * * This is one of the preferred ways to create a phone number that's a Norwegian landline. * Other methods should prefer to hand off a parsed string to this method. * * @param terseRepresentation This code expects a <i>terse representation</i> of the phone number. <br> * This means that the string must be either: * <ol> * <li> 8 characters long, and all digits </li> * <li> 11 characters long, and start with "+47"</li> * </lo> * In addition it must adhere to the Norwegian standards for landline numbers: * It must start with 2, 3, 5, 6, or 7.<br> <br> * @return a ready-built phone number. * @throws IllegalPhoneNumberException if there are any errors in building the phone number. */ public static NorwegianLandlineNumber of(final String terseRepresentation) { String normalized = normalizeNorwegianNumberOrThrow(terseRepresentation); NorwegianPhonenumberType.assertStringRepresentsCorrectPhoneNumberOrThrow(terseRepresentation, NorwegianPhonenumberType.Landline); Matcher matcher = pattern.matcher(normalized); matcher.matches(); String localPrettyPrintedNumber = String.format( "%s %s %s %s", matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4)); return new NorwegianLandlineNumber(normalized, localPrettyPrintedNumber); } /** * This is an incredibly lazy parser. If will look for numbers or a +, and proceed from there, trying to pick up digits until it has enough, * and then it will use the of-factory method. If the input is bad, the of method will complain. * TODO: This should probably be moved to the NorwegianPhoneNumber class, do a switch on the enumerated type, and then build from there. * We'd end up doing the classification twice, but that's okay. * @param text the text to be parsed. * @return a NorwegianLandLineNumber consisting of the digits you passed in. */ public static NorwegianLandlineNumber relaxedParser(String text) { StringBuilder picker = new StringBuilder(); // This makes subsequent processing simpler. for(char c : text.toCharArray()) { if("1234567890+".indexOf(c) != -1) { picker.append(c); } } if(picker.length() < 3) { throw new IllegalPhoneNumberException("There are less than 3 legal characters in '" + text + "'. Cannot create phone number"); } // This is clunky, but it essentially removes the +47 prefix if it exists, and removes + chars that are still left. String digits = (picker.toString().startsWith("+47")? picker.substring(3) : picker.toString()).replace("+", ""); if(digits.length() < 8) { throw new IllegalPhoneNumberException("There needs to be at least 8 legal digits for a landline, and '" + text + "' has only " + digits.length()); } return of(digits.substring(0,8)); } }
agpl-3.0
gnosygnu/xowa_android
_150_gfui/src/main/java/gplx/gfui/controls/GfuiBorderMgr.java
2676
package gplx.gfui.controls; import gplx.*; import gplx.gfui.*; import gplx.gfui.draws.*; import gplx.gfui.gfxs.*; import gplx.core.strings.*; public class GfuiBorderMgr { public PenAdp All() {return all;} public GfuiBorderMgr All_(PenAdp v) {SyncPens(true); all = v; return this;} PenAdp all; public PenAdp Left() {return left;} public GfuiBorderMgr Left_(PenAdp v) {SyncPens(false); left = v; return this;} PenAdp left; public PenAdp Right() {return right;} public GfuiBorderMgr Right_(PenAdp v) {SyncPens(false); right = v; return this;} PenAdp right; public PenAdp Top() {return top;} public GfuiBorderMgr Top_(PenAdp v) {SyncPens(false); top = v; return this;} PenAdp top; public PenAdp Bot() {return bot;} public GfuiBorderMgr Bot_(PenAdp v) {SyncPens(false); bot = v; return this;} PenAdp bot; public void Bounds_sync(RectAdp v) {bounds = v;} RectAdp bounds = RectAdp_.Zero; public void DrawData(GfxAdp gfx) { if (all != null) gfx.DrawRect(all, bounds); else { if (left != null) gfx.DrawLine(left, bounds.CornerBL(), bounds.CornerTL()); if (right != null) gfx.DrawLine(right, bounds.CornerTR(), bounds.CornerBR()); if (top != null) gfx.DrawLine(top, bounds.CornerTL(), bounds.CornerTR()); if (bot != null) gfx.DrawLine(bot, bounds.CornerBR(), bounds.CornerBL()); } } public GfuiBorderMgr None_() {Edge_set(GfuiBorderEdge.All, null); return this;} public void Edge_setObj(Object o) { if (o == null) this.None_(); else { Object[] ary = (Object[])o; this.Edge_set(GfuiBorderEdge.All, PenAdp_.new_((ColorAdp)ary[1], Float_.cast(ary[0]))); } } public void Edge_set(GfuiBorderEdge edge, PenAdp pen) { int val = edge.Val(); if (val == GfuiBorderEdge.All.Val()) {all = pen; return;} else if (val == GfuiBorderEdge.Left.Val()) {left = pen; return;} else if (val == GfuiBorderEdge.Right.Val()) {right = pen; return;} else if (val == GfuiBorderEdge.Top.Val()) {top = pen; return;} else if (val == GfuiBorderEdge.Bot.Val()) {bot = pen; return;} else throw Err_.new_unhandled(edge); } void SyncPens(boolean isAll) { if (isAll) { left = null; right = null; top = null; bot = null; } else { if (all != null) { left = all.Clone(); right = all.Clone(); top = all.Clone(); bot = all.Clone(); } all = null; } } public String To_str() {return String_bldr_.new_().Add_kv_obj("all", all).Add_kv_obj("left", left).Add_kv_obj("right", right).Add_kv_obj("top", top).Add_kv_obj("bot", bot).To_str();} @Override public String toString() {return To_str();} public static GfuiBorderMgr new_() {return new GfuiBorderMgr();} GfuiBorderMgr() {} }
agpl-3.0
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/application/Application.java
18455
/* * Application.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.application; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.RunAsyncCallback; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.rstudio.core.client.Debug; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.widget.Operation; import org.rstudio.studio.client.application.events.*; import org.rstudio.studio.client.application.model.SessionSerializationAction; import org.rstudio.studio.client.application.ui.RequestLogVisualization; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.satellite.SatelliteManager; import org.rstudio.studio.client.projects.Projects; import org.rstudio.studio.client.server.*; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.workbench.ClientStateUpdater; import org.rstudio.studio.client.workbench.Workbench; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.events.SessionInitEvent; import org.rstudio.studio.client.workbench.model.Agreement; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.source.editors.text.themes.AceThemes; @Singleton public class Application implements ApplicationEventHandlers { public interface Binder extends CommandBinder<Commands, Application> {} @Inject public Application(ApplicationView view, GlobalDisplay globalDisplay, EventBus events, Binder binder, Commands commands, Server server, Session session, Projects projects, SatelliteManager satelliteManager, ApplicationUncaughtExceptionHandler uncaughtExHandler, Provider<UIPrefs> uiPrefs, Provider<Workbench> workbench, Provider<EventBus> eventBusProvider, Provider<ClientStateUpdater> clientStateUpdater, Provider<ApplicationClientInit> pClientInit, Provider<AceThemes> pAceThemes) { // save references view_ = view ; globalDisplay_ = globalDisplay; events_ = events; session_ = session; commands_ = commands; satelliteManager_ = satelliteManager; clientStateUpdater_ = clientStateUpdater; server_ = server; uiPrefs_ = uiPrefs; workbench_ = workbench; eventBusProvider_ = eventBusProvider; pClientInit_ = pClientInit; pAceThemes_ = pAceThemes; // bind to commands binder.bind(commands_, this); // register as main window satelliteManager.initialize(); // subscribe to events events.addHandler(LogoutRequestedEvent.TYPE, this); events.addHandler(UnauthorizedEvent.TYPE, this); events.addHandler(ReloadEvent.TYPE, this); events.addHandler(QuitEvent.TYPE, this); events.addHandler(SuicideEvent.TYPE, this); events.addHandler(SessionAbendWarningEvent.TYPE, this); events.addHandler(SessionSerializationEvent.TYPE, this); events.addHandler(ServerUnavailableEvent.TYPE, this); events.addHandler(InvalidClientVersionEvent.TYPE, this); events.addHandler(ServerOfflineEvent.TYPE, this); // register for uncaught exceptions uncaughtExHandler.register(); } public void go(RootLayoutPanel rootPanel, final Command dismissLoadingProgress) { Widget w = view_.getWidget(); rootPanel.add(w); rootPanel.setWidgetTopBottom(w, 0, Style.Unit.PX, 0, Style.Unit.PX); rootPanel.setWidgetLeftRight(w, 0, Style.Unit.PX, 0, Style.Unit.PX); // attempt init pClientInit_.get().execute( new ServerRequestCallback<SessionInfo>() { public void onResponseReceived(final SessionInfo sessionInfo) { // initialize workbench after verifying agreement verifyAgreement(sessionInfo, new Operation() { public void execute() { dismissLoadingProgress.execute(); session_.setSessionInfo(sessionInfo); // configure workbench initializeWorkbench(); } }); } public void onError(ServerError error) { Debug.logError(error); dismissLoadingProgress.execute(); globalDisplay_.showErrorMessage("RStudio Initialization Error", error.getUserMessage()); } }) ; } @Handler public void onShowToolbar() { setToolbarPref(true); } @Handler public void onHideToolbar() { setToolbarPref(false); } @Handler public void onGoToFileFunction() { view_.performGoToFunction(); } public void onUnauthorized(UnauthorizedEvent event) { navigateToSignIn(); } public void onServerOffline(ServerOfflineEvent event) { cleanupWorkbench(); view_.showApplicationOffline(); } public void onLogoutRequested(LogoutRequestedEvent event) { navigateWindowTo("auth-sign-out"); } @Handler public void onHelpUsingRStudio() { String customDocsURL = session_.getSessionInfo().docsURL(); if (customDocsURL.length() > 0) globalDisplay_.openWindow(customDocsURL); else globalDisplay_.openRStudioLink("docs"); } @Handler public void onHelpKeyboardShortcuts() { openApplicationURL("docs/keyboard.htm"); } private void showAgreement() { globalDisplay_.openWindow(server_.getApplicationURL("agreement")); } @Handler public void onRstudioSupport() { globalDisplay_.openRStudioLink("support"); } @Handler public void onRstudioLicense() { showAgreement(); } @Handler public void onRstudioAgreement() { showAgreement(); } @Handler public void onUpdateCredentials() { server_.updateCredentials(); } @Handler public void onRaiseException() { throw new RuntimeException("foo"); } @Handler public final native void onRaiseException2() /*-{ $wnd.welfkjweg(); }-*/; @Handler public void onShowRequestLog() { GWT.runAsync(new RunAsyncCallback() { public void onFailure(Throwable reason) { Window.alert(reason.toString()); } public void onSuccess() { final RequestLogVisualization viz = new RequestLogVisualization( server_); final RootLayoutPanel root = RootLayoutPanel.get(); root.add(viz); root.setWidgetTopBottom(viz, 10, Unit.PX, 10, Unit.PX); root.setWidgetLeftRight(viz, 10, Unit.PX, 10, Unit.PX); viz.addCloseHandler(new CloseHandler<RequestLogVisualization>() { public void onClose(CloseEvent<RequestLogVisualization> event) { root.remove(viz); } }); } }); } @Handler public void onLogFocusedElement() { Element el = DomUtils.getActiveElement(); DomUtils.dump(el, "Focused Element: "); } public void onSessionSerialization(SessionSerializationEvent event) { switch(event.getAction().getType()) { case SessionSerializationAction.LOAD_DEFAULT_WORKSPACE: view_.showSerializationProgress( "Loading workspace" + getSuffix(event), false, // non-modal, appears to user as std latency 500, // willing to show progress earlier since // this will always be at workbench startup 0); // no timeout break; case SessionSerializationAction.SAVE_DEFAULT_WORKSPACE: view_.showSerializationProgress( "Saving workspace image" + getSuffix(event), true, // modal, inputs will fall dead anyway 0, // show immediately 0); // no timeout break; case SessionSerializationAction.SUSPEND_SESSION: view_.showSerializationProgress( "Backing up R session...", true, // modal, inputs will fall dead anyway 0, // show immediately 60000); // timeout after 60 seconds. this is done // in case the user suspends or loses // connectivity during the backup (in which // case the 'completed' event dies with // server and is never received by the client break; case SessionSerializationAction.RESUME_SESSION: view_.showSerializationProgress( "Resuming R session...", false, // non-modal, appears to user as std latency 2000, // don't show this for reasonable restore time // (happens inline while using a running // workbench so be more conservative) 0); // no timeout break; case SessionSerializationAction.COMPLETED: view_.hideSerializationProgress(); break; } } private String getSuffix(SessionSerializationEvent event) { SessionSerializationAction action = event.getAction(); String targetPath = action.getTargetPath(); if (targetPath != null) { String verb = " from "; if (action.getType() == SessionSerializationAction.SAVE_DEFAULT_WORKSPACE) verb = " to "; return verb + targetPath + "..."; } else { return "..."; } } public void onServerUnavailable(ServerUnavailableEvent event) { view_.hideSerializationProgress(); } public void onReload(ReloadEvent event) { cleanupWorkbench(); Window.Location.reload(); } public void onQuit(QuitEvent event) { cleanupWorkbench(); // only show the quit state in server mode (desktop mode has its // own handling triggered to process exit) if (!Desktop.isDesktop()) { // if we are switching projects then reload after a delay (to allow // the R session to fully exit on the server) if (event.getSwitchProjects()) { new Timer() { @Override public void run() { Window.Location.reload(); } }.schedule(100); } else { view_.showApplicationQuit(); } } } public void onSuicide(SuicideEvent event) { cleanupWorkbench(); view_.showApplicationSuicide(event.getMessage()); } public void onClientDisconnected(ClientDisconnectedEvent event) { cleanupWorkbench(); view_.showApplicationDisconnected(); } public void onInvalidClientVersion(InvalidClientVersionEvent event) { cleanupWorkbench(); view_.showApplicationUpdateRequired(); } public void onSessionAbendWarning(SessionAbendWarningEvent event) { view_.showSessionAbendWarning(); } private void verifyAgreement(SessionInfo sessionInfo, final Operation verifiedOperation) { // get the agreeeent (if any) final Agreement agreement = sessionInfo.pendingAgreement(); // if there is an agreement then prompt user for agreement (otherwise just // execute the verifiedOperation immediately) if (agreement != null) { // append updated to the title if necessary String title = agreement.getTitle(); if (agreement.getUpdated()) title += " (Updated)"; view_.showApplicationAgreement( // title and contents title, agreement.getContents(), // bail to sign in page if the user doesn't confirm new Operation() { public void execute() { if (Desktop.isDesktop()) { server_.quitSession(false, null, new SimpleRequestCallback<Void>()); } else navigateToSignIn(); } }, // user confirmed new Operation() { public void execute() { // call verified operation verifiedOperation.execute(); // record agreement on server server_.acceptAgreement(agreement, new VoidServerRequestCallback()); } } ); } else { // no agreement pending verifiedOperation.execute(); } } private void navigateWindowTo(String relativeUrl) { cleanupWorkbench(); String url = GWT.getHostPageBaseURL() + relativeUrl; Window.Location.replace(url); } private void openApplicationURL(String relativeURL) { String url = GWT.getHostPageBaseURL() + relativeURL; globalDisplay_.openWindow(url); } private void initializeWorkbench() { pAceThemes_.get(); // subscribe to ClientDisconnected event (wait to do this until here // because there were spurious ClientDisconnected events occuring // after a session interrupt sequence. we couldn't figure out why, // and since this is a temporary hack why not add another temporary // hack to go with it here :-) // TOOD: move this back tot he constructor after we revise the // interrupt hack(s) events_.addHandler(ClientDisconnectedEvent.TYPE, this); // create workbench Workbench wb = workbench_.get(); eventBusProvider_.get().fireEvent(new SessionInitEvent()) ; // hide the agreement menu item if we don't have one if (!session_.getSessionInfo().hasAgreement()) commands_.rstudioAgreement().setVisible(false); // show workbench view_.showWorkbenchView(wb.getMainView().asWidget()); // toolbar (must be after call to showWorkbenchView because // showing the toolbar repositions the workbench view widget) showToolbar( uiPrefs_.get().toolbarVisible().getValue()); // sync to changes in the toolbar visibility state uiPrefs_.get().toolbarVisible().addValueChangeHandler( new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { showToolbar(event.getValue()); } }); clientStateUpdaterInstance_ = clientStateUpdater_.get(); } private void setToolbarPref(boolean showToolbar) { uiPrefs_.get().toolbarVisible().setGlobalValue(showToolbar); uiPrefs_.get().writeUIPrefs(); } private void showToolbar(boolean showToolbar) { // show or hide the toolbar view_.showToolbar(showToolbar); // manage commands commands_.showToolbar().setVisible(!showToolbar); commands_.hideToolbar().setVisible(showToolbar); } private void cleanupWorkbench() { server_.disconnect(); satelliteManager_.closeAllSatellites(); if (clientStateUpdaterInstance_ != null) { clientStateUpdaterInstance_.suspend(); clientStateUpdaterInstance_ = null; } } private void navigateToSignIn() { navigateWindowTo("auth-sign-in"); } private final ApplicationView view_ ; private final GlobalDisplay globalDisplay_ ; private final EventBus events_; private final Session session_; private final Commands commands_; private final SatelliteManager satelliteManager_; private final Provider<ClientStateUpdater> clientStateUpdater_; private final Server server_; private final Provider<UIPrefs> uiPrefs_; private final Provider<Workbench> workbench_; private final Provider<EventBus> eventBusProvider_; private final Provider<ApplicationClientInit> pClientInit_; private final Provider<AceThemes> pAceThemes_; private ClientStateUpdater clientStateUpdaterInstance_; }
agpl-3.0
stevansen/MySasa
MySasa_Web/src/it/unibz/mysasa/domain/PercorsoLine.java
479
package it.unibz.mysasa.domain; import it.unibz.mysasa.util.Tools; public class PercorsoLine { private String LI_NR = null; private PercorsoRotta[] varlist = null; public String getLineNr() { return LI_NR; } public void setLineNr(String lI_NR) { LI_NR = lI_NR; } public PercorsoRotta[] getRotta() { return varlist; } public void setRotta(PercorsoRotta[] varlist) { this.varlist = varlist; } public Integer getLiNr() { return Tools.getInt(LI_NR); } }
agpl-3.0
safety-data/talismane
talismane_machine_learning/src/main/java/com/joliciel/talismane/machineLearning/features/GreaterThanIntegerOperator.java
2779
/////////////////////////////////////////////////////////////////////////////// //Copyright (C) 2014 Joliciel Informatique // //This file is part of Talismane. // //Talismane 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. // //Talismane 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 Talismane. If not, see <http://www.gnu.org/licenses/>. ////////////////////////////////////////////////////////////////////////////// package com.joliciel.talismane.machineLearning.features; /** * Returns operand1 &gt; operand2. * @author Assaf Urieli * */ public class GreaterThanIntegerOperator<T> extends AbstractCachableFeature<T,Boolean> implements BooleanFeature<T> { private IntegerFeature<T> operand1; private IntegerFeature<T> operand2; public GreaterThanIntegerOperator(IntegerFeature<T> operand1, IntegerFeature<T> operand2) { super(); this.operand1 = operand1; this.operand2 = operand2; this.setName("(" + operand1.getName() + ">" + operand2.getName() + ")"); } @Override protected FeatureResult<Boolean> checkInternal(T context, RuntimeEnvironment env) { FeatureResult<Boolean> featureResult = null; FeatureResult<Integer> operand1Result = operand1.check(context, env); FeatureResult<Integer> operand2Result = operand2.check(context, env); if (operand1Result!=null && operand2Result!=null) { boolean result = operand1Result.getOutcome() > operand2Result.getOutcome(); featureResult = this.generateResult(result); } return featureResult; } @Override public boolean addDynamicSourceCode(DynamicSourceCodeBuilder<T> builder, String variableName) { String operand1Name = builder.addFeatureVariable(operand1, "operand"); String operand2Name = builder.addFeatureVariable(operand2, "operand"); builder.append("if (" + operand1Name + "!=null && " + operand2Name + "!=null) {"); builder.indent(); builder.append(variableName + "=" + operand1Name + ">" + operand2Name + ";"); builder.outdent(); builder.append("}"); return true; } public IntegerFeature<T> getOperand1() { return operand1; } public void setOperand1(IntegerFeature<T> operand1) { this.operand1 = operand1; } public IntegerFeature<T> getOperand2() { return operand2; } public void setOperand2(IntegerFeature<T> operand2) { this.operand2 = operand2; } }
agpl-3.0
jamesunger/muteswan
android/muteswan/src/org/muteswan/client/data/CircleStore.java
6491
/* Copyright 2011-2012 James Unger, Chris Churnick. This file is part of Muteswan. Muteswan 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. Muteswan 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 Muteswan. If not, see <http://www.gnu.org/licenses/>. */ package org.muteswan.client.data; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import org.muteswan.client.Main; import org.muteswan.client.MuteLog; import org.muteswan.client.MuteswanHttp; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; @SuppressWarnings("serial") final public class CircleStore extends LinkedList<Circle> { public static boolean libsLoaded = false; public Context context; private MuteswanHttp muteswanHttp; private String cipherSecret; private SharedPreferences prefs; public CircleStore(String secret, Context applicationContext, boolean readDb, boolean initCache, MuteswanHttp muteswanHttp) { MuteLog.Log("CircleStore", "Circle store called!"); context = applicationContext; this.muteswanHttp = muteswanHttp; this.cipherSecret = secret; prefs = context.getSharedPreferences("circles",0); MuteLog.Log("CircleStore", "Circle store is " + cipherSecret); if (readDb && initCache) { initStore(muteswanHttp,true); } else if (readDb) { initStore(muteswanHttp,false); } } public CircleStore(String secret, Context applicationContext, boolean readDb, boolean initCache) { MuteLog.Log("CircleStore", "Circle store called!"); context = applicationContext; this.cipherSecret = secret; prefs = context.getSharedPreferences("circles",0); if (readDb && initCache) { initStore(true); } else if (readDb) { initStore(false); } } public CircleStore(String cipherSecret,Context applicationContext) { context = applicationContext; this.cipherSecret = cipherSecret; prefs = context.getSharedPreferences("circles",0); } final public void deleteCircle(Circle circle) { if (cipherSecret == null) { MuteLog.Log("Circle", "Error: refusing use database with null cipherSecret"); return; } prefs.edit().remove(Main.genHexHash(circle.getFullText())).commit(); circle.deleteAllMessages(true); } final public String getAsString() { String returnString = ""; for (Circle r : this) { returnString = returnString + r.getFullText() + "---"; } return(returnString); } private void initStore(MuteswanHttp muteswanHttp, boolean initCache) { if (cipherSecret == null) { MuteLog.Log("Circle", "Error: refusing use database with null cipherSecret"); return; } MuteLog.Log("CIPHER", "Initialize circle store with " + cipherSecret); Map<String, ?> allCircles = prefs.getAll(); for (String cir : allCircles.keySet()) { //Circle r = new Circle(cipherSecret,context,cir); //add(r); String circleText = (String) allCircles.get(cir); try { JSONObject jsonObject = new JSONObject(circleText); Circle r = new Circle(cipherSecret,context,jsonObject,muteswanHttp); add(r); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //FIXME decrypt } } private void initStore(boolean initCache) { if (cipherSecret == null) { MuteLog.Log("Circle", "Error: refusing use database with null cipherSecret"); return; } MuteLog.Log("CIPHER", "Initialize circle store with " + cipherSecret); Map<String, ?> allCircles = prefs.getAll(); for (String cir : allCircles.keySet()) { String circleText = (String) allCircles.get(cir); try { JSONObject jsonObject = new JSONObject(circleText); Circle r = new Circle(cipherSecret,context,jsonObject); add(r); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void updateStore(String contents) { Circle circle = new Circle(cipherSecret,context,contents); for (Circle r : this) { if (r.getFullText().equals(contents)) { return; } } addCircleToDb(circle); } public void updateStore(String key, String uuid, String shortname, String server) { Circle circle = new Circle(cipherSecret,context,key,uuid,shortname,server); for (Circle r : this) { if (r.getKey().equals(key) && r.getShortname().equals(shortname) && r.getServer().equals(server)) { return; } } addCircleToDb(circle); } private void addCircleToDb(Circle circle) { if (cipherSecret == null) { MuteLog.Log("Circle", "Error: refusing use database with null cipherSecret"); return; } JSONObject jsonObject = circle.getCryptJSON(cipherSecret); prefs.edit().putString(Main.genHexHash(circle.getFullText()), jsonObject.toString()).commit(); circle.createLastMessage(0); add(circle); } public HashMap<String,Circle> asHashMap() { HashMap<String,Circle> map = new HashMap<String,Circle>(); for (Circle r : this) { map.put(Main.genHexHash(r.getFullText()), r); } return map; } public boolean containsShortname(String shortname) { for (Circle r : this) { if (r.getShortname().contains(shortname)) { return true; } } return false; } public Set<String> getUniqServers() { HashMap<String,String> map = new HashMap<String,String>(); CIRCLE: for (Circle r : this) { for (String s : map.keySet()) { if (s.equals(r.getServer())) { continue CIRCLE; } } map.put(r.getServer(), ""); } return map.keySet(); } }
agpl-3.0
crosslink/xowa
dev/110_gfml/src_300_gdoc/gplx/gfml/GfmlScopeItm.java
2570
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012 gnosygnu@gmail.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 gplx.gfml; import gplx.*; interface GfmlScopeItm { String Key(); GfmlDocPos DocPos(); } class GfmlScopeRegy { public boolean Has(String key) { GfmlScopeList list = (GfmlScopeList)hash.Fetch(key); if (list == null) return false; return list.Count() > 0; } public void Add(GfmlScopeItm itm) { GfmlScopeList list = ItmOrNew(itm.Key()); list.Add(itm); } public void Del(GfmlScopeItm itm) { GfmlScopeList list = (GfmlScopeList)hash.Fetch(itm.Key()); if (list == null) return; list.Del(itm); if (list.Count() == 0) hash.Del(itm.Key()); } public GfmlScopeItm Fetch(String key, GfmlDocPos pos) { GfmlScopeList list = (GfmlScopeList)hash.Fetch(key); if (list == null) return null; return list.Fetch(pos); } GfmlScopeList ItmOrNew(String key) { GfmlScopeList rv = (GfmlScopeList)hash.Fetch(key); if (rv == null) { rv = GfmlScopeList.new_(key); hash.Add(key, rv); } return rv; } HashAdp hash = HashAdp_.new_(); public static GfmlScopeRegy new_() {return new GfmlScopeRegy();} } class GfmlScopeList { public String Key() {return key;} private String key; public int Count() {return list.Count();} public void Add(GfmlScopeItm itm) {list.Add(itm);} public void Del(GfmlScopeItm itm) {list.Del(itm);} public GfmlScopeItm Fetch(GfmlDocPos pos) { if (list.Count() == 0) return null; GfmlScopeItm rv = null; for (Object itemObj : list) { GfmlScopeItm itm = (GfmlScopeItm)itemObj; if (CompareAble_.Is_moreOrSame(pos, itm.DocPos())) rv = itm; else break; // ASSUME: insertion is done in order; first lessThan means rest will also be lessThan } return rv; } ListAdp list = ListAdp_.new_(); public static GfmlScopeList new_(String key) { GfmlScopeList rv = new GfmlScopeList(); rv.key = key; return rv; } GfmlScopeList() {} }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-ar/src/main/java/org/kuali/kfs/module/ar/service/impl/CustomerViewServiceImpl.java
5950
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * 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 org.kuali.kfs.module.ar.service.impl; import org.apache.commons.collections.CollectionUtils; import org.kuali.kfs.integration.ar.AccountsReceivableModuleBillingService; import org.kuali.kfs.kns.web.ui.Field; import org.kuali.kfs.kns.web.ui.Row; import org.kuali.kfs.kns.web.ui.Section; import org.kuali.kfs.krad.util.ObjectUtils; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.service.CustomerViewService; import org.kuali.kfs.sys.service.NonTransactional; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Implementation of the Customer View Service. */ @NonTransactional public class CustomerViewServiceImpl implements CustomerViewService { protected AccountsReceivableModuleBillingService accountsReceivableModuleBillingService; /** * @see org.kuali.kfs.module.ar.service.CustomerViewService#getSections(java.util.List) */ @Override public List getSections(List<Section> sections) { if (!getAccountsReceivableModuleBillingService().isContractsGrantsBillingEnhancementActive()) { for (Iterator<Section> it = sections.iterator(); it.hasNext(); ) { Section section = it.next(); if (getSectionsToIgnore().contains(section.getSectionId())) { it.remove(); } else { for (Row row : section.getRows()) { row.setFields(getFieldsToDisplay(row)); } } } } return sections; } /** * Go through the fields in the row, filtering out the ones we want to ignore * and returning a new list of fields to display. * * @param row contains fields to process * @return List of fields to display */ protected List<Field> getFieldsToDisplay(Row row) { List<Field> fieldsToDisplay = new ArrayList<Field>(); for (Field field : row.getFields()) { if (field.getCONTAINER().equalsIgnoreCase(field.getFieldType())) { List<Row> containerRowsToDisplay = getContainerRowsToDisplay(field); if (CollectionUtils.isNotEmpty(containerRowsToDisplay)) { field.setContainerRows(containerRowsToDisplay); fieldsToDisplay.add(field); } } else if (!getFieldsToIgnore().contains(field.getPropertyName())) { fieldsToDisplay.add(field); } } return fieldsToDisplay; } /** * For a Container Field, go through the container rows and filter out any fields * we don't want to display. * * @param field container field to process * @return List of container rows to display */ protected List<Row> getContainerRowsToDisplay(Field field) { List<Row> containerRowsToDisplay = new ArrayList<Row>(); for (Row containerRow : field.getContainerRows()) { List<Field> updatedContainerRowFields = new ArrayList<Field>(); for (Field containerRowfield : containerRow.getFields()) { if (!getFieldsToIgnore().contains(ObjectUtils.getNestedAttributePrimitive(containerRowfield.getPropertyName()))) { updatedContainerRowFields.add(containerRowfield); } } if (CollectionUtils.isNotEmpty(updatedContainerRowFields)) { containerRow.setFields(updatedContainerRowFields); containerRowsToDisplay.add(containerRow); } } return containerRowsToDisplay; } /** * Return list of section ids to ignore if the Contracts & Grants Billing (CGB) enhancement is disabled. * * @return list of sections to ignore */ protected List<String> getSectionsToIgnore() { List<String> sectionsToIgnore = new ArrayList<String>(); sectionsToIgnore.add(ArPropertyConstants.SectionId.CUSTOMER_COLLECTIONS_SECTION_ID); return sectionsToIgnore; } /** * Return list of fields to ignore if the Contracts & Grants Billing (CGB) enhancement is disabled. * * @return list of fields to ignore */ protected List<String> getFieldsToIgnore() { List<String> fieldsToIgnore = new ArrayList<String>(); fieldsToIgnore.add(ArPropertyConstants.CustomerFields.CUSTOMER_INVOICE_TEMPLATE_CODE); fieldsToIgnore.add(ArPropertyConstants.INVOICE_TRANSMISSION_METHOD_CODE); fieldsToIgnore.add(ArPropertyConstants.CustomerFields.CUSTOMER_COPIES_TO_PRINT); fieldsToIgnore.add(ArPropertyConstants.CustomerFields.CUSTOMER_ENVELOPES_TO_PRINT_QUANTITY); return fieldsToIgnore; } public AccountsReceivableModuleBillingService getAccountsReceivableModuleBillingService() { return accountsReceivableModuleBillingService; } public void setAccountsReceivableModuleBillingService(AccountsReceivableModuleBillingService accountsReceivableModuleBillingService) { this.accountsReceivableModuleBillingService = accountsReceivableModuleBillingService; } }
agpl-3.0
jredden/cosmos
src/main/java/com/zenred/cosmos/Star.java
3236
//Source file: C:/VisualCafe/JAVA/LIB/com.zenred.cosmos/Star.java package com.zenred.cosmos; import java.util.Enumeration; import java.util.ArrayList; import java.util.List; import com.zenred.util.OrderedListCollection; import com.zenred.util.OrderedArrayListCollection; import com.zenred.util.AnonBlock; public class Star { private Enumeration type; private DrawRolls drawrolls; private ArrayList<StarSpread> drawlist; private static final boolean DEBUG = true; // private static final boolean DEBUG = false; // finals to bugger up anonymous class private StarSpread found_star_profile; private int draw; /** * construction - no arguments */ public Star() { initStarList(); } /** * construction - avec seed */ public Star(long seed_random) { drawrolls = new DrawRolls(seed_random); initStarList(); } /** * construction extention */ private void initStarList() { drawlist = new ArrayList<StarSpread>(); for (int idex = 0; idex < InSystemConstraintsIF.STARCONFIGS.length; idex++) { if (DEBUG) System.out.println("idex::" + idex + "::"); drawlist.add(idex, new StarSpread( InSystemConstraintsIF.STARNUM[idex], InSystemConstraintsIF.STARMAX[idex], InSystemConstraintsIF.STARMIN[idex], InSystemConstraintsIF.STARCONFIGS[idex])); } } /** * see if a range is matched * * @param - range */ private boolean testDraw(Object starspread, int draw) { if (DEBUG) System.out .println("testDraw:" + starspread.toString() + ":" + draw); boolean _min = ((StarSpread) starspread).getMinRangeOnDraw() <= draw; boolean _max = ((StarSpread) starspread).getMaxRangeOnDraw() >= draw; return (_min && _max) ? true : false; } /** * gen_star_prile draws a random number and * * @return Star profile that matches draw */ private StarSpread get_star_profile() { for(StarSpread starSpread : drawlist){ if (testDraw(starSpread, draw)) { found_star_profile = starSpread; break; } } /* final int draw = _draw; System.out.println("<<<draw:"+draw+">>>"); found_star_profile[0] = null; drawlist.forEachDo(new AnonBlock() { public void exec(Object each) { if (testDraw(each, draw)) { found_star_profile[0] = (StarSpread) each; return; } } }); */ return found_star_profile; } /** * genStars returns a list of cluster reps - where each clusterrep is a ClusterRep object */ public List<ClusterRep> genStars() { StarSpreadConstraint starspreadconstraint = new StarSpreadConstraint(); if (DEBUG) System.out.println("Gen UnderConstraint"); drawrolls = new DrawRolls(); for(int idex = 0;idex < 2 ;idex++){ drawrolls.getD1000(); // give it a kick, don't know why it gets non-random. //System.out.println("next:"+drawrolls.getD1000()); } this.draw = drawrolls.getD1000(); System.out.println("<<<draw:"+this.draw+">>>"); starspreadconstraint.genUnderConstraint(get_star_profile()); List<ClusterRep> _list = starspreadconstraint.getListOfClusters(); return _list; } /** * test */ public static void main(String[] Argv) { Star star = new Star(); List _star_list = star.genStars(); if (DEBUG) System.out.println("<" + _star_list.size() + ">"); } }
agpl-3.0
ArsenShnurkov/libreplan
libreplan-business/src/main/java/org/libreplan/business/planner/entities/GenericDayAssignment.java
7343
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * 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 org.libreplan.business.planner.entities; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.Validate; import org.hibernate.validator.NotNull; import org.joda.time.LocalDate; import org.libreplan.business.common.BaseEntity; import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.scenarios.entities.Scenario; import org.libreplan.business.util.deepcopy.OnCopy; import org.libreplan.business.util.deepcopy.Strategy; import org.libreplan.business.workingday.EffortDuration; /** * * @author Diego Pino García <dpino@igalia.com> * */ public class GenericDayAssignment extends DayAssignment { private abstract class ParentState { abstract GenericResourceAllocation getResourceAllocation(); abstract ParentState setParent( GenericResourceAllocation genericResourceAllocation); abstract ParentState setParent(GenericDayAssignmentsContainer container); abstract Scenario getScenario(); } private class ContainerNotSpecified extends ParentState { private GenericResourceAllocation parent; @Override GenericResourceAllocation getResourceAllocation() { return parent; } @Override ParentState setParent( GenericResourceAllocation genericResourceAllocation) { if (parent != null && parent != genericResourceAllocation) { throw new IllegalStateException( "the allocation cannot be changed once it has been set"); } this.parent = genericResourceAllocation; return this; } @Override ParentState setParent(GenericDayAssignmentsContainer container) { return new OnContainer(container); } @Override Scenario getScenario() { return null; } } private class OnContainer extends ParentState { OnContainer(GenericDayAssignmentsContainer container) { Validate.notNull(container); GenericDayAssignment.this.container = container; } public OnContainer() { } @Override GenericResourceAllocation getResourceAllocation() { return container.getResourceAllocation(); } @Override ParentState setParent( GenericResourceAllocation genericResourceAllocation) { throw new IllegalStateException("parent already set"); } @Override ParentState setParent(GenericDayAssignmentsContainer container) { throw new IllegalStateException("parent already set"); } @Override Scenario getScenario() { return container.getScenario(); } } public static GenericDayAssignment create(LocalDate day, EffortDuration duration, Resource resource) { return create(new GenericDayAssignment(day, duration, resource)); } public static Set<GenericDayAssignment> copy( GenericDayAssignmentsContainer newParent, Collection<? extends GenericDayAssignment> assignemnts) { Set<GenericDayAssignment> result = new HashSet<GenericDayAssignment>(); for (GenericDayAssignment a : assignemnts) { GenericDayAssignment created = copy(newParent, a); created.associateToResource(); result.add(created); } return result; } private static GenericDayAssignment copy( GenericDayAssignmentsContainer newParent, GenericDayAssignment toBeCopied) { GenericDayAssignment result = copyFromWithoutParent(toBeCopied); result.setConsolidated(toBeCopied.isConsolidated()); result.parentState = result.parentState.setParent(newParent); result.associateToResource(); return result; } private static GenericDayAssignment copyFromWithoutParent( GenericDayAssignment toBeCopied) { GenericDayAssignment copy = create(toBeCopied.getDay(), toBeCopied.getDuration(), toBeCopied.getResource()); copy.setConsolidated(toBeCopied.isConsolidated()); return copy; } public static List<GenericDayAssignment> copyToAssignmentsWithoutParent( Collection<? extends GenericDayAssignment> assignments) { List<GenericDayAssignment> result = new ArrayList<GenericDayAssignment>(); for (GenericDayAssignment each : assignments) { result.add(copyFromWithoutParent(each)); } return result; } private GenericDayAssignment(LocalDate day, EffortDuration duration, Resource resource) { super(day, duration, resource); parentState = new ContainerNotSpecified(); } /** * Constructor for hibernate. DO NOT USE! */ public GenericDayAssignment() { parentState = new OnContainer(); } @NotNull private GenericDayAssignmentsContainer container; @OnCopy(Strategy.IGNORE) private ParentState parentState; public GenericResourceAllocation getGenericResourceAllocation() { return parentState.getResourceAllocation(); } protected void setGenericResourceAllocation( GenericResourceAllocation genericResourceAllocation) { parentState = parentState.setParent(genericResourceAllocation); } protected void detachFromAllocation() { this.parentState = new ContainerNotSpecified(); } @Override protected BaseEntity getParent() { return getGenericResourceAllocation(); } @Override public String toString() { return super.toString() + " duration: " + getDuration() + ", consolidated: " + isConsolidated(); } @Override public Scenario getScenario() { return parentState.getScenario(); } public DayAssignment withDuration(EffortDuration newDuration) { GenericDayAssignment result = create(getDay(), newDuration, getResource()); if (container != null) { result.parentState.setParent(container); } else if (this.getGenericResourceAllocation() != null) { result.parentState.setParent(this.getGenericResourceAllocation()); } return result; } }
agpl-3.0
Asqatasun/Asqatasun
rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule060305.java
2514
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa30; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.ruleimplementation.link.AbstractLinkRuleImplementation; import org.asqatasun.rules.elementchecker.link.LinkPertinenceChecker; import org.asqatasun.rules.elementselector.SvgLinkElementSelector; import static org.asqatasun.rules.keystore.AttributeStore.TITLE_ATTR; import static org.asqatasun.rules.keystore.HtmlElementStore.TEXT_ELEMENT2; import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG; import static org.asqatasun.rules.keystore.RemarkMessageStore.UNEXPLICIT_LINK_MSG; /** * Implementation of the rule 6.3.5 of the referential Rgaa 3.0. * * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/06.Links/Rule-6-3-5.html">the rule 6.3.5 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-6-3-5"> 6.3.5 rule specification</a> */ public class Rgaa30Rule060305 extends AbstractLinkRuleImplementation { /** * Default constructor */ public Rgaa30Rule060305 () { // context is not taken into consideration super(new SvgLinkElementSelector(false), new LinkPertinenceChecker( // not pertinent solution TestSolution.FAILED, // not pertinent message UNEXPLICIT_LINK_MSG, // manual check message CHECK_LINK_PERTINENCE_MSG, // evidence elements TEXT_ELEMENT2, TITLE_ATTR ), null); } }
agpl-3.0
apotocki/fex
src/main/java/com/fluidops/fedx/evaluation/join/SynchronousJoin.java
2304
/* * Copyright (C) 2008-2013, fluid Operations AG * * FedX 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.fluidops.fedx.evaluation.join; import java.util.concurrent.Callable; import org.openrdf.query.BindingSet; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.algebra.TupleExpr; import com.fluidops.fedx.evaluation.FederationEvalStrategy; import com.fluidops.fedx.structures.QueryInfo; import info.aduna.iteration.CloseableIteration; /** * Execute the nested loop join in a synchronous fashion, i.e. one binding after the other * * @author Andreas Schwarte */ public class SynchronousJoin extends JoinExecutorBase<BindingSet> { public SynchronousJoin(FederationEvalStrategy strategy, CloseableIteration<BindingSet, QueryEvaluationException> leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) { super(strategy, leftIter, rightArg, bindings, queryInfo); handleBindings(); } @Override protected void handleBindings() { int totalBindings=0; while (!closed && leftIter.hasNext()) { addTask(new Callable<CloseableIteration<BindingSet,QueryEvaluationException>>() { @Override public CloseableIteration<BindingSet, QueryEvaluationException> call() throws Exception { return strategy.evaluate(rightArg, leftIter.next()); } }); totalBindings++; } // XXX remove output if not needed anymore log.debug("JoinStats: left iter of join #" + this.joinId + " had " + totalBindings + " results."); } @Override protected void doAddTask(JoinExecutorBase<BindingSet>.JoinTask jt) { jt.run(); } }
agpl-3.0
WASP-System/central
wasp-core/src/main/java/edu/yu/einstein/wasp/grid/work/SoftwareManager.java
820
/** * */ package edu.yu.einstein.wasp.grid.work; import java.util.Set; import edu.yu.einstein.wasp.grid.GridExecutionException; /** * @author calder * */ public interface SoftwareManager { /** * Get configuration string from software manager. For example, if the Modules manager determines * that a WorkUnit uses bzip2 and BWA, it might return the string "module load bzip2/v1\nmodule load bwa/v1". * @param w * @return */ public abstract String getConfiguration(WorkUnit w) throws GridExecutionException; /** * Get configured software properties. * @param s */ public abstract String getConfiguredSetting(String key); /** * Return a string representation of a software configuration. * @param data * @return */ public Set<String> parseSoftwareListFromText(String data); }
agpl-3.0
splicemachine/spliceengine
hbase_storage/src/main/java/com/splicemachine/si/data/hbase/coprocessor/HBaseComparator.java
4040
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine 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, or (at your option) any later version. * Splice Machine 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 Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.si.data.hbase.coprocessor; import com.splicemachine.primitives.ByteComparator; import org.apache.hadoop.hbase.util.Bytes; import java.nio.ByteBuffer; /** * @author Scott Fines * Date: 4/20/16 */ public class HBaseComparator implements ByteComparator{ public static final HBaseComparator INSTANCE = new HBaseComparator(); private HBaseComparator(){} @Override public int compare(byte[] b1,int b1Offset,int b1Length,byte[] b2,int b2Offset,int b2Length){ return Bytes.compareTo(b1,b1Offset,b1Length,b2,b2Offset,b2Length); } @Override public int compare(ByteBuffer buffer,byte[] b2,int b2Offset,int b2Length){ byte[] b; int bOff; int bLen; if(buffer.hasArray()){ b = buffer.array(); bOff = buffer.position(); bLen = buffer.remaining(); }else{ b=new byte[buffer.remaining()]; buffer.mark(); buffer.get(b); buffer.reset(); bOff=0; bLen=b.length; } return compare(b,bOff,bLen,b2,b2Offset,b2Length); } @Override public int compare(ByteBuffer lBuffer,ByteBuffer rBuffer){ byte[] b; int bOff; int bLen; if(rBuffer.hasArray()){ b = rBuffer.array(); bOff = rBuffer.position(); bLen = rBuffer.remaining(); }else{ b=new byte[rBuffer.remaining()]; rBuffer.mark(); rBuffer.get(b); rBuffer.reset(); bOff=0; bLen=b.length; } return compare(lBuffer,b,bOff,bLen); } @Override public boolean equals(byte[] b1,int b1Offset,int b1Length,byte[] b2,int b2Offset,int b2Length){ return compare(b1,b1Offset,b1Length,b2,b2Offset,b2Length)==0; } @Override public boolean equals(byte[] b1,byte[] b2){ return equals(b1,0,b1.length,b2,0,b2.length); } @Override public boolean equals(ByteBuffer buffer,byte[] b2,int b2Offset,int b2Length){ byte[] b; int bOff; int bLen; if(buffer.hasArray()){ b = buffer.array(); bOff = buffer.position(); bLen = buffer.remaining(); }else{ b=new byte[buffer.remaining()]; buffer.mark(); buffer.get(b); buffer.reset(); bOff=0; bLen=b.length; } return equals(b,bOff,bLen,b2,b2Offset,b2Length); } @Override public boolean equals(ByteBuffer lBuffer,ByteBuffer rBuffer){ byte[] b; int bOff; int bLen; if(rBuffer.hasArray()){ b = rBuffer.array(); bOff = rBuffer.position(); bLen = rBuffer.remaining(); }else{ b=new byte[rBuffer.remaining()]; rBuffer.mark(); rBuffer.get(b); rBuffer.reset(); bOff=0; bLen=b.length; } return equals(lBuffer,b,bOff,bLen); } @Override public boolean isEmpty(byte[] stop){ return stop==null||stop.length<=0; } @Override public int compare(byte[] o1,byte[] o2){ return compare(o1,0,o1.length,o2,0,o2.length); } }
agpl-3.0
axelor/axelor-business-suite
axelor-stock/src/main/java/com/axelor/apps/stock/service/InventoryLineService.java
4604
/* * Axelor Business Solutions * * Copyright (C) 2022 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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.axelor.apps.stock.service; import com.axelor.apps.base.db.Product; import com.axelor.apps.stock.db.Inventory; import com.axelor.apps.stock.db.InventoryLine; import com.axelor.apps.stock.db.StockLocation; import com.axelor.apps.stock.db.StockLocationLine; import com.axelor.apps.stock.db.TrackingNumber; import com.axelor.apps.stock.db.repo.StockConfigRepository; import com.axelor.apps.stock.db.repo.StockLocationLineRepository; import com.axelor.inject.Beans; import java.math.BigDecimal; import java.math.RoundingMode; public class InventoryLineService { public InventoryLine createInventoryLine( Inventory inventory, Product product, BigDecimal currentQty, String rack, TrackingNumber trackingNumber) { InventoryLine inventoryLine = new InventoryLine(); inventoryLine.setInventory(inventory); inventoryLine.setProduct(product); inventoryLine.setRack(rack); inventoryLine.setCurrentQty(currentQty); inventoryLine.setTrackingNumber(trackingNumber); this.compute(inventoryLine, inventory); return inventoryLine; } public InventoryLine updateInventoryLine(InventoryLine inventoryLine, Inventory inventory) { StockLocation stockLocation = inventory.getStockLocation(); Product product = inventoryLine.getProduct(); if (product != null) { StockLocationLine stockLocationLine = Beans.get(StockLocationLineService.class) .getOrCreateStockLocationLine(stockLocation, product); if (stockLocationLine != null) { inventoryLine.setCurrentQty(stockLocationLine.getCurrentQty()); inventoryLine.setRack(stockLocationLine.getRack()); if (inventoryLine.getTrackingNumber() != null) { inventoryLine.setCurrentQty( Beans.get(StockLocationLineRepository.class) .all() .filter( "self.product = :product and self.detailsStockLocation = :stockLocation and self.trackingNumber = :trackingNumber") .bind("product", inventoryLine.getProduct()) .bind("stockLocation", stockLocation) .bind("trackingNumber", inventoryLine.getTrackingNumber()) .fetchStream() .map(it -> it.getCurrentQty()) .reduce(BigDecimal.ZERO, (a, b) -> a.add(b))); } } else { inventoryLine.setCurrentQty(null); inventoryLine.setRack(null); } } return inventoryLine; } public InventoryLine compute(InventoryLine inventoryLine, Inventory inventory) { StockLocation stockLocation = inventory.getStockLocation(); Product product = inventoryLine.getProduct(); if (product != null) { inventoryLine.setUnit(product.getUnit()); BigDecimal gap = inventoryLine.getRealQty() != null ? inventoryLine .getCurrentQty() .subtract(inventoryLine.getRealQty()) .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO; inventoryLine.setGap(gap); BigDecimal price; int value = stockLocation.getCompany().getStockConfig().getInventoryValuationTypeSelect(); switch (value) { case StockConfigRepository.VALUATION_TYPE_ACCOUNTING_VALUE: price = product.getCostPrice(); break; case StockConfigRepository.VALUATION_TYPE_SALE_VALUE: price = product.getSalePrice(); break; default: price = product.getAvgPrice(); break; } inventoryLine.setGapValue(gap.multiply(price).setScale(2, RoundingMode.HALF_UP)); inventoryLine.setRealValue( inventoryLine.getRealQty() != null ? inventoryLine.getRealQty().multiply(price).setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO); } return inventoryLine; } }
agpl-3.0
asm-products/giraff-android
app/src/main/java/assembly/giraff/andtinder/model/Likes.java
1017
/** * AndTinder v0.1 for Android * * @Author: Enrique López Mañas <eenriquelopez@gmail.com> * http://www.lopez-manas.com * * TAndTinder is a native library for Android that provide a * Tinder card like effect. A card can be constructed using an * image and displayed with animation effects, dismiss-to-like * and dismiss-to-unlike, and use different sorting mechanisms. * * AndTinder is compatible with API Level 13 and upwards * * @copyright: Enrique López Mañas * @license: Apache License 2.0 */ package assembly.giraff.andtinder.model; public class Likes { public enum Like { None(0), Liked(1), Disliked(2); public final int value; private Like(int value) { this.value = value; } public static Like fromValue(int value) { for (Like style : Like.values()) { if (style.value == value) { return style; } } return null; } } }
agpl-3.0
automenta/java_dann
src/syncleus/dann/graph/drawing/CompactTreeLayout.java
31966
///* // * 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 syncleus.dann.graph.drawing; // //package com.mxgraph.layout; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.HashSet; // import java.util.List; // import java.util.Set; // // import com.mxgraph.model.mxGraphModel; // import com.mxgraph.model.mxIGraphModel; // import com.mxgraph.util.mxPoint; // import com.mxgraph.util.mxRectangle; // import com.mxgraph.util.mxUtils; // import com.mxgraph.view.mxCellState; // import com.mxgraph.view.mxGraph; // import com.mxgraph.view.mxGraphView; // import syncleus.dann.graph.Graph; // ///** // * @author https://raw.githubusercontent.com/jgraph/jgraphx/master/src/com/mxgraph/layout/mxCompactTreeLayout.java // */ //public class mxCompactTreeLayout<G extends Graph> implements GraphDrawer<G> { // // /** // * Specifies the orientation of the layout. Default is true. // */ // protected boolean horizontal; // // /** // * Specifies if edge directions should be inverted. Default is false. // */ // protected boolean invert; // // /** // * If the parents should be resized to match the width/height of the // * children. Default is true. // */ // protected boolean resizeParent = true; // // /** // * Padding added to resized parents // */ // protected int groupPadding = 10; // // /** // * A set of the parents that need updating based on children // * process as part of the layout // */ // protected Set<Object> parentsChanged = null; // // /** // * Specifies if the tree should be moved to the top, left corner // * if it is inside a top-level layer. Default is false. // */ // protected boolean moveTree = false; // // /** // * Specifies if all edge points of traversed edges should be removed. // * Default is true. // */ // protected boolean resetEdges = true; // // /** // * Holds the levelDistance. Default is 10. // */ // protected int levelDistance = 10; // // /** // * Holds the nodeDistance. Default is 20. // */ // protected int nodeDistance = 20; // // /** // * The preferred horizontal distance between edges exiting a vertex // */ // protected int prefHozEdgeSep = 5; // // /** // * The preferred vertical offset between edges exiting a vertex // */ // protected int prefVertEdgeOff = 2; // // /** // * The minimum distance for an edge jetty from a vertex // */ // protected int minEdgeJetty = 12; // // /** // * The size of the vertical buffer in the center of inter-rank channels // * where edge control points should not be placed // */ // protected int channelBuffer = 4; // // /** // * Whether or not to apply the internal tree edge routing // */ // protected boolean edgeRouting = true; // // /** // * @param graph // */ // public mxCompactTreeLayout(mxGraph graph) { // this(graph, true); // } // // /** // * @param graph // * @param horizontal // */ // public mxCompactTreeLayout(mxGraph graph, boolean horizontal) { // this(graph, horizontal, false); // } // // /** // * @param graph // * @param horizontal // * @param invert // */ // public mxCompactTreeLayout(mxGraph graph, boolean horizontal, boolean invert) { // super(graph); // this.horizontal = horizontal; // this.invert = invert; // } // // /** // * Returns a boolean indicating if the given <mxCell> should be ignored as a // * vertex. This returns true if the cell has no connections. // * // * @param vertex Object that represents the vertex to be tested. // * @return Returns true if the vertex should be ignored. // */ // public boolean isVertexIgnored(Object vertex) { // return super.isVertexIgnored(vertex) // || graph.getConnections(vertex).length == 0; // } // // /** // * @return the horizontal // */ // public boolean isHorizontal() { // return horizontal; // } // // /** // * @param horizontal the horizontal to set // */ // public void setHorizontal(boolean horizontal) { // this.horizontal = horizontal; // } // // /** // * @return the invert // */ // public boolean isInvert() { // return invert; // } // // /** // * @param invert the invert to set // */ // public void setInvert(boolean invert) { // this.invert = invert; // } // // /** // * @return the resizeParent // */ // public boolean isResizeParent() { // return resizeParent; // } // // /** // * @param resizeParent the resizeParent to set // */ // public void setResizeParent(boolean resizeParent) { // this.resizeParent = resizeParent; // } // // /** // * @return the moveTree // */ // public boolean isMoveTree() { // return moveTree; // } // // /** // * @param moveTree the moveTree to set // */ // public void setMoveTree(boolean moveTree) { // this.moveTree = moveTree; // } // // /** // * @return the resetEdges // */ // public boolean isResetEdges() { // return resetEdges; // } // // /** // * @param resetEdges the resetEdges to set // */ // public void setResetEdges(boolean resetEdges) { // this.resetEdges = resetEdges; // } // // public boolean isEdgeRouting() { // return edgeRouting; // } // // public void setEdgeRouting(boolean edgeRouting) { // this.edgeRouting = edgeRouting; // } // // /** // * @return the levelDistance // */ // public int getLevelDistance() { // return levelDistance; // } // // /** // * @param levelDistance the levelDistance to set // */ // public void setLevelDistance(int levelDistance) { // this.levelDistance = levelDistance; // } // // /** // * @return the nodeDistance // */ // public int getNodeDistance() { // return nodeDistance; // } // // /** // * @param nodeDistance the nodeDistance to set // */ // public void setNodeDistance(int nodeDistance) { // this.nodeDistance = nodeDistance; // } // // public double getGroupPadding() { // return groupPadding; // } // // public void setGroupPadding(int groupPadding) { // this.groupPadding = groupPadding; // } // // /* // * (non-Javadoc) // * @see com.mxgraph.layout.mxIGraphLayout#execute(java.lang.Object) // */ // public void execute(Object parent) { // super.execute(parent); // execute(parent, null); // } // // /** // * Implements <mxGraphLayout.execute>. // * <p/> // * If the parent has any connected edges, then it is used as the root of // * the tree. Else, <mxGraph.findTreeRoots> will be used to find a suitable // * root node within the set of children of the given parent. // */ // public void execute(Object parent, Object root) { // mxIGraphModel model = graph.getModel(); // // if (root == null) { // // Takes the parent as the root if it has outgoing edges // if (graph.getEdges(parent, model.getParent(parent), invert, // !invert, false).length > 0) { // root = parent; // } // // // Tries to find a suitable root in the parent's // // children // else { // List<Object> roots = findTreeRoots(parent, invert); // // if (roots.size() > 0) { // for (int i = 0; i < roots.size(); i++) { // if (!isVertexIgnored(roots.get(i)) // && graph.getEdges(roots.get(i), null, invert, // !invert, false).length > 0) { // root = roots.get(i); // break; // } // } // } // } // } // // if (root != null) { // if (resizeParent) { // parentsChanged = new HashSet<Object>(); // } else { // parentsChanged = null; // } // // model.beginUpdate(); // // try { // TreeNode node = dfs(root, parent, null); // // if (node != null) { // layout(node); // // double x0 = graph.getGridSize(); // double y0 = x0; // // if (!moveTree) { // mxRectangle g = getVertexBounds(root); // // if (g != null) { // x0 = g.getX(); // y0 = g.getY(); // } // } // // mxRectangle bounds = null; // // if (horizontal) { // bounds = horizontalLayout(node, x0, y0, null); // } else { // bounds = verticalLayout(node, null, x0, y0, null); // } // // if (bounds != null) { // double dx = 0; // double dy = 0; // // if (bounds.getX() < 0) { // dx = Math.abs(x0 - bounds.getX()); // } // // if (bounds.getY() < 0) { // dy = Math.abs(y0 - bounds.getY()); // } // // if (dx != 0 || dy != 0) { // moveNode(node, dx, dy); // } // // if (resizeParent) { // adjustParents(); // } // // if (edgeRouting) { // // Iterate through all edges setting their positions // localEdgeProcessing(node); // } // } // } // } finally { // model.endUpdate(); // } // } // } // // /** // * Returns all visible children in the given parent which do not have // * incoming edges. If the result is empty then the children with the // * maximum difference between incoming and outgoing edges are returned. // * This takes into account edges that are being promoted to the given // * root due to invisible children or collapsed cells. // * // * @param parent Cell whose children should be checked. // * @param invert Specifies if outgoing or incoming edges should be counted // * for a tree root. If false then outgoing edges will be counted. // * @return List of tree roots in parent. // */ // public List<Object> findTreeRoots(Object parent, boolean invert) { // List<Object> roots = new ArrayList<Object>(); // // if (parent != null) { // mxIGraphModel model = graph.getModel(); // int childCount = model.getChildCount(parent); // Object best = null; // int maxDiff = 0; // // for (int i = 0; i < childCount; i++) { // Object cell = model.getChildAt(parent, i); // // if (model.isVertex(cell) && graph.isCellVisible(cell)) { // Object[] conns = graph.getConnections(cell, parent, true); // int fanOut = 0; // int fanIn = 0; // // for (int j = 0; j < conns.length; j++) { // Object src = graph.getView().getVisibleTerminal( // conns[j], true); // // if (src == cell) { // fanOut++; // } else { // fanIn++; // } // } // // if ((invert && fanOut == 0 && fanIn > 0) // || (!invert && fanIn == 0 && fanOut > 0)) { // roots.add(cell); // } // // int diff = (invert) ? fanIn - fanOut : fanOut - fanIn; // // if (diff > maxDiff) { // maxDiff = diff; // best = cell; // } // } // } // // if (roots.isEmpty() && best != null) { // roots.add(best); // } // } // // return roots; // } // // /** // * Moves the specified node and all of its children by the given amount. // */ // protected void moveNode(TreeNode node, double dx, double dy) { // node.x += dx; // node.y += dy; // apply(node, null); // // TreeNode child = node.child; // // while (child != null) { // moveNode(child, dx, dy); // child = child.next; // } // } // // /** // * Does a depth first search starting at the specified cell. // * Makes sure the specified parent is never left by the // * algorithm. // */ // protected TreeNode dfs(Object cell, Object parent, Set<Object> visited) { // if (visited == null) { // visited = new HashSet<Object>(); // } // // TreeNode node = null; // // if (cell != null && !visited.contains(cell) && !isVertexIgnored(cell)) { // visited.add(cell); // node = createNode(cell); // // mxIGraphModel model = graph.getModel(); // TreeNode prev = null; // Object[] out = graph.getEdges(cell, parent, invert, !invert, false, // true); // mxGraphView view = graph.getView(); // // for (int i = 0; i < out.length; i++) { // Object edge = out[i]; // // if (!isEdgeIgnored(edge)) { // // Resets the points on the traversed edge // if (resetEdges) { // setEdgePoints(edge, null); // } // // if (edgeRouting) { // setEdgeStyleEnabled(edge, false); // setEdgePoints(edge, null); // } // // // Checks if terminal in same swimlane // mxCellState state = view.getState(edge); // Object target = (state != null) ? state // .getVisibleTerminal(invert) : view // .getVisibleTerminal(edge, invert); // TreeNode tmp = dfs(target, parent, visited); // // if (tmp != null && model.getGeometry(target) != null) { // if (prev == null) { // node.child = tmp; // } else { // prev.next = tmp; // } // // prev = tmp; // } // } // } // } // // return node; // } // // /** // * Starts the actual compact tree layout algorithm // * at the given node. // */ // protected void layout(TreeNode node) { // if (node != null) { // TreeNode child = node.child; // // while (child != null) { // layout(child); // child = child.next; // } // // if (node.child != null) { // attachParent(node, join(node)); // } else { // layoutLeaf(node); // } // } // } // // /** // * // */ // protected mxRectangle horizontalLayout(TreeNode node, double x0, double y0, // mxRectangle bounds) { // node.x += x0 + node.offsetX; // node.y += y0 + node.offsetY; // bounds = apply(node, bounds); // TreeNode child = node.child; // // if (child != null) { // bounds = horizontalLayout(child, node.x, node.y, bounds); // double siblingOffset = node.y + child.offsetY; // TreeNode s = child.next; // // while (s != null) { // bounds = horizontalLayout(s, node.x + child.offsetX, // siblingOffset, bounds); // siblingOffset += s.offsetY; // s = s.next; // } // } // // return bounds; // } // // /** // * // */ // protected mxRectangle verticalLayout(TreeNode node, Object parent, // double x0, double y0, mxRectangle bounds) { // node.x += x0 + node.offsetY; // node.y += y0 + node.offsetX; // bounds = apply(node, bounds); // TreeNode child = node.child; // // if (child != null) { // bounds = verticalLayout(child, node, node.x, node.y, bounds); // double siblingOffset = node.x + child.offsetY; // TreeNode s = child.next; // // while (s != null) { // bounds = verticalLayout(s, node, siblingOffset, node.y // + child.offsetX, bounds); // siblingOffset += s.offsetY; // s = s.next; // } // } // // return bounds; // } // // /** // * // */ // protected void attachParent(TreeNode node, double height) { // double x = nodeDistance + levelDistance; // double y2 = (height - node.width) / 2 - nodeDistance; // double y1 = y2 + node.width + 2 * nodeDistance - height; // // node.child.offsetX = x + node.height; // node.child.offsetY = y1; // // node.contour.upperHead = createLine(node.height, 0, // createLine(x, y1, node.contour.upperHead)); // node.contour.lowerHead = createLine(node.height, 0, // createLine(x, y2, node.contour.lowerHead)); // } // // /** // * // */ // protected void layoutLeaf(TreeNode node) { // double dist = 2 * nodeDistance; // // node.contour.upperTail = createLine(node.height + dist, 0, null); // node.contour.upperHead = node.contour.upperTail; // node.contour.lowerTail = createLine(0, -node.width - dist, null); // node.contour.lowerHead = createLine(node.height + dist, 0, // node.contour.lowerTail); // } // // /** // * // */ // protected double join(TreeNode node) { // double dist = 2 * nodeDistance; // // TreeNode child = node.child; // node.contour = child.contour; // double h = child.width + dist; // double sum = h; // child = child.next; // // while (child != null) { // double d = merge(node.contour, child.contour); // child.offsetY = d + h; // child.offsetX = 0; // h = child.width + dist; // sum += d + h; // child = child.next; // } // // return sum; // } // // /** // * // */ // protected double merge(Polygon p1, Polygon p2) { // double x = 0; // double y = 0; // double total = 0; // // Polyline upper = p1.lowerHead; // Polyline lower = p2.upperHead; // // while (lower != null && upper != null) { // double d = offset(x, y, lower.dx, lower.dy, upper.dx, upper.dy); // y += d; // total += d; // // if (x + lower.dx <= upper.dx) { // x += lower.dx; // y += lower.dy; // lower = lower.next; // } else { // x -= upper.dx; // y -= upper.dy; // upper = upper.next; // } // } // // if (lower != null) { // Polyline b = bridge(p1.upperTail, 0, 0, lower, x, y); // p1.upperTail = (b.next != null) ? p2.upperTail : b; // p1.lowerTail = p2.lowerTail; // } else { // Polyline b = bridge(p2.lowerTail, x, y, upper, 0, 0); // // if (b.next == null) { // p1.lowerTail = b; // } // } // // p1.lowerHead = p2.lowerHead; // // return total; // } // // /** // * // */ // protected double offset(double p1, double p2, double a1, double a2, // double b1, double b2) { // double d = 0; // // if (b1 <= p1 || p1 + a1 <= 0) { // return 0; // } // // double t = b1 * a2 - a1 * b2; // // if (t > 0) { // if (p1 < 0) { // double s = p1 * a2; // d = s / a1 - p2; // } else if (p1 > 0) { // double s = p1 * b2; // d = s / b1 - p2; // } else { // d = -p2; // } // } else if (b1 < p1 + a1) { // double s = (b1 - p1) * a2; // d = b2 - (p2 + s / a1); // } else if (b1 > p1 + a1) { // double s = (a1 + p1) * b2; // d = s / b1 - (p2 + a2); // } else { // d = b2 - (p2 + a2); // } // // if (d > 0) { // return d; // } // // return 0; // } // // /** // * // */ // protected Polyline bridge(Polyline line1, double x1, double y1, // Polyline line2, double x2, double y2) { // double dx = x2 + line2.dx - x1; // double dy = 0; // double s = 0; // // if (line2.dx == 0) { // dy = line2.dy; // } else { // s = dx * line2.dy; // dy = s / line2.dx; // } // // Polyline r = createLine(dx, dy, line2.next); // line1.next = createLine(0, y2 + line2.dy - dy - y1, r); // // return r; // } // // /** // * // */ // protected TreeNode createNode(Object cell) { // TreeNode node = new TreeNode(cell); // // mxRectangle geo = getVertexBounds(cell); // // if (geo != null) { // if (horizontal) { // node.width = geo.getHeight(); // node.height = geo.getWidth(); // } else { // node.width = geo.getWidth(); // node.height = geo.getHeight(); // } // } // // return node; // } // // /** // * @param node // * @param bounds // * @return // */ // protected mxRectangle apply(TreeNode node, mxRectangle bounds) { // mxIGraphModel model = graph.getModel(); // Object cell = node.cell; // mxRectangle g = model.getGeometry(cell); // // if (cell != null && g != null) { // if (isVertexMovable(cell)) { // g = setVertexLocation(cell, node.x, node.y); // // if (resizeParent) { // parentsChanged.add(model.getParent(cell)); // } // } // // if (bounds == null) { // bounds = new mxRectangle(g.getX(), g.getY(), g.getWidth(), // g.getHeight()); // } else { // bounds = new mxRectangle(Math.min(bounds.getX(), g.getX()), // Math.min(bounds.getY(), g.getY()), Math.max( // bounds.getX() + bounds.getWidth(), // g.getX() + g.getWidth()), Math.max( // bounds.getY() + bounds.getHeight(), g.getY() // + g.getHeight())); // } // } // // return bounds; // } // // /** // * // */ // protected Polyline createLine(double dx, double dy, Polyline next) { // return new Polyline(dx, dy, next); // } // // /** // * Adjust parent cells whose child geometries have changed. The default // * implementation adjusts the group to just fit around the children with // * a padding. // */ // protected void adjustParents() { // arrangeGroups(mxUtils.sortCells(this.parentsChanged, true).toArray(), groupPadding); // } // // /** // * Moves the specified node and all of its children by the given amount. // */ // protected void localEdgeProcessing(TreeNode node) { // processNodeOutgoing(node); // TreeNode child = node.child; // // while (child != null) { // localEdgeProcessing(child); // child = child.next; // } // } // // /** // * Separates the x position of edges as they connect to vertices // * // * @param node the root node of the tree // */ // protected void processNodeOutgoing(TreeNode node) { // mxIGraphModel model = graph.getModel(); // // TreeNode child = node.child; // Object parentCell = node.cell; // // int childCount = 0; // List<WeightedCellSorter> sortedCells = new ArrayList<WeightedCellSorter>(); // // while (child != null) { // childCount++; // // double sortingCriterion = child.x; // // if (this.horizontal) { // sortingCriterion = child.y; // } // // sortedCells.add(new WeightedCellSorter(child, // (int) sortingCriterion)); // child = child.next; // } // // WeightedCellSorter[] sortedCellsArray = sortedCells // .toArray(new WeightedCellSorter[sortedCells.size()]); // Arrays.sort(sortedCellsArray); // // double availableWidth = node.width; // // double requiredWidth = (childCount + 1) * prefHozEdgeSep; // // // Add a buffer on the edges of the vertex if the edge count allows // if (availableWidth > requiredWidth + (2 * prefHozEdgeSep)) { // availableWidth -= 2 * prefHozEdgeSep; // } // // double edgeSpacing = availableWidth / childCount; // // double currentXOffset = edgeSpacing / 2.0; // // if (availableWidth > requiredWidth + (2 * prefHozEdgeSep)) { // currentXOffset += prefHozEdgeSep; // } // // double currentYOffset = minEdgeJetty - prefVertEdgeOff; // double maxYOffset = 0; // // mxRectangle parentBounds = getVertexBounds(parentCell); // child = node.child; // // for (int j = 0; j < sortedCellsArray.length; j++) { // Object childCell = sortedCellsArray[j].cell.cell; // mxRectangle childBounds = getVertexBounds(childCell); // // Object[] edges = mxGraphModel.getEdgesBetween(model, parentCell, // childCell); // // List<mxPoint> newPoints = new ArrayList<mxPoint>(3); // double x = 0; // double y = 0; // // for (int i = 0; i < edges.length; i++) { // if (this.horizontal) { // // Use opposite co-ords, calculation was done for // // // x = parentBounds.getX() + parentBounds.getWidth(); // y = parentBounds.getY() + currentXOffset; // newPoints.add(new mxPoint(x, y)); // x = parentBounds.getX() + parentBounds.getWidth() // + currentYOffset; // newPoints.add(new mxPoint(x, y)); // y = childBounds.getY() + childBounds.getHeight() / 2.0; // newPoints.add(new mxPoint(x, y)); // setEdgePoints(edges[i], newPoints); // } else { // x = parentBounds.getX() + currentXOffset; // y = parentBounds.getY() + parentBounds.getHeight(); // newPoints.add(new mxPoint(x, y)); // y = parentBounds.getY() + parentBounds.getHeight() // + currentYOffset; // newPoints.add(new mxPoint(x, y)); // x = childBounds.getX() + childBounds.getWidth() / 2.0; // newPoints.add(new mxPoint(x, y)); // setEdgePoints(edges[i], newPoints); // } // } // // if (j < (float) childCount / 2.0f) { // currentYOffset += prefVertEdgeOff; // } else if (j > (float) childCount / 2.0f) { // currentYOffset -= prefVertEdgeOff; // } // // Ignore the case if equals, this means the second of 2 // // jettys with the same y (even number of edges) // // // pos[k * 2] = currentX; // currentXOffset += edgeSpacing; // // pos[k * 2 + 1] = currentYOffset; // // maxYOffset = Math.max(maxYOffset, currentYOffset); // } // } // // /** // * A utility class used to track cells whilst sorting occurs on the weighted // * sum of their connected edges. Does not violate (x.compareTo(y)==0) == // * (x.equals(y)) // */ // protected class WeightedCellSorter implements Comparable<Object> { // // /** // * The weighted value of the cell stored // */ // public int weightedValue = 0; // // /** // * Whether or not to flip equal weight values. // */ // public boolean nudge = false; // // /** // * Whether or not this cell has been visited in the current assignment // */ // public boolean visited = false; // // /** // * The cell whose median value is being calculated // */ // public TreeNode cell = null; // // public WeightedCellSorter() { // this(null, 0); // } // // public WeightedCellSorter(TreeNode cell, int weightedValue) { // this.cell = cell; // this.weightedValue = weightedValue; // } // // /** // * comparator on the medianValue // * // * @param arg0 the object to be compared to // * @return the standard return you would expect when comparing two // * double // */ // public int compareTo(Object arg0) { // if (arg0 instanceof WeightedCellSorter) { // if (weightedValue > ((WeightedCellSorter) arg0).weightedValue) { // return 1; // } else if (weightedValue < ((WeightedCellSorter) arg0).weightedValue) { // return -1; // } // } // // return 0; // } // } // // /** // * // */ // protected static class TreeNode { // /** // * // */ // protected Object cell; // // /** // * // */ // protected double x, y, width, height, offsetX, offsetY; // // /** // * // */ // protected TreeNode child, next; // parent, sibling // // /** // * // */ // protected Polygon contour = new Polygon(); // // /** // * // */ // public TreeNode(Object cell) { // this.cell = cell; // } // // } // // /** // * // */ // protected static class Polygon { // // /** // * // */ // protected Polyline lowerHead, lowerTail, upperHead, upperTail; // // } // // /** // * // */ // protected static class Polyline { // // /** // * // */ // protected double dx, dy; // // /** // * // */ // protected Polyline next; // // /** // * // */ // protected Polyline(double dx, double dy, Polyline next) { // this.dx = dx; // this.dy = dy; // this.next = next; // } // // } // //}
agpl-3.0
BeardlessBrady/Currency-Mod
src/main/java/beardlessbrady/modcurrency2/ConfigCurrency.java
1706
package beardlessbrady.modcurrency2; import beardlessbrady.modcurrency2.proxy.CommonProxy; import net.minecraftforge.common.config.Configuration; /** * This class was created by BeardlessBrady. It is distributed as * part of The Currency-Mod. Source Code located on github: * https://github.com/BeardlessBrady/Currency-Mod * - * Copyright (C) All Rights Reserved * File Created 2019-02-07 */ public class ConfigCurrency { private static final String CATEGORY_CURRENCY = "dynamic currency"; public static String[] currencyValues = {"0.01", "0.05", "0.10" , "0.25 " , "1 ", "2 ", "1" , "5" , "10" , "20" , "50" , "100"}; public static String[] currencyNames = {"One Cent", "Five Cents", "Ten Cents", "Twenty-Five Cents", "One Dollar", "Two Dollars", "One Dollar", "Five Dollars", "Ten Dollars", "Twenty Dollars", "Fifty Dollars", "One-Hundred Dollars"}; public static void readConfig(){ Configuration cfg = CommonProxy.config; try{ cfg.load(); initItemsConfig(cfg); }catch (Exception e){ } finally { if (cfg.hasChanged()){ cfg.save(); } } } private static void initItemsConfig(Configuration cfg){ cfg.addCustomCategoryComment(CATEGORY_CURRENCY, "Configure the value and name of the currencies in the mod.\nYou can add more elements then the default but MAKE SURE TO ADD TO BOTH VALUES AND NAMES."); currencyValues = cfg.getStringList("Currency Values", CATEGORY_CURRENCY, currencyValues , "Set currency values"); currencyNames = cfg.getStringList("Currency Names", CATEGORY_CURRENCY, currencyNames, "Set currency names"); } }
agpl-3.0
axelor/axelor-business-suite
axelor-account/src/main/java/com/axelor/apps/account/service/invoice/generator/invoice/RefundInvoice.java
3291
/* * Axelor Business Solutions * * Copyright (C) 2022 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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.axelor.apps.account.service.invoice.generator.invoice; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.InvoiceLine; import com.axelor.apps.account.exception.IExceptionMessage; import com.axelor.apps.account.service.invoice.InvoiceToolService; import com.axelor.apps.account.service.invoice.generator.InvoiceGenerator; import com.axelor.db.JPA; import com.axelor.exception.AxelorException; import com.axelor.exception.db.repo.TraceBackRepository; import com.axelor.i18n.I18n; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RefundInvoice extends InvoiceGenerator implements InvoiceStrategy { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private Invoice invoice; public RefundInvoice(Invoice invoice) { super(); this.invoice = invoice; } @Override public Invoice generate() throws AxelorException { LOG.debug("Creating a refund for invoice {}", invoice.getInvoiceId()); Invoice refund = JPA.copy(invoice, true); InvoiceToolService.resetInvoiceStatusOnCopy(refund); refund.setOperationTypeSelect(this.inverseOperationType(refund.getOperationTypeSelect())); List<InvoiceLine> refundLines = new ArrayList<>(); if (refund.getInvoiceLineList() != null) { refundLines.addAll(refund.getInvoiceLineList()); } populate(refund, refundLines); // Payment mode should not be the invoice payment mode. It must come // from the partner or the company, or be null. refund.setPaymentMode(InvoiceToolService.getPaymentMode(refund)); if (refund.getPaymentMode() == null) { throw new AxelorException( TraceBackRepository.CATEGORY_MISSING_FIELD, I18n.get(IExceptionMessage.REFUND_INVOICE_1), I18n.get(com.axelor.apps.base.exceptions.IExceptionMessage.EXCEPTION)); } return refund; } @Override public void populate(Invoice invoice, List<InvoiceLine> invoiceLines) throws AxelorException { super.populate(invoice, invoiceLines); } /** * Mets à jour les lignes de facture en appliquant la négation aux prix unitaires et au total hors * taxe. * * @param invoiceLines */ @Deprecated protected void refundInvoiceLines(List<InvoiceLine> invoiceLines) { for (InvoiceLine invoiceLine : invoiceLines) { invoiceLine.setQty(invoiceLine.getQty().negate()); invoiceLine.setExTaxTotal(invoiceLine.getExTaxTotal().negate()); } } }
agpl-3.0
piersharding/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ChunkIconsManager.java
13506
/* * ChunkIconsManager.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.regex.Match; import org.rstudio.core.client.regex.Pattern; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.console.shell.assist.PopupPositioner; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DisplayChunkOptionsEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.ExecuteChunksEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Renderer; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.events.AfterAceRenderEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.themes.AceThemes; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class ChunkIconsManager { public ChunkIconsManager() { RStudioGinjector.INSTANCE.injectMembers(this); events_.addHandler( AfterAceRenderEvent.TYPE, new AfterAceRenderEvent.Handler() { @Override public void onAfterAceRender(AfterAceRenderEvent event) { manageChunkIcons(event.getEditor()); } }); } @Inject private void initialize(EventBus events, Commands commands, UIPrefs uiPrefs, AceThemes themes) { events_ = events; commands_ = commands; uiPrefs_ = uiPrefs; themes_ = themes; } private boolean isPseudoMarker(Element el) { return el.getOffsetHeight() == 0 || el.getOffsetWidth() == 0; } private boolean shouldDisplayIcons(AceEditorNative editor) { String id = editor.getSession().getMode().getId(); return id.equals("mode/rmarkdown"); // also Rpres } private Position toDocumentPosition(Element el, AceEditorNative editor) { int pageX = el.getAbsoluteLeft(); int pageY = el.getAbsoluteTop(); return editor.getRenderer().screenToTextCoordinates(pageX, pageY); } private boolean isRunnableChunk(Element el, AceEditorNative editor) { Position pos = toDocumentPosition(el, editor); String text = editor.getSession().getLine(pos.getRow()); // Check for R Markdown chunks, and verify that the engine is 'r' or 'rscript'. // First, check for chunk headers of the form: // // ```{r ...} // // as opposed to // // ```{sh ...} String lower = text.toLowerCase().trim(); if (lower.startsWith("```{")) { Pattern reREngine = Pattern.create("```{r(?:script)?[ ,}]", ""); if (!reREngine.test(lower)) return false; } // If this is an 'R' chunk, it's possible that an alternate engine // has been specified, e.g. // // ```{r, engine = 'awk'} // // which is the 'old-fashioned' way of specifying non-R chunks. Pattern pattern = Pattern.create("engine\\s*=\\s*['\"]([^'\"]*)['\"]", ""); Match match = pattern.match(text, 0); if (match == null) return true; String engine = match.getGroup(1).toLowerCase(); return engine.equals("r") || engine.equals("rscript"); } private void manageChunkIcons(AceEditorNative editor) { Element container = editor.getContainer(); if (container == null) return; Element[] icons = DomUtils.getElementsByClassName( container, ThemeStyles.INSTANCE.inlineChunkToolbar()); for (Element icon : icons) icon.removeFromParent(); if (!uiPrefs_.showInlineToolbarForRCodeChunks().getValue()) return; if (!shouldDisplayIcons(editor)) return; Element[] chunkStarts = DomUtils.getElementsByClassName("rstudio_chunk_start"); for (int i = 0; i < chunkStarts.length; i++) { Element el = chunkStarts[i]; if (isPseudoMarker(el)) continue; if (!isRunnableChunk(el, editor)) continue; if (!DomUtils.isVisibleVert(container, el)) continue; if (el.getChildCount() > 0) el.removeAllChildren(); addToolbar(el, isSetupChunk(el, editor), editor); } } private boolean isSetupChunk(Element el, AceEditorNative editor) { int pageX = el.getAbsoluteLeft() + 5; int pageY = el.getAbsoluteTop() + 5; Position position = editor.getRenderer().screenToTextCoordinates(pageX, pageY); String line = editor.getSession().getLine(position.getRow()); return line.contains("r setup"); } private void addToolbar(Element el, boolean isSetupChunk, AceEditorNative editor) { FlowPanel toolbarPanel = new FlowPanel(); toolbarPanel.addStyleName(ThemeStyles.INSTANCE.inlineChunkToolbar()); boolean isDark = themes_.isDark( themes_.getEffectiveThemeName(uiPrefs_.theme().getValue())); Image optionsIcon = createOptionsIcon(isDark, isSetupChunk); optionsIcon.getElement().getStyle().setMarginRight(9, Unit.PX); toolbarPanel.add(optionsIcon); // Note that 'run current chunk' currently only operates within Rmd if (editor.getSession().getMode().getId().equals("mode/rmarkdown")) { if (!isSetupChunk) { Image runPreviousIcon = createRunPreviousIcon(isDark); runPreviousIcon.getElement().getStyle().setMarginRight(8, Unit.PX); toolbarPanel.add(runPreviousIcon); } Image runIcon = createRunIcon(); toolbarPanel.add(runIcon); } display(toolbarPanel, el); } private void display(Widget panel, Element underlyingMarker) { // Bail if the underlying marker isn't wide enough if (underlyingMarker.getOffsetWidth() < 250) return; // Get the 'virtual' parent -- this is the Ace scroller that houses all // of the Ace content, where we want our icons to live. We need them // to live here so that they properly hide when the user scrolls and // e.g. markers are only partially visible. Element virtualParent = DomUtils.getParent(underlyingMarker, 3); // We'd prefer to use 'getOffsetTop()' here, but that seems to give // some janky dimensions due to how the Ace layers are ... layered, // so we manually compute it. int top = underlyingMarker.getAbsoluteTop() - virtualParent.getAbsoluteTop(); panel.getElement().getStyle().setTop(top, Unit.PX); virtualParent.appendChild(panel.getElement()); } private Image createRunIcon() { Image icon = new Image(ThemeResources.INSTANCE.runChunk()); icon.addStyleName(ThemeStyles.INSTANCE.highlightIcon()); icon.setTitle(commands_.executeCurrentChunk().getTooltip()); bindNativeClickToExecuteChunk(this, icon.getElement()); return icon; } private Image createRunPreviousIcon(boolean dark) { Image icon = new Image(dark ? ThemeResources.INSTANCE.runPreviousChunksDark() : ThemeResources.INSTANCE.runPreviousChunksLight()); icon.addStyleName(ThemeStyles.INSTANCE.highlightIcon()); icon.setTitle(commands_.executePreviousChunks().getTooltip()); bindNativeClickToExecutePreviousChunks(this, icon.getElement()); return icon; } private Image createOptionsIcon(boolean dark, boolean setupChunk) { Image icon = new Image(dark ? ThemeResources.INSTANCE.chunkOptionsDark() : ThemeResources.INSTANCE.chunkOptionsLight()); icon.addStyleName(ThemeStyles.INSTANCE.highlightIcon()); if (setupChunk) icon.addStyleName(RES.styles().setupChunk()); icon.setTitle("Modify chunk options"); bindNativeClickToOpenOptions(this, icon.getElement()); return icon; } private static final native void bindNativeClickToExecutePreviousChunks( ChunkIconsManager manager, Element element) /*-{ element.addEventListener("click", $entry(function(evt) { manager.@org.rstudio.studio.client.workbench.views.source.editors.text.ChunkIconsManager::fireExecutePreviousChunksEvent(Ljava/lang/Object;)(evt); })); }-*/; private static final native void bindNativeClickToExecuteChunk(ChunkIconsManager manager, Element element) /*-{ element.addEventListener("click", $entry(function(evt) { manager.@org.rstudio.studio.client.workbench.views.source.editors.text.ChunkIconsManager::fireExecuteChunkEvent(Ljava/lang/Object;)(evt); })); }-*/; private static final native void bindNativeClickToOpenOptions(ChunkIconsManager manager, Element element) /*-{ element.addEventListener("click", $entry(function(evt) { manager.@org.rstudio.studio.client.workbench.views.source.editors.text.ChunkIconsManager::fireDisplayChunkOptionsEvent(Ljava/lang/Object;)(evt); })); }-*/; private final void fireExecuteChunkEvent(Object object) { fireExecuteChunksEvent(ExecuteChunksEvent.Scope.Current, object); } private final void fireExecutePreviousChunksEvent(Object object) { fireExecuteChunksEvent(ExecuteChunksEvent.Scope.Previous, object); } private final void fireExecuteChunksEvent(ExecuteChunksEvent.Scope scope, Object object) { if (!(object instanceof NativeEvent)) return; NativeEvent event = (NativeEvent) object; events_.fireEvent(new ExecuteChunksEvent(scope, event.getClientX(), event.getClientY())); } private final void fireDisplayChunkOptionsEvent(Object object) { if (!(object instanceof NativeEvent)) return; NativeEvent event = (NativeEvent) object; events_.fireEvent(new DisplayChunkOptionsEvent(event)); } public void displayChunkOptions(AceEditor editor, NativeEvent event) { // Translate the 'pageX' + 'pageY' position to document position int pageX = event.getClientX(); int pageY = event.getClientY(); Renderer renderer = editor.getWidget().getEditor().getRenderer(); Position position = renderer.screenToTextCoordinates(pageX, pageY); if (optionsPanel_ != null) optionsPanel_ = null; Element el = event.getEventTarget().cast(); if (el.hasClassName(RES.styles().setupChunk())) optionsPanel_ = new SetupChunkOptionsPopupPanel(); else optionsPanel_ = new DefaultChunkOptionsPopupPanel(); optionsPanel_.init(editor.getWidget(), position); optionsPanel_.show(); optionsPanel_.focus(); PopupPositioner.setPopupPosition( optionsPanel_, pageX, pageY, 10); } private ChunkOptionsPopupPanel optionsPanel_; private Commands commands_; private EventBus events_; private UIPrefs uiPrefs_; private AceThemes themes_; public interface Styles extends CssResource { String setupChunk(); } public interface Resources extends ClientBundle { @Source("ChunkIconsManager.css") Styles styles(); } private static Resources RES = GWT.create(Resources.class); static { RES.styles().ensureInjected(); } }
agpl-3.0
anhnv-3991/VoltDB
tests/test_apps/aggbench/src/aggregationbenchmark/AggregationBenchmark.java
9497
/* This file is part of VoltDB. * Copyright (C) 2008-2015 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package aggregationbenchmark; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.List; import org.voltdb.CLIConfig; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.ClientStatusListenerExt; public class AggregationBenchmark { // handy, rather than typing this out several times static final String HORIZONTAL_RULE = "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "\n"; // validated command line configuration final AggConfig config; // Reference to the database connection we will use final Client client; AtomicInteger total = new AtomicInteger(); // Statistics manager objects from the client final ClientStatsContext fullStatsContext; /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ static class AggConfig extends CLIConfig { @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; @Option(desc = "Number of invocations.") int invocations = 6; @Option(desc = "Restore the data from snapshot or not.") int restore = 0; @Option(desc = "Snapshot path.") String snapshotpath = ""; @Option(desc = "Stored procedure number ( an integer from 1 to 20 )") int proc = 1; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Override public void validate() { if (proc <= 0 || proc > 20) exitWithMessageAndUsage("procedure number must be in range [1, 20]"); } } /** * Provides a callback to be notified on node failure. * This example only logs the event. */ class StatusListener extends ClientStatusListenerExt { @Override public void connectionLost(String hostname, int port, int connectionsLeft, DisconnectCause cause) { // if the benchmark is still active System.err.printf("Connection to %s:%d was lost.\n", hostname, port); } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ public AggregationBenchmark(AggConfig config) { this.config = config; ClientConfig clientConfig = new ClientConfig("", "", new StatusListener()); client = ClientFactory.createClient(clientConfig); fullStatsContext = client.createStatsContext(); System.out.print(HORIZONTAL_RULE); System.out.println(" Command Line Configuration"); System.out.println(HORIZONTAL_RULE); System.out.println(config.getConfigDumpString()); } /** * Connect to a single server with retry. Limited exponential backoff. * No timeout. This will run until the process is killed if it's not * able to connect. * * @param server hostname:port or just hostname (hostname can be ip). */ void connectToOneServerWithRetry(String server) { int sleep = 1000; while (true) { try { client.createConnection(server); break; } catch (Exception e) { System.err.printf("Connection failed - retrying in %d second(s).\n", sleep / 1000); try { Thread.sleep(sleep); } catch (Exception interruted) {} if (sleep < 8000) sleep += sleep; } } System.out.printf("Connected to VoltDB node at: %s.\n", server); } /** * Connect to a set of servers in parallel. Each will retry until * connection. This call will block until all have connected. * * @param servers A comma separated list of servers using the hostname:port * syntax (where :port is optional). * @throws InterruptedException if anything bad happens with the threads. */ void connect(String servers) throws InterruptedException { System.out.println("Connecting to VoltDB..."); String[] serverArray = servers.split(","); final CountDownLatch connections = new CountDownLatch(serverArray.length); // use a new thread to connect to each server for (final String server : serverArray) { new Thread(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); connections.countDown(); } }).start(); } // block until all have connected connections.await(); } void restoreDatabase() throws Exception { ClientResponse resp = null; try { resp = client.callProcedure("@SnapshotRestore", config.snapshotpath, "TestBackupAggBench"); } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { // connect to one or more servers, loop until success connect(config.servers); if (config.restore > 0) { System.out.println("\nLoading data from snapshot..."); restoreDatabase(); } FileWriter fw = null; if ((config.statsfile != null) && (config.statsfile.length() != 0)) { fw = new FileWriter(config.statsfile); } System.out.print(HORIZONTAL_RULE); System.out.println("\nRunning Benchmark"); System.out.println(HORIZONTAL_RULE); // Benchmark start time long queryStartTS, queryElapse; int counter = config.invocations; String procName = "Q" + config.proc; List<Long> m = new ArrayList<Long>(); System.out.println(String.format("Running procedure %s for the %d times...", procName, counter)); queryStartTS = System.nanoTime(); VoltTable vt = null; for (int i = 1; i <= counter; i++) { vt = client.callProcedure(procName).getResults()[0]; if (vt.getRowCount() <= 0) { System.err.println("ERROR Query %d empty result set"); System.exit(-1); } } double avg = (double)(System.nanoTime() - queryStartTS) / counter; System.out.printf("\n\n(Returned %d rows in average %f us)\n", vt.getRowCount(), avg); // block until all outstanding txns return client.drain(); //retrieve stats ClientStats stats = fullStatsContext.fetch().getStats(); // write stats to file //client.writeSummaryCSV(stats, config.statsfile); fw.append(String.format("%s,%d,-1,0,0,0,0,%f,0,0,0,0,0,0\n", "Q" + String.format("%02d", config.proc), stats.getStartTimestamp(), avg/1000.0)); // close down the client connections client.close(); if (fw != null) fw.close(); } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link AggConfig} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments AggConfig config = new AggConfig(); config.parse(AggregationBenchmark.class.getName(), args); AggregationBenchmark benchmark = new AggregationBenchmark(config); benchmark.runBenchmark(); } }
agpl-3.0
zhaozw/android-1
src/net/java/sip/communicator/impl/protocol/jabber/extensions/keepalive/KeepAliveEvent.java
1603
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.jabber.extensions.keepalive; import org.jivesoftware.smack.packet.*; /** * KeepAlive Event. Events are sent if there are no received packets * for a specified interval of time. * XEP-0199: XMPP Ping. * * @author Damian Minkov */ public class KeepAliveEvent extends IQ { /** * Element name for ping. */ public static final String ELEMENT_NAME = "ping"; /** * Namespace for ping. */ public static final String NAMESPACE = "urn:xmpp:ping"; /** * Constructs empty packet */ public KeepAliveEvent() {} /** * Construct packet for sending. * * @param from the address of the contact that the packet coming from. * @param to the address of the contact that the packet is to be sent to. */ public KeepAliveEvent(String from, String to) { if (to == null) { throw new IllegalArgumentException("Parameter cannot be null"); } setType(Type.GET); setTo(to); setFrom(from); } /** * Returns the sub-element XML section of this packet * * @return the packet as XML. */ public String getChildElementXML() { StringBuffer buf = new StringBuffer(); buf.append("<").append(ELEMENT_NAME). append(" xmlns=\"").append(NAMESPACE). append("\"/>"); return buf.toString(); } }
lgpl-2.1
kenweezy/teiid
build/kits/embedded/examples/hbase-as-a-datasource/src/org/teiid/example/TeiidEmbeddedHBaseDataSource.java
5229
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package org.teiid.example; import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.sql.DataSource; import org.teiid.runtime.EmbeddedConfiguration; import org.teiid.runtime.EmbeddedServer; import org.teiid.translator.hbase.HBaseExecutionFactory; import bitronix.tm.resource.jdbc.PoolingDataSource; @SuppressWarnings("nls") public class TeiidEmbeddedHBaseDataSource { private static void execute(Connection connection, String sql, boolean closeConn) throws Exception { try { Statement statement = connection.createStatement(); boolean hasResults = statement.execute(sql); if (hasResults) { ResultSet results = statement.getResultSet(); ResultSetMetaData metadata = results.getMetaData(); int columns = metadata.getColumnCount(); System.out.println("Results"); for (int row = 1; results.next(); row++) { System.out.print(row + ": "); for (int i = 0; i < columns; i++) { if (i > 0) { System.out.print(","); } System.out.print(results.getString(i+1)); } System.out.println(); } results.close(); } statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null && closeConn) { connection.close(); } } } public static void main(String[] args) throws Exception { DataSource ds = setupPhoenixDataSource("java:/hbaseDS", JDBC_DRIVER, JDBC_URL, JDBC_USER, JDBC_PASS); initSamplesData(ds); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "bitronix.tm.jndi.BitronixInitialContextFactory"); EmbeddedServer server = new EmbeddedServer(); HBaseExecutionFactory factory = new HBaseExecutionFactory(); factory.start(); server.addTranslator("translator-hbase", factory); server.start(new EmbeddedConfiguration()); server.deployVDB(new FileInputStream(new File("hbase-vdb.xml"))); Connection c = server.getDriver().connect("jdbc:teiid:hbasevdb", null); execute(c, "SELECT * FROM Customer", false); execute(c, "SELECT * FROM Customer ORDER BY name, city DESC", true); server.stop(); } private static void initSamplesData(DataSource ds) throws Exception { Connection conn = ds.getConnection(); // init test data execute(conn, CUSTOMER, false); execute(conn, "UPSERT INTO \"Customer\" VALUES('101', 'Los Angeles, CA', 'John White', '$400.00', 'Chairs')", false); execute(conn, "UPSERT INTO \"Customer\" VALUES('102', 'Atlanta, GA', 'Jane Brown', '$200.00', 'Lamps')", false); execute(conn, "UPSERT INTO \"Customer\" VALUES('103', 'Pittsburgh, PA', 'Bill Green', '$500.00', 'Desk')", false); execute(conn, "UPSERT INTO \"Customer\" VALUES('104', 'St. Louis, MO', 'Jack Black', '$8000.00', 'Bed')", false); execute(conn, "UPSERT INTO \"Customer\" VALUES('105', 'Los Angeles, CA', 'John White', '$400.00', 'Chairs')", true); } static final String CUSTOMER = "CREATE TABLE IF NOT EXISTS \"Customer\"(\"ROW_ID\" VARCHAR PRIMARY KEY, \"customer\".\"city\" VARCHAR, \"customer\".\"name\" VARCHAR, \"sales\".\"amount\" VARCHAR, \"sales\".\"product\" VARCHAR)"; static final String JDBC_DRIVER = "org.apache.phoenix.jdbc.PhoenixDriver"; static final String JDBC_URL = "jdbc:phoenix:127.0.0.1:2181"; static final String JDBC_USER = ""; static final String JDBC_PASS = ""; static PoolingDataSource pds = null ; private static DataSource setupPhoenixDataSource(String jndiName, String driver, String url, String user, String pass) { if (null != pds) return pds; pds = new PoolingDataSource(); pds.setUniqueName(jndiName); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties().put("user", user); pds.getDriverProperties().put("password", pass); pds.getDriverProperties().put("url", url); pds.getDriverProperties().put("driverClassName", driver); pds.init(); return pds; } }
lgpl-2.1
lukeorland/joshua
src/joshua/decoder/ff/RuleFF.java
2077
package joshua.decoder.ff; import java.util.List; import joshua.corpus.Vocabulary; import joshua.decoder.JoshuaConfiguration; import joshua.decoder.chart_parser.SourcePath; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.tm.Rule; import joshua.decoder.hypergraph.HGNode; import joshua.decoder.segment_file.Sentence; /** * This feature just counts rules that are used. You can restrict it with a number of flags: * * -owner OWNER * Only count rules owned by OWNER * -target|-source * Only count the target or source side (plus the LHS) * * TODO: add an option to separately provide a list of rule counts, restrict to counts above a threshold. */ public class RuleFF extends StatelessFF { private enum Sides { SOURCE, TARGET, BOTH }; private int owner = 0; private Sides sides = Sides.BOTH; public RuleFF(FeatureVector weights, String[] args, JoshuaConfiguration config) { super(weights, "RuleFF", args, config); owner = Vocabulary.id(parsedArgs.get("owner")); if (parsedArgs.containsKey("source")) sides = Sides.SOURCE; else if (parsedArgs.containsKey("target")) sides = Sides.TARGET; } @Override public DPState compute(Rule rule, List<HGNode> tailNodes, int i, int j, SourcePath sourcePath, Sentence sentence, Accumulator acc) { if (owner > 0 && rule.getOwner() == owner) { String ruleString = getRuleString(rule); acc.add(ruleString, 1); } return null; } private String getRuleString(Rule rule) { String ruleString = ""; switch(sides) { case BOTH: ruleString = String.format("%s %s %s", Vocabulary.word(rule.getLHS()), rule.getFrenchWords(), rule.getEnglishWords()); break; case SOURCE: ruleString = String.format("%s %s", Vocabulary.word(rule.getLHS()), rule.getFrenchWords()); break; case TARGET: ruleString = String.format("%s %s", Vocabulary.word(rule.getLHS()), rule.getEnglishWords()); break; } return ruleString.replaceAll("[ =]", "~"); } }
lgpl-2.1
raedle/univis
lib/springframework-1.2.8/src/org/springframework/jdbc/support/incrementer/HsqlMaxValueIncrementer.java
5168
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.support.incrementer; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.support.JdbcUtils; /** * Class to increment maximum value of a given HSQL table with the equivalent * of an auto-increment column. Note: If you use this class, your HSQL key * column should <i>NOT</i> be auto-increment, as the sequence table does the job. * * <p>The sequence is kept in a table. There should be one sequence table per * table that needs an auto-generated key. * * <p>Example: * * <pre> * create table tab (id int not null primary key, text varchar(100)); * create table tab_sequence (value identity); * insert into tab_sequence values(0);</pre> * * If cacheSize is set, the intermediate values are served without querying the * database. If the server or your application is stopped or crashes or a transaction * is rolled back, the unused values will never be served. The maximum hole size in * numbering is consequently the value of cacheSize. * * @author Isabelle Muszynski * @author Jean-Pierre Pawlak * @author Thomas Risberg */ public class HsqlMaxValueIncrementer extends AbstractDataFieldMaxValueIncrementer { /** The name of the column for this sequence */ private String columnName; /** The number of keys buffered in a cache */ private int cacheSize = 1; private long[] valueCache = null; /** The next id to serve from the value cache */ private int nextValueIndex = -1; /** * Default constructor. **/ public HsqlMaxValueIncrementer() { } /** * Convenience constructor. * @param ds the DataSource to use * @param incrementerName the name of the sequence/table to use * @param columnName the name of the column in the sequence table to use **/ public HsqlMaxValueIncrementer(DataSource ds, String incrementerName, String columnName) { setDataSource(ds); setIncrementerName(incrementerName); this.columnName = columnName; afterPropertiesSet(); } /** * Set the name of the column in the sequence table. */ public void setColumnName(String columnName) { this.columnName = columnName; } /** * Return the name of the column in the sequence table. */ public String getColumnName() { return this.columnName; } /** * Set the number of buffered keys. */ public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } /** * Return the number of buffered keys. */ public int getCacheSize() { return this.cacheSize; } public void afterPropertiesSet() { super.afterPropertiesSet(); if (this.columnName == null) { throw new IllegalArgumentException("columnName is required"); } } protected synchronized long getNextKey() throws DataAccessException { if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) { /* * Need to use straight JDBC code because we need to make sure that the insert and select * are performed on the same connection (otherwise we can't be sure that last_insert_id() * returned the correct value) */ Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null; try { stmt = con.createStatement(); DataSourceUtils.applyTransactionTimeout(stmt, getDataSource()); this.valueCache = new long[getCacheSize()]; this.nextValueIndex = 0; for (int i = 0; i < getCacheSize(); i++) { stmt.executeUpdate("insert into " + getIncrementerName() + " values(null)"); ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName()); try { if (!rs.next()) { throw new DataAccessResourceFailureException("identity() failed after executing an update"); } this.valueCache[i] = rs.getLong(1); } finally { JdbcUtils.closeResultSet(rs); } } long maxValue = this.valueCache[(this.valueCache.length - 1)]; stmt.executeUpdate("delete from " + getIncrementerName() + " where " + this.columnName + " < " + maxValue); } catch (SQLException ex) { throw new DataAccessResourceFailureException("Could not obtain identity()", ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } } return this.valueCache[this.nextValueIndex++]; } }
lgpl-2.1
cacheonix/cacheonix-core
test/src/org/cacheonix/impl/cache/distributed/partitioned/AtomicRemoveRequestTest.java
3189
/* * Cacheonix Systems licenses this file to You under the LGPL 2.1 * (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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.cache.distributed.partitioned; import java.io.IOException; import org.cacheonix.CacheonixTestCase; import org.cacheonix.TestUtils; import org.cacheonix.impl.cache.item.Binary; import org.cacheonix.impl.net.ClusterNodeAddress; import org.cacheonix.impl.net.serializer.Serializer; import org.cacheonix.impl.net.serializer.SerializerFactory; import org.cacheonix.impl.net.serializer.Wireable; /** * AtomicRemoveRequestTest Tester. * * @author simeshev@cacheonix.org * @version 1.0 */ public final class AtomicRemoveRequestTest extends CacheonixTestCase { private static final String CACHE_NAME = "cache.name"; private static final Binary KEY = toBinary("key"); private static final Binary VALUE = toBinary("value"); private AtomicRemoveRequest request = null; private ClusterNodeAddress clusterNodeAddress; /** * Tests that no exceptions occur when creating the object using a default constructor. */ public void testDefaultConstructor() { assertNotNull(new AtomicRemoveRequest().toString()); } public void testGetPartitionName() { assertEquals(CACHE_NAME, request.getCacheName()); } public void testGetKey() { assertEquals(KEY, request.getKey()); } public void testGetValue() { assertEquals(VALUE, request.getValue()); } public void testToString() { assertNotNull(request.toString()); } public void testGetProcessID() { assertEquals(clusterNodeAddress, request.getSender()); } public void testSerializeDeserialize() throws IOException { final Serializer ser = SerializerFactory.getInstance().getSerializer(Serializer.TYPE_JAVA); final AtomicRemoveRequest deserializedRequest = (AtomicRemoveRequest) ser.deserialize(ser.serialize(request)); assertEquals(request, deserializedRequest); assertEquals(request.getValue(), deserializedRequest.getValue()); } public void testHashCode() { assertTrue(request.hashCode() != 0); } public void testGetType() { assertEquals(Wireable.TYPE_CACHE_ATOMIC_REMOVE_REQUEST, request.getWireableType()); } protected void setUp() throws Exception { super.setUp(); clusterNodeAddress = TestUtils.createTestAddress(); request = new AtomicRemoveRequest(clusterNodeAddress, CACHE_NAME, KEY, VALUE); } public String toString() { return "AtomicRemoveRequestTest{" + "request=" + request + ", clusterNodeAddress=" + clusterNodeAddress + "} " + super.toString(); } }
lgpl-2.1
jaredbracken/sonic-ndk
src/com/badlogic/gdx/utils/Json.java
34255
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.JsonWriter.OutputType; import com.badlogic.gdx.utils.ObjectMap.Entry; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** Reads/writes Java objects to/from JSON, automatically. * @author Nathan Sweet */ public class Json { private static final boolean debug = false; private JsonWriter writer; private String typeName = "class"; private boolean usePrototypes = true; private OutputType outputType; private final ObjectMap<Class, ObjectMap<String, FieldMetadata>> typeToFields = new ObjectMap(); private final ObjectMap<String, Class> tagToClass = new ObjectMap(); private final ObjectMap<Class, String> classToTag = new ObjectMap(); private final ObjectMap<Class, Serializer> classToSerializer = new ObjectMap(); private final ObjectMap<Class, Object[]> classToDefaultValues = new ObjectMap(); private boolean ignoreUnknownFields; public Json () { outputType = OutputType.minimal; } public Json (OutputType outputType) { this.outputType = outputType; } public void setIgnoreUnknownFields (boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } public void setOutputType (OutputType outputType) { this.outputType = outputType; } public void addClassTag (String tag, Class type) { tagToClass.put(tag, type); classToTag.put(type, tag); } public Class getClass (String tag) { Class type = tagToClass.get(tag); if (type != null) return type; try { return Class.forName(tag); } catch (ClassNotFoundException ex) { throw new SerializationException(ex); } } public String getTag (Class type) { String tag = classToTag.get(type); if (tag != null) return tag; return type.getName(); } /** Sets the name of the JSON field to store the Java class name or class tag when required to avoid ambiguity during * deserialization. Set to null to never output this information, but be warned that deserialization may fail. */ public void setTypeName (String typeName) { this.typeName = typeName; } public <T> void setSerializer (Class<T> type, Serializer<T> serializer) { classToSerializer.put(type, serializer); } public <T> Serializer<T> getSerializer (Class<T> type) { return classToSerializer.get(type); } public void setUsePrototypes (boolean usePrototypes) { this.usePrototypes = usePrototypes; } public void setElementType (Class type, String fieldName, Class elementType) { ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); FieldMetadata metadata = fields.get(fieldName); if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")"); metadata.elementType = elementType; } private ObjectMap<String, FieldMetadata> cacheFields (Class type) { ArrayList<Field> allFields = new ArrayList(); Class nextClass = type; while (nextClass != Object.class) { Collections.addAll(allFields, nextClass.getDeclaredFields()); nextClass = nextClass.getSuperclass(); } ObjectMap<String, FieldMetadata> nameToField = new ObjectMap(); for (int i = 0, n = allFields.size(); i < n; i++) { Field field = allFields.get(i); int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) continue; if (Modifier.isStatic(modifiers)) continue; if (field.isSynthetic()) continue; if (!field.isAccessible()) { try { field.setAccessible(true); } catch (AccessControlException ex) { continue; } } nameToField.put(field.getName(), new FieldMetadata(field)); } typeToFields.put(type, nameToField); return nameToField; } public String toJson (Object object) { return toJson(object, object == null ? null : object.getClass(), (Class)null); } public String toJson (Object object, Class knownType) { return toJson(object, knownType, (Class)null); } public String toJson (Object object, Class knownType, Class elementType) { StringWriter buffer = new StringWriter(); toJson(object, knownType, elementType, buffer); return buffer.toString(); } public void toJson (Object object, FileHandle file) { toJson(object, object == null ? null : object.getClass(), null, file); } public void toJson (Object object, Class knownType, FileHandle file) { toJson(object, knownType, null, file); } public void toJson (Object object, Class knownType, Class elementType, FileHandle file) { Writer writer = null; try { writer = file.writer(false); toJson(object, knownType, elementType, writer); } catch (Exception ex) { throw new SerializationException("Error writing file: " + file, ex); } finally { try { if (writer != null) writer.close(); } catch (IOException ignored) { } } } public void toJson (Object object, Writer writer) { toJson(object, object == null ? null : object.getClass(), null, writer); } public void toJson (Object object, Class knownType, Writer writer) { toJson(object, knownType, null, writer); } public void toJson (Object object, Class knownType, Class elementType, Writer writer) { if (!(writer instanceof JsonWriter)) { writer = new JsonWriter(writer); } ((JsonWriter)writer).setOutputType(outputType); this.writer = (JsonWriter)writer; try { writeValue(object, knownType, elementType); } finally { this.writer = null; } } public void writeFields (Object object) { Class type = object.getClass(); Object[] defaultValues = getDefaultValues(type); ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); int i = 0; for (FieldMetadata metadata : fields.values()) { Field field = metadata.field; try { Object value = field.get(object); if (defaultValues != null) { Object defaultValue = defaultValues[i++]; if (value == null && defaultValue == null) continue; if (value != null && defaultValue != null && value.equals(defaultValue)) continue; } if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")"); writer.name(field.getName()); writeValue(value, field.getType(), metadata.elementType); } catch (IllegalAccessException ex) { throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex); } catch (SerializationException ex) { ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } catch (Exception runtimeEx) { SerializationException ex = new SerializationException(runtimeEx); ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } } } private Object[] getDefaultValues (Class type) { if (!usePrototypes) return null; if (classToDefaultValues.containsKey(type)) return classToDefaultValues.get(type); Object object; try { object = newInstance(type); } catch (Exception ex) { classToDefaultValues.put(type, null); return null; } ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); Object[] values = new Object[fields.size]; classToDefaultValues.put(type, values); int i = 0; for (FieldMetadata metadata : fields.values()) { Field field = metadata.field; try { values[i++] = field.get(object); } catch (IllegalAccessException ex) { throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex); } catch (SerializationException ex) { ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { SerializationException ex = new SerializationException(runtimeEx); ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } } return values; } public void writeField (Object object, String name) { writeField(object, name, name, null); } public void writeField (Object object, String name, Class elementType) { writeField(object, name, name, elementType); } public void writeField (Object object, String fieldName, String jsonName) { writeField(object, fieldName, jsonName, null); } public void writeField (Object object, String fieldName, String jsonName, Class elementType) { Class type = object.getClass(); ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); FieldMetadata metadata = fields.get(fieldName); if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")"); Field field = metadata.field; if (elementType == null) elementType = metadata.elementType; try { if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")"); writer.name(jsonName); writeValue(field.get(object), field.getType(), elementType); } catch (IllegalAccessException ex) { throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex); } catch (SerializationException ex) { ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } catch (Exception runtimeEx) { SerializationException ex = new SerializationException(runtimeEx); ex.addTrace(field + " (" + type.getName() + ")"); throw ex; } } public void writeValue (String name, Object value) { try { writer.name(name); } catch (IOException ex) { throw new SerializationException(ex); } writeValue(value, value.getClass(), null); } public void writeValue (String name, Object value, Class knownType) { try { writer.name(name); } catch (IOException ex) { throw new SerializationException(ex); } writeValue(value, knownType, null); } public void writeValue (String name, Object value, Class knownType, Class elementType) { try { writer.name(name); } catch (IOException ex) { throw new SerializationException(ex); } writeValue(value, knownType, elementType); } public void writeValue (Object value) { writeValue(value, value.getClass(), null); } public void writeValue (Object value, Class knownType) { writeValue(value, knownType, null); } public void writeValue (Object value, Class knownType, Class elementType) { try { if (value == null) { writer.value(null); return; } Class actualType = value.getClass(); if (actualType.isPrimitive() || actualType == String.class || actualType == Integer.class || actualType == Boolean.class || actualType == Float.class || actualType == Long.class || actualType == Double.class || actualType == Short.class || actualType == Byte.class || actualType == Character.class) { writer.value(value); return; } if (value instanceof Serializable) { writeObjectStart(actualType, knownType); ((Serializable)value).write(this); writeObjectEnd(); return; } Serializer serializer = classToSerializer.get(actualType); if (serializer != null) { serializer.write(this, value, knownType); return; } if (value instanceof Array) { if (knownType != null && actualType != knownType) throw new SerializationException("Serialization of an Array other than the known type is not supported.\n" + "Known type: " + knownType + "\nActual type: " + actualType); writeArrayStart(); Array array = (Array)value; for (int i = 0, n = array.size; i < n; i++) writeValue(array.get(i), elementType, null); writeArrayEnd(); return; } if (value instanceof Collection) { if (knownType != null && actualType != knownType && actualType != ArrayList.class) throw new SerializationException("Serialization of a Collection other than the known type is not supported.\n" + "Known type: " + knownType + "\nActual type: " + actualType); writeArrayStart(); for (Object item : (Collection)value) writeValue(item, elementType, null); writeArrayEnd(); return; } if (actualType.isArray()) { if (elementType == null) elementType = actualType.getComponentType(); int length = java.lang.reflect.Array.getLength(value); writeArrayStart(); for (int i = 0; i < length; i++) writeValue(java.lang.reflect.Array.get(value, i), elementType, null); writeArrayEnd(); return; } if (value instanceof OrderedMap) { if (knownType == null) knownType = OrderedMap.class; writeObjectStart(actualType, knownType); OrderedMap map = (OrderedMap)value; for (Object key : map.orderedKeys()) { writer.name(convertToString(key)); writeValue(map.get(key), elementType, null); } writeObjectEnd(); return; } if (value instanceof ArrayMap) { if (knownType == null) knownType = ArrayMap.class; writeObjectStart(actualType, knownType); ArrayMap map = (ArrayMap)value; for (int i = 0, n = map.size; i < n; i++) { writer.name(convertToString(map.keys[i])); writeValue(map.values[i], elementType, null); } writeObjectEnd(); return; } if (value instanceof ObjectMap) { if (knownType == null) knownType = OrderedMap.class; writeObjectStart(actualType, knownType); for (Entry entry : ((ObjectMap<?, ?>)value).entries()) { writer.name(convertToString(entry.key)); writeValue(entry.value, elementType, null); } writeObjectEnd(); return; } if (value instanceof Map) { if (knownType == null) knownType = OrderedMap.class; writeObjectStart(actualType, knownType); for (Map.Entry entry : ((Map<?, ?>)value).entrySet()) { writer.name(convertToString(entry.getKey())); writeValue(entry.getValue(), elementType, null); } writeObjectEnd(); return; } if (actualType.isEnum()) { writer.value(value); return; } writeObjectStart(actualType, knownType); writeFields(value); writeObjectEnd(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeObjectStart (String name) { try { writer.name(name); } catch (IOException ex) { throw new SerializationException(ex); } writeObjectStart(); } public void writeObjectStart (String name, Class actualType, Class knownType) { try { writer.name(name); } catch (IOException ex) { throw new SerializationException(ex); } writeObjectStart(actualType, knownType); } public void writeObjectStart () { try { writer.object(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeObjectStart (Class actualType, Class knownType) { try { writer.object(); } catch (IOException ex) { throw new SerializationException(ex); } if (knownType == null || knownType != actualType) writeType(actualType); } public void writeObjectEnd () { try { writer.pop(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeArrayStart (String name) { try { writer.name(name); writer.array(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeArrayStart () { try { writer.array(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeArrayEnd () { try { writer.pop(); } catch (IOException ex) { throw new SerializationException(ex); } } public void writeType (Class type) { if (typeName == null) return; String className = classToTag.get(type); if (className == null) className = type.getName(); try { writer.set(typeName, className); } catch (IOException ex) { throw new SerializationException(ex); } if (debug) System.out.println("Writing type: " + type.getName()); } public <T> T fromJson (Class<T> type, Reader reader) { return (T)readValue(type, null, new JsonReader().parse(reader)); } public <T> T fromJson (Class<T> type, Class elementType, Reader reader) { return (T)readValue(type, elementType, new JsonReader().parse(reader)); } public <T> T fromJson (Class<T> type, InputStream input) { return (T)readValue(type, null, new JsonReader().parse(input)); } public <T> T fromJson (Class<T> type, Class elementType, InputStream input) { return (T)readValue(type, elementType, new JsonReader().parse(input)); } public <T> T fromJson (Class<T> type, FileHandle file) { try { return (T)readValue(type, null, new JsonReader().parse(file)); } catch (Exception ex) { throw new SerializationException("Error reading file: " + file, ex); } } public <T> T fromJson (Class<T> type, Class elementType, FileHandle file) { try { return (T)readValue(type, elementType, new JsonReader().parse(file)); } catch (Exception ex) { throw new SerializationException("Error reading file: " + file, ex); } } public <T> T fromJson (Class<T> type, char[] data, int offset, int length) { return (T)readValue(type, null, new JsonReader().parse(data, offset, length)); } public <T> T fromJson (Class<T> type, Class elementType, char[] data, int offset, int length) { return (T)readValue(type, elementType, new JsonReader().parse(data, offset, length)); } public <T> T fromJson (Class<T> type, String json) { return (T)readValue(type, null, new JsonReader().parse(json)); } public <T> T fromJson (Class<T> type, Class elementType, String json) { return (T)readValue(type, elementType, new JsonReader().parse(json)); } public void readField (Object object, String name, Object jsonData) { readField(object, name, name, null, jsonData); } public void readField (Object object, String name, Class elementType, Object jsonData) { readField(object, name, name, elementType, jsonData); } public void readField (Object object, String fieldName, String jsonName, Object jsonData) { readField(object, fieldName, jsonName, null, jsonData); } public void readField (Object object, String fieldName, String jsonName, Class elementType, Object jsonData) { OrderedMap jsonMap = (OrderedMap)jsonData; Class type = object.getClass(); ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); FieldMetadata metadata = fields.get(fieldName); if (metadata == null) throw new SerializationException("Field not found: " + fieldName + " (" + type.getName() + ")"); Field field = metadata.field; Object jsonValue = jsonMap.get(jsonName); if (jsonValue == null) return; if (elementType == null) elementType = metadata.elementType; try { field.set(object, readValue(field.getType(), elementType, jsonValue)); } catch (IllegalAccessException ex) { throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex); } catch (SerializationException ex) { ex.addTrace(field.getName() + " (" + type.getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { SerializationException ex = new SerializationException(runtimeEx); ex.addTrace(field.getName() + " (" + type.getName() + ")"); throw ex; } } public void readFields (Object object, Object jsonData) { OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData; Class type = object.getClass(); ObjectMap<String, FieldMetadata> fields = typeToFields.get(type); if (fields == null) fields = cacheFields(type); for (Entry<String, Object> entry : jsonMap.entries()) { FieldMetadata metadata = fields.get(entry.key); if (metadata == null) { if (ignoreUnknownFields) { if (debug) System.out.println("Ignoring unknown field: " + entry.key + " (" + type.getName() + ")"); continue; } else throw new SerializationException("Field not found: " + entry.key + " (" + type.getName() + ")"); } Field field = metadata.field; if (entry.value == null) continue; try { field.set(object, readValue(field.getType(), metadata.elementType, entry.value)); } catch (IllegalAccessException ex) { throw new SerializationException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex); } catch (SerializationException ex) { ex.addTrace(field.getName() + " (" + type.getName() + ")"); throw ex; } catch (RuntimeException runtimeEx) { SerializationException ex = new SerializationException(runtimeEx); ex.addTrace(field.getName() + " (" + type.getName() + ")"); throw ex; } } } public <T> T readValue (String name, Class<T> type, Object jsonData) { OrderedMap jsonMap = (OrderedMap)jsonData; return (T)readValue(type, null, jsonMap.get(name)); } public <T> T readValue (String name, Class<T> type, T defaultValue, Object jsonData) { OrderedMap jsonMap = (OrderedMap)jsonData; Object jsonValue = jsonMap.get(name); if (jsonValue == null) return defaultValue; return (T)readValue(type, null, jsonValue); } public <T> T readValue (String name, Class<T> type, Class elementType, Object jsonData) { OrderedMap jsonMap = (OrderedMap)jsonData; return (T)readValue(type, elementType, jsonMap.get(name)); } public <T> T readValue (String name, Class<T> type, Class elementType, T defaultValue, Object jsonData) { OrderedMap jsonMap = (OrderedMap)jsonData; Object jsonValue = jsonMap.get(name); if (jsonValue == null) return defaultValue; return (T)readValue(type, elementType, jsonValue); } public <T> T readValue (Class<T> type, Class elementType, T defaultValue, Object jsonData) { return (T)readValue(type, elementType, jsonData); } public <T> T readValue (Class<T> type, Object jsonData) { return (T)readValue(type, null, jsonData); } public <T> T readValue (Class<T> type, Class elementType, Object jsonData) { if (jsonData == null) return null; if (jsonData instanceof OrderedMap) { OrderedMap<String, Object> jsonMap = (OrderedMap)jsonData; String className = typeName == null ? null : (String)jsonMap.remove(typeName); if (className != null) { try { type = (Class<T>)Class.forName(className); } catch (ClassNotFoundException ex) { type = tagToClass.get(className); if (type == null) throw new SerializationException(ex); } } Object object; if (type != null) { Serializer serializer = classToSerializer.get(type); if (serializer != null) return (T)serializer.read(this, jsonMap, type); object = newInstance(type); if (object instanceof Serializable) { ((Serializable)object).read(this, jsonMap); return (T)object; } if (object instanceof HashMap) { HashMap result = (HashMap)object; for (Entry entry : jsonMap.entries()) result.put(entry.key, readValue(elementType, null, entry.value)); return (T)result; } } else object = new OrderedMap(); if (object instanceof ObjectMap) { ObjectMap result = (ObjectMap)object; for (String key : jsonMap.orderedKeys()) result.put(key, readValue(elementType, null, jsonMap.get(key))); return (T)result; } readFields(object, jsonMap); return (T)object; } if (type != null) { Serializer serializer = classToSerializer.get(type); if (serializer != null) return (T)serializer.read(this, jsonData, type); } if (jsonData instanceof Array) { Array array = (Array)jsonData; if (type == null || Array.class.isAssignableFrom(type)) { Array newArray = new Array(array.size); for (int i = 0, n = array.size; i < n; i++) newArray.add(readValue(elementType, null, array.get(i))); return (T)newArray; } if (ArrayList.class.isAssignableFrom(type)) { ArrayList newArray = new ArrayList(array.size); for (int i = 0, n = array.size; i < n; i++) newArray.add(readValue(elementType, null, array.get(i))); return (T)newArray; } if (type.isArray()) { Class componentType = type.getComponentType(); if (elementType == null) elementType = componentType; Object newArray = java.lang.reflect.Array.newInstance(componentType, array.size); for (int i = 0, n = array.size; i < n; i++) java.lang.reflect.Array.set(newArray, i, readValue(elementType, null, array.get(i))); return (T)newArray; } throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")"); } if (jsonData instanceof Float) { Float floatValue = (Float)jsonData; try { if (type == null || type == float.class || type == Float.class) return (T)(Float)floatValue; if (type == int.class || type == Integer.class) return (T)(Integer)floatValue.intValue(); if (type == long.class || type == Long.class) return (T)(Long)floatValue.longValue(); if (type == double.class || type == Double.class) return (T)(Double)floatValue.doubleValue(); if (type == short.class || type == Short.class) return (T)(Short)floatValue.shortValue(); if (type == byte.class || type == Byte.class) return (T)(Byte)floatValue.byteValue(); } catch (NumberFormatException ignored) { } jsonData = String.valueOf(jsonData); } if (jsonData instanceof Boolean) jsonData = String.valueOf(jsonData); if (jsonData instanceof String) { String string = (String)jsonData; if (type == null || type == String.class) return (T)jsonData; try { if (type == int.class || type == Integer.class) return (T)Integer.valueOf(string); if (type == float.class || type == Float.class) return (T)Float.valueOf(string); if (type == long.class || type == Long.class) return (T)Long.valueOf(string); if (type == double.class || type == Double.class) return (T)Double.valueOf(string); if (type == short.class || type == Short.class) return (T)Short.valueOf(string); if (type == byte.class || type == Byte.class) return (T)Byte.valueOf(string); } catch (NumberFormatException ignored) { } if (type == boolean.class || type == Boolean.class) return (T)Boolean.valueOf(string); if (type == char.class || type == Character.class) return (T)(Character)string.charAt(0); if (type.isEnum()) { Object[] constants = type.getEnumConstants(); for (int i = 0, n = constants.length; i < n; i++) if (string.equals(constants[i].toString())) return (T)constants[i]; } if (type == CharSequence.class) return (T)string; throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")"); } return null; } private String convertToString (Object object) { if (object instanceof Class) return ((Class)object).getName(); return String.valueOf(object); } private Object newInstance (Class type) { try { return type.newInstance(); } catch (Exception ex) { try { // Try a private constructor. Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { if (type.isArray()) throw new SerializationException("Encountered JSON object when expected array of type: " + type.getName(), ex); else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) throw new SerializationException("Class cannot be created (non-static member class): " + type.getName(), ex); else throw new SerializationException("Class cannot be created (missing no-arg constructor): " + type.getName(), ex); } catch (Exception privateConstructorException) { ex = privateConstructorException; } throw new SerializationException("Error constructing instance of class: " + type.getName(), ex); } } public String prettyPrint (Object object) { return prettyPrint(object, 0); } public String prettyPrint (String json) { return prettyPrint(json, 0); } public String prettyPrint (Object object, int singleLineColumns) { return prettyPrint(toJson(object), singleLineColumns); } public String prettyPrint (String json, int singleLineColumns) { StringBuilder buffer = new StringBuilder(512); prettyPrint(new JsonReader().parse(json), buffer, 0, singleLineColumns); return buffer.toString(); } private void prettyPrint (Object object, StringBuilder buffer, int indent, int singleLineColumns) { if (object instanceof OrderedMap) { OrderedMap<String, ?> map = (OrderedMap)object; if (map.size == 0) { buffer.append("{}"); } else { boolean newLines = !isFlat(map); int start = buffer.length(); outer: while (true) { buffer.append(newLines ? "{\n" : "{ "); int i = 0; for (String key : map.orderedKeys()) { if (newLines) indent(indent, buffer); buffer.append(outputType.quoteName(key)); buffer.append(": "); prettyPrint(map.get(key), buffer, indent + 1, singleLineColumns); if (i++ < map.size - 1) buffer.append(","); buffer.append(newLines ? '\n' : ' '); if (!newLines && buffer.length() - start > singleLineColumns) { buffer.setLength(start); newLines = true; continue outer; } } break; } if (newLines) indent(indent - 1, buffer); buffer.append('}'); } } else if (object instanceof Array) { Array array = (Array)object; if (array.size == 0) { buffer.append("[]"); } else { boolean newLines = !isFlat(array); int start = buffer.length(); outer: while (true) { buffer.append(newLines ? "[\n" : "[ "); for (int i = 0, n = array.size; i < n; i++) { if (newLines) indent(indent, buffer); prettyPrint(array.get(i), buffer, indent + 1, singleLineColumns); if (i < array.size - 1) buffer.append(","); buffer.append(newLines ? '\n' : ' '); if (!newLines && buffer.length() - start > singleLineColumns) { buffer.setLength(start); newLines = true; continue outer; } } break; } if (newLines) indent(indent - 1, buffer); buffer.append(']'); } } else if (object instanceof String) { buffer.append(outputType.quoteValue((String)object)); } else if (object instanceof Float) { Float floatValue = (Float)object; int intValue = floatValue.intValue(); buffer.append(floatValue - intValue == 0 ? intValue : object); } else if (object instanceof Boolean) { buffer.append(object); } else if (object == null) { buffer.append("null"); } else throw new SerializationException("Unknown object type: " + object.getClass()); } static private boolean isFlat (ObjectMap<?, ?> map) { for (Entry entry : map.entries()) { if (entry.value instanceof ObjectMap) return false; if (entry.value instanceof Array) return false; } return true; } static private boolean isFlat (Array array) { for (int i = 0, n = array.size; i < n; i++) { Object value = array.get(i); if (value instanceof ObjectMap) return false; if (value instanceof Array) return false; } return true; } static private void indent (int count, StringBuilder buffer) { for (int i = 0; i < count; i++) buffer.append('\t'); } static private class FieldMetadata { Field field; Class elementType; public FieldMetadata (Field field) { this.field = field; Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { Type[] actualTypes = ((ParameterizedType)genericType).getActualTypeArguments(); if (actualTypes.length == 1) { Type actualType = actualTypes[0]; if (actualType instanceof Class) elementType = (Class)actualType; else if (actualType instanceof ParameterizedType) elementType = (Class)((ParameterizedType)actualType).getRawType(); } } } } static public interface Serializer<T> { public void write (Json json, T object, Class knownType); public T read (Json json, Object jsonData, Class type); } static abstract public class ReadOnlySerializer<T> implements Serializer<T> { public void write (Json json, T object, Class knownType) { } abstract public T read (Json json, Object jsonData, Class type); } static public interface Serializable { public void write (Json json); public void read (Json json, OrderedMap<String, Object> jsonData); } }
lgpl-2.1
aloubyansky/wildfly-core
controller/src/test/java/org/jboss/as/controller/test/GlobalOperationsTestCase.java
51962
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.controller.test; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES_ONLY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CAPABILITIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CAPABILITY_REFERENCE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CAPABILITY_REFERENCE_PATTERN_ELEMENTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DYNAMIC; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DYNAMIC_ELEMENTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INHERITED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NOTIFICATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NOTIFICATION_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_RESOURCES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_TYPES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_OPERATION_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUEST_PROPERTIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESOURCE_ADDED_NOTIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESOURCE_REMOVED_NOTIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNTIME_ONLY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.Set; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.junit.Assert; import org.junit.Test; /** * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> * @version $Revision: 1.1 $ */ public class GlobalOperationsTestCase extends AbstractGlobalOperationsTestCase { @Test public void testRecursiveRead() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); assertTrue(result.hasDefined("profile")); assertTrue(result.get("profile").hasDefined("profileA")); //Defaults are included by default } @Test public void testRecursiveReadResourceAndReadAttributeWithAndWithoutDefaults() throws Exception { ////////////////////////////////////////////////////////////////////// // 1) Check that the recursive sub resources don't include defaults //Defaults are included by default ModelNode operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); assertTrue(result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "default").isDefined()); Assert.assertEquals("Default string", result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "default").asString()); Assert.assertEquals("Name2", result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "name").asString()); //Explicitly say to include defaults operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); operation.get(INCLUDE_DEFAULTS).set(true); result = executeForResult(operation); assertTrue(result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "default").isDefined()); Assert.assertEquals("Default string", result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "default").asString()); Assert.assertEquals("Name2", result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "name").asString()); //Explicitly say to not include defaults operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); operation.get(INCLUDE_DEFAULTS).set(false); result = executeForResult(operation); assertFalse(result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "default").isDefined()); Assert.assertEquals("Name2", result.get("profile", "profileA", "subsystem", "subsystem1", "type2", "other", "name").asString()); ////////////////////////////////////////////////////////////////////// // 2) Now check that include-defaults works directly on the resource //Defaults should be included by default operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); result = executeForResult(operation); Assert.assertEquals("Name2", result.get("name").asString()); Assert.assertEquals("Default string", result.get("default").asString()); //Explicitly say to include defaults operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); operation.get(INCLUDE_DEFAULTS).set(true); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); result = executeForResult(operation); Assert.assertEquals("Name2", result.get("name").asString()); Assert.assertEquals("Default string", result.get("default").asString()); //Explicitly say to not include defaults operation = createOperation(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); operation.get(INCLUDE_DEFAULTS).set(false); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); result = executeForResult(operation); Assert.assertEquals("Name2", result.get("name").asString()); Assert.assertFalse(result.get("default").isDefined()); ////////////////////////////////////////////////////////////////////// // 2) Read the default attribute //Defaults should be included by default operation = createOperation(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); operation.get(NAME).set("default"); result = executeForResult(operation); Assert.assertEquals("Default string", result.asString()); //Explicitly say to include defaults operation = createOperation(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); operation.get(NAME).set("default"); operation.get(INCLUDE_DEFAULTS).set(true); result = executeForResult(operation); Assert.assertEquals("Default string", result.asString()); //Explicitly say to not include defaults operation = createOperation(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).add("profile", "profileA").add("subsystem", "subsystem1").add( "type2", "other"); operation.get(NAME).set("default"); operation.get(INCLUDE_DEFAULTS).set(false); result = executeForResult(operation); Assert.assertFalse(result.isDefined()); } @Test public void testRecursiveReadSubModelOperationSimple() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); assertNotNull(result); checkRecursiveSubsystem1(result); assertFalse(result.get("metric1").isDefined()); // Query runtime metrics operation = createOperation(READ_RESOURCE_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(INCLUDE_RUNTIME).set(true); result = executeForResult(operation); assertTrue(result.get("metric1").isDefined()); assertTrue(result.get("metric2").isDefined()); } @Test public void testNonRecursiveReadSubModelOperationSimple() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(RECURSIVE).set(false); ModelNode result = executeForResult(operation); assertNotNull(result); checkNonRecursiveSubsystem1(result, false); } @Test public void testRecursiveReadSubModelOperationComplex() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_OPERATION, "profile", "profileA", "subsystem", "subsystem2"); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); assertNotNull(result); checkRecursiveSubsystem2(result); } @Test public void testReadAttributeValue() throws Exception { ModelNode operation = createOperation(READ_ATTRIBUTE_OPERATION, "profile", "profileA", "subsystem", "subsystem2"); operation.get(NAME).set("int"); ModelNode result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.INT, result.getType()); assertEquals(102, result.asInt()); operation.get(NAME).set("string1"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.STRING, result.getType()); assertEquals("s1", result.asString()); operation.get(NAME).set("list"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); List<ModelNode> list = result.asList(); assertEquals(2, list.size()); assertEquals("l1A", list.get(0).asString()); assertEquals("l1B", list.get(1).asString()); operation.get(NAME).set("non-existent-attribute"); try { result = executeForResult(operation); fail("Expected error for non-existent attribute"); } catch (OperationFailedException expected) { } operation.get(NAME).set("string2"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.STRING, result.getType()); assertEquals("s2", result.asString()); operation = createOperation(READ_ATTRIBUTE_OPERATION, "profile", "profileC", "subsystem", "subsystem4"); operation.get(NAME).set("name"); executeForFailure(operation); operation = createOperation(READ_ATTRIBUTE_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); operation.get(NAME).set("name"); result = executeForResult(operation); assertNotNull(result); assertEquals("Overridden by special read handler", result.asString()); operation = createOperation(READ_ATTRIBUTE_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(NAME).set("metric1"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.INT, result.getType()); } @Test public void testWriteAttributeValue() throws Exception { ModelNode read = createOperation(READ_ATTRIBUTE_OPERATION, "profile", "profileA", "subsystem", "subsystem2"); read.get(NAME).set("long"); ModelNode result = executeForResult(read); assertEquals(ModelType.LONG, result.getType()); long original = result.asLong(); ModelNode write = createOperation(WRITE_ATTRIBUTE_OPERATION, "profile", "profileA", "subsystem", "subsystem2"); write.get(NAME).set("long"); try { write.get(VALUE).set(99999L); executeForResult(write); result = executeForResult(read); assertEquals(ModelType.LONG, result.getType()); assertEquals(99999L, result.asLong()); write.get(VALUE).set("Not Valid"); try { executeForResult(write); fail("Expected error setting long property to string"); } catch (Exception expected) { } //TODO How to set a value to null? } finally { write.get(VALUE).set(original); executeForResult(write); result = executeForResult(read); assertEquals(ModelType.LONG, result.getType()); assertEquals(original, result.asLong()); } write.get(NAME).set("string1"); write.get(VALUE).set("Hello"); try { executeForResult(write); fail("Expected error setting property with no write handler"); } catch (Exception expected) { } } @Test public void testReadChildrenNames() throws Exception { ModelNode operation = createOperation(READ_CHILDREN_NAMES_OPERATION, "profile", "profileA"); operation.get(CHILD_TYPE).set("subsystem"); ModelNode result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertEquals(2, result.asList().size()); List<String> names = modelNodeListToStringList(result.asList()); assertTrue(names.contains("subsystem1")); assertTrue(names.contains("subsystem2")); operation = createOperation(READ_CHILDREN_NAMES_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(CHILD_TYPE).set("type2"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); names = modelNodeListToStringList(result.asList()); assertEquals(1, names.size()); assertTrue(names.contains("other")); operation.get(CHILD_TYPE).set("non-existent-child"); try { result = executeForResult(operation); fail("Expected error for non-existent child"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_NAMES_OPERATION, "profile", "profileC", "subsystem", "subsystem4"); operation.get(CHILD_TYPE).set("type1"); // BES 2011/06/06 These assertions make no sense; as they are no different from "non-existent-child" case // Replacing with a fail check // result = executeForResult(operation); // assertNotNull(result); // assertEquals(ModelType.LIST, result.getType()); // assertTrue(result.asList().isEmpty()); try { result = executeForResult(operation); fail("Expected error for type1 child under subsystem4"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_NAMES_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); operation.get(CHILD_TYPE).set("type1"); // BES 2011/06/06 see comment above result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertTrue(result.asList().isEmpty()); // try { // result = executeForResult(operation); // fail("Expected error for type1 child under subsystem5"); // } catch (OperationFailedException expected) { // } } @Test public void testReadChildrenTypes() throws Exception { ModelNode operation = createOperation(READ_CHILDREN_TYPES_OPERATION, "profile", "profileA"); ModelNode result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertEquals(1, result.asList().size()); assertEquals("subsystem", result.asList().get(0).asString()); operation = createOperation(READ_CHILDREN_TYPES_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertEquals(2, result.asList().size()); List<String> stringList = modelNodeListToStringList(result.asList()); assertTrue(Arrays.asList("type1", "type2").containsAll(stringList)); operation = createOperation(READ_CHILDREN_TYPES_OPERATION, "profile", "profileA", "subsystem", "non-existent"); try { result = executeForResult(operation); fail("Expected error for non-existent child"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_TYPES_OPERATION, "profile", "profileC", "subsystem", "subsystem4"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertTrue(result.asList().isEmpty()); operation = createOperation(READ_CHILDREN_TYPES_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.LIST, result.getType()); assertEquals(1, result.asList().size()); assertEquals("type1", result.asList().get(0).asString()); } @Test public void testReadChildrenResources() throws Exception { ModelNode operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileA"); operation.get(CHILD_TYPE).set("subsystem"); operation.get(INCLUDE_RUNTIME).set(true); ModelNode result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertEquals(2, result.asList().size()); ModelNode subsystem1 = null; ModelNode subsystem2 = null; for(Property property : result.asPropertyList()) { if("subsystem1".equals(property.getName())) { subsystem1 = property.getValue(); } else if("subsystem2".equals(property.getName())) { subsystem2 = property.getValue(); } } assertNotNull(subsystem1); checkNonRecursiveSubsystem1(subsystem1, true); assertNotNull(subsystem2); checkRecursiveSubsystem2(subsystem2); operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(CHILD_TYPE).set("type2"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertEquals(1, result.asList().size()); ModelNode other = null; for(Property property : result.asPropertyList()) { if("other".equals(property.getName())) { other = property.getValue(); } } assertNotNull(other); assertEquals("Name2", other.require(NAME).asString()); operation.get(CHILD_TYPE).set("non-existent-child"); try { result = executeForResult(operation); fail("Expected error for non-existent child"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileC", "subsystem", "subsystem4"); operation.get(CHILD_TYPE).set("type1"); // BES 2011/06/06 These assertions make no sense; as they are no different from "non-existent-child" case // Replacing with a fail check // result = executeForResult(operation); // assertNotNull(result); // assertEquals(ModelType.LIST, result.getType()); // assertTrue(result.asList().isEmpty()); try { result = executeForResult(operation); fail("Expected error for type1 child under subsystem4"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); operation.get(CHILD_TYPE).set("type1"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertTrue(result.asList().isEmpty()); } @Test public void testReadChildrenResourcesRecursive() throws Exception { ModelNode operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileA"); operation.get(CHILD_TYPE).set("subsystem"); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertEquals(2, result.asList().size()); ModelNode subsystem1 = null; ModelNode subsystem2 = null; for(Property property : result.asPropertyList()) { if("subsystem1".equals(property.getName())) { subsystem1 = property.getValue(); } else if("subsystem2".equals(property.getName())) { subsystem2 = property.getValue(); } } assertNotNull(subsystem1); checkRecursiveSubsystem1(subsystem1); assertNotNull(subsystem2); checkRecursiveSubsystem2(subsystem2); operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(CHILD_TYPE).set("type2"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertEquals(1, result.asList().size()); ModelNode other = null; for(Property property : result.asPropertyList()) { if("other".equals(property.getName())) { other = property.getValue(); } } assertNotNull(other); assertEquals("Name2", other.require(NAME).asString()); operation.get(CHILD_TYPE).set("non-existent-child"); try { result = executeForResult(operation); fail("Expected error for non-existent child"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileC", "subsystem", "subsystem4"); operation.get(CHILD_TYPE).set("type1"); // BES 2011/06/06 These assertions make no sense; as they are no different from "non-existent-child" case // Replacing with a fail check // result = executeForResult(operation); // assertNotNull(result); // assertEquals(ModelType.LIST, result.getType()); // assertTrue(result.asList().isEmpty()); try { result = executeForResult(operation); fail("Expected error for type1 child under subsystem4"); } catch (OperationFailedException expected) { } operation = createOperation(READ_CHILDREN_RESOURCES_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); operation.get(CHILD_TYPE).set("type1"); result = executeForResult(operation); assertNotNull(result); assertEquals(ModelType.OBJECT, result.getType()); assertTrue(result.asList().isEmpty()); } @Test public void testReadOperationNamesOperation() throws Exception { ModelNode operation = createOperation(READ_OPERATION_NAMES_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); ModelNode result = executeForResult(operation); assertEquals(ModelType.LIST, result.getType()); assertEquals(23, result.asList().size()); List<String> names = modelNodeListToStringList(result.asList()); assertTrue(names.contains("testA1-1")); assertTrue(names.contains("testA1-2")); assertTrue(names.contains(READ_RESOURCE_OPERATION)); assertTrue(names.contains(READ_ATTRIBUTE_OPERATION)); assertTrue(names.contains(READ_RESOURCE_DESCRIPTION_OPERATION)); assertTrue(names.contains(READ_CHILDREN_NAMES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_TYPES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_RESOURCES_OPERATION)); assertTrue(names.contains(READ_OPERATION_NAMES_OPERATION)); assertTrue(names.contains(READ_OPERATION_DESCRIPTION_OPERATION)); assertTrue(names.contains(WRITE_ATTRIBUTE_OPERATION)); operation = createOperation(READ_OPERATION_NAMES_OPERATION, "profile", "profileA", "subsystem", "subsystem2"); result = executeForResult(operation); assertEquals(ModelType.LIST, result.getType()); assertEquals(22, result.asList().size()); names = modelNodeListToStringList(result.asList()); assertTrue(names.contains("testA2")); assertTrue(names.contains(READ_RESOURCE_OPERATION)); assertTrue(names.contains(READ_ATTRIBUTE_OPERATION)); assertTrue(names.contains(READ_RESOURCE_DESCRIPTION_OPERATION)); assertTrue(names.contains(READ_CHILDREN_NAMES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_TYPES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_RESOURCES_OPERATION)); assertTrue(names.contains(READ_OPERATION_NAMES_OPERATION)); assertTrue(names.contains(READ_OPERATION_DESCRIPTION_OPERATION)); assertTrue(names.contains(WRITE_ATTRIBUTE_OPERATION)); operation = createOperation(READ_OPERATION_NAMES_OPERATION, "profile", "profileB"); result = executeForResult(operation); assertEquals(ModelType.LIST, result.getType()); assertEquals(21, result.asList().size()); assertTrue(names.contains(READ_RESOURCE_OPERATION)); assertTrue(names.contains(READ_ATTRIBUTE_OPERATION)); assertTrue(names.contains(READ_RESOURCE_DESCRIPTION_OPERATION)); assertTrue(names.contains(READ_CHILDREN_NAMES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_TYPES_OPERATION)); assertTrue(names.contains(READ_CHILDREN_RESOURCES_OPERATION)); assertTrue(names.contains(READ_OPERATION_NAMES_OPERATION)); assertTrue(names.contains(READ_OPERATION_DESCRIPTION_OPERATION)); assertTrue(names.contains(WRITE_ATTRIBUTE_OPERATION)); } @Test public void testReadOperationDescriptionOperation() throws Exception { ModelNode operation = createOperation(READ_OPERATION_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(NAME).set("Nothing"); try { ModelNode result = executeForResult(operation); fail("Received invalid successful result " + result.toString()); } catch (OperationFailedException good) { // the correct result } operation.get(NAME).set("testA1-2"); ModelNode result = executeForResult(operation); assertEquals(ModelType.OBJECT, result.getType()); assertEquals("testA1-2", result.require(OPERATION_NAME).asString()); assertEquals(ModelType.STRING, result.require(REQUEST_PROPERTIES).require("paramA2").require(TYPE).asType()); assertEquals(false, result.require(RUNTIME_ONLY).asBoolean()); operation = createOperation(READ_OPERATION_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem6"); operation.get(NAME).set("testA"); result = executeForResult(operation); assertEquals(true, result.require(RUNTIME_ONLY).asBoolean()); } @Test public void testReadResourceDescriptionOperation() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, false, false, false); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA"); result = executeForResult(operation); checkProfileNodeDescription(result, false, false, false); //TODO this is not possible - the wildcard address does not correspond to anything in the real model //operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "*"); //result = execute(operation); //checkProfileNodeDescription(result, false); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); result = executeForResult(operation); checkSubsystem1Description(result, false, false, false); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); result = executeForResult(operation); checkType1Description(result); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); result = executeForResult(operation); checkType1Description(result); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); result = executeForResult(operation); checkType2Description(result); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem3"); result = executeForResult(operation); ModelNode capabilityReferenceAttribute = result.require(ATTRIBUTES).require("test_capability"); assertEquals("org.wildfly.test.capability", capabilityReferenceAttribute.require(CAPABILITY_REFERENCE).asString()); assertTrue(capabilityReferenceAttribute.hasDefined(CAPABILITY_REFERENCE_PATTERN_ELEMENTS)); List<ModelNode> dynamicElements= capabilityReferenceAttribute.require(CAPABILITY_REFERENCE_PATTERN_ELEMENTS).asList(); assertEquals(3, dynamicElements.size()); assertEquals("param1", dynamicElements.get(0).asString()); assertEquals("param2", dynamicElements.get(1).asString()); assertEquals("test_capability", dynamicElements.get(2).asString()); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem4"); result = executeForResult(operation); capabilityReferenceAttribute = result.require(ATTRIBUTES).require("simple_ref"); assertEquals("org.wildfly.test.capability", capabilityReferenceAttribute.require(CAPABILITY_REFERENCE).asString()); assertFalse(capabilityReferenceAttribute.hasDefined(CAPABILITY_REFERENCE_PATTERN_ELEMENTS)); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileC", "subsystem", "subsystem5"); result = executeForResult(operation); List<ModelNode> capabilities = result.require(CAPABILITIES).asList(); assertEquals(1, capabilities.size()); ModelNode requirement = capabilities.get(0); assertEquals("org.wildfly.test.capability.req", requirement.require(NAME).asString()); assertTrue(requirement.require(REQUIRED).asBoolean()); assertTrue(requirement.require(DYNAMIC).asBoolean()); dynamicElements = requirement.require(DYNAMIC_ELEMENTS).asList(); assertEquals(2, dynamicElements.size()); assertEquals("profile", dynamicElements.get(0).asString()); assertEquals("subsystem5", dynamicElements.get(1).asString());//fixed value assertFalse(result.get(OPERATIONS).isDefined()); } @Test public void testReadRecursiveResourceDescriptionOperation() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, true, false, false); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA"); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkProfileNodeDescription(result, true, false, false); //TODO this is not possible - the wildcard address does not correspond to anything in the real model //operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "*"); //operation.get(RECURSIVE).set(true); //result = execute(operation); //checkProfileNodeDescription(result, false); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkSubsystem1Description(result, true, false, false); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); assertFalse(result.get(OPERATIONS).isDefined()); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType2Description(result); assertFalse(result.get(OPERATIONS).isDefined()); } @Test public void testReadResourceDescriptionWithOperationsOperation() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(OPERATIONS).set(true); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, false, true, false); assertTrue(result.require(OPERATIONS).isDefined()); Set<String> ops = result.require(OPERATIONS).keys(); assertTrue(ops.contains(READ_ATTRIBUTE_OPERATION)); assertTrue(ops.contains(READ_CHILDREN_NAMES_OPERATION)); assertTrue(ops.contains(READ_CHILDREN_TYPES_OPERATION)); assertTrue(ops.contains(READ_OPERATION_DESCRIPTION_OPERATION)); assertTrue(ops.contains(READ_OPERATION_NAMES_OPERATION)); assertTrue(ops.contains(READ_RESOURCE_DESCRIPTION_OPERATION)); assertTrue(ops.contains(READ_RESOURCE_OPERATION)); for (String op : ops) { assertEquals(op, result.require(OPERATIONS).require(op).require(OPERATION_NAME).asString()); } operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(OPERATIONS).set(true); result = executeForResult(operation); checkSubsystem1Description(result, false, true, false); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); operation.get(OPERATIONS).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); operation.get(OPERATIONS).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); operation.get(OPERATIONS).set(true); result = executeForResult(operation); checkType2Description(result); } @Test public void testRecursiveReadResourceDescriptionWithOperationsOperation() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(OPERATIONS).set(true); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, true, true, false); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(OPERATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkSubsystem1Description(result, true, true, false); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); operation.get(OPERATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); operation.get(OPERATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); operation.get(OPERATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType2Description(result); } @Test public void testReadResourceDescriptionOperationWithNotifications() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(NOTIFICATIONS).set(true); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, false, false, true); assertTrue(result.require(NOTIFICATIONS).isDefined()); Set<String> notifs = result.require(NOTIFICATIONS).keys(); assertTrue(notifs.contains(RESOURCE_ADDED_NOTIFICATION)); assertTrue(notifs.contains(RESOURCE_REMOVED_NOTIFICATION)); assertTrue(notifs.contains(ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION)); for (String notif : notifs) { assertEquals(notif, result.require(NOTIFICATIONS).require(notif).require(NOTIFICATION_TYPE).asString()); } operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(NOTIFICATIONS).set(true); result = executeForResult(operation); checkSubsystem1Description(result, false, false, true); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); operation.get(NOTIFICATIONS).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); operation.get(NOTIFICATIONS).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); operation.get(NOTIFICATIONS).set(true); result = executeForResult(operation); checkType2Description(result); } @Test public void testReadResourceDescriptionOperationWithNotInheritedNotifications() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(NOTIFICATIONS).set(true); operation.get(INHERITED).set(false); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, false, false, true); assertTrue(result.require(NOTIFICATIONS).isDefined()); Set<String> notifs = result.require(NOTIFICATIONS).keys(); assertTrue(notifs.contains(RESOURCE_ADDED_NOTIFICATION)); assertTrue(notifs.contains(RESOURCE_REMOVED_NOTIFICATION)); assertTrue(notifs.contains(ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION)); for (String notif : notifs) { assertEquals(notif, result.require(NOTIFICATIONS).require(notif).require(NOTIFICATION_TYPE).asString()); } operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(NOTIFICATIONS).set(true); operation.get(INHERITED).set(false); result = executeForResult(operation); checkSubsystem1Description(result, false, false, false); } @Test public void testRecursiveReadResourceDescriptionOperationWithNotifications() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION); operation.get(NOTIFICATIONS).set(true); operation.get(RECURSIVE).set(true); ModelNode result = executeForResult(operation); checkRootNodeDescription(result, true, false, true); assertTrue(result.require(NOTIFICATIONS).isDefined()); Set<String> notifs = result.require(NOTIFICATIONS).keys(); assertTrue(notifs.contains(RESOURCE_ADDED_NOTIFICATION)); assertTrue(notifs.contains(RESOURCE_REMOVED_NOTIFICATION)); assertTrue(notifs.contains(ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION)); for (String notif : notifs) { assertEquals(notif, result.require(NOTIFICATIONS).require(notif).require(NOTIFICATION_TYPE).asString()); } operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1"); operation.get(NOTIFICATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkSubsystem1Description(result, true, false, true); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing1"); operation.get(NOTIFICATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type1", "thing2"); operation.get(NOTIFICATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType1Description(result); operation = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, "profile", "profileA", "subsystem", "subsystem1", "type2", "other"); operation.get(NOTIFICATIONS).set(true); operation.get(RECURSIVE).set(true); result = executeForResult(operation); checkType2Description(result); } @Test public void testReadResourceAttributesOnly() throws Exception { ModelNode operation = createOperation(READ_RESOURCE_OPERATION); operation.get(ATTRIBUTES_ONLY).set(true); ModelNode result = executeForResult(operation); Assert.assertEquals(0, result.keys().size()); operation.get(OP_ADDR).add("profile", "profileB"); result = executeForResult(operation); Assert.assertEquals(1, result.keys().size()); Assert.assertEquals("Profile B", result.get("name").asString()); operation.get(OP_ADDR).setEmptyList().add("profile", "profileA").add("subsystem", "subsystem1"); result = executeForResult(operation); Assert.assertEquals(3, result.keys().size()); List<ModelNode> list = result.get("attr1").asList(); Assert.assertEquals(2, list.size()); Assert.assertEquals(1, list.get(0).asInt()); Assert.assertEquals(2, list.get(1).asInt()); assertTrue(result.has("read-only")); assertTrue(result.has("read-write")); assertFalse(result.hasDefined("read-only")); assertFalse(result.hasDefined("read-write")); operation.get(RECURSIVE).set(true); executeForFailure(operation); } private void checkNonRecursiveSubsystem1(ModelNode result, boolean includeRuntime) { assertEquals(includeRuntime ? 7 : 5, result.keys().size()); ModelNode content = result.require("attr1"); List<ModelNode> list = content.asList(); assertEquals(2, list.size()); assertEquals(1, list.get(0).asInt()); assertEquals(2, list.get(1).asInt()); assertTrue(result.has("read-only")); assertTrue(result.has("read-write")); assertFalse(result.hasDefined("read-only")); assertFalse(result.hasDefined("read-write")); assertEquals(2, result.require("type1").keys().size()); assertTrue(result.require("type1").has("thing1")); assertFalse(result.require("type1").get("thing1").isDefined()); assertTrue(result.require("type1").has("thing2")); assertFalse(result.require("type1").get("thing2").isDefined()); assertEquals(1, result.require("type2").keys().size()); assertTrue(result.require("type2").has("other")); assertFalse(result.require("type2").get("other").isDefined()); if (includeRuntime) { assertEquals(ModelType.INT, result.require("metric1").getType()); assertEquals(ModelType.INT, result.require("metric2").getType()); } } private void checkRecursiveSubsystem1(ModelNode result) { assertEquals(5, result.keys().size()); List<ModelNode> list = result.require("attr1").asList(); assertEquals(2, list.size()); assertEquals(1, list.get(0).asInt()); assertEquals(2, list.get(1).asInt()); assertTrue(result.has("read-only")); assertTrue(result.has("read-write")); assertFalse(result.hasDefined("read-only")); assertFalse(result.hasDefined("read-write")); assertEquals("Name11", result.require("type1").require("thing1").require("name").asString()); assertEquals(201, result.require("type1").require("thing1").require("value").asInt()); assertEquals("Name12", result.require("type1").require("thing2").require("name").asString()); assertEquals(202, result.require("type1").require("thing2").require("value").asInt()); assertEquals("Name2", result.require("type2").require("other").require("name").asString()); } private void checkRecursiveSubsystem2(ModelNode result) { assertEquals(14, result.keys().size()); assertEquals(new BigDecimal(100), result.require("bigdecimal").asBigDecimal()); assertEquals(new BigInteger("101"), result.require("biginteger").asBigInteger()); assertTrue(result.require("boolean").asBoolean()); assertEquals(3, result.require("bytes").asBytes().length); assertEquals(1, result.require("bytes").asBytes()[0]); assertEquals(2, result.require("bytes").asBytes()[1]); assertEquals(3, result.require("bytes").asBytes()[2]); assertEquals(Double.MAX_VALUE, result.require("double").asDouble(), 0.0d); assertEquals("{expr}", result.require("expression").asString()); assertEquals(102, result.require("int").asInt()); List<ModelNode> list = result.require("list").asList(); assertEquals(2, list.size()); assertEquals("l1A", list.get(0).asString()); assertEquals("l1B", list.get(1).asString()); assertEquals(Long.MAX_VALUE, result.require("long").asLong()); assertEquals("objVal", result.require("object").require("value").asString()); Property prop = result.require("property").asProperty(); assertEquals("prop1", prop.getName()); assertEquals("value1", prop.getValue().asString()); assertEquals("s1", result.require("string1").asString()); assertEquals("s2", result.require("string2").asString()); assertEquals(ModelType.TYPE, result.require("type").asType()); } }
lgpl-2.1
xwiki/xwiki-rendering
xwiki-rendering-api/src/main/java/org/xwiki/rendering/block/FigureBlock.java
1952
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.block; import java.util.List; import java.util.Map; import org.xwiki.rendering.listener.Listener; /** * Tags the content as a figure (image(s), diagram, code fragment, audio, video, charts, etc). * This is similar to the HTML5 {@code <figure>} element), with the ability to associate a caption to the figure. * * @version $Id$ * @since 10.2 */ public class FigureBlock extends AbstractBlock { /** * @param blocks the children blocks of the figure */ public FigureBlock(List<Block> blocks) { super(blocks); } /** * @param blocks the children blocks of the figure * @param parameters the parameters of the figure */ public FigureBlock(List<Block> blocks, Map<String, String> parameters) { super(blocks, parameters); } @Override public void before(Listener listener) { listener.beginFigure(getParameters()); } @Override public void after(Listener listener) { listener.endFigure(getParameters()); } }
lgpl-2.1
geotools/geotools
modules/library/main/src/main/java/org/geotools/feature/visitor/StandardDeviationVisitor.java
4970
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.feature.visitor; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.geotools.data.simple.SimpleFeatureCollection; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.expression.Expression; /** * Determines the standard deviation. * * <pre> * ---------------------------- * | 1 --- * Std dev = | ___ \ ( x - mean ) ^ 2 * \| N /__ * </pre> * * aka std dev = sqrt((sum((x-mean)^2))/N) where N is the number of samples. * * <p>It uses the rolling variance algorithm described here: * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm * * @author Cory Horner, Refractions Research Inc. * @author Andrea Aime, GeoSolutions */ public class StandardDeviationVisitor implements FeatureCalc, FeatureAttributeVisitor { public static class Result extends AbstractCalcResult { final Double deviation; public Result() { this.deviation = null; } public Result(double deviation) { this.deviation = deviation; } @Override public Object getValue() { return deviation; } } private Expression expr; boolean visited = false; int countNull = 0; int countNaN = 0; int count = 0; double mean = 0; double m2 = 0; Result result; /** Constructs a standard deviation visitor based on the specified expression */ public StandardDeviationVisitor(Expression expr) { this.expr = expr; } public void init(SimpleFeatureCollection collection) { // do nothing } public Expression getExpression() { return expr; } public void setValue(Object value) { reset(); if (value instanceof Result) { this.result = (Result) value; } else if (value instanceof Number) { this.result = new Result(((Number) value).doubleValue()); } else { throw new IllegalArgumentException( "Result must be a " + Result.class.getName() + " or a Number"); } } @Override public List<Expression> getExpressions() { return Arrays.asList(expr); } @Override public Optional<List<Class>> getResultType(List<Class> inputTypes) { if (inputTypes == null || inputTypes.size() != 1) throw new IllegalArgumentException( "Expecting a single type in input, not " + inputTypes); return Optional.of(Collections.singletonList(Double.class)); } @Override public CalcResult getResult() { if (result != null) return result; if (count == 0) { return CalcResult.NULL_RESULT; } return new Result(Math.sqrt(m2 / count)); } public void visit(SimpleFeature feature) { visit((org.opengis.feature.Feature) feature); } @Override public void visit(org.opengis.feature.Feature feature) { Object value = expr.evaluate(feature); if (value == null) { countNull++; // increment the null count return; // don't store this value } if (value instanceof Double) { double doubleVal = ((Double) value).doubleValue(); if (Double.isNaN(doubleVal) || Double.isInfinite(doubleVal)) { countNaN++; // increment the NaN count return; // don't store NaN value } } double x = ((Number) value).doubleValue(); count++; double delta = x - mean; mean = mean + delta / count; m2 = m2 + delta * (x - mean); // This expression uses the new value of mean } public void reset() { this.count = 0; this.countNull = 0; this.countNaN = 0; this.m2 = 0; this.mean = 0; } /** mean value generated when calcualting standard deviation */ public double getMean() { return mean; } /** @return the number of features which returned a NaN */ public int getNaNCount() { return countNaN; } /** @return the number of features which returned a null */ public int getNullCount() { return countNull; } }
lgpl-2.1
sanyaade-mediadev/vars
vars-query/src/test/java/vars/query/DAOTests.java
1211
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vars.query; import com.google.inject.Injector; import org.junit.Before; import org.junit.Test; import org.mbari.util.Dispatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vars.knowledgebase.Concept; import vars.knowledgebase.ConceptDAO; import vars.knowledgebase.KnowledgebaseDAOFactory; import vars.query.ui.Lookup; /** * * @author brian */ public class DAOTests { private final Logger log = LoggerFactory.getLogger(getClass()); KnowledgebaseDAOFactory knowledgebaseDAOFactory; QueryPersistenceService queryDAO; @Before public void setup() { Dispatcher dispatcher = Lookup.getGuiceInjectorDispatcher(); Injector injector = (Injector) dispatcher.getValueObject(); knowledgebaseDAOFactory = injector.getInstance(KnowledgebaseDAOFactory.class); queryDAO = injector.getInstance(QueryPersistenceService.class); } @Test public void test1() { ConceptDAO dao = knowledgebaseDAOFactory.newConceptDAO(); Concept concept = dao.findRoot(); log.info("Found root concept: " + concept); } }
lgpl-2.1
halfspiral/tuxguitar
TuxGuitar/src/org/herac/tuxguitar/app/view/component/tab/edit/MouseKit.java
3368
package org.herac.tuxguitar.app.view.component.tab.edit; import org.herac.tuxguitar.app.TuxGuitar; import org.herac.tuxguitar.app.action.impl.edit.tablature.TGMenuShownAction; import org.herac.tuxguitar.app.action.impl.edit.tablature.TGMouseClickAction; import org.herac.tuxguitar.app.action.impl.edit.tablature.TGMouseExitAction; import org.herac.tuxguitar.app.action.impl.edit.tablature.TGMouseMoveAction; import org.herac.tuxguitar.app.action.listener.gui.TGActionProcessingListener; import org.herac.tuxguitar.editor.TGEditorManager; import org.herac.tuxguitar.editor.action.TGActionProcessor; import org.herac.tuxguitar.player.base.MidiPlayer; import org.herac.tuxguitar.ui.event.UIMenuEvent; import org.herac.tuxguitar.ui.event.UIMenuHideListener; import org.herac.tuxguitar.ui.event.UIMenuShowListener; import org.herac.tuxguitar.ui.event.UIMouseDownListener; import org.herac.tuxguitar.ui.event.UIMouseEvent; import org.herac.tuxguitar.ui.event.UIMouseExitListener; import org.herac.tuxguitar.ui.event.UIMouseMoveListener; import org.herac.tuxguitar.ui.event.UIMouseUpListener; import org.herac.tuxguitar.ui.resource.UIPosition; import org.herac.tuxguitar.util.TGContext; public class MouseKit implements UIMouseDownListener, UIMouseUpListener, UIMouseMoveListener, UIMouseExitListener, UIMenuShowListener, UIMenuHideListener { private EditorKit kit; private UIPosition position; private boolean menuOpen; public MouseKit(EditorKit kit){ this.kit = kit; this.position = new UIPosition(0,0); this.menuOpen = false; } public boolean isBusy() { TGContext context = this.kit.getTablature().getContext(); return (TGEditorManager.getInstance(context).isLocked() || MidiPlayer.getInstance(context).isRunning()); } public void executeAction(String actionId, float x, float y, boolean byPassProcessing) { TGActionProcessor tgActionProcessor = new TGActionProcessor(this.kit.getTablature().getContext(), actionId); tgActionProcessor.setAttribute(EditorKit.ATTRIBUTE_X, x); tgActionProcessor.setAttribute(EditorKit.ATTRIBUTE_Y, y); tgActionProcessor.setAttribute(TGActionProcessingListener.ATTRIBUTE_BY_PASS, byPassProcessing); tgActionProcessor.process(); } public void onMouseDown(UIMouseEvent event) { this.position.setX(event.getPosition().getX()); this.position.setY(event.getPosition().getY()); } public void onMouseUp(UIMouseEvent event) { this.position.setX(event.getPosition().getX()); this.position.setY(event.getPosition().getY()); this.executeAction(TGMouseClickAction.NAME, event.getPosition().getX(), event.getPosition().getY(), false); } public void onMouseMove(UIMouseEvent event) { if(!this.menuOpen && this.kit.isMouseEditionAvailable() && !this.isBusy()){ this.executeAction(TGMouseMoveAction.NAME, event.getPosition().getX(), event.getPosition().getY(), true); } } public void onMouseExit(UIMouseEvent event) { if(!this.menuOpen && this.kit.isMouseEditionAvailable()) { this.executeAction(TGMouseExitAction.NAME, event.getPosition().getX(), event.getPosition().getY(), true); } } public void onMenuShow(UIMenuEvent event) { this.menuOpen = true; this.executeAction(TGMenuShownAction.NAME, this.position.getX(), this.position.getY(), false); } public void onMenuHide(UIMenuEvent event) { this.menuOpen = false; TuxGuitar.getInstance().updateCache(true); } }
lgpl-2.1
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/workflow/CountClassVersions.java
6249
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2007 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.workflow; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.charsets.UTF8; import edu.umd.cs.findbugs.charsets.UserTextFile; import edu.umd.cs.findbugs.config.CommandLine; import edu.umd.cs.findbugs.util.DualKeyHashMap; import edu.umd.cs.findbugs.util.Util; /** * @author William Pugh */ public class CountClassVersions { public static List<String> readFromStandardInput() throws IOException { return readFrom(UserTextFile.reader(System.in)); } public static List<String> readFrom(Reader r) throws IOException { BufferedReader in = new BufferedReader(r); List<String> lst = new LinkedList<>(); while (true) { String s = in.readLine(); if (s == null) { return lst; } lst.add(s); } } static class CountClassVersionsCommandLine extends CommandLine { public String prefix = ""; public String inputFileList; long maxAge = Long.MIN_VALUE; CountClassVersionsCommandLine() { addOption("-maxAge", "days", "maximum age in days (ignore jar files older than this"); addOption("-inputFileList", "filename", "text file containing names of jar files"); addOption("-prefix", "class name prefix", "prefix of class names that should be analyzed e.g., edu.umd.cs.)"); } @Override protected void handleOption(String option, String optionExtraPart) throws IOException { throw new IllegalArgumentException("Unknown option : " + option); } @Override protected void handleOptionWithArgument(String option, String argument) throws IOException { if ("-prefix".equals(option)) { prefix = argument; } else if ("-inputFileList".equals(option)) { inputFileList = argument; } else if ("-maxAge".equals(option)) { maxAge = System.currentTimeMillis() - (24 * 60 * 60 * 1000L) * Integer.parseInt(argument); } else { throw new IllegalArgumentException("Unknown option : " + option); } } } public static void main(String args[]) throws Exception { FindBugs.setNoAnalysis(); CountClassVersionsCommandLine commandLine = new CountClassVersionsCommandLine(); int argCount = commandLine.parse(args, 0, Integer.MAX_VALUE, "Usage: " + CountClassVersions.class.getName() + " [options] [<jarFile>+] "); List<String> fileList; if (commandLine.inputFileList != null) { fileList = readFrom(UTF8.fileReader(commandLine.inputFileList)); } else if (argCount == args.length) { fileList = readFromStandardInput(); } else { fileList = Arrays.asList(args).subList(argCount, args.length - 1); } byte buffer[] = new byte[8192]; MessageDigest digest = Util.getMD5Digest(); DualKeyHashMap<String, String, String> map = new DualKeyHashMap<>(); for (String fInName : fileList) { File f = new File(fInName); if (f.lastModified() < commandLine.maxAge) { System.err.println("Skipping " + fInName + ", too old (" + new Date(f.lastModified()) + ")"); continue; } System.err.println("Opening " + f); try (ZipFile zipInputFile = new ZipFile(f)) { for (Enumeration<? extends ZipEntry> e = zipInputFile.entries(); e.hasMoreElements();) { ZipEntry ze = e.nextElement(); if (ze == null) { break; } if (ze.isDirectory()) { continue; } String name = ze.getName(); if (!name.endsWith(".class")) { continue; } if (!name.replace('/', '.').startsWith(commandLine.prefix)) { continue; } InputStream zipIn = zipInputFile.getInputStream(ze); while (true) { int bytesRead = zipIn.read(buffer); if (bytesRead < 0) { break; } digest.update(buffer, 0, bytesRead); } String hash = new BigInteger(1, digest.digest()).toString(16); map.put(name, hash, fInName); } } catch (IOException e) { e.printStackTrace(); continue; } } for (String s : map.keySet()) { Map<String, String> values = map.get(s); if (values.size() > 1) { System.out.println(values.size() + "\t" + s + "\t" + values.values()); } } } }
lgpl-2.1
cogtool/cogtool
java/edu/cmu/cs/hcii/cogtool/uimodel/GraphicalCheckBox.java
4751
/******************************************************************************* * CogTool Copyright Notice and Distribution Terms * CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * CogTool is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * CogTool 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 CogTool; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * CogTool makes use of several third-party components, with the * following notices: * * Eclipse SWT version 3.448 * Eclipse GEF Draw2D version 3.2.1 * * Unless otherwise indicated, all Content made available by the Eclipse * Foundation is provided to you under the terms and conditions of the Eclipse * Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this * Content and is also available at http://www.eclipse.org/legal/epl-v10.html. * * CLISP version 2.38 * * Copyright (c) Sam Steingold, Bruno Haible 2001-2006 * This software is distributed under the terms of the FSF Gnu Public License. * See COPYRIGHT file in clisp installation folder for more information. * * ACT-R 6.0 * * Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere & * John R Anderson. * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * Apache Jakarta Commons-Lang 2.1 * * This product contains software developed by the Apache Software Foundation * (http://www.apache.org/) * * jopt-simple version 1.0 * * Copyright (c) 2004-2013 Paul R. Holser, Jr. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Mozilla XULRunner 1.9.0.5 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The J2SE(TM) Java Runtime Environment version 5.0 * * Copyright 2009 Sun Microsystems, Inc., 4150 * Network Circle, Santa Clara, California 95054, U.S.A. All * rights reserved. U.S. * See the LICENSE file in the jre folder for more information. ******************************************************************************/ package edu.cmu.cs.hcii.cogtool.uimodel; import edu.cmu.cs.hcii.cogtool.model.CheckBox; public class GraphicalCheckBox extends GraphicalGridButton { public GraphicalCheckBox(CheckBox c, int color, boolean useToolTip, int rolloverCursor, FrameUIModel displayComputer, WidgetFigureSupport spt, DefaultSEUIModel ovr) { super(c, color, useToolTip, rolloverCursor, displayComputer, spt, ovr); } }
lgpl-2.1
hal/core
gui/src/main/java/org/jboss/as/console/client/shared/subsys/web/LoadSocketBindingsCmd.java
10339
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.subsys.web; import com.google.gwt.user.client.rpc.AsyncCallback; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.model.ModelAdapter; import org.jboss.dmr.client.ModelDescriptionConstants; import org.jboss.dmr.client.ModelNode; import org.jboss.dmr.client.dispatch.DispatchAsync; import org.jboss.dmr.client.dispatch.impl.DMRAction; import org.jboss.dmr.client.dispatch.impl.DMRResponse; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.jboss.dmr.client.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.dmr.client.ModelDescriptionConstants.RECURSIVE; /** * @author Pavel Slegr * @date 3/19/12 */ public class LoadSocketBindingsCmd { private DispatchAsync dispatcher; private int syncCounter; private Map<String,String> sgbBind; private String finalSGB = "standard-sockets"; public LoadSocketBindingsCmd(DispatchAsync dispatcher) { this.dispatcher = dispatcher; } public void loadSocketBindingGroupForName(String groupName, final AsyncCallback<List<String>> callback) { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION); op.get(ModelDescriptionConstants.ADDRESS).add("socket-binding-group", groupName); op.get(ModelDescriptionConstants.CHILD_TYPE).set("socket-binding"); dispatcher.execute(new DMRAction(op), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(ModelAdapter.wasSuccess(response)) { List<ModelNode> payload = response.get("result").asList(); List<String> records = new ArrayList<String>(payload.size()); for(ModelNode binding : payload) { if(binding.asString().contains("socket-binding")){} records.add(binding.asString()); } callback.onSuccess(records); } else { callback.onFailure(new RuntimeException("Failed to load socket binding groups")); } } }); } private void loadServerGroupNames(final AsyncCallback<List<String>> callback) { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION); op.get(ModelDescriptionConstants.OP_ADDR).setEmptyList(); op.get(ModelDescriptionConstants.CHILD_TYPE).set("server-group"); dispatcher.execute(new DMRAction(op), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(ModelAdapter.wasSuccess(response)) { List<ModelNode> payload = response.get("result").asList(); List<String> records = new ArrayList<String>(payload.size()); for(ModelNode binding : payload) { records.add(binding.asString()); } callback.onSuccess(records); } else { callback.onFailure(new RuntimeException("Failed to load socket binding groups")); } } }); } private void getSocketBindingGroupForServerGroup(final String groupName, final AsyncCallback<String[]> callback) { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); op.get(ModelDescriptionConstants.ADDRESS).add("server-group", groupName); op.get(RECURSIVE).set(true); op.get(INCLUDE_RUNTIME).set(true); dispatcher.execute(new DMRAction(op), new AsyncCallback<DMRResponse>() { @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(ModelAdapter.wasSuccess(response)) { List<ModelNode> payload = response.get("result").asList(); List<String> records = new ArrayList<String>(payload.size()); String profile = null; String sbgRef = null; for(ModelNode binding : payload) { if(binding.asString().contains("\"profile\"")){ profile = sanitizeProperty(binding.asString()); } if(binding.asString().contains("\"socket-binding-group\"")){ sbgRef = sanitizeProperty(binding.asString()); } records.add(binding.asString()); } callback.onSuccess(new String[]{profile,sbgRef}); } else { callback.onFailure(new RuntimeException("Failed load server config " + groupName)); } } }); } public void loadSocketBindingGroupForSelectedProfile(final AsyncCallback<List<String>> callback) { final String selectedProfile = Console.MODULES.getCurrentSelectedProfile().getName(); if(selectedProfile != null){ this.loadServerGroupNames(new SimpleCallback<List<String>>() { @Override public void onSuccess(final List<String> groupNames) { sgbBind = new HashMap<String,String>(); if(groupNames.isEmpty()) { //edge case: no server groups exist callback.onSuccess(Collections.EMPTY_LIST); } else { // regular case for(final String groupName : groupNames){ getSocketBindingGroupForServerGroup(groupName, new SimpleCallback<String[]>() { @Override public void onSuccess(String[] result) { sgbBind.put(result[0], result[1]); if(sync(groupNames.size())){ loadSocketBindingGroupForName(finalSGB,new SimpleCallback<List<String>>() { @Override public void onSuccess(List<String> result) { callback.onSuccess(result); } }); } } @Override public void onFailure(Throwable caught) { super.onFailure(caught); // increase syncCounter in case of Failure to prevent to show empty list of sockets, but rather show standard-sockets one syncCounter++; } }); } } } }); } else{ loadSocketBindingGroupForName(finalSGB,new SimpleCallback<List<String>>() { @Override public void onSuccess(List<String> result) { callback.onSuccess(result); } }); } } private String sanitizeProperty(String value){ String prop = value; String propSubstr = prop.substring(prop.indexOf("=>"),prop.length()); int beginIndex = propSubstr.indexOf("\""); int endIndex = propSubstr.lastIndexOf("\""); return propSubstr.substring(beginIndex + 1, endIndex); } private boolean sync(int maxCounts){ this.syncCounter++; if(this.syncCounter == maxCounts){ final String selectedProfile = Console.MODULES.getCurrentSelectedProfile().getName(); if(this.sgbBind.containsKey(selectedProfile)) { this.finalSGB = this.sgbBind.get(selectedProfile); } else{ this.finalSGB = "standard-sockets"; } this.syncCounter = 0; this.sgbBind = new HashMap<String,String>(); return true; } return false; } }
lgpl-2.1
deegree/deegree3
uncoupled/deegree-spring/src/main/java/org/deegree/spring/db/SpringConnectionProviderProvider.java
2775
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2013 by: IDgis bv This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: IDgis bv Boomkamp 16 7461 AX Rijssen The Netherlands http://idgis.nl/ lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.spring.db; import java.net.URL; import org.deegree.db.ConnectionProvider; import org.deegree.db.ConnectionProviderProvider; import org.deegree.workspace.ResourceLocation; import org.deegree.workspace.Workspace; /** * SpringConnectionProviderProvider provides a * {@link org.deegree.spring.db.SpringConnectionProviderMetadata} object * which is subsequently used to construct a * {@link org.deegree.spring.db.SpringConnectionProviderBuilder}. * * @author <a href="mailto:reijer.copier@idgis.nl">Reijer Copier</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class SpringConnectionProviderProvider extends ConnectionProviderProvider { private static final String CONFIG_NS = "http://www.deegree.org/spring/db"; static final URL CONFIG_SCHEMA = SpringConnectionProviderProvider.class.getResource( "/META-INF/schemas/spring/3.4.0/db.xsd" ); @Override public String getNamespace() { return CONFIG_NS; } @Override public SpringConnectionProviderMetadata createFromLocation( Workspace workspace, ResourceLocation<ConnectionProvider> location ) { return new SpringConnectionProviderMetadata( workspace, location, this ); } @Override public URL getSchema() { return CONFIG_SCHEMA; } }
lgpl-2.1
johann8384/opentsdb
src/query/expression/Alias.java
3174
// This file is part of OpenTSDB. // Copyright (C) 2015 The OpenTSDB Authors. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or (at your // option) any later version. This 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 Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.query.expression; import java.util.List; import java.util.Map; import com.google.common.base.Joiner; import net.opentsdb.core.DataPoint; import net.opentsdb.core.DataPoints; import net.opentsdb.core.MutableDataPoint; import net.opentsdb.core.TSQuery; /** * Returns an alias if provided or the original metric name if not. * @since 2.3 */ public class Alias implements Expression { static Joiner COMMA_JOINER = Joiner.on(',').skipNulls(); @Override public DataPoints[] evaluate(TSQuery data_query, List<DataPoints[]> queryResults, List<String> queryParams) { if (queryResults == null || queryResults.size() == 0) { throw new NullPointerException("No query results"); } String aliasTemplate = "__default"; if (queryParams != null && queryParams.size() >= 0) { aliasTemplate = COMMA_JOINER.join(queryParams); } DataPoints[] inputPoints = queryResults.get(0); DataPoint[][] dps = new DataPoint[inputPoints.length][]; for (int j = 0; j < dps.length; j++) { DataPoints base = inputPoints[j]; dps[j] = new DataPoint[base.size()]; int i = 0; for (DataPoint pt : base) { if (pt.isInteger()) { dps[j][i] = MutableDataPoint.ofDoubleValue(pt.timestamp(), pt.longValue()); } else { dps[j][i] = MutableDataPoint.ofDoubleValue(pt.timestamp(), pt.doubleValue()); } i++; } } DataPoints[] resultArray = new DataPoints[queryResults.get(0).length]; for (int i = 0; i < resultArray.length; i++) { PostAggregatedDataPoints result = new PostAggregatedDataPoints(inputPoints[i], dps[i]); String alias = aliasTemplate; for (Map.Entry<String, String> e : inputPoints[i].getTags().entrySet()) { alias = alias.replace("@" + e.getKey(), e.getValue()); } result.setAlias(alias); resultArray[i] = result; } return resultArray; } @Override public String writeStringField(List<String> queryParams, String innerExpression) { if (queryParams == null || queryParams.size() == 0) { return "NULL"; } return queryParams.get(0); } }
lgpl-2.1
BaderLab/AutoAnnotateApp
AutoAnnotate/src/main/java/org/baderlab/autoannotate/internal/Setting.java
751
package org.baderlab.autoannotate.internal; public class Setting<T> { // Note: WarnDialog settings are in WarnDialogModule public final static Setting<Boolean> OVERRIDE_GROUP_LABELS = new Setting<Boolean>("overrideGroupLabels", Boolean.class, true); public final static Setting<Boolean> USE_EASY_MODE = new Setting<Boolean>("useEasyMode", Boolean.class, true); private final String key; private final Class<T> type; private final T defaultValue; private Setting(String key, Class<T> type, T defaultValue) { this.key = key; this.type = type; this.defaultValue = defaultValue; } public String getKey() { return key; } public Class<T> getType() { return type; } public T getDefaultValue() { return defaultValue; } }
lgpl-2.1
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsCheckableDatePanel.java
11037
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.acacia.client.widgets.serialdate; import org.opencms.gwt.client.ui.input.CmsCheckBox; import org.opencms.util.CmsPair; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.SortedSet; import java.util.TreeSet; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.Widget; /** Special list for checkboxes with dates. */ public class CmsCheckableDatePanel extends Composite implements HasValueChangeHandlers<SortedSet<Date>> { /** The various style options for the checkable date panel. */ public static enum Style { /** One column. */ ONE_COLUMN, /** Two columns. */ TWO_COLUMNS, /** Three columns. */ THREE_COLUMNS; /** * Get the width of elements dependent on the style. * @return the element width, e.g., "50%" */ public String getWidth() { switch (this) { case ONE_COLUMN: return "100%"; case TWO_COLUMNS: return "50%"; case THREE_COLUMNS: return "33%"; default: return "100%"; } } } /** Default date format to use if no other format is specified in the message bundle. */ private static final String DEFAULT_DATE_FORMAT = "E, MMMM d, yyyy"; /** The map from the checkboxes in the list to the dates of the boxes. */ SortedSet<CmsCheckBox> m_checkBoxes; /** The dates in the widget. */ SortedSet<Date> m_dates; /** The date format. */ DateTimeFormat m_dateFormat; /** The panel where checkboxes with the dates are places. */ Panel m_panel; /** Flag, indicating if only labels should be shown. */ boolean m_onlyLabels; /** The style of the panel. */ Style m_style; /** The element width determined by the style. */ String m_width; /** * Constructor for creating a one column list with check boxes. * @param dateFormat The date format to use. */ public CmsCheckableDatePanel(String dateFormat) { this(dateFormat, Style.ONE_COLUMN, false); } /** * Constructor for creating a list with check boxes. * @param dateFormat The date format to use. * @param style the style to use for displaying the dates. */ public CmsCheckableDatePanel(String dateFormat, Style style) { this(dateFormat, style, false); } /** * Constructor where all options can be set. * @param dateFormat The date format to use. * @param style the style to use for displaying the dates. * @param onlyLabels flag, indicating if only labels should be shown. */ public CmsCheckableDatePanel(String dateFormat, Style style, boolean onlyLabels) { m_panel = new FlowPanel(); m_style = null == style ? Style.ONE_COLUMN : style; m_width = m_style.getWidth(); m_onlyLabels = onlyLabels; initWidget(m_panel); m_checkBoxes = new TreeSet<CmsCheckBox>(new Comparator<CmsCheckBox>() { public int compare(CmsCheckBox o1, CmsCheckBox o2) { Date date1 = (Date)o1.getElement().getPropertyObject("date"); Date date2 = (Date)o2.getElement().getPropertyObject("date"); if ((null == date1) || (null == date2)) { return 0; } else { return date1.compareTo(date2); } } }); try { m_dateFormat = DateTimeFormat.getFormat(dateFormat); } catch (@SuppressWarnings("unused") Exception e) { m_dateFormat = DateTimeFormat.getFormat(DEFAULT_DATE_FORMAT); } m_dates = new TreeSet<>(); } /** * Adds a date to the list (unchecked). * @param date the date to add. */ public void addDate(Date date) { addDateWithCheckState(date, false); } /** * Adds a date that is already checked. * @param date the date to add. */ public void addDateChecked(Date date) { addDateWithCheckState(date, true); } /** * @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler) */ public HandlerRegistration addValueChangeHandler(ValueChangeHandler<SortedSet<Date>> handler) { return addHandler(handler, ValueChangeEvent.getType()); } /** * Returns all checked dates. * @return all checked dates. */ public SortedSet<Date> getCheckedDates() { return getDates(Boolean.TRUE); } /** * Returns all dates in the list. * @return all dates in the list. */ public SortedSet<Date> getDates() { return new TreeSet<Date>(m_dates); } /** * Returns all dates with the specified check state, if the check state is <code>null</code>, all dates are returned. * @param checkState the check state, the returned dates should have. * @return all dates with the specified check state, if the check state is <code>null</code>, all dates are returned. */ public SortedSet<Date> getDates(Boolean checkState) { TreeSet<Date> result = new TreeSet<Date>(); for (CmsCheckBox cb : m_checkBoxes) { if ((checkState == null) || (cb.isChecked() == checkState.booleanValue())) { Date date = (Date)cb.getElement().getPropertyObject("date"); result.add(date); } } return result; } /** * Returns all dates that are not checked. * @return all dates that are not checked. */ public SortedSet<Date> getUncheckedDates() { return getDates(Boolean.FALSE); } /** * Sets all dates in the list (unchecked). * @param dates the dates to set. */ public void setDates(SortedSet<Date> dates) { setDates(dates, false); } /** * Sets all dates in the list. * @param dates the dates to set * @param checked flag, indicating if all should be checked or unchecked. */ public void setDates(SortedSet<Date> dates, boolean checked) { m_checkBoxes.clear(); for (Date date : dates) { CmsCheckBox cb = generateCheckBox(date, checked); m_checkBoxes.add(cb); } reInitLayoutElements(); setDatesInternal(dates); } /** * Set dates with the provided check states. * @param datesWithCheckInfo the dates to set, accompanied with the check state to set. */ public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) { SortedSet<Date> dates = new TreeSet<>(); m_checkBoxes.clear(); for (CmsPair<Date, Boolean> p : datesWithCheckInfo) { addCheckBox(p.getFirst(), p.getSecond().booleanValue()); dates.add(p.getFirst()); } reInitLayoutElements(); setDatesInternal(dates); } /** * Add a new check box. * @param date the date for the check box * @param checkState the initial check state. */ private void addCheckBox(Date date, boolean checkState) { CmsCheckBox cb = generateCheckBox(date, checkState); m_checkBoxes.add(cb); reInitLayoutElements(); } /** * Add a date with a certain check state. * @param date the date to add. * @param checkState the check state. */ private void addDateWithCheckState(Date date, boolean checkState) { addCheckBox(date, checkState); if (!m_dates.contains(date)) { m_dates.add(date); fireValueChange(); } } /** * Fire a value change event. */ private void fireValueChange() { ValueChangeEvent.fire(this, m_dates); } /** * Generate a new check box with the provided date and check state. * @param date date for the check box. * @param checkState the initial check state. * @return the created check box */ private CmsCheckBox generateCheckBox(Date date, boolean checkState) { CmsCheckBox cb = new CmsCheckBox(); cb.setText(m_dateFormat.format(date)); cb.setChecked(checkState); cb.getElement().setPropertyObject("date", date); return cb; } /** * Refresh the layout element. */ private void reInitLayoutElements() { m_panel.clear(); for (CmsCheckBox cb : m_checkBoxes) { m_panel.add(setStyle(m_onlyLabels ? new Label(cb.getText()) : cb)); } } /** * Updates the internal list of dates and fires a value change if necessary. * * @param dates the dates to set. */ private void setDatesInternal(SortedSet<Date> dates) { if (!m_dates.equals(dates)) { m_dates = new TreeSet<>(dates); fireValueChange(); } } /** * Set the style for the widgets in the panel according to the chosen style option. * @param widget the widget that should be styled. * @return the styled widget. */ private Widget setStyle(Widget widget) { widget.setWidth(m_width); widget.getElement().getStyle().setDisplay(Display.INLINE_BLOCK); return widget; } }
lgpl-2.1
herculeshssj/imobiliariaweb
src/br/com/hslife/imobiliaria/db/HibernateUtility.java
3804
/*** Copyright (c) 2011, 2014 Hércules S. S. José Este arquivo é parte do programa Imobiliária Web. Imobiliária Web é um software livre; você pode redistribui-lo e/ou modificá-lo dentro dos termos da Licença Pública Geral Menor GNU como publicada pela Fundação do Software Livre (FSF); na versão 2.1 da Licença. Este programa é distribuído na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral Menor GNU em português para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral Menor GNU sob o nome de "LICENSE.TXT" junto com este programa, se não, acesse o site HSlife no endereco www.hslife.com.br ou escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. Para mais informações sobre o programa Imobiliária Web e seus autores acesso o endereço www.hslife.com.br, pelo e-mail contato@hslife.com.br ou escreva para Hércules S. S. José, Av. Ministro Lafaeyte de Andrade, 1683 - Bl. 3 Apt 404, Marco II - Nova Iguaçu, RJ, Brasil. ***/ package br.com.hslife.imobiliaria.db; import java.sql.Connection; import org.hibernate.CacheMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; /** * Hibernate Utility class with a convenient method to get Session Factory object. * * @author Hércules */ public class HibernateUtility { private static final SessionFactory sessionFactory; private static final ThreadLocal<Session> sessionThread = new ThreadLocal<Session>(); private static final ThreadLocal<Transaction> transactionThread = new ThreadLocal<Transaction>(); static { try { sessionFactory = new AnnotationConfiguration().configure( "br/com/hslife/imobiliaria/db/hibernate.cfg.xml") .buildSessionFactory(); } catch (RuntimeException e) { e.printStackTrace(); throw e; } } public static Session getSession() { if (sessionThread.get() == null) { Session session = sessionFactory.openSession(); session.setCacheMode(CacheMode.IGNORE); sessionThread.set(session); System.out.println("Nova sessão criada"); } return (Session) sessionThread.get(); } public static Connection getConnection() { return getSession().connection(); } public static void closeSession() { Session session = (Session) sessionThread.get(); if (session != null && session.isOpen()) { sessionThread.set(null); session.close(); System.out.println("Sessão atual fechada"); } } public static void beginTransaction() { Transaction transaction = getSession().beginTransaction(); transactionThread.set(transaction); System.out.println("Transacao iniciada"); } public static void commitTransaction() { Transaction transaction = (Transaction) transactionThread.get(); if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) { transaction.commit(); transactionThread.set(null); System.out.println("Transação finalizada com sucesso"); } } public static void rollbackTransaction() { Transaction transaction = (Transaction) transactionThread.get(); if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) { transaction.rollback(); transactionThread.set(null); System.out.println("Transacao finalizada com falha. Alteraçoes desfeitas"); } } }
lgpl-2.1
icholy/geokettle-2.0
src/org/pentaho/di/trans/steps/parallelgzipcsv/ParGzipCsvInputMeta.java
23424
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans.steps.parallelgzipcsv; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceDefinition; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceNamingInterface; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.resource.ResourceNamingInterface.FileNamingType; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.steps.textfileinput.InputFileMetaInterface; import org.pentaho.di.trans.steps.textfileinput.TextFileInputField; import org.pentaho.di.trans.steps.textfileinput.TextFileInputMeta; import org.w3c.dom.Node; /** * @since 2009-03-06 * @author matt * @version 3.2 */ public class ParGzipCsvInputMeta extends BaseStepMeta implements StepMetaInterface, InputFileMetaInterface { private String filename; private String filenameField; private boolean includingFilename; private String rowNumField; private boolean headerPresent; private String delimiter; private String enclosure; private String bufferSize; private boolean lazyConversionActive; private TextFileInputField[] inputFields; private boolean isaddresult; private boolean runningInParallel; private String encoding; public ParGzipCsvInputMeta() { super(); // allocate BaseStepMeta allocate(0); } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode); } public Object clone() { Object retval = super.clone(); return retval; } public void setDefault() { delimiter = "," ; enclosure = "\"" ; headerPresent = true; lazyConversionActive=true; isaddresult=false; bufferSize="50000"; } private void readData(Node stepnode) throws KettleXMLException { try { filename = XMLHandler.getTagValue(stepnode, "filename"); filenameField = XMLHandler.getTagValue(stepnode, "filename_field"); rowNumField = XMLHandler.getTagValue(stepnode, "rownum_field"); includingFilename = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "include_filename")); delimiter = XMLHandler.getTagValue(stepnode, "separator"); enclosure = XMLHandler.getTagValue(stepnode, "enclosure"); bufferSize = XMLHandler.getTagValue(stepnode, "buffer_size"); headerPresent = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "header")); lazyConversionActive= "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "lazy_conversion")); isaddresult= "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "add_filename_result")); runningInParallel = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "parallel")); encoding = XMLHandler.getTagValue(stepnode, "encoding"); Node fields = XMLHandler.getSubNode(stepnode, "fields"); int nrfields = XMLHandler.countNodes(fields, "field"); allocate(nrfields); for (int i = 0; i < nrfields; i++) { inputFields[i] = new TextFileInputField(); Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i); inputFields[i].setName( XMLHandler.getTagValue(fnode, "name") ); inputFields[i].setType( ValueMeta.getType(XMLHandler.getTagValue(fnode, "type")) ); inputFields[i].setFormat( XMLHandler.getTagValue(fnode, "format") ); inputFields[i].setCurrencySymbol( XMLHandler.getTagValue(fnode, "currency") ); inputFields[i].setDecimalSymbol( XMLHandler.getTagValue(fnode, "decimal") ); inputFields[i].setGroupSymbol( XMLHandler.getTagValue(fnode, "group") ); inputFields[i].setLength( Const.toInt(XMLHandler.getTagValue(fnode, "length"), -1) ); inputFields[i].setPrecision( Const.toInt(XMLHandler.getTagValue(fnode, "precision"), -1) ); inputFields[i].setTrimType( ValueMeta.getTrimTypeByCode( XMLHandler.getTagValue(fnode, "trim_type") ) ); } } catch (Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public void allocate(int nrFields) { inputFields = new TextFileInputField[nrFields]; } public String getXML() { StringBuffer retval = new StringBuffer(500); retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); retval.append(" ").append(XMLHandler.addTagValue("filename_field", filenameField)); retval.append(" ").append(XMLHandler.addTagValue("rownum_field", rowNumField)); retval.append(" ").append(XMLHandler.addTagValue("include_filename", includingFilename)); retval.append(" ").append(XMLHandler.addTagValue("separator", delimiter)); retval.append(" ").append(XMLHandler.addTagValue("enclosure", enclosure)); retval.append(" ").append(XMLHandler.addTagValue("header", headerPresent)); retval.append(" ").append(XMLHandler.addTagValue("buffer_size", bufferSize)); retval.append(" ").append(XMLHandler.addTagValue("lazy_conversion", lazyConversionActive)); retval.append(" ").append(XMLHandler.addTagValue("add_filename_result", isaddresult)); retval.append(" ").append(XMLHandler.addTagValue("parallel", runningInParallel)); retval.append(" ").append(XMLHandler.addTagValue("encoding", encoding)); retval.append(" <fields>").append(Const.CR); for (int i = 0; i < inputFields.length; i++) { TextFileInputField field = inputFields[i]; retval.append(" <field>").append(Const.CR); retval.append(" ").append(XMLHandler.addTagValue("name", field.getName())); retval.append(" ").append(XMLHandler.addTagValue("type", ValueMeta.getTypeDesc(field.getType()))); retval.append(" ").append(XMLHandler.addTagValue("format", field.getFormat())); retval.append(" ").append(XMLHandler.addTagValue("currency", field.getCurrencySymbol())); retval.append(" ").append(XMLHandler.addTagValue("decimal", field.getDecimalSymbol())); retval.append(" ").append(XMLHandler.addTagValue("group", field.getGroupSymbol())); retval.append(" ").append(XMLHandler.addTagValue("length", field.getLength())); retval.append(" ").append(XMLHandler.addTagValue("precision", field.getPrecision())); retval.append(" ").append(XMLHandler.addTagValue("trim_type", ValueMeta.getTrimTypeCode(field.getTrimType()))); retval.append(" </field>").append(Const.CR); } retval.append(" </fields>").append(Const.CR); return retval.toString(); } public void readRep(Repository rep, long id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { filename = rep.getStepAttributeString(id_step, "filename"); filenameField = rep.getStepAttributeString(id_step, "filename_field"); rowNumField = rep.getStepAttributeString(id_step, "rownum_field"); includingFilename = rep.getStepAttributeBoolean(id_step, "include_filename"); delimiter = rep.getStepAttributeString(id_step, "separator"); enclosure = rep.getStepAttributeString(id_step, "enclosure"); headerPresent = rep.getStepAttributeBoolean(id_step, "header"); bufferSize = rep.getStepAttributeString(id_step, "buffer_size"); lazyConversionActive = rep.getStepAttributeBoolean(id_step, "lazy_conversion"); isaddresult = rep.getStepAttributeBoolean(id_step, "add_filename_result"); runningInParallel = rep.getStepAttributeBoolean(id_step, "parallel"); encoding = rep.getStepAttributeString(id_step, "encoding"); int nrfields = rep.countNrStepAttributes(id_step, "field_name"); allocate(nrfields); for (int i = 0; i < nrfields; i++) { inputFields[i] = new TextFileInputField(); inputFields[i].setName( rep.getStepAttributeString(id_step, i, "field_name") ); inputFields[i].setType( ValueMeta.getType(rep.getStepAttributeString(id_step, i, "field_type")) ); inputFields[i].setFormat( rep.getStepAttributeString(id_step, i, "field_format") ); inputFields[i].setCurrencySymbol( rep.getStepAttributeString(id_step, i, "field_currency") ); inputFields[i].setDecimalSymbol( rep.getStepAttributeString(id_step, i, "field_decimal") ); inputFields[i].setGroupSymbol( rep.getStepAttributeString(id_step, i, "field_group") ); inputFields[i].setLength( (int) rep.getStepAttributeInteger(id_step, i, "field_length") ); inputFields[i].setPrecision( (int) rep.getStepAttributeInteger(id_step, i, "field_precision") ); inputFields[i].setTrimType( ValueMeta.getTrimTypeByCode( rep.getStepAttributeString(id_step, i, "field_trim_type")) ); } } catch (Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "filename", filename); rep.saveStepAttribute(id_transformation, id_step, "filename_field", filenameField); rep.saveStepAttribute(id_transformation, id_step, "rownum_field", rowNumField); rep.saveStepAttribute(id_transformation, id_step, "include_filename", includingFilename); rep.saveStepAttribute(id_transformation, id_step, "separator", delimiter); rep.saveStepAttribute(id_transformation, id_step, "enclosure", enclosure); rep.saveStepAttribute(id_transformation, id_step, "buffer_size", bufferSize); rep.saveStepAttribute(id_transformation, id_step, "header", headerPresent); rep.saveStepAttribute(id_transformation, id_step, "lazy_conversion", lazyConversionActive); rep.saveStepAttribute(id_transformation, id_step, "add_filename_result", isaddresult); rep.saveStepAttribute(id_transformation, id_step, "parallel", runningInParallel); rep.saveStepAttribute(id_transformation, id_step, "encoding", encoding); for (int i = 0; i < inputFields.length; i++) { TextFileInputField field = inputFields[i]; rep.saveStepAttribute(id_transformation, id_step, i, "field_name", field.getName()); rep.saveStepAttribute(id_transformation, id_step, i, "field_type", ValueMeta.getTypeDesc(field.getType())); rep.saveStepAttribute(id_transformation, id_step, i, "field_format", field.getFormat()); rep.saveStepAttribute(id_transformation, id_step, i, "field_currency", field.getCurrencySymbol()); rep.saveStepAttribute(id_transformation, id_step, i, "field_decimal", field.getDecimalSymbol()); rep.saveStepAttribute(id_transformation, id_step, i, "field_group", field.getGroupSymbol()); rep.saveStepAttribute(id_transformation, id_step, i, "field_length", field.getLength()); rep.saveStepAttribute(id_transformation, id_step, i, "field_precision", field.getPrecision()); rep.saveStepAttribute(id_transformation, id_step, i, "field_trim_type", ValueMeta.getTrimTypeCode( field.getTrimType())); } } catch (Exception e) { throw new KettleException("Unable to save step information to the repository for id_step=" + id_step, e); } } public void getFields(RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { rowMeta.clear(); // Start with a clean slate, eats the input for (int i=0;i<inputFields.length;i++) { TextFileInputField field = inputFields[i]; ValueMetaInterface valueMeta = new ValueMeta(field.getName(), field.getType()); valueMeta.setConversionMask( field.getFormat() ); valueMeta.setLength( field.getLength() ); valueMeta.setPrecision( field.getPrecision() ); valueMeta.setConversionMask( field.getFormat() ); valueMeta.setDecimalSymbol( field.getDecimalSymbol() ); valueMeta.setGroupingSymbol( field.getGroupSymbol() ); valueMeta.setCurrencySymbol( field.getCurrencySymbol() ); valueMeta.setTrimType( field.getTrimType() ); if (lazyConversionActive) valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); valueMeta.setStringEncoding(space.environmentSubstitute(encoding)); // In case we want to convert Strings... // Using a copy of the valueMeta object means that the inner and outer representation format is the same. // Preview will show the data the same way as we read it. // This layout is then taken further down the road by the metadata through the transformation. // ValueMetaInterface storageMetadata = valueMeta.clone(); storageMetadata.setType(ValueMetaInterface.TYPE_STRING); storageMetadata.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL); storageMetadata.setLength(-1,-1); // we don't really know the lengths of the strings read in advance. valueMeta.setStorageMetadata(storageMetadata); valueMeta.setOrigin(origin); rowMeta.addValueMeta(valueMeta); } if (!Const.isEmpty(filenameField) && includingFilename) { ValueMetaInterface filenameMeta = new ValueMeta(filenameField, ValueMetaInterface.TYPE_STRING); filenameMeta.setOrigin(origin); if (lazyConversionActive) { filenameMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); filenameMeta.setStorageMetadata(new ValueMeta(filenameField, ValueMetaInterface.TYPE_STRING)); } rowMeta.addValueMeta(filenameMeta); } if (!Const.isEmpty(rowNumField)) { ValueMetaInterface rowNumMeta = new ValueMeta(rowNumField, ValueMetaInterface.TYPE_INTEGER); rowNumMeta.setLength(10); rowNumMeta.setOrigin(origin); rowMeta.addValueMeta(rowNumMeta); } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { CheckResult cr; if (prev==null || prev.size()==0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("ParGzipCsvInputMeta.CheckResult.NotReceivingFields"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("ParGzipCsvInputMeta.CheckResult.StepRecevingData",prev.size()+""), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); } // See if we have input streams leading to this step! if (input.length>0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("ParGzipCsvInputMeta.CheckResult.StepRecevingData2"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("ParGzipCsvInputMeta.CheckResult.NoInputReceivedFromOtherSteps"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans) { return new ParGzipCsvInput(stepMeta, stepDataInterface, cnr, tr, trans); } public StepDataInterface getStepData() { return new ParGzipCsvInputData(); } /** * @return the delimiter */ public String getDelimiter() { return delimiter; } /** * @param delimiter the delimiter to set */ public void setDelimiter(String delimiter) { this.delimiter = delimiter; } /** * @return the filename */ public String getFilename() { return filename; } /** * @param filename the filename to set */ public void setFilename(String filename) { this.filename = filename; } /** * @return the bufferSize */ public String getBufferSize() { return bufferSize; } /** * @param bufferSize the bufferSize to set */ public void setBufferSize(String bufferSize) { this.bufferSize = bufferSize; } /** * @return true if lazy conversion is turned on: conversions are delayed as long as possible, perhaps to never occur at all. */ public boolean isLazyConversionActive() { return lazyConversionActive; } /** * @param lazyConversionActive true if lazy conversion is to be turned on: conversions are delayed as long as possible, perhaps to never occur at all. */ public void setLazyConversionActive(boolean lazyConversionActive) { this.lazyConversionActive = lazyConversionActive; } /** * @return the headerPresent */ public boolean isHeaderPresent() { return headerPresent; } /** * @param headerPresent the headerPresent to set */ public void setHeaderPresent(boolean headerPresent) { this.headerPresent = headerPresent; } /** * @return the enclosure */ public String getEnclosure() { return enclosure; } /** * @param enclosure the enclosure to set */ public void setEnclosure(String enclosure) { this.enclosure = enclosure; } @Override public List<ResourceReference> getResourceDependencies(TransMeta transMeta, StepMeta stepInfo) { List<ResourceReference> references = new ArrayList<ResourceReference>(5); ResourceReference reference = new ResourceReference(stepInfo); references.add(reference); if (!Const.isEmpty(filename)) { // Add the filename to the references, including a reference to this // step meta data. // reference.getEntries().add(new ResourceEntry(transMeta.environmentSubstitute(filename), ResourceType.FILE)); } return references; } /** * @return the inputFields */ public TextFileInputField[] getInputFields() { return inputFields; } /** * @param inputFields * the inputFields to set */ public void setInputFields(TextFileInputField[] inputFields) { this.inputFields = inputFields; } public int getFileFormatTypeNr() { return TextFileInputMeta.FILE_FORMAT_MIXED; // TODO: check this } public String[] getFilePaths(VariableSpace space) { return new String[] { space.environmentSubstitute(filename), }; } public int getNrHeaderLines() { return 1; } public boolean hasHeader() { return isHeaderPresent(); } public String getErrorCountField() { return null; } public String getErrorFieldsField() { return null; } public String getErrorTextField() { return null; } public String getEscapeCharacter() { return null; } public String getFileType() { return "CSV"; } public String getSeparator() { return delimiter; } public boolean includeFilename() { return false; } public boolean includeRowNumber() { return false; } public boolean isErrorIgnored() { return false; } public boolean isErrorLineSkipped() { return false; } /** * @return the filenameField */ public String getFilenameField() { return filenameField; } /** * @param filenameField the filenameField to set */ public void setFilenameField(String filenameField) { this.filenameField = filenameField; } /** * @return the includingFilename */ public boolean isIncludingFilename() { return includingFilename; } /** * @param includingFilename the includingFilename to set */ public void setIncludingFilename(boolean includingFilename) { this.includingFilename = includingFilename; } /** * @return the rowNumField */ public String getRowNumField() { return rowNumField; } /** * @param rowNumField the rowNumField to set */ public void setRowNumField(String rowNumField) { this.rowNumField = rowNumField; } /** * @param isaddresult The isaddresult to set. */ public void setAddResultFile(boolean isaddresult) { this.isaddresult = isaddresult; } /** * @return Returns isaddresult. */ public boolean isAddResultFile() { return isaddresult; } /** * @return the runningInParallel */ public boolean isRunningInParallel() { return runningInParallel; } /** * @param runningInParallel the runningInParallel to set */ public void setRunningInParallel(boolean runningInParallel) { this.runningInParallel = runningInParallel; } /** * @return the encoding */ public String getEncoding() { return encoding; } /** * @param encoding the encoding to set */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively. * So what this does is turn the name of files into absolute paths OR it simply includes the resource in the ZIP file. * For now, we'll simply turn it into an absolute path and pray that the file is on a shared drive or something like that. * TODO: create options to configure this behavior */ public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface, Repository repository) throws KettleException { try { // The object that we're modifying here is a copy of the original! // So let's change the filename from relative to absolute by grabbing the file object... // In case the name of the file comes from previous steps, forget about this! // if (Const.isEmpty(filenameField)) { // From : ${Internal.Transformation.Filename.Directory}/../foo/bar.csv // To : /home/matt/test/files/foo/bar.csv // FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(filename)); // If the file doesn't exist, forget about this effort too! // if (fileObject.exists()) { // Convert to an absolute path... // filename = resourceNamingInterface.nameResource(fileObject.getName().getBaseName(), fileObject.getParent().getName().getPath(), space.toString(), FileNamingType.DATA_FILE); return filename; } } return null; } catch (Exception e) { throw new KettleException(e); //$NON-NLS-1$ } } }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/AttachmentVersioningStore.java
2748
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.store; import org.xwiki.component.annotation.Role; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiAttachmentArchive; /** * Interface for storing attachment versions. * * @version $Id$ * @since 1.4M2 */ @Role public interface AttachmentVersioningStore { /** * @return the role hint of the component * @since 9.10RC1 */ String getHint(); /** * Load attachment archive from store. * * @return attachment archive. not null. return empty archive if it is not exist in store. * @param attachment The attachment of archive. * @param context The current context. * @param bTransaction Should use old transaction (false) or create new (true). * @throws XWikiException If an error occurs. */ XWikiAttachmentArchive loadArchive(XWikiAttachment attachment, XWikiContext context, boolean bTransaction) throws XWikiException; /** * Save or update attachment archive. * * @param archive The attachment archive to save. * @param context The current context. * @param bTransaction Should use old transaction (false) or create new (true). * @throws XWikiException If an error occurs. */ void saveArchive(XWikiAttachmentArchive archive, XWikiContext context, boolean bTransaction) throws XWikiException; /** * Permanently delete attachment archive. * * @param attachment The attachment to delete. * @param context The current context. * @param bTransaction Should use old transaction (false) or create new (true). * @throws XWikiException If an error occurs. */ void deleteArchive(XWikiAttachment attachment, XWikiContext context, boolean bTransaction) throws XWikiException; }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/extensions-mondrian/src/main/java/org/pentaho/reporting/engine/classic/extensions/datasources/mondrian/writer/DriverDataSourceProviderWriteHandler.java
5481
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.writer; import org.pentaho.reporting.engine.classic.core.modules.parser.base.PasswordEncryptionService; import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.BundleWriterException; import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.BundleWriterState; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriterContext; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriterException; import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.DataSourceProvider; import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.DriverDataSourceProvider; import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.MondrianDataFactoryModule; import org.pentaho.reporting.libraries.docbundle.WriteableDocumentBundle; import org.pentaho.reporting.libraries.xmlns.writer.XmlWriter; import org.pentaho.reporting.libraries.xmlns.writer.XmlWriterSupport; import java.io.IOException; /** * Todo: Document me! * <p/> * Date: 25.08.2009 Time: 18:56:13 * * @author Thomas Morgner. */ public class DriverDataSourceProviderWriteHandler implements DataSourceProviderBundleWriteHandler, DataSourceProviderWriteHandler { /** * Writes a data-source into a XML-stream. * * @param bundle the document bundle that is produced. * @param state the current writer state. * @param xmlWriter the XML writer that will receive the generated XML data. * @param dataSourceProvider the data factory that should be written. * @throws java.io.IOException if any error occured */ public void write( final WriteableDocumentBundle bundle, final BundleWriterState state, final XmlWriter xmlWriter, final DataSourceProvider dataSourceProvider ) throws IOException, BundleWriterException { if ( dataSourceProvider instanceof DriverDataSourceProvider == false ) { throw new BundleWriterException( "This is not a Driver connection" ); } write( xmlWriter, (DriverDataSourceProvider) dataSourceProvider ); } /** * Writes a data-source into a XML-stream. * * @param reportWriter the writer context that holds all factories. * @param xmlWriter the XML writer that will receive the generated XML data. * @param dataFactory the data factory that should be written. * @throws java.io.IOException if any error * occured * @throws org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriterException if the data * factory * cannot be written. */ public void write( final ReportWriterContext reportWriter, final XmlWriter xmlWriter, final DataSourceProvider dataFactory ) throws IOException, ReportWriterException { if ( dataFactory instanceof DriverDataSourceProvider == false ) { throw new ReportWriterException( "This is not a Driver connection" ); } write( xmlWriter, (DriverDataSourceProvider) dataFactory ); } protected void write( XmlWriter writer, final DriverDataSourceProvider provider ) throws IOException { writer.writeTag( MondrianDataFactoryModule.NAMESPACE, "driver", XmlWriter.OPEN ); writer.writeTag( MondrianDataFactoryModule.NAMESPACE, "driver", XmlWriter.OPEN ); writer.writeTextNormalized( provider.getDriver(), false ); writer.writeCloseTag(); writer.writeTag( MondrianDataFactoryModule.NAMESPACE, "url", XmlWriter.OPEN ); writer.writeTextNormalized( provider.getUrl(), false ); writer.writeCloseTag(); writer.writeTag ( MondrianDataFactoryModule.NAMESPACE, "properties", XmlWriterSupport.OPEN ); final String[] propertyNames = provider.getPropertyNames(); for ( int i = 0; i < propertyNames.length; i++ ) { final String name = propertyNames[ i ]; final String value = provider.getProperty( name ); writer.writeTag( MondrianDataFactoryModule.NAMESPACE, "property", "name", name, XmlWriterSupport.OPEN ); if ( name.toLowerCase().contains( "password" ) ) { writer.writeTextNormalized( PasswordEncryptionService.getInstance().encrypt( value ), false ); } else { writer.writeTextNormalized( value, false ); } writer.writeCloseTag(); } writer.writeCloseTag(); writer.writeCloseTag(); } }
lgpl-2.1
JaeWoongOh/markj
uni/src/main/java/com/markjmind/uni/thread/aop/AopOnExceptionAdapter.java
543
package com.markjmind.uni.thread.aop; /** * Created by Muabe on 2018-05-11. */ public abstract class AopOnExceptionAdapter implements AopListener{ @Override public void beforeOnPre() {} @Override public void afterOnPre() {} @Override public void beforeOnLoad() {} @Override public void afterOnLoad() {} @Override public void beforeOnPost() {} @Override public void afterOnPost() {} @Override public void beforeOnCancel() {} @Override public void afterOnCancel() {} }
lgpl-2.1
cisco/jfnr
src/main/java/com/cisco/fnr/FNRUtils.java
3398
package com.cisco.fnr; /* * jfnr - uses JNA for calling native implementation of libFNR * * jfnr extensions are contributed by Bhanu Prakash Gopularam (bhanprak@cisco.com) * * libFNR - A reference implementation library for FNR encryption mode. * * FNR represents "Flexible Naor and Reingold" mode * FNR is a small domain block cipher to encrypt small domain * objects ( < 128 bits ) like IPv4, MAC, Credit Card numbers etc. * FNR is designed by Sashank Dara (sadara@cisco.com), Scott Fluhrer (sfluhrer@cisco.com) * * * Copyright (C) 2014 , Cisco Systems Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * **/ import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; public class FNRUtils { public static byte[] rankIPAddress(String ipAddress){ int a,b,c,d ; String[] comps = ipAddress.split("\\."); a = Integer.valueOf( comps[0]); b = Integer.valueOf( comps[1]); c = Integer.valueOf( comps[2]); d = Integer.valueOf( comps[3]); int ip = (a << 24) + (b << 16) + (c << 8) + d; return ByteBuffer.allocate(4).putInt(ip).array(); } public static String deRankIPAddress(byte[] ipBytes){ final int ip = ByteBuffer.wrap(ipBytes).getInt(); return toIPv4String(ip); } public static String toIPv4String (int address) { StringBuilder sb = new StringBuilder(16); for (int ii = 3; ii >= 0; ii--) { sb.append((int) (0xFF & (address >> (8*ii)))); if (ii > 0) sb.append("."); } return sb.toString(); } public static SecretKeySpec getSecretKeySpec(String password, byte[] saltyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException { int pswdIterations = 65536 ; int keySize = 128; // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec( password.toCharArray(),saltyBytes, pswdIterations, keySize ); SecretKey secretKey = factory.generateSecret(spec); return new SecretKeySpec(secretKey.getEncoded(), "AES"); } public static byte[] getRandomBytes(int count) { // Generate the Salt SecureRandom random = new SecureRandom(); byte[] saltyBytes = new byte[count]; random.nextBytes(saltyBytes); return saltyBytes; } }
lgpl-2.1
molindo/maxmind-geoip
src/main/java/at/molindo/thirdparty/com/maxmind/geoip/LookupService.java
44501
/** * LookupService.java * * Copyright (C) 2003 MaxMind LLC. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package at.molindo.thirdparty.com.maxmind.geoip; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.Inet6Address; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Hashtable; import java.util.StringTokenizer; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; /** * Provides a lookup service for information based on an IP address. The location of * a database file is supplied when creating a lookup service instance. The edition of * the database determines what information is available about an IP address. See the * DatabaseInfo class for further details.<p> * * The following code snippet demonstrates looking up the country that an IP * address is from: * <pre> * // First, create a LookupService instance with the location of the database. * LookupService lookupService = new LookupService("c:\\geoip.dat"); * // Assume we have a String ipAddress (in dot-decimal form). * Country country = lookupService.getCountry(ipAddress); * System.out.println("The country is: " + country.getName()); * System.out.println("The country code is: " + country.getCode()); * </pre> * * In general, a single LookupService instance should be created and then reused * repeatedly.<p> * * <i>Tip:</i> Those deploying the GeoIP API as part of a web application may find it * difficult to pass in a File to create the lookup service, as the location of the * database may vary per deployment or may even be part of the web-application. In this * case, the database should be added to the classpath of the web-app. For example, by * putting it into the WEB-INF/classes directory of the web application. The following code * snippet demonstrates how to create a LookupService using a database that can be found * on the classpath: * * <pre> * String fileName = getClass().getResource("/GeoIP.dat").toExternalForm().substring(6); * LookupService lookupService = new LookupService(fileName);</pre> * * @author Matt Tucker (matt@jivesoftware.com) */ public class LookupService { /** * Database file. */ private RandomAccessFile file = null; private File databaseFile = null; /** * Information about the database. */ private DatabaseInfo databaseInfo = null; /** * The database type. Default is the country edition. */ byte databaseType = DatabaseInfo.COUNTRY_EDITION; int databaseSegments[]; int recordLength; String licenseKey; int dnsService = 0; int dboptions; byte dbbuffer[]; byte index_cache[]; long mtime; int last_netmask; private final static int US_OFFSET = 1; private final static int CANADA_OFFSET = 677; private final static int WORLD_OFFSET = 1353; private final static int FIPS_RANGE = 360; private final static int COUNTRY_BEGIN = 16776960; private final static int STATE_BEGIN_REV0 = 16700000; private final static int STATE_BEGIN_REV1 = 16000000; private final static int STRUCTURE_INFO_MAX_SIZE = 20; private final static int DATABASE_INFO_MAX_SIZE = 100; public final static int GEOIP_STANDARD = 0; public final static int GEOIP_MEMORY_CACHE = 1; public final static int GEOIP_CHECK_CACHE = 2; public final static int GEOIP_INDEX_CACHE = 4; public final static int GEOIP_UNKNOWN_SPEED = 0; public final static int GEOIP_DIALUP_SPEED = 1; public final static int GEOIP_CABLEDSL_SPEED = 2; public final static int GEOIP_CORPORATE_SPEED = 3; private final static int SEGMENT_RECORD_LENGTH = 3; private final static int STANDARD_RECORD_LENGTH = 3; private final static int ORG_RECORD_LENGTH = 4; private final static int MAX_RECORD_LENGTH = 4; private final static int MAX_ORG_RECORD_LENGTH = 300; private final static int FULL_RECORD_LENGTH = 60; private final Country UNKNOWN_COUNTRY = new Country("--", "N/A"); private static final HashMap hashmapcountryCodetoindex = new HashMap(512); private static final HashMap hashmapcountryNametoindex = new HashMap(512); private static final String[] countryCode = { "--","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR", "AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ", "BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF", "CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ", "DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI", "FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL", "GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR", "HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP", "KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC", "LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK", "ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY", "MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM", "PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY", "QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ", "SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG", "TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG", "UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE", "YT","RS","ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL", "MF"}; private static final String[] countryName = { "N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates", "Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia", "Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa", "Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina", "Barbados","Bangladesh","Belgium","Burkina Faso","Bulgaria","Bahrain", "Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas", "Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada", "Cocos (Keeling) Islands","Congo, The Democratic Republic of the", "Central African Republic","Congo","Switzerland","Cote D'Ivoire", "Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba", "Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany", "Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador", "Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland", "Fiji","Falkland Islands (Malvinas)","Micronesia, Federated States of", "Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom", "Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland","Gambia", "Guinea","Guadeloupe","Equatorial Guinea","Greece", "South Georgia and the South Sandwich Islands","Guatemala","Guam", "Guinea-Bissau","Guyana","Hong Kong","Heard Island and McDonald Islands", "Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India", "British Indian Ocean Territory","Iraq","Iran, Islamic Republic of", "Iceland","Italy","Jamaica","Jordan","Japan","Kenya","Kyrgyzstan","Cambodia", "Kiribati","Comoros","Saint Kitts and Nevis", "Korea, Democratic People's Republic of","Korea, Republic of","Kuwait", "Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon", "Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania", "Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco", "Moldova, Republic of","Madagascar","Marshall Islands", "Macedonia","Mali","Myanmar","Mongolia", "Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat", "Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique", "Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua", "Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama", "Peru","French Polynesia","Papua New Guinea","Philippines","Pakistan", "Poland","Saint Pierre and Miquelon","Pitcairn Islands","Puerto Rico","" + "Palestinian Territory","Portugal","Palau","Paraguay","Qatar", "Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia", "Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena", "Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino", "Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador", "Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad", "French Southern Territories","Togo","Thailand","Tajikistan","Tokelau", "Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago", "Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda", "United States Minor Outlying Islands","United States","Uruguay","Uzbekistan", "Holy See (Vatican City State)","Saint Vincent and the Grenadines", "Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam", "Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia", "South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy", "Satellite Provider","Other","Aland Islands","Guernsey","Isle of Man","Jersey", "Saint Barthelemy","Saint Martin"}; /* init the hashmap once at startup time */ static { int i; if(countryCode.length!=countryName.length) throw new AssertionError("countryCode.length!=countryName.length"); // distributed service only for (i = 0; i < countryCode.length ;i++){ hashmapcountryCodetoindex.put(countryCode[i],Integer.valueOf(i)); hashmapcountryNametoindex.put(countryName[i],Integer.valueOf(i)); } }; /** * Create a new distributed lookup service using the license key * * @param databaseFile String representation of the database file. * @param licenseKey license key provided by Maxmind to access distributed service */ public LookupService(String databaseFile,String licenseKey) throws IOException { this(new File(databaseFile)); this.licenseKey = licenseKey; dnsService = 1; } /** * Create a new distributed lookup service using the license key * * @param databaseFile the database file. * @param licenseKey license key provided by Maxmind to access distributed service */ public LookupService(File databaseFile,String licenseKey) throws IOException { this(databaseFile); this.licenseKey = licenseKey; dnsService = 1; } /** * Create a new distributed lookup service using the license key * * @param options Resevered for future use * @param licenseKey license key provided by Maxmind to access distributed service */ public LookupService(int options,String licenseKey) throws IOException { this.licenseKey = licenseKey; dnsService = 1; init(); } /** * Create a new lookup service using the specified database file. * * @param databaseFile String representation of the database file. * @throws java.io.IOException if an error occured creating the lookup service * from the database file. */ public LookupService(String databaseFile) throws IOException { this(new File(databaseFile)); } /** * Create a new lookup service using the specified database file. * * @param databaseFile the database file. * @throws java.io.IOException if an error occured creating the lookup service * from the database file. */ public LookupService(File databaseFile) throws IOException { this.databaseFile = databaseFile; this.file = new RandomAccessFile(databaseFile, "r"); init(); } /** * Create a new lookup service using the specified database file. * * @param databaseFile String representation of the database file. * @param options database flags to use when opening the database * GEOIP_STANDARD read database from disk * GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM * @throws java.io.IOException if an error occured creating the lookup service * from the database file. */ public LookupService(String databaseFile, int options) throws IOException{ this(new File(databaseFile),options); } /** * Create a new lookup service using the specified database file. * * @param databaseFile the database file. * @param options database flags to use when opening the database * GEOIP_STANDARD read database from disk * GEOIP_MEMORY_CACHE cache the database in RAM and read it from RAM * @throws java.io.IOException if an error occured creating the lookup service * from the database file. */ public LookupService(File databaseFile, int options) throws IOException{ this.databaseFile = databaseFile; this.file = new RandomAccessFile(databaseFile, "r"); dboptions = options; init(); } /** * Reads meta-data from the database file. * * @throws java.io.IOException if an error occurs reading from the database file. */ private void init() throws IOException { int i, j; byte [] delim = new byte[3]; byte [] buf = new byte[SEGMENT_RECORD_LENGTH]; if (file == null) { return; } if ((dboptions & GEOIP_CHECK_CACHE) != 0) { mtime = databaseFile.lastModified(); } file.seek(file.length() - 3); for (i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) { file.readFully(delim); if (delim[0] == -1 && delim[1] == -1 && delim[2] == -1) { databaseType = file.readByte(); if (databaseType >= 106) { // Backward compatibility with databases from April 2003 and earlier databaseType -= 105; } // Determine the database type. if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV0; recordLength = STANDARD_RECORD_LENGTH; }else if (databaseType == DatabaseInfo.REGION_EDITION_REV1){ databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV1; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ORG_EDITION || databaseType == DatabaseInfo.ORG_EDITION_V6 || databaseType == DatabaseInfo.ISP_EDITION || databaseType == DatabaseInfo.ISP_EDITION_V6 || databaseType == DatabaseInfo.DOMAIN_EDITION || databaseType == DatabaseInfo.DOMAIN_EDITION_V6 || databaseType == DatabaseInfo.ASNUM_EDITION || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6 ) { databaseSegments = new int[1]; databaseSegments[0] = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ASNUM_EDITION_V6 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1 || databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV0_V6 || databaseType == DatabaseInfo.CITY_EDITION_REV1_V6 || databaseType == DatabaseInfo.ASNUM_EDITION) { recordLength = STANDARD_RECORD_LENGTH; } else { recordLength = ORG_RECORD_LENGTH; } file.readFully(buf); for (j = 0; j < SEGMENT_RECORD_LENGTH; j++) { databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8)); } } break; } else { file.seek(file.getFilePointer() - 4); } } if ((databaseType == DatabaseInfo.COUNTRY_EDITION) || (databaseType == DatabaseInfo.COUNTRY_EDITION_V6) || (databaseType == DatabaseInfo.PROXY_EDITION) || (databaseType == DatabaseInfo.NETSPEED_EDITION)) { databaseSegments = new int[1]; databaseSegments[0] = COUNTRY_BEGIN; recordLength = STANDARD_RECORD_LENGTH; } if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { int l = (int) file.length(); dbbuffer = new byte[l]; file.seek(0); file.readFully(dbbuffer,0,l); databaseInfo = this.getDatabaseInfo(); file.close(); } if ((dboptions & GEOIP_INDEX_CACHE) != 0) { int l = databaseSegments[0] * recordLength * 2; index_cache = new byte[l]; if (index_cache != null){ file.seek(0); file.readFully(index_cache,0,l); } } else { index_cache = null; } } /** * Closes the lookup service. */ public void close() { try { if (file != null){ file.close(); } file = null; } catch (Exception e) { } } /** * Returns the country the IP address is in. * * @param ipAddress String version of an IPv6 address, i.e. "::127.0.0.1" * @return the country the IP address is from. */ public Country getCountryV6(String ipAddress) { InetAddress addr; try { addr = Inet6Address.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountryV6(addr); } /** * Returns the country the IP address is in. * * @param ipAddress String version of an IP address, i.e. "127.0.0.1" * @return the country the IP address is from. */ public Country getCountry(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountry(bytesToLong(addr.getAddress())); } /** * Returns the country the IP address is in. * * @param ipAddress the IP address. * @return the country the IP address is from. */ public synchronized Country getCountry(InetAddress ipAddress) { return getCountry(bytesToLong(ipAddress.getAddress())); } /** * Returns the country the IP address is in. * * @param addr the IP address as Inet6Address. * @return the country the IP address is from. */ public Country getCountryV6(InetAddress addr) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } int ret = seekCountryV6(addr) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } /** * Returns the country the IP address is in. * * @param ipAddress the IP address in long format. * @return the country the IP address is from. */ public Country getCountry(long ipAddress) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } int ret = seekCountry(ipAddress) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } public int getID(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return 0; } return getID(bytesToLong(addr.getAddress())); } public int getID(InetAddress ipAddress) { return getID(bytesToLong(ipAddress.getAddress())); } public synchronized int getID(long ipAddress) { if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) { throw new IllegalStateException("Database has been closed."); } int ret = seekCountry(ipAddress) - databaseSegments[0]; return ret; } public int last_netmask() { return this.last_netmask; } public void netmask(int nm){ this.last_netmask = nm; } /** * Returns information about the database. * * @return database info. */ public synchronized DatabaseInfo getDatabaseInfo() { if (databaseInfo != null) { return databaseInfo; } try { _check_mtime(); boolean hasStructureInfo = false; byte [] delim = new byte[3]; // Advance to part of file where database info is stored. file.seek(file.length() - 3); for (int i=0; i<STRUCTURE_INFO_MAX_SIZE; i++) { int read = file.read( delim ); if( read==3 && (delim[0]&0xFF)==255 && (delim[1]&0xFF) == 255 && (delim[2]&0xFF)==255 ){ hasStructureInfo = true; break; } file.seek(file.getFilePointer() - 4); } if (hasStructureInfo) { file.seek(file.getFilePointer() - 6); } else { // No structure info, must be pre Sep 2002 database, go back to end. file.seek(file.length() - 3); } // Find the database info string. for (int i=0; i<DATABASE_INFO_MAX_SIZE; i++) { file.readFully(delim); if (delim[0]==0 && delim[1]==0 && delim[2]==0) { byte[] dbInfo = new byte[i]; file.readFully(dbInfo); // Create the database info object using the string. this.databaseInfo = new DatabaseInfo(new String(dbInfo)); return databaseInfo; } file.seek(file.getFilePointer() -4); } } catch (Exception e) { e.printStackTrace(); } return new DatabaseInfo(""); } synchronized void _check_mtime(){ try { if ((dboptions & GEOIP_CHECK_CACHE) != 0){ long t = databaseFile.lastModified(); if (t != mtime){ /* GeoIP Database file updated */ /* refresh filehandle */ file.close(); file = new RandomAccessFile(databaseFile,"r"); databaseInfo = null; init(); } } } catch (IOException e) { System.out.println("file not found"); } } // for GeoIP City only public Location getLocationV6(String str) { if (dnsService == 0) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getLocationV6(addr); } else { String str2 = getDnsAttributes(str); return getLocationwithdnsservice(str2); // TODO if DNS is not available, go to local file as backup } } // for GeoIP City only public Location getLocation(InetAddress addr) { return getLocation(bytesToLong(addr.getAddress())); } // for GeoIP City only public Location getLocation(String str) { if (dnsService == 0) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getLocation(addr); } else { String str2 = getDnsAttributes(str); return getLocationwithdnsservice(str2); // TODO if DNS is not available, go to local file as backup } } String getDnsAttributes(String ip) { try { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); // TODO don't specify ws1, instead use ns servers for s.maxmind.com env.put("java.naming.provider.url","dns://ws1.maxmind.com/"); DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[] {"txt"}); //System.out.println(attrs.get("txt").get()); String str = attrs.get("txt").get().toString(); return str; } catch(NamingException e) { // TODO fix this to handle exceptions System.out.println("DNS error"); return null; } } public Location getLocationwithdnsservice(String str) { Location record = new Location(); String key; String value; StringTokenizer st = new StringTokenizer(str,";=\""); while (st.hasMoreTokens()) { key = st.nextToken(); if (st.hasMoreTokens()) { value = st.nextToken(); } else { value = "";} if (key.equals("co")) { Integer i = (Integer)hashmapcountryCodetoindex.get(value); record.countryCode = value; record.countryName = countryName[i.intValue()]; } if (key.equals("ci")) { record.city = value; } if (key.equals("re")) { record.region = value; } if (key.equals("zi")) { record.postalCode = value; } // TODO, ISP and Organization //if (key.equals("or")) { //record.org = value; //} //if (key.equals("is")) { //record.isp = value; //} if (key.equals("la")) { try{ record.latitude = Float.parseFloat(value); } catch(NumberFormatException e) { /* * msp: latitude=0 is a valid latitude, shouldn't it be an invalid number such as -1? */ record.latitude = 0; } } if (key.equals("lo")) { try{ record.longitude = Float.parseFloat(value); } catch(NumberFormatException e) { /* * msp: longitude=0 is a valid longitude, shouldn't it be an invalid number such as -1? */ record.longitude = 0; } } // dm depreciated use me ( metro_code ) instead if (key.equals("dm") || key.equals("me")) { try{ record.metro_code = record.dma_code = Integer.parseInt(value); } catch(NumberFormatException e) { record.metro_code = record.dma_code = 0; } } if (key.equals("ac")) { try{ record.area_code = Integer.parseInt(value); } catch(NumberFormatException e) { record.area_code = 0; } } } return record; } public synchronized Region getRegion(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getRegion(bytesToLong(addr.getAddress())); } public synchronized Region getRegion(long ipnum) { Region record = new Region(); int seek_region = 0; if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { seek_region = seekCountry(ipnum) - STATE_BEGIN_REV0; char ch[] = new char[2]; if (seek_region >= 1000) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - 1000)/26) + 65); ch[1] = (char)(((seek_region - 1000)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[seek_region]; record.countryName = countryName[seek_region]; record.region = ""; } } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { seek_region = seekCountry(ipnum) - STATE_BEGIN_REV1; char ch[] = new char[2]; if (seek_region < US_OFFSET) { record.countryCode = ""; record.countryName = ""; record.region = ""; } else if (seek_region < CANADA_OFFSET) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - US_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - US_OFFSET)%26) + 65); record.region = new String(ch); } else if (seek_region < WORLD_OFFSET) { record.countryCode = "CA"; record.countryName = "Canada"; ch[0] = (char)(((seek_region - CANADA_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - CANADA_OFFSET)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.region = ""; } } return record; } public synchronized Location getLocationV6(InetAddress addr) { int record_pointer; byte record_buf[] = new byte[FULL_RECORD_LENGTH]; int record_buf_offset = 0; Location record = new Location(); int str_length = 0; int j, seek_country; double latitude = 0, longitude = 0; try { seek_country = seekCountryV6(addr); if (seek_country == databaseSegments[0]) { return null; } record_pointer = seek_country + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory System.arraycopy(dbbuffer, record_pointer, record_buf, 0, Math.min(dbbuffer.length - record_pointer, FULL_RECORD_LENGTH)); } else { //read from disk file.seek(record_pointer); file.readFully(record_buf); } // get country record.countryCode = countryCode[unsignedByteToInt(record_buf[0])]; record.countryName = countryName[unsignedByteToInt(record_buf[0])]; record_buf_offset++; // get region while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.region = new String(record_buf, record_buf_offset, str_length); } record_buf_offset += str_length + 1; str_length = 0; // get city while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.city = new String(record_buf, record_buf_offset, str_length, "ISO-8859-1"); } record_buf_offset += str_length + 1; str_length = 0; // get postal code while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.postalCode = new String(record_buf, record_buf_offset, str_length); } record_buf_offset += str_length + 1; // get latitude for (j = 0; j < 3; j++) latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.latitude = (float) latitude/10000 - 180; record_buf_offset += 3; // get longitude for (j = 0; j < 3; j++) longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.longitude = (float) longitude/10000 - 180; record.dma_code = record.metro_code = 0; record.area_code = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV1) { // get DMA code int metroarea_combo = 0; if (record.countryCode == "US") { record_buf_offset += 3; for (j = 0; j < 3; j++) metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.metro_code = record.dma_code = metroarea_combo/1000; record.area_code = metroarea_combo % 1000; } } } catch (IOException e) { System.err.println("IO Exception while seting up segments"); } return record; } public synchronized Location getLocation(long ipnum) { int record_pointer; byte record_buf[] = new byte[FULL_RECORD_LENGTH]; int record_buf_offset = 0; Location record = new Location(); int str_length = 0; int j, seek_country; double latitude = 0, longitude = 0; try { seek_country = seekCountry(ipnum); if (seek_country == databaseSegments[0]) { return null; } record_pointer = seek_country + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory System.arraycopy(dbbuffer, record_pointer, record_buf, 0, Math.min(dbbuffer.length - record_pointer, FULL_RECORD_LENGTH)); } else { //read from disk file.seek(record_pointer); file.readFully(record_buf); } // get country record.countryCode = countryCode[unsignedByteToInt(record_buf[0])]; record.countryName = countryName[unsignedByteToInt(record_buf[0])]; record_buf_offset++; // get region while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.region = new String(record_buf, record_buf_offset, str_length); } record_buf_offset += str_length + 1; str_length = 0; // get city while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.city = new String(record_buf, record_buf_offset, str_length, "ISO-8859-1"); } record_buf_offset += str_length + 1; str_length = 0; // get postal code while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.postalCode = new String(record_buf, record_buf_offset, str_length); } record_buf_offset += str_length + 1; // get latitude for (j = 0; j < 3; j++) latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.latitude = (float) latitude/10000 - 180; record_buf_offset += 3; // get longitude for (j = 0; j < 3; j++) longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.longitude = (float) longitude/10000 - 180; record.dma_code = record.metro_code = 0; record.area_code = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV1) { // get DMA code int metroarea_combo = 0; if (record.countryCode == "US") { record_buf_offset += 3; for (j = 0; j < 3; j++) metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.metro_code = record.dma_code = metroarea_combo/1000; record.area_code = metroarea_combo % 1000; } } } catch (IOException e) { System.err.println("IO Exception while seting up segments"); } return record; } public String getOrg(InetAddress addr) { return getOrg(bytesToLong(addr.getAddress())); } public String getOrg(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getOrg(addr); } // GeoIP Organization and ISP Edition methods public synchronized String getOrg(long ipnum) { int seek_org; int record_pointer; int str_length = 0; byte [] buf = new byte[MAX_ORG_RECORD_LENGTH]; String org_buf; try { seek_org = seekCountry(ipnum); if (seek_org == databaseSegments[0]) { return null; } record_pointer = seek_org + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory System.arraycopy(dbbuffer, record_pointer, buf, 0, Math.min(dbbuffer.length - record_pointer, MAX_ORG_RECORD_LENGTH)); } else { //read from disk file.seek(record_pointer); try{ // read as much as possible file.readFully(buf); } catch(IOException e){} } while (buf[str_length] != '\0') { str_length++; } org_buf = new String(buf, 0, str_length, "ISO-8859-1"); return org_buf; } catch (IOException e) { System.out.println("IO Exception"); return null; } } public String getOrgV6(String str) { InetAddress addr; try { addr = InetAddress.getByName(str); } catch (UnknownHostException e) { return null; } return getOrgV6(addr); } // GeoIP Organization and ISP Edition methods public synchronized String getOrgV6(InetAddress addr) { int seek_org; int record_pointer; int str_length = 0; byte [] buf = new byte[MAX_ORG_RECORD_LENGTH]; String org_buf; try { seek_org = seekCountryV6(addr); if (seek_org == databaseSegments[0]) { return null; } record_pointer = seek_org + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory System.arraycopy(dbbuffer, record_pointer, buf, 0, Math.min(dbbuffer.length - record_pointer, MAX_ORG_RECORD_LENGTH)); } else { //read from disk file.seek(record_pointer); file.readFully(buf); } while (buf[str_length] != '\0') { str_length++; } org_buf = new String(buf, 0, str_length, "ISO-8859-1"); return org_buf; } catch (IOException e) { System.out.println("IO Exception"); return null; } } /** * Finds the country index value given an IPv6 address. * * @param addr the ip address to find in long format. * @return the country index. */ private synchronized int seekCountryV6(InetAddress addr) { byte [] v6vec = addr.getAddress(); byte [] buf = new byte[2 * MAX_RECORD_LENGTH]; int [] x = new int[2]; int offset = 0; _check_mtime(); for (int depth = 127; depth >= 0; depth--) { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) { buf[i] = dbbuffer[(2 * recordLength * offset)+i]; } } else if ((dboptions & GEOIP_INDEX_CACHE) != 0) { //read from index cache for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) { buf[i] = index_cache[(2 * recordLength * offset)+i]; } } else { //read from disk try { file.seek(2 * recordLength * offset); file.readFully(buf); } catch (IOException e) { System.out.println("IO Exception"); } } for (int i = 0; i<2; i++) { x[i] = 0; for (int j = 0; j<recordLength; j++) { int y = buf[i*recordLength+j]; if (y < 0) { y+= 256; } x[i] += (y << (j * 8)); } } int bnum = 127 - depth; int idx = bnum >> 3; int b_mask = 1 << ( bnum & 7 ^ 7 ); if ((v6vec[idx] & b_mask) > 0) { if (x[1] >= databaseSegments[0]) { last_netmask = 128 - depth; return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { last_netmask = 128 - depth; return x[0]; } offset = x[0]; } } // shouldn't reach here System.err.println("Error seeking country while seeking " + addr.getHostAddress() ); return 0; } /** * Finds the country index value given an IP address. * * @param ipAddress the ip address to find in long format. * @return the country index. */ private synchronized int seekCountry(long ipAddress) { byte [] buf = new byte[2 * MAX_RECORD_LENGTH]; int [] x = new int[2]; int offset = 0; _check_mtime(); for (int depth = 31; depth >= 0; depth--) { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { //read from memory for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) { buf[i] = dbbuffer[(2 * recordLength * offset)+i]; } } else if ((dboptions & GEOIP_INDEX_CACHE) != 0) { //read from index cache for (int i = 0;i < 2 * MAX_RECORD_LENGTH;i++) { buf[i] = index_cache[(2 * recordLength * offset)+i]; } } else { //read from disk try { file.seek(2 * recordLength * offset); file.readFully(buf); } catch (IOException e) { System.out.println("IO Exception"); } } for (int i = 0; i<2; i++) { x[i] = 0; for (int j = 0; j<recordLength; j++) { int y = buf[i*recordLength+j]; if (y < 0) { y+= 256; } x[i] += (y << (j * 8)); } } if ((ipAddress & (1 << depth)) > 0) { if (x[1] >= databaseSegments[0]) { last_netmask = 32 - depth; return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { last_netmask = 32 - depth; return x[0]; } offset = x[0]; } } // shouldn't reach here System.err.println("Error seeking country while seeking " + ipAddress); return 0; } /** * Returns the long version of an IP address given an InetAddress object. * * @param address the InetAddress. * @return the long form of the IP address. */ private static long bytesToLong(byte [] address) { long ipnum = 0; for (int i = 0; i < 4; ++i) { long y = address[i]; if (y < 0) { y+= 256; } ipnum += y << ((3-i)*8); } return ipnum; } private static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }
lgpl-2.1
phoenixctms/ctsms
core/src/main/java/org/phoenixctms/ctsms/domain/BankIdentificationDaoImpl.java
6851
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge. // license-header java merge-point /** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. */ package org.phoenixctms.ctsms.domain; import java.util.Collection; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.phoenixctms.ctsms.query.CategoryCriterion; import org.phoenixctms.ctsms.query.CriteriaUtil; import org.phoenixctms.ctsms.util.DefaultSettings; import org.phoenixctms.ctsms.util.SettingCodes; import org.phoenixctms.ctsms.util.Settings; import org.phoenixctms.ctsms.util.Settings.Bundle; import org.phoenixctms.ctsms.vo.BankIdentificationVO; /** * @see BankIdentification */ public class BankIdentificationDaoImpl extends BankIdentificationDaoBase { private static void applyBankIdentificationCriterions(org.hibernate.Criteria bankIdentificationCriteria, String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix) { CategoryCriterion.applyAnd(bankIdentificationCriteria, new CategoryCriterion(bankCodeNumberPrefix, "bankCodeNumber", MatchMode.START), new CategoryCriterion(bicPrefix, "bic", MatchMode.START), new CategoryCriterion(bankNameInfix, "bankName", MatchMode.ANYWHERE)); } /** * @inheritDoc */ @Override public BankIdentification bankIdentificationVOToEntity(BankIdentificationVO bankIdentificationVO) { BankIdentification entity = this.loadBankIdentificationFromBankIdentificationVO(bankIdentificationVO); this.bankIdentificationVOToEntity(bankIdentificationVO, entity, true); return entity; } /** * @inheritDoc */ @Override public void bankIdentificationVOToEntity( BankIdentificationVO source, BankIdentification target, boolean copyIfNull) { super.bankIdentificationVOToEntity(source, target, copyIfNull); } private org.hibernate.Criteria createBankIdentificationCriteria() { org.hibernate.Criteria bankIdentificationCriteria = this.getSession().createCriteria(BankIdentification.class); bankIdentificationCriteria.setCacheable(true); return bankIdentificationCriteria; } /** * @inheritDoc */ @Override protected Collection<String> handleFindBankCodeNumbers(String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit) { org.hibernate.Criteria bankIdentificationCriteria = createBankIdentificationCriteria(); applyBankIdentificationCriterions(bankIdentificationCriteria, bankCodeNumberPrefix, bicPrefix, bankNameInfix); bankIdentificationCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("bankCodeNumber", ""), Restrictions.isNull("bankCodeNumber")))); bankIdentificationCriteria.addOrder(Order.asc("bankCodeNumber")); bankIdentificationCriteria.setProjection(Projections.distinct(Projections.property("bankCodeNumber"))); CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.BANK_CODE_NUMBER_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.BANK_CODE_NUMBER_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), bankIdentificationCriteria); return bankIdentificationCriteria.list(); } /** * @inheritDoc */ @Override protected Collection<BankIdentificationVO> handleFindBankIdentifications(String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit) { org.hibernate.Criteria bankIdentificationCriteria = createBankIdentificationCriteria(); applyBankIdentificationCriterions(bankIdentificationCriteria, bankCodeNumberPrefix, bicPrefix, bankNameInfix); bankIdentificationCriteria.addOrder(Order.asc("bankName")); CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.BANK_IDENTIFICATION_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.BANK_IDENTIFICATION_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), bankIdentificationCriteria); return bankIdentificationCriteria.list(); } /** * @inheritDoc */ @Override protected Collection<String> handleFindBankNames(String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit) { org.hibernate.Criteria bankIdentificationCriteria = createBankIdentificationCriteria(); applyBankIdentificationCriterions(bankIdentificationCriteria, bankCodeNumberPrefix, bicPrefix, bankNameInfix); bankIdentificationCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("bankName", ""), Restrictions.isNull("bankName")))); bankIdentificationCriteria.addOrder(Order.asc("bankName")); bankIdentificationCriteria.setProjection(Projections.distinct(Projections.property("bankName"))); CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.BANK_NAME_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.BANK_NAME_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), bankIdentificationCriteria); return bankIdentificationCriteria.list(); } /** * @inheritDoc */ @Override protected Collection<String> handleFindBics(String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit) { org.hibernate.Criteria bankIdentificationCriteria = createBankIdentificationCriteria(); applyBankIdentificationCriterions(bankIdentificationCriteria, bankCodeNumberPrefix, bicPrefix, bankNameInfix); bankIdentificationCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("bic", ""), Restrictions.isNull("bic")))); bankIdentificationCriteria.addOrder(Order.asc("bic")); bankIdentificationCriteria.setProjection(Projections.distinct(Projections.property("bic"))); CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.BIC_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.BIC_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), bankIdentificationCriteria); return bankIdentificationCriteria.list(); } /** * Retrieves the entity object that is associated with the specified value object * from the object store. If no such entity object exists in the object store, * a new, blank entity is created */ private BankIdentification loadBankIdentificationFromBankIdentificationVO(BankIdentificationVO bankIdentificationVO) { BankIdentification bankIdentification = null; Long id = bankIdentificationVO.getId(); if (id != null) { bankIdentification = this.load(id); } if (bankIdentification == null) { bankIdentification = BankIdentification.Factory.newInstance(); } return bankIdentification; } /** * @inheritDoc */ @Override public BankIdentificationVO toBankIdentificationVO(final BankIdentification entity) { return super.toBankIdentificationVO(entity); } /** * @inheritDoc */ @Override public void toBankIdentificationVO( BankIdentification source, BankIdentificationVO target) { super.toBankIdentificationVO(source, target); } }
lgpl-2.1
hferentschik/hibernate-ogm
core/src/test/java/org/hibernate/ogm/backendtck/type/BuiltInTypeTest.java
8088
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.backendtck.type; import static org.hibernate.ogm.utils.TestHelper.extractEntityTuple; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.Map; import java.util.Random; import java.util.TimeZone; import java.util.UUID; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.ogm.backendtck.type.Bookmark.Classifier; import org.hibernate.ogm.model.impl.DefaultEntityKeyMetadata; import org.hibernate.ogm.model.key.spi.EntityKey; import org.hibernate.ogm.model.key.spi.EntityKeyMetadata; import org.hibernate.ogm.util.impl.Log; import org.hibernate.ogm.util.impl.LoggerFactory; import org.hibernate.ogm.utils.OgmTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author Emmanuel Bernard &lt;emmanuel@hibernate.org&gt; * @author Nicolas Helleringer * @author Oliver Carr <ocarr@redhat.com> */ public class BuiltInTypeTest extends OgmTestCase { private static final Log log = LoggerFactory.make(); private static final Random RANDOM = new Random(); private static TimeZone originalTimeZone = null; @BeforeClass public static void setDefaultTimeZone() { originalTimeZone = TimeZone.getDefault(); TimeZone.setDefault( TimeZone.getTimeZone( "UTC" ) ); } @AfterClass public static void resetDefautlTimeZone() { TimeZone.setDefault( originalTimeZone ); } @Test public void testTypesSupport() throws Exception { final Session session = openSession(); Transaction transaction = session.beginTransaction(); Bookmark b = new Bookmark(); b.setId( "42" ); b.setDescription( "Hibernate Site" ); b.setUrl( new URL( "http://www.hibernate.org/" ) ); BigDecimal weight = new BigDecimal( "21.77" ); b.setSiteWeight( weight ); BigInteger visitCount = new BigInteger( "444" ); b.setVisitCount( visitCount ); b.setFavourite( Boolean.TRUE ); Byte displayMask = Byte.valueOf( (byte) '8' ); b.setDisplayMask( displayMask ); b.setClassifier( Classifier.HOME ); b.setClassifierAsOrdinal( Classifier.WORK ); Date now = new Date( System.currentTimeMillis() ); Calendar nowCalendar = Calendar.getInstance(); nowCalendar.setTime( now ); b.setCreationDate( now ); b.setDestructionDate( now ); b.setUpdateTime( now ); b.setCreationCalendar( nowCalendar ); b.setDestructionCalendar( nowCalendar ); byte[] blob = new byte[5]; blob[0] = '1'; blob[1] = '2'; blob[2] = '3'; blob[3] = '4'; blob[4] = '5'; b.setBlob( blob ); UUID serialNumber = UUID.randomUUID(); b.setSerialNumber( serialNumber ); final Long userId = RANDOM.nextLong(); log.infof( "User ID created: $s", userId ); b.setUserId( userId ); final Integer stockCount = Integer.valueOf( RANDOM.nextInt() ); b.setStockCount( stockCount ); b.setType( BookmarkType.URL ); b.setTaxPercentage( 12.34d ); session.persist( b ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); b = (Bookmark) session.get( Bookmark.class, b.getId() ); assertEquals( "http://www.hibernate.org/", b.getUrl().toString() ); assertEquals( weight, b.getSiteWeight() ); assertEquals( visitCount, b.getVisitCount() ); assertEquals( Boolean.TRUE, b.isFavourite() ); assertEquals( displayMask, b.getDisplayMask() ); assertEquals( "serial number incorrect", serialNumber, b.getSerialNumber() ); assertEquals( "user id incorrect", userId, b.getUserId() ); assertEquals( "stock count incorrect", stockCount, b.getStockCount() ); assertEquals( "stock count incorrect", stockCount, b.getStockCount() ); assertEquals( "Tax percentage as double inscorrect", 0, b.getTaxPercentage().compareTo( 12.34d ) ); assertEquals( "Classifier as enum string is incorrect", Classifier.HOME, b.getClassifier() ); assertEquals( "Classifier stored as enum ordinal is incorrect", Classifier.WORK, b.getClassifierAsOrdinal() ); //Date - DATE Calendar creationDate = Calendar.getInstance(); creationDate.setTime( b.getCreationDate() ); assertEquals( nowCalendar.get( Calendar.YEAR ), creationDate.get( Calendar.YEAR ) ); assertEquals( nowCalendar.get( Calendar.MONTH ), creationDate.get( Calendar.MONTH ) ); assertEquals( nowCalendar.get( Calendar.DAY_OF_MONTH ), creationDate.get( Calendar.DAY_OF_MONTH ) ); //Date - TIME Calendar updateTime = Calendar.getInstance(); updateTime.setTime( b.getUpdateTime() ); assertEquals( nowCalendar.get( Calendar.HOUR_OF_DAY ), updateTime.get( Calendar.HOUR_OF_DAY ) ); assertEquals( nowCalendar.get( Calendar.MINUTE ), updateTime.get( Calendar.MINUTE ) ); assertEquals( nowCalendar.get( Calendar.SECOND ), updateTime.get( Calendar.SECOND ) ); //Date - TIMESTAMP assertEquals( "Destruction date incorrect", now, b.getDestructionDate() ); //Calendar - DATE assertEquals( "getCreationCalendar time zone incorrect", nowCalendar.getTimeZone().getRawOffset(), b.getCreationCalendar().getTimeZone().getRawOffset() ); assertEquals( nowCalendar.get( Calendar.YEAR ), b.getCreationCalendar().get( Calendar.YEAR ) ); assertEquals( nowCalendar.get( Calendar.MONTH ), b.getCreationCalendar().get( Calendar.MONTH ) ); assertEquals( nowCalendar.get( Calendar.DAY_OF_MONTH ), b.getCreationCalendar().get( Calendar.DAY_OF_MONTH ) ); //Calendar - TIMESTAMP assertEquals( "destructionCalendar time zone incorrect", nowCalendar.getTimeZone().getRawOffset(), b.getDestructionCalendar().getTimeZone().getRawOffset() ); assertEquals( "destructionCalendar timestamp incorrect", nowCalendar.getTimeInMillis(), b.getDestructionCalendar().getTimeInMillis() ); assertEquals( "Byte array incorrect length", blob.length, b.getBlob().length ); assertEquals( blob[0], b.getBlob()[0] ); assertEquals( '1', b.getBlob()[0] ); assertEquals( '2', b.getBlob()[1] ); assertEquals( '3', b.getBlob()[2] ); assertEquals( '4', b.getBlob()[3] ); assertEquals( '5', b.getBlob()[4] ); assertEquals( BookmarkType.URL, b.getType() ); session.delete( b ); transaction.commit(); session.close(); } @Test public void testStringMappedTypeSerialisation() throws Exception { final Session session = openSession(); Transaction transaction = session.beginTransaction(); Bookmark b = new Bookmark(); b.setId( "42" ); b.setUrl( new URL( "http://www.hibernate.org/" ) ); BigDecimal weight = new BigDecimal( "21.77" ); b.setSiteWeight( weight ); BigInteger visitCount = new BigInteger( "444" ); b.setVisitCount( visitCount ); UUID serialNumber = UUID.randomUUID(); b.setSerialNumber( serialNumber ); final Long userId = RANDOM.nextLong(); b.setUserId( userId ); final Integer stockCount = Integer.valueOf( RANDOM.nextInt() ); b.setStockCount( stockCount ); session.persist( b ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); b = (Bookmark) session.get( Bookmark.class, b.getId() ); //Check directly in the cache the values stored EntityKeyMetadata keyMetadata = new DefaultEntityKeyMetadata( "Bookmark", new String[]{ "id" } ); EntityKey key = new EntityKey( keyMetadata, new Object[]{ "42" } ); Map<String, Object> entity = extractEntityTuple( sessions, key ); assertEquals( "Entity visits count incorrect", entity.get( "visits_count" ), "444" ); assertEquals( "Entity serial number incorrect", entity.get( "serialNumber" ), serialNumber.toString() ); assertEquals( "Entity URL incorrect", entity.get( "url" ), "http://www.hibernate.org/" ); assertEquals( "Entity site weight incorrect", entity.get( "site_weight" ), "21.77" ); session.delete( b ); transaction.commit(); session.close(); } @Override protected Class<?>[] getAnnotatedClasses() { return new Class<?>[]{ Bookmark.class }; } }
lgpl-2.1
metteo/jts
jts-core/src/main/java/com/vividsolutions/jts/geom/GeometryCollectionIterator.java
4925
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.geom; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterates over all {@link Geometry}s in a {@link Geometry}, * (which may be either a collection or an atomic geometry). * The iteration sequence follows a pre-order, depth-first traversal of the * structure of the <code>GeometryCollection</code> * (which may be nested). The original <code>Geometry</code> object is * returned as well (as the first object), as are all sub-collections and atomic elements. * It is simple to ignore the intermediate <code>GeometryCollection</code> objects if they are not * needed. * *@version 1.7 */ public class GeometryCollectionIterator implements Iterator { /** * The <code>Geometry</code> being iterated over. */ private Geometry parent; /** * Indicates whether or not the first element * (the root <code>GeometryCollection</code>) has been returned. */ private boolean atStart; /** * The number of <code>Geometry</code>s in the the <code>GeometryCollection</code>. */ private int max; /** * The index of the <code>Geometry</code> that will be returned when <code>next</code> * is called. */ private int index; /** * The iterator over a nested <code>Geometry</code>, or <code>null</code> * if this <code>GeometryCollectionIterator</code> is not currently iterating * over a nested <code>GeometryCollection</code>. */ private GeometryCollectionIterator subcollectionIterator; /** * Constructs an iterator over the given <code>Geometry</code>. * *@param parent the geometry over which to iterate; also, the first * element returned by the iterator. */ public GeometryCollectionIterator(Geometry parent) { this.parent = parent; atStart = true; index = 0; max = parent.getNumGeometries(); } /** * Tests whether any geometry elements remain to be returned. * * @return true if more geometry elements remain */ public boolean hasNext() { if (atStart) { return true; } if (subcollectionIterator != null) { if (subcollectionIterator.hasNext()) { return true; } subcollectionIterator = null; } if (index >= max) { return false; } return true; } /** * Gets the next geometry in the iteration sequence. * * @return the next geometry in the iteration */ public Object next() { // the parent GeometryCollection is the first object returned if (atStart) { atStart = false; if (isAtomic(parent)) index++; return parent; } if (subcollectionIterator != null) { if (subcollectionIterator.hasNext()) { return subcollectionIterator.next(); } else { subcollectionIterator = null; } } if (index >= max) { throw new NoSuchElementException(); } Geometry obj = parent.getGeometryN(index++); if (obj instanceof GeometryCollection) { subcollectionIterator = new GeometryCollectionIterator((GeometryCollection) obj); // there will always be at least one element in the sub-collection return subcollectionIterator.next(); } return obj; } private static boolean isAtomic(Geometry geom) { return ! (geom instanceof GeometryCollection); } /** * Removal is not supported. * * @throws UnsupportedOperationException This method is not implemented. */ public void remove() { throw new UnsupportedOperationException(getClass().getName()); } }
lgpl-2.1
geotools/geotools
modules/unsupported/css/src/test/java/org/geotools/styling/css/util/FilterTypeVisitorTest.java
3285
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2017, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.styling.css.util; import static org.junit.Assert.assertEquals; import java.util.Date; import org.geotools.filter.text.cql2.CQL; import org.geotools.filter.text.ecql.ECQL; import org.junit.Before; import org.junit.Test; import org.locationtech.jts.geom.Geometry; import org.opengis.filter.Filter; public class FilterTypeVisitorTest { private FilterTypeVisitor visitor; private TypeAggregator aggregator; @Before public void setup() { aggregator = new TypeAggregator(); visitor = new FilterTypeVisitor(aggregator); } @Test public void testGreterThan() throws Exception { Filter filter = CQL.toFilter("myAtt > 10"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Long.class, aggregator.types.get("myAtt")); } @Test public void testTimeEquals() throws Exception { Filter filter = CQL.toFilter("time TEQUALS 2006-11-30T01:30:00Z"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Date.class, aggregator.types.get("time")); } @Test public void testBetween() throws Exception { Filter filter = CQL.toFilter("a between 10 and 20.5"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Double.class, aggregator.types.get("a")); } @Test public void testMath() throws Exception { Filter filter = ECQL.toFilter("a + 3 > 5"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Double.class, aggregator.types.get("a")); } @Test public void testAnd() throws Exception { Filter filter = ECQL.toFilter("a > 5 and a < 10.0"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Double.class, aggregator.types.get("a")); } @Test public void testGeometry() throws Exception { Filter filter = ECQL.toFilter("CONTAINS(geom, POINT(1 2))"); filter.accept(visitor, null); assertEquals(1, aggregator.types.size()); assertEquals(Geometry.class, aggregator.types.get("geom")); } @Test public void testFunction() throws Exception { Filter filter = ECQL.toFilter("CONTAINS(buffer(geom, distance), POINT(1 2))"); filter.accept(visitor, null); assertEquals(2, aggregator.types.size()); assertEquals(Geometry.class, aggregator.types.get("geom")); assertEquals(Number.class, aggregator.types.get("distance")); } }
lgpl-2.1
nict-wisdom/rasc
msgpack-rpc-java/src/main/java/org/msgpack/rpc/RequestEx.java
2454
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // 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. // /* * Copyright (C) 2014 Information Analysis Laboratory, NICT * * RaSC is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2.1 of the License, or (at * your option) any later version. * * RaSC 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package org.msgpack.rpc; import org.msgpack.rpc.message.ResponseDataMessage; import org.msgpack.rpc.transport.MessageSendable; import org.msgpack.type.Value; /** * Request拡張クラス. * @author kishimoto * */ public class RequestEx extends Request { /** * コンストラクタ. * @param channel * @param msgid * @param method * @param args */ public RequestEx(MessageSendable channel, int msgid, String method,Value args) { super(channel, msgid, method, args); } /** * コンストラクタ. * @param method * @param args */ public RequestEx(String method, Value args) { super(method, args); } /** * ストリーミングデータ送信. * @param result * @param error */ public synchronized void sendResponseData(Object result, Object error) { if (channel == null) { return; } ResponseDataMessage msg = new ResponseDataMessage(msgid, error, result); channel.sendMessage(msg); } }
lgpl-2.1
evlist/orbeon-forms
src/main/java/org/orbeon/oxf/processor/RedirectProcessor.java
3590
/** * Copyright (C) 2009 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.processor; import org.dom4j.Node; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.xml.XPathUtils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class RedirectProcessor extends ProcessorImpl { public static final String REDIRECT_SCHEMA_URI = "http://orbeon.org/oxf/redirect"; public RedirectProcessor() { addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA, REDIRECT_SCHEMA_URI)); } public void start(PipelineContext context) { try { // Read the data stream entirely final Node node = readCacheInputAsDOM4J(context, INPUT_DATA); // Is this a server-side redirect? final String serverSideString = XPathUtils.selectStringValueNormalize(node, "redirect-url/server-side"); final boolean isServerSide = "true".equals(serverSideString); // Is this going to exit the portal, if any? final String exitPortalString = XPathUtils.selectStringValueNormalize(node, "redirect-url/exit-portal"); final boolean isExitPortal = "true".equals(exitPortalString); // Build parameters final String pathInfo = XPathUtils.selectStringValueNormalize(node, "normalize-space(redirect-url/path-info)"); final Map<String, String[]> parameters = new HashMap<String, String[]>(); for (Iterator i = XPathUtils.selectIterator(node, "redirect-url/parameters/parameter"); i.hasNext();) { final Node parameter = (Node) i.next(); final String name = XPathUtils.selectStringValue(parameter, "name"); final int valueCount = XPathUtils.selectIntegerValue(parameter, "count(value)"); final String[] values = new String[valueCount]; int valueIndex = 0; for (Iterator j = XPathUtils.selectIterator(parameter, "value"); j.hasNext(); valueIndex++) { final Node value = (Node) j.next(); values[valueIndex] = XPathUtils.selectStringValue(value, "."); } parameters.put(name, values); } // Send the redirect final ExternalContext externalContext = (ExternalContext) context.getAttribute(PipelineContext.EXTERNAL_CONTEXT); final ExternalContext.Response response = externalContext.getResponse(); // Don't rewrite the path if doing a server-side redirect, because the forward expects a URL without the servlet context final String redirectURL = isServerSide ? pathInfo : response.rewriteRenderURL(pathInfo); response.sendRedirect(redirectURL, parameters, isServerSide, isExitPortal); } catch (Exception e) { throw new OXFException(e); } } }
lgpl-2.1
windauer/exist
extensions/modules/persistentlogin/src/main/java/org/exist/xquery/modules/persistentlogin/PersistentLogin.java
7708
package org.exist.xquery.modules.persistentlogin; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.util.Base64Encoder; import org.exist.xquery.XPathException; import org.exist.xquery.value.DateTimeValue; import org.exist.xquery.value.DurationValue; import java.security.SecureRandom; import java.util.*; /** * A persistent login feature ("remember me") similar to the implementation in <a href="https://github.com/SpringSource/spring-security">Spring Security</a>, * which is based on <a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">Improved Persistent Login Cookie * Best Practice</a> . * * The one-time tokens generated by this class are purely random and do not contain a user name or other information. For security reasons, * tokens and user information are not stored anywhere, so if the database is shut down, registered tokens will be gone. * * The one-time token approach has the negative effect that requests need to be made in sequence, which is sometimes difficult if an app uses * concurrent AJAX requests. Unfortunately, this is the price we have to pay for a sufficiently secure protection against * cookie stealing attacks. * * @author Wolfgang Meier */ public class PersistentLogin { private final static PersistentLogin instance = new PersistentLogin(); public static PersistentLogin getInstance() { return instance; } private final static Logger LOG = LogManager.getLogger(PersistentLogin.class); public final static int DEFAULT_SERIES_LENGTH = 16; public final static int DEFAULT_TOKEN_LENGTH = 16; public final static int INVALIDATION_TIMEOUT = 20000; private Map<String, LoginDetails> seriesMap = Collections.synchronizedMap(new HashMap<>()); private SecureRandom random; public PersistentLogin() { random = new SecureRandom(); } /** * Register the user and generate a first login token which will be valid for the next * call to {@link #lookup(String)}. * * The generated token will have the format base64(series-hash):base64(token-hash). * * @param user the user name * @param password the password * @param timeToLive timeout of the token * @return a first login token * @throws XPathException if a query error occurs */ public LoginDetails register(String user, String password, DurationValue timeToLive) throws XPathException { DateTimeValue now = new DateTimeValue(new Date()); DateTimeValue expires = (DateTimeValue) now.plus(timeToLive); LoginDetails login = new LoginDetails(user, password, timeToLive, expires.getTimeInMillis()); seriesMap.put(login.getSeries(), login); return login; } /** * Look up the given token and return login details. If the token is found, it will be updated * with a new hash before returning and the old hash is removed. * * @param token the token string provided by the user * @return login details for the user or null if no session was found or it was expired * @throws XPathException series matched but the token not. may indicate a cookie theft attack * or an out-of-sequence request. */ public LoginDetails lookup(String token) throws XPathException { String[] tokens = token.split(":"); LoginDetails data = seriesMap.get(tokens[0]); if (data == null) { LOG.debug("No session found for series " + tokens[0]); return null; } long now = System.currentTimeMillis(); if (now > data.expires) { LOG.debug("Persistent session expired"); seriesMap.remove(tokens[0]); return null; } // sequential token checking is disabled by default if (data.seqBehavior) { LOG.debug("Using sequential tokens"); if (!data.checkAndUpdateToken(tokens[1])) { LOG.debug("Out-of-sequence request or cookie theft attack. Deleting session."); seriesMap.remove(tokens[0]); throw new XPathException("Token mismatch. This may indicate an out-of-sequence request (likely) or a cookie theft attack. " + "Session is deleted for security reasons."); } } return data; } /** * Invalidate the session associated with the token string. Looks up the series hash * and deletes it. * * @param token token string provided by the user */ public void invalidate(String token) { String[] tokens = token.split(":"); seriesMap.remove(tokens[0]); } private String generateSeriesToken() { byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH]; random.nextBytes(newSeries); Base64Encoder encoder = new Base64Encoder(); encoder.translate(newSeries); return new String(encoder.getCharArray()); } private String generateToken() { byte[] newSeries = new byte[DEFAULT_TOKEN_LENGTH]; random.nextBytes(newSeries); Base64Encoder encoder = new Base64Encoder(); encoder.translate(newSeries); return new String(encoder.getCharArray()); } public class LoginDetails { private String userName; private String password; private String token; private String series; private long expires; private DurationValue timeToLive; // disable sequential token checking by default private boolean seqBehavior = false; private Map<String, Long> invalidatedTokens = new HashMap<>(); public LoginDetails(String user, String password, DurationValue timeToLive, long expires) { this.userName = user; this.password = password; this.timeToLive = timeToLive; this.expires = expires; this.token = generateToken(); this.series = generateSeriesToken(); } public String getToken() { return this.token; } public String getSeries() { return this.series; } public String getUser() { return this.userName; } public String getPassword() { return this.password; } public DurationValue getTimeToLive() { return timeToLive; } public boolean checkAndUpdateToken(String token) { if (this.token.equals(token)) { update(); return true; } // check map of invalidating tokens Long timeout = invalidatedTokens.get(token); if (timeout == null) return false; // timed out: remove if (System.currentTimeMillis() > timeout) { invalidatedTokens.remove(token); return false; } // found invalidating token: return true but do not replace token return true; } public String update() { timeoutCheck(); // leave a small time window until previous token is deleted // to allow for concurrent requests invalidatedTokens.put(this.token, System.currentTimeMillis() + INVALIDATION_TIMEOUT); this.token = generateToken(); return this.token; } private void timeoutCheck() { long now = System.currentTimeMillis(); invalidatedTokens.entrySet().removeIf(entry -> entry.getValue() < now); } @Override public String toString() { return this.series + ":" + this.token; } } }
lgpl-2.1
jbossws/jbossws-cxf
modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/clientConfig/CustomHandler.java
2939
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.ws.jaxws.clientConfig; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.ws.WebServiceException; import javax.xml.ws.handler.soap.SOAPMessageContext; import org.jboss.logging.Logger; import org.jboss.ws.api.handler.GenericSOAPHandler; public class CustomHandler extends GenericSOAPHandler<SOAPMessageContext> { // Provide logging private static Logger log = Logger.getLogger(CustomHandler.class); @Override protected boolean handleInbound(SOAPMessageContext msgContext) { log.info("handleInbound"); try { SOAPMessage soapMessage = msgContext.getMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); SOAPBodyElement soapBodyElement = (SOAPBodyElement)soapBody.getChildElements().next(); SOAPElement soapElement = (SOAPElement)soapBodyElement.getChildElements().next(); String value = soapElement.getValue(); soapElement.setValue(value + "|CustomIn"); } catch (SOAPException e) { throw new WebServiceException(e); } return true; } @Override protected boolean handleOutbound(SOAPMessageContext msgContext) { log.info("handleOutbound"); try { SOAPMessage soapMessage = msgContext.getMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); SOAPBodyElement soapBodyElement = (SOAPBodyElement)soapBody.getChildElements().next(); SOAPElement soapElement = (SOAPElement)soapBodyElement.getChildElements().next(); String value = soapElement.getValue(); soapElement.setValue(value + "|CustomOut"); } catch (SOAPException e) { throw new WebServiceException(e); } return true; } }
lgpl-2.1
netarchivesuite/netarchivesuite-svngit-migration
src/dk/netarkivet/archive/bitarchive/distribute/HeartBeatMessage.java
3390
/* File: $Id$ * Revision: $Revision$ * Author: $Author$ * Date: $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package dk.netarkivet.archive.bitarchive.distribute; import dk.netarkivet.archive.distribute.ArchiveMessage; import dk.netarkivet.archive.distribute.ArchiveMessageVisitor; import dk.netarkivet.common.distribute.ChannelID; import dk.netarkivet.common.distribute.Channels; import dk.netarkivet.common.exceptions.ArgumentNotValid; /** * Simple class representing a HeartBeat message from a bit archive application. * A heartbeat has an applicationId, that identifies the application * that generated the heartbeat. * * TODO This class should probably contain more status data from bit archive application later. * */ public class HeartBeatMessage extends ArchiveMessage { /** time when heartbeat occurred. Note that timestamps cannot be compared between processes. */ private long timestamp; /** id of the application sending the heartbeat.*/ private String applicationId; /** * Creates a heartbeat message. * The time of the heartbeat is set to the creation of this object. * * @param inReceiver ChannelID for the recipient of this message. * @param applicationId - id of the application that sent the heartbeat */ public HeartBeatMessage(ChannelID inReceiver, String applicationId) { super(inReceiver, Channels.getError()); ArgumentNotValid.checkNotNullOrEmpty(applicationId, "applicationId"); timestamp = System.currentTimeMillis(); this.applicationId = applicationId; } /** * @return time of heartbeat occurrence. */ public long getTimestamp() { return timestamp; } /** * @return id of the application that generated the heartbeat. */ public String getBitarchiveID() { return applicationId; } /** * Retrieval of a string representation of this instance. * * @return The string representation of this instance. */ public String toString() { return ("Heartbeat for " + applicationId + " at " + timestamp); } /** * Should be implemented as a part of the visitor pattern. fx.: public void * accept(ArchiveMessageVisitor v) { v.visit(this); } * * @param v A message visitor */ public void accept(ArchiveMessageVisitor v) { v.visit(this); } }
lgpl-2.1
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7/tabs/tabitemsD.java
505
package fr.toss.FF7.tabs; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import fr.toss.FF7.ItemRegistry1; public final class tabitemsD extends CreativeTabs { public tabitemsD(int par1, String par2Str) { super(par1, par2Str); } @SideOnly(Side.CLIENT) public Item getTabIconItem() { return ItemRegistry1.blockicon; } }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/demo/src/main/java/org/pentaho/reporting/engine/classic/demo/ancient/demo/form/Patient.java
3041
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.demo.ancient.demo.form; import java.util.ArrayList; public class Patient { private String name; private String address; private String town; private String ssn; private String insurance; private String symptoms; private String allergy; private String level; private ArrayList treatments; public Patient() { treatments = new ArrayList(); } public Patient(final String name, final String address, final String town, final String ssn, final String insurance, final String symptoms) { treatments = new ArrayList(); this.name = name; this.address = address; this.town = town; this.ssn = ssn; this.insurance = insurance; this.symptoms = symptoms; } public String getAddress() { return address; } public void setAddress(final String address) { this.address = address; } public String getInsurance() { return insurance; } public void setInsurance(final String insurance) { this.insurance = insurance; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getSsn() { return ssn; } public void setSsn(final String ssn) { this.ssn = ssn; } public String getSymptoms() { return symptoms; } public void setSymptoms(final String symptoms) { this.symptoms = symptoms; } public String getTown() { return town; } public void setTown(final String town) { this.town = town; } public int getTreatmentCount() { return treatments.size(); } public Treatment getTreatment(final int i) { return (Treatment) treatments.get(i); } public void addTreament(final Treatment t) { treatments.add(t); } public void removeTreatment(final Treatment t) { treatments.remove(t); } public String getAllergy() { return allergy; } public void setAllergy(final String allergy) { this.allergy = allergy; } public String getLevel() { return level; } public void setLevel(final String level) { this.level = level; } }
lgpl-2.1
sagara177/nexentastor-rest
src/rest/nexentastor/JsonRequest.java
1237
package rest.nexentastor; import java.util.ArrayList; /** * <p> * This class provides NexentaStor RESTful API's request format in JSON. see * NexentaStor REST API document[1]. * </p> * * <p> * [1] 'REST-API User Guide v1.0 - Nexenta', * <a href="http://www.nexenta.com/corp/static/docs-stable/NexentaStor-RESTful-API.pdf"> * http://www.nexenta.com/corp/static/docs-stable/NexentaStor-RESTful-API.pdf</a> * </p> * * @author sagara * */ public class JsonRequest extends JsonData { String object; ArrayList<Object> params; String method; public JsonRequest() { } public JsonRequest(String object, ArrayList<Object> params, String method) { this.object = object; this.params = params; this.method = method; } public String getObject() { return object; } public void setObject(String object) { this.object = object; } public ArrayList<Object> getParams() { return params; } public void setParams(ArrayList<Object> params) { this.params = params; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } }
lgpl-2.1
IDgis/geoportaal
querydsl-tsvector/src/main/java/nl/idgis/querydsl/TsVectorExpression.java
647
package nl.idgis.querydsl; import com.querydsl.core.types.Expression; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.SimpleExpression; public abstract class TsVectorExpression<T extends TsVector> extends SimpleExpression<T> { private static final long serialVersionUID = 2302357736274141901L; public TsVectorExpression(Expression<T> mixin) { super(mixin); } public BooleanExpression query(String language, String query) { return Expressions.booleanTemplate("{0} @@ to_tsquery('" + language + "', {1})", mixin, query); } }
lgpl-2.1
lucee/Lucee
core/src/main/java/lucee/runtime/err/ErrorPageImpl.java
2058
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.err; import lucee.runtime.PageSource; /** * */ public final class ErrorPageImpl implements ErrorPage { /** Type of exception. Required if type = "exception" or "monitor". */ private String exception = "any"; /** The relative path to the custom error page. */ private PageSource template; /** * The e-mail address of the administrator to notify of the error. The value is available to your * custom error page in the MailTo property of the error object. */ private String mailto = ""; private short type; @Override public void setMailto(String mailto) { this.mailto = mailto; } @Override public void setTemplate(PageSource template) { this.template = template; } @Override public void setTypeAsString(String exception) { setException(exception); } @Override public void setException(String exception) { this.exception = exception; } @Override public String getMailto() { return mailto; } @Override public PageSource getTemplate() { return template; } @Override public String getTypeAsString() { return getException(); } @Override public String getException() { return exception; } @Override public void setType(short type) { this.type = type; } @Override public short getType() { return type; } }
lgpl-2.1
Mikeware/minueto
src/samples/org/minueto/sample/image/ArcDemo.java
3718
package org.minueto.sample.image; /** * @(#)ArcDemo.java 1.00 12/11/2013 * * Minueto - The Game Development Framework * Copyright (c) 2004-2013 McGill University * 3480 University Street, Montreal, Quebec H3A 2A7 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **/ import org.minueto.MinuetoColor; import org.minueto.image.MinuetoCircle; import org.minueto.image.MinuetoFont; import org.minueto.image.MinuetoImage; import org.minueto.image.MinuetoText; import org.minueto.window.MinuetoFrame; import org.minueto.window.MinuetoWindow; /** * Sample that draws a growing Arc. * * @since 2.1 **/ public class ArcDemo { public ArcDemo() { MinuetoWindow window; // The Minueto window MinuetoImage circle; MinuetoImage circle2; int r = 0; // Rotation angle + size // Create a 640 by 480 window window = new MinuetoFrame(640, 480, true); // Show the game window. window.setVisible(true); circle = new MinuetoCircle(52, MinuetoColor.BLUE, true); circle2 = new MinuetoCircle(108, 108, MinuetoColor.GREEN, true); // Game/rendering loop while(true) { // Clear the window. window.clear(); // Change the rotation angle. Our demo does a demonstration // of rotation by changing the rotation angle at each frame. r++; if (r > 360) { r = 0; } window.draw(circle2, 50, 50); // Remember the drawing coordinate is the top-left window.draw(circle, 52, 52); // Draw the transformed image. // Note: Normally it's better to create a single image and reuse it // we're going to be changing parameters all the time though window.draw(new MinuetoText("S: " + r + " Ang: " + r, MinuetoFont.DefaultFont, MinuetoColor.RED), 54, 34); window.draw(new MinuetoCircle(50, MinuetoColor.RED, true, r, r), 54, 54); window.draw(new MinuetoText("S: 0 Ang: " + r, MinuetoFont.DefaultFont, MinuetoColor.GREEN), 164, 34); window.draw(new MinuetoCircle(50, MinuetoColor.GREEN, true, 0, r), 164, 54); window.draw(new MinuetoText("S: -" + r + " Ang: 135", MinuetoFont.DefaultFont, MinuetoColor.GREEN), 164, 284); window.draw(new MinuetoCircle(50, MinuetoColor.GREEN, true, -r, 135), 164, 164); window.draw(new MinuetoText("S: " + r + " Ang: 90", MinuetoFont.DefaultFont, MinuetoColor.BLUE), 274, 34); window.draw(new MinuetoCircle(50, MinuetoColor.BLUE, true, r, 90), 274, 54); window.draw(new MinuetoText("S: " + r + " Ang: -135", MinuetoFont.DefaultFont, MinuetoColor.BLUE), 274, 284); window.draw(new MinuetoCircle(50, MinuetoColor.BLUE, true, r, -135), 274, 164); // Render all graphics in the back buffer. window.render(); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } } /** * We need this to make our demo runnable from the command line. **/ public static void main(String[] args) { @SuppressWarnings("unused") ArcDemo arcExample = new ArcDemo(); } }
lgpl-2.1
elkafoury/tux
src/org/herac/tuxguitar/gui/actions/settings/EditConfigAction.java
643
/* * Created on 17-dic-2005 * */ package org.herac.tuxguitar.gui.actions.settings; import org.eclipse.swt.events.TypedEvent; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.actions.Action; import org.herac.tuxguitar.gui.system.config.TGConfigEditor; /** * @author julian * */ public class EditConfigAction extends Action{ public static final String NAME = "action.settings.configure"; public EditConfigAction() { super(NAME, AUTO_LOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE ); } protected int execute(TypedEvent e){ new TGConfigEditor().showDialog(TuxGuitar.instance().getShell()); return 0; } }
lgpl-2.1
roboidstudio/embedded
org.roboid.studio.contentscomposer/src/org/roboid/studio/contentscomposer/editparts/MotionClipCloneBlockEditPart.java
2157
/* * Part of the ROBOID project * Copyright (C) 2016 Kwang-Hyun Park (akaii@kw.ac.kr) and Kyoung Jin Kim * https://github.com/roboidstudio/embedded * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.roboid.studio.contentscomposer.editparts; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.swt.graphics.Image; import org.roboid.studio.contentscomposer.Activator; import org.roboid.studio.contentscomposer.MotionClipCloneBlock; /** * @author Kyoung Jin Kim * @author Kwang-Hyun Park */ public class MotionClipCloneBlockEditPart extends BlockElementEditPart { private static final String IMAGE = "/icons/clone_mc2.png"; private static final Image image = Activator.getImageDescriptor(IMAGE).createImage(); @Override protected IFigure createFigure() { // ¸ð¼Ç Ŭ¸³ÀÇ º¹»çº»À» ±×¸°´Ù. BlockFigure figure = new BlockFigure(this) { @Override protected void fillShape(Graphics g) { int x = getClientArea().x; int y = getClientArea().y; g.drawImage(image, x, y); // ¿øº»ÀÇ À̸§À» ³»ºÎ¿¡ Ç¥½ÃÇÑ´Ù. g.drawText(getOriginalClipName(), x + 20, y + 5); } }; figure.setSize(96, 24); return figure; } private MotionClipCloneBlock getCastedModel() { return (MotionClipCloneBlock)getModel(); } private String getOriginalClipName() { if(getCastedModel().getOriginal() == null) return ""; return getCastedModel().getOriginal().getName(); } }
lgpl-2.1
icholy/geokettle-2.0
src/org/pentaho/di/trans/steps/filesfromresult/FilesFromResult.java
3169
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans.steps.filesfromresult; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Reads results from a previous transformation in a Job * * @author Matt * @since 2-jun-2003 */ public class FilesFromResult extends BaseStep implements StepInterface { private FilesFromResultMeta meta; private FilesFromResultData data; public FilesFromResult(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); meta = (FilesFromResultMeta) getStepMeta().getStepMetaInterface(); data = (FilesFromResultData) stepDataInterface; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { if (data.resultFilesList == null || getLinesRead() >= data.resultFilesList.size()) { setOutputDone(); return false; } ResultFile resultFile = (ResultFile) data.resultFilesList.get((int) getLinesRead()); RowMetaAndData r = resultFile.getRow(); data.outputRowMeta = r.getRowMeta(); smi.getFields(data.outputRowMeta, getStepname(), null, null, this); incrementLinesRead(); putRow(data.outputRowMeta, r.getData()); // copy row to possible alternate // rowset(s). if (checkFeedback(getLinesRead())) logBasic(Messages.getString("FilesFromResult.Log.LineNumber") + getLinesRead()); //$NON-NLS-1$ return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (FilesFromResultMeta) smi; data = (FilesFromResultData) sdi; if (super.init(smi, sdi)) { Result result = getTransMeta().getPreviousResult(); if (result != null) { data.resultFilesList = result.getResultFilesList(); } else { data.resultFilesList = null; } // Add init code here. return true; } return false; } // // Run is were the action happens! public void run() { BaseStep.runStepThread(this, meta, data); } }
lgpl-2.1
felixion/flxsmb
src/jcifs/smb/SmbRandomAccessFile.java
11911
/* jcifs smb client library in Java * Copyright (C) 2003 "Michael B. Allen" <jcifs at samba dot org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.smb; import java.io.DataInput; import java.io.DataOutput; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.UnknownHostException; import jcifs.util.Encdec; public class SmbRandomAccessFile implements DataOutput, DataInput { private static final int WRITE_OPTIONS = 0x0842; private SmbFile file; private long fp; private int openFlags, access = 0, readSize, writeSize, ch, options = 0; private byte[] tmp = new byte[8]; private SmbComWriteAndXResponse write_andx_resp = null; public SmbRandomAccessFile( String url, String mode, int shareAccess ) throws SmbException, MalformedURLException, UnknownHostException { this( new SmbFile( url, "", null, shareAccess ), mode ); } public SmbRandomAccessFile( SmbFile file, String mode ) throws SmbException, MalformedURLException, UnknownHostException { this.file = file; if( mode.equals( "r" )) { this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDONLY; } else if( mode.equals( "rw" )) { this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDWR | SmbFile.O_APPEND; write_andx_resp = new SmbComWriteAndXResponse(); options = WRITE_OPTIONS; access = SmbConstants.FILE_READ_DATA | SmbConstants.FILE_WRITE_DATA; } else { throw new IllegalArgumentException( "Invalid mode" ); } file.open( openFlags, access, SmbFile.ATTR_NORMAL, options ); boolean isSigningEnabled = (file.tree.session.transport.flags2 & ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES) == ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES; if(!isSigningEnabled && (file.tree.session.transport.server.capabilities & SmbConstants.CAP_LARGE_READX) == SmbConstants.CAP_LARGE_READX) { readSize = Math.min(SmbConstants.RCV_BUF_SIZE - 70, 0xFFFF -70); } else { readSize = file.tree.session.transport.rcv_buf_size - 70; } if(!isSigningEnabled && (file.tree.session.transport.server.capabilities & SmbConstants.CAP_LARGE_WRITEX) == SmbConstants.CAP_LARGE_WRITEX) { writeSize = Math.min(SmbConstants.SND_BUF_SIZE - 70, 0xFFFF - 70); } else { writeSize = Math.min( file.tree.session.transport.snd_buf_size - 70, file.tree.session.transport.server.maxBufferSize - 70 ); } fp = 0L; } public int read() throws SmbException { if( read( tmp, 0, 1 ) == -1 ) { return -1; } return tmp[0] & 0xFF; } public int read( byte b[] ) throws SmbException { return read( b, 0, b.length ); } public int read( byte b[], int off, int len ) throws SmbException { if( len <= 0 ) { return 0; } long start = fp; // ensure file is open if( file.isOpen() == false ) { file.open( openFlags, 0, SmbFile.ATTR_NORMAL, options ); } int r, n; SmbComReadAndXResponse response = new SmbComReadAndXResponse( b, off ); do { r = len > readSize ? readSize : len; file.send( new SmbComReadAndX( file.fid, fp, r, null ), response ); if(( n = response.dataLength ) <= 0 ) { return (int)((fp - start) > 0L ? fp - start : -1); } fp += n; len -= n; response.off += n; } while( len > 0 && n == r ); return (int)(fp - start); } public final void readFully( byte b[] ) throws SmbException { readFully( b, 0, b.length ); } public final void readFully( byte b[], int off, int len ) throws SmbException { int n = 0, count; do { count = this.read( b, off + n, len - n ); if( count < 0 ) throw new SmbException( "EOF" ); n += count; fp += count; } while( n < len ); } public int skipBytes( int n ) throws SmbException { if (n > 0) { fp += n; return n; } return 0; } public void write( int b ) throws SmbException { tmp[0] = (byte)b; write( tmp, 0, 1 ); } public void write( byte b[] ) throws SmbException { write( b, 0, b.length ); } public void write( byte b[], int off, int len ) throws SmbException { if( len <= 0 ) { return; } // ensure file is open if( file.isOpen() == false ) { file.open( openFlags, 0, SmbFile.ATTR_NORMAL, options ); } int w; do { w = len > writeSize ? writeSize : len; file.send( new SmbComWriteAndX( file.fid, fp, len - w, b, off, w, null ), write_andx_resp ); fp += write_andx_resp.count; len -= write_andx_resp.count; off += write_andx_resp.count; } while( len > 0 ); } public long getFilePointer() throws SmbException { return fp; } public void seek( long pos ) throws SmbException { fp = pos; } public long length() throws SmbException { return file.length(); } public void setLength( long newLength ) throws SmbException { // ensure file is open if( file.isOpen() == false ) { file.open( openFlags, 0, SmbFile.ATTR_NORMAL, options ); } SmbComWriteResponse rsp = new SmbComWriteResponse(); file.send( new SmbComWrite( file.fid, (int)(newLength & 0xFFFFFFFFL), 0, tmp, 0, 0 ), rsp ); } public void close() throws SmbException { file.close(); } public final boolean readBoolean() throws SmbException { if((read( tmp, 0, 1 )) < 0 ) { throw new SmbException( "EOF" ); } return tmp[0] != (byte)0x00; } public final byte readByte() throws SmbException { if((read( tmp, 0, 1 )) < 0 ) { throw new SmbException( "EOF" ); } return tmp[0]; } public final int readUnsignedByte() throws SmbException { if((read( tmp, 0, 1 )) < 0 ) { throw new SmbException( "EOF" ); } return tmp[0] & 0xFF; } public final short readShort() throws SmbException { if((read( tmp, 0, 2 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_uint16be( tmp, 0 ); } public final int readUnsignedShort() throws SmbException { if((read( tmp, 0, 2 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_uint16be( tmp, 0 ) & 0xFFFF; } public final char readChar() throws SmbException { if((read( tmp, 0, 2 )) < 0 ) { throw new SmbException( "EOF" ); } return (char)Encdec.dec_uint16be( tmp, 0 ); } public final int readInt() throws SmbException { if((read( tmp, 0, 4 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_uint32be( tmp, 0 ); } public final long readLong() throws SmbException { if((read( tmp, 0, 8 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_uint64be( tmp, 0 ); } public final float readFloat() throws SmbException { if((read( tmp, 0, 4 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_floatbe( tmp, 0 ); } public final double readDouble() throws SmbException { if((read( tmp, 0, 8 )) < 0 ) { throw new SmbException( "EOF" ); } return Encdec.dec_doublebe( tmp, 0 ); } public final String readLine() throws SmbException { StringBuffer input = new StringBuffer(); int c = -1; boolean eol = false; while (!eol) { switch( c = read() ) { case -1: case '\n': eol = true; break; case '\r': eol = true; long cur = fp; if( read() != '\n' ) { fp = cur; } break; default: input.append( (char)c ); break; } } if ((c == -1) && (input.length() == 0)) { return null; } return input.toString(); } public final String readUTF() throws SmbException { int size = readUnsignedShort(); byte[] b = new byte[size]; read( b, 0, size ); try { return Encdec.dec_utf8( b, 0, size ); } catch( IOException ioe ) { throw new SmbException( "", ioe ); } } public final void writeBoolean( boolean v ) throws SmbException { tmp[0] = (byte)(v ? 1 : 0); write( tmp, 0, 1 ); } public final void writeByte( int v ) throws SmbException { tmp[0] = (byte)v; write( tmp, 0, 1 ); } public final void writeShort( int v ) throws SmbException { Encdec.enc_uint16be( (short)v, tmp, 0 ); write( tmp, 0, 2 ); } public final void writeChar( int v ) throws SmbException { Encdec.enc_uint16be( (short)v, tmp, 0 ); write( tmp, 0, 2 ); } public final void writeInt( int v ) throws SmbException { Encdec.enc_uint32be( v, tmp, 0 ); write( tmp, 0, 4 ); } public final void writeLong( long v ) throws SmbException { Encdec.enc_uint64be( v, tmp, 0 ); write( tmp, 0, 8 ); } public final void writeFloat( float v ) throws SmbException { Encdec.enc_floatbe( v, tmp, 0 ); write( tmp, 0, 4 ); } public final void writeDouble( double v ) throws SmbException { Encdec.enc_doublebe( v, tmp, 0 ); write( tmp, 0, 8 ); } public final void writeBytes( String s ) throws SmbException { byte[] b = s.getBytes(); write( b, 0, b.length ); } public final void writeChars( String s ) throws SmbException { int clen = s.length(); int blen = 2 * clen; byte[] b = new byte[blen]; char[] c = new char[clen]; s.getChars( 0, clen, c, 0 ); for( int i = 0, j = 0; i < clen; i++ ) { b[j++] = (byte)(c[i] >>> 8); b[j++] = (byte)(c[i] >>> 0); } write( b, 0, blen ); } public final void writeUTF( String str ) throws SmbException { int len = str.length(); int ch, size = 0; byte[] dst; for( int i = 0; i < len; i++ ) { ch = str.charAt( i ); size += ch > 0x07F ? (ch > 0x7FF ? 3 : 2) : 1; } dst = new byte[size]; writeShort( size ); try { Encdec.enc_utf8( str, dst, 0, size ); } catch( IOException ioe ) { throw new SmbException( "", ioe ); } write( dst, 0, size ); } }
lgpl-2.1
fiduciagad/active-notification-framework
src/main/java/de/fiduciagad/anflibrary/anFReceiver/anFMessages/view/anFMessageNotificationViews/anFClicked/NotificationClickedActivity.java
986
package de.fiduciagad.anflibrary.anFReceiver.anFMessages.view.anFMessageNotificationViews.anFClicked; import android.content.Context; import android.content.Intent; import de.fiduciagad.anflibrary.anFReceiver.anFMessages.view.ViewConstants; /** * Created by Felix Schiefer on 16.01.2016. */ public class NotificationClickedActivity { private static final String CLASS_NAME = NotificationClickedActivity.class.getSimpleName(); /** * @param context * @param id * @return Das Intent wird an die Notification als Reply gesetzt. Sobald ein klick auf das Notification * Ribbon durchgeführt wird. Über den AnFConnector wird die passende Instanz des MessageBuilderInterface * genutzt. */ public static Intent getMessageActivity(Context context, int id) { Intent clickedService = new Intent(context, NotificationClickedService.class); clickedService.putExtra(ViewConstants.ID_EXTRA, id); return clickedService; } }
lgpl-2.1
nfinit-gaming/BetterAgriculture
src/main/java/betteragriculture/client/model/ModelEntityMobCow1.java
7228
package betteragriculture.client.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ModelEntityMobCow1 extends ModelBase { public ModelRenderer Head; public ModelRenderer Body1; public ModelRenderer Body2; public ModelRenderer Body3; public ModelRenderer Lshoulder1; public ModelRenderer Rshoulder1; public ModelRenderer Lshoulder2; public ModelRenderer Rshoulder2; public ModelRenderer Larm1; public ModelRenderer Larm2; public ModelRenderer Rarm1; public ModelRenderer Rarm2; public ModelRenderer Back1; public ModelRenderer Back2; public ModelRenderer Back3; public ModelRenderer Back4; public ModelRenderer Back5; public ModelRenderer Back6; public ModelRenderer Back7; public ModelRenderer Back8; public ModelRenderer Back9; public ModelEntityMobCow1() { textureWidth = 64; textureHeight = 32; Head = new ModelRenderer(this, 0, 0); Head.addBox(-3.5F, -7F, -3.5F, 7, 7, 7); Head.setRotationPoint(0F, 0F, 0F); Head.setTextureSize(64, 32); Head.mirror = true; setRotation(Head, 0F, 0F, 0F); Body1 = new ModelRenderer(this, 20, 14); Body1.addBox(-1.5F, -1F, -1.5F, 3, 10, 3); Body1.setRotationPoint(0F, 0F, 0F); Body1.setTextureSize(64, 32); Body1.mirror = true; setRotation(Body1, 0.4461433F, 0F, 0F); Body2 = new ModelRenderer(this, 28, 0); Body2.addBox(0F, 0F, 0F, 3, 6, 3); Body2.setRotationPoint(-1.5F, 7F, 2F); Body2.setTextureSize(64, 32); Body2.mirror = true; setRotation(Body2, 0F, 0F, 0F); Body3 = new ModelRenderer(this, 28, 0); Body3.addBox(0F, 0F, 0F, 3, 6, 3); Body3.setRotationPoint(-1.5F, 11F, 2.5F); Body3.setTextureSize(64, 32); Body3.mirror = true; setRotation(Body3, -0.5948578F, 0F, 0F); Lshoulder1 = new ModelRenderer(this, 40, 0); Lshoulder1.addBox(0F, 0F, 0F, 3, 2, 2); Lshoulder1.setRotationPoint(1.5F, 0F, 0F); Lshoulder1.setTextureSize(64, 32); Lshoulder1.mirror = true; setRotation(Lshoulder1, 0F, 0F, 0F); Rshoulder1 = new ModelRenderer(this, 40, 0); Rshoulder1.addBox(0F, 0F, 0F, 3, 2, 2); Rshoulder1.setRotationPoint(-4.5F, 0F, 0F); Rshoulder1.setTextureSize(64, 32); Rshoulder1.mirror = true; setRotation(Rshoulder1, 0F, 0F, 0F); Lshoulder2 = new ModelRenderer(this, 40, 0); Lshoulder2.addBox(0F, 0F, 0F, 3, 2, 2); Lshoulder2.setRotationPoint(1.5F, 5F, 2F); Lshoulder2.setTextureSize(64, 32); Lshoulder2.mirror = true; setRotation(Lshoulder2, 0F, 0F, 0F); Rshoulder2 = new ModelRenderer(this, 40, 0); Rshoulder2.addBox(0F, 0F, 0F, 3, 2, 2); Rshoulder2.setRotationPoint(-4.5F, 5F, 2F); Rshoulder2.setTextureSize(64, 32); Rshoulder2.mirror = true; setRotation(Rshoulder2, 0F, 0F, 0F); Larm1 = new ModelRenderer(this, 0, 14); Larm1.addBox(0F, -1F, -7F, 2, 2, 8); Larm1.setRotationPoint(4.5F, 1F, 1F); Larm1.setTextureSize(64, 32); Larm1.mirror = true; setRotation(Larm1, 0F, 0F, 0F); Larm2 = new ModelRenderer(this, 0, 14); Larm2.addBox(0F, -1F, -7F, 2, 2, 8); Larm2.setRotationPoint(4.5F, 6F, 3F); Larm2.setTextureSize(64, 32); Larm2.mirror = true; setRotation(Larm2, 0F, 0F, 0F); Rarm1 = new ModelRenderer(this, 0, 14); Rarm1.addBox(-2F, -1F, -7F, 2, 2, 8); Rarm1.setRotationPoint(-4.5F, 1F, 1F); Rarm1.setTextureSize(64, 32); Rarm1.mirror = true; setRotation(Rarm1, 0F, 0F, 0F); Rarm2 = new ModelRenderer(this, 0, 14); Rarm2.addBox(-2F, -1F, -7F, 2, 2, 8); Rarm2.setRotationPoint(-4.5F, 6F, 3F); Rarm2.setTextureSize(64, 32); Rarm2.mirror = true; setRotation(Rarm2, 0F, 0F, 0F); Back1 = new ModelRenderer(this, 50, 0); Back1.addBox(0F, 0F, 0F, 1, 2, 1); Back1.setRotationPoint(-0.5F, 2F, 4F); Back1.setTextureSize(64, 32); Back1.mirror = true; setRotation(Back1, -1.041002F, 0F, 0F); Back2 = new ModelRenderer(this, 50, 0); Back2.addBox(0F, 0F, 0F, 1, 2, 1); Back2.setRotationPoint(-0.5F, 4F, 5F); Back2.setTextureSize(64, 32); Back2.mirror = true; setRotation(Back2, -1.041002F, 0F, 0F); Back3 = new ModelRenderer(this, 50, 0); Back3.addBox(0F, 0F, 0F, 1, 2, 1); Back3.setRotationPoint(-0.5F, 0F, 3F); Back3.setTextureSize(64, 32); Back3.mirror = true; setRotation(Back3, -1.041002F, 0F, 0F); Back4 = new ModelRenderer(this, 50, 0); Back4.addBox(0F, 0F, 0F, 1, 1, 2); Back4.setRotationPoint(-0.5F, 8F, 4.5F); Back4.setTextureSize(64, 32); Back4.mirror = true; setRotation(Back4, 0F, 0F, 0F); Back5 = new ModelRenderer(this, 50, 0); Back5.addBox(0F, 0F, 0F, 1, 1, 2); Back5.setRotationPoint(-0.5F, 10F, 4.5F); Back5.setTextureSize(64, 32); Back5.mirror = true; setRotation(Back5, 0F, 0F, 0F); Back6 = new ModelRenderer(this, 50, 0); Back6.addBox(0F, 0F, 0F, 1, 1, 2); Back6.setRotationPoint(-0.5F, 12F, 4.5F); Back6.setTextureSize(64, 32); Back6.mirror = true; setRotation(Back6, 0F, 0F, 0F); Back7 = new ModelRenderer(this, 50, 0); Back7.addBox(0F, 0F, 0F, 1, 2, 1); Back7.setRotationPoint(-0.5F, 14F, 3.5F); Back7.setTextureSize(64, 32); Back7.mirror = true; setRotation(Back7, 1.00382F, 0F, 0F); Back8 = new ModelRenderer(this, 50, 0); Back8.addBox(0F, 0F, 0F, 1, 2, 1); Back8.setRotationPoint(-0.5F, 15.5F, 2.5F); Back8.setTextureSize(64, 32); Back8.mirror = true; setRotation(Back8, 1.00382F, 0F, 0F); Back9 = new ModelRenderer(this, 50, 0); Back9.addBox(0F, 0F, 0F, 1, 2, 1); Back9.setRotationPoint(-0.5F, 17F, 1.5F); Back9.setTextureSize(64, 32); Back9.mirror = true; setRotation(Back9, 1.00382F, 0F, 0F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Head.render(f5); Body1.render(f5); Body2.render(f5); Body3.render(f5); Lshoulder1.render(f5); Rshoulder1.render(f5); Lshoulder2.render(f5); Rshoulder2.render(f5); Larm1.render(f5); Larm2.render(f5); Rarm1.render(f5); Rarm2.render(f5); Back1.render(f5); Back2.render(f5); Back3.render(f5); Back4.render(f5); Back5.render(f5); Back6.render(f5); Back7.render(f5); Back8.render(f5); Back9.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } @Override public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity par7Entity) { Head.rotateAngleY = par4 / (180F / (float)Math.PI); Head.rotateAngleX = par5 / (180F / (float)Math.PI); Rarm1.rotateAngleX = MathHelper.cos(par1 * 0.6662F + (float)Math.PI) * 2.0F * par2 * 0.5F; Larm1.rotateAngleX = MathHelper.cos(par1 * 0.6662F) * 2.0F * par2 * 0.5F; Rarm2.rotateAngleX = MathHelper.cos(par1 * 0.6662F + (float)Math.PI) * 2.0F * par2 * 0.5F * 0.1F; Larm2.rotateAngleX = MathHelper.cos(par1 * 0.6662F) * 2.0F * par2 * 0.5F * 0.1F; Rarm1.rotateAngleZ = 0.0F; Larm1.rotateAngleZ = 0.0F; Rarm2.rotateAngleZ = 0.0F; Larm2.rotateAngleZ = 0.0F; } }
lgpl-2.1
JiriOndrusek/wildfly-core
controller/src/main/java/org/jboss/as/controller/parsing/ExtensionParsingContext.java
4659
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.controller.parsing; import java.util.List; import java.util.function.Supplier; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.RunningMode; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * Context in effect when the {@code extension} element for a given {@link org.jboss.as.controller.Extension} is being parsed. Allows the * extension to {@link org.jboss.as.controller.Extension#initializeParsers(ExtensionParsingContext) initialize the XML parsers} that can * be used for parsing the {@code subsystem} elements that contain the configuration for its subsystems. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public interface ExtensionParsingContext { /** * Gets the type of the current process. * @return the current process type. Will not be {@code null} */ ProcessType getProcessType(); /** * Gets the current running mode of the process. * @return the current running mode. Will not be {@code null} */ RunningMode getRunningMode(); /** * Set the parser for the profile-wide subsystem configuration XML element. The element is always * called {@code "subsystem"}. The reader should populate the given model node with the appropriate * "subsystem add" update, without the address or operation name as that information will be automatically * populated. * * @param subsystemName the name of the subsystem. Cannot be {@code null} * @param namespaceUri the URI of the subsystem's XML namespace, in string form. Cannot be {@code null} * @param reader the element reader. Cannot be {@code null} * * @throws IllegalStateException if another {@link org.jboss.as.controller.Extension} has already registered a subsystem with the given * {@code subsystemName} * @deprecated Use {@link ExtensionParsingContext#setSubsystemXmlMapping(java.lang.String, java.lang.String, java.util.function.Supplier)} instead. */ @Deprecated void setSubsystemXmlMapping(String subsystemName, String namespaceUri, XMLElementReader<List<ModelNode>> reader); /** * Set the parser for the profile-wide subsystem configuration XML element. The element is always * called {@code "subsystem"}. The reader should populate the given model node with the appropriate * "subsystem add" update, without the address or operation name as that information will be automatically * populated. * It is recommended that supplier always creates new instance of the {@link XMLElementReader} * instead of caching and returning always same instance. * * @param subsystemName the name of the subsystem. Cannot be {@code null} * @param namespaceUri the URI of the sussystem's XML namespace, in string form. Cannot be {@code null} * @param supplier of the element reader. Cannot be {@code null} * * @throws IllegalStateException if another {@link org.jboss.as.controller.Extension} has already registered a subsystem with the given * {@code subsystemName} */ void setSubsystemXmlMapping(String subsystemName, String namespaceUri, Supplier<XMLElementReader<List<ModelNode>>> supplier); /** * Registers a {@link ProfileParsingCompletionHandler} to receive a callback upon completion of parsing of a * profile. * * @param handler the handler. Cannot be {@code null} */ void setProfileParsingCompletionHandler(ProfileParsingCompletionHandler handler); }
lgpl-2.1
maikelsteneker/checkstyle-throwsIndent
src/tests/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java
1731
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class AutomaticBeanTest { private static class TestBean extends AutomaticBean { public void setName(String aName) { } } private final DefaultConfiguration mConf = new DefaultConfiguration( "testConf"); private final TestBean mTestBean = new TestBean(); @Test(expected = CheckstyleException.class) public void testNoSuchAttribute() throws CheckstyleException { mConf.addAttribute("NonExisting", "doesn't matter"); mTestBean.configure(mConf); } }
lgpl-2.1
deegree/deegree3
deegree-datastores/deegree-tilestores/deegree-tilestore-geotiff/src/main/java/org/deegree/tile/persistence/geotiff/GeoTiffTileStoreMetadata.java
3350
/*---------------------------------------------------------------------------- This file is part of deegree Copyright (C) 2001-2013 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - and - Occam Labs UG (haftungsbeschränkt) - and others This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: e-mail: info@deegree.org website: http://www.deegree.org/ ----------------------------------------------------------------------------*/ package org.deegree.tile.persistence.geotiff; import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; import org.deegree.tile.TileMatrixSet; import org.deegree.tile.persistence.TileStore; import org.deegree.tile.persistence.geotiff.jaxb.GeoTIFFTileStoreJAXB; import org.deegree.tile.tilematrixset.TileMatrixSetProvider; import org.deegree.workspace.ResourceBuilder; import org.deegree.workspace.ResourceInitException; import org.deegree.workspace.ResourceLocation; import org.deegree.workspace.Workspace; import org.deegree.workspace.standard.AbstractResourceMetadata; import org.deegree.workspace.standard.AbstractResourceProvider; import org.deegree.workspace.standard.DefaultResourceIdentifier; /** * Resource metadata implementation for geotiff tile stores. * * @author <a href="mailto:schmitz@occamlabs.de">Andreas Schmitz</a> * * @since 3.4 */ public class GeoTiffTileStoreMetadata extends AbstractResourceMetadata<TileStore> { public GeoTiffTileStoreMetadata( Workspace workspace, ResourceLocation<TileStore> location, AbstractResourceProvider<TileStore> provider ) { super( workspace, location, provider ); } @Override public ResourceBuilder<TileStore> prepare() { try { GeoTIFFTileStoreJAXB cfg = (GeoTIFFTileStoreJAXB) unmarshall( "org.deegree.tile.persistence.geotiff.jaxb", provider.getSchema(), location.getAsStream(), workspace ); for ( GeoTIFFTileStoreJAXB.TileDataSet tds : cfg.getTileDataSet() ) { dependencies.add( new DefaultResourceIdentifier<TileMatrixSet>( TileMatrixSetProvider.class, tds.getTileMatrixSetId() ) ); } return new GeoTiffTileStoreBuilder( cfg, workspace, this ); } catch ( Exception e ) { throw new ResourceInitException( "Unable to prepare resource " + getIdentifier() + ": " + e.getLocalizedMessage(), e ); } } }
lgpl-2.1
comundus/opencms-comundus
src/main/java/org/opencms/cache/CmsVfsDiskCache.java
6706
/* * File : $Source: /usr/local/cvs/opencms/src/org/opencms/cache/CmsVfsDiskCache.java,v $ * Date : $Date: 2008-04-17 13:47:06 $ * Version: $Revision: 1.6 $ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.cache; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsStringUtil; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Implements a RFS file based disk cache, that handles parameter based versions of VFS files, * providing a cache for the "online" and another for the "offline" project.<p> * * @author Alexander Kandzior * * @version $Revision: 1.6 $ * * @since 6.2.0 */ public class CmsVfsDiskCache { /** The name of the cache base repository folder in the RFS. */ private String m_rfsRepository; /** * Creates a new disk cache.<p> * * @param basepath the base path for the cache in the RFS * @param foldername the folder name for this cache, to be used a subfolder for the base folder */ public CmsVfsDiskCache(String basepath, String foldername) { // normalize the given folder name m_rfsRepository = CmsFileUtil.normalizePath(basepath + foldername + File.separatorChar); } /** * Saves the given file content to a RFS file of the given name (full path).<p> * * If the required parent folders do not exists, they are also created.<p> * * @param rfsName the RFS name of the file to save the content in * @param content the content of the file to save * * @return a reference to the File that was saved * * @throws IOException in case of disk access errors */ public static File saveFile(String rfsName, byte[] content) throws IOException { File f = new File(rfsName); File p = f.getParentFile(); if (!p.exists()) { // create parent folders p.mkdirs(); } // write file contents FileOutputStream fs = new FileOutputStream(f); fs.write(content); fs.close(); return f; } /** * Returns the content of the requested file in the disk cache, or <code>null</code> if the * file is not found in the cache, or is found but outdated.<p> * * @param rfsName the file RFS name to look up in the cache * @param dateLastModified the date of last modification for the cache * * @return the content of the requested file in the VFS disk cache, or <code>null</code> */ public byte[] getCacheContent(String rfsName, long dateLastModified) { dateLastModified = simplifyDateLastModified(dateLastModified); try { File f = new File(rfsName); if (f.exists()) { if (f.lastModified() != dateLastModified) { // last modification time different, remove cached file in RFS f.delete(); } else { return CmsFileUtil.readFile(f); } } } catch (IOException e) { // unable to read content } return null; } /** * Returns the RFS name to use for caching the given VFS resource with parameters in the disk cache.<p> * * @param online if true, the online disk cache is used, the offline disk cache otherwise * @param rootPath the VFS resource root path to get the RFS cache name for * @param parameters the parameters of the request to the VFS resource * * @return the RFS name to use for caching the given VFS resource with parameters */ public String getCacheName(boolean online, String rootPath, String parameters) { String rfsName = CmsFileUtil.getRepositoryName(m_rfsRepository, rootPath, online); if (CmsStringUtil.isNotEmpty(parameters)) { String extension = CmsFileUtil.getExtension(rfsName); // build the RFS name for the VFS name with parameters rfsName = CmsFileUtil.getRfsPath(rfsName, extension, parameters); } return rfsName; } /** * Returns the absolute path of the cache repository in the RFS.<p> * * @return the absolute path of the cache repository in the RFS */ public String getRepositoryPath() { return m_rfsRepository; } /** * Saves the given file content in the disk cache.<p> * * @param rfsName the RFS name of the file to save the content in * @param content the content of the file to save * @param dateLastModified the date of last modification to set for the save file * * @throws IOException in case of disk access errors */ public void saveCacheFile(String rfsName, byte[] content, long dateLastModified) throws IOException { dateLastModified = simplifyDateLastModified(dateLastModified); File f = saveFile(rfsName, content); // set last modification date f.setLastModified(dateLastModified); } /** * Simplifies the "date last modified" from the OpenCms VFS based milliseconds * to just seconds, to support file systems that don't use milliseconds.<p> * * @param dateLastModified the date to simplify * * @return the simplified date last modified */ private long simplifyDateLastModified(long dateLastModified) { return dateLastModified / 1000L; } }
lgpl-2.1
esig/dss
dss-pades/src/test/java/eu/europa/esig/dss/pades/validation/suite/PAdESOCSPSigningCertificateTest.java
2685
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.pades.validation.suite; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.List; import eu.europa.esig.dss.diagnostic.CertificateRefWrapper; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.diagnostic.RelatedCertificateWrapper; import eu.europa.esig.dss.diagnostic.RevocationWrapper; import eu.europa.esig.dss.enumerations.CertificateRefOrigin; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; public class PAdESOCSPSigningCertificateTest extends AbstractPAdESTestValidation { @Override protected DSSDocument getSignedDocument() { return new InMemoryDocument(getClass().getResourceAsStream("/validation/pades-ocsp-sign-cert.pdf")); } @Override protected void checkRevocationData(DiagnosticData diagnosticData) { super.checkRevocationData(diagnosticData); for (RevocationWrapper revocationWrapper : diagnosticData.getAllRevocationData()) { assertNotNull(revocationWrapper.getSigningCertificate()); List<RelatedCertificateWrapper> relatedCertificates = revocationWrapper.foundCertificates().getRelatedCertificates(); assertEquals(1, relatedCertificates.size()); assertEquals(0, revocationWrapper.foundCertificates().getOrphanCertificates().size()); RelatedCertificateWrapper relatedCertificateWrapper = relatedCertificates.get(0); assertEquals(1, relatedCertificateWrapper.getReferences().size()); CertificateRefWrapper certificateRefWrapper = relatedCertificateWrapper.getReferences().get(0); assertEquals(CertificateRefOrigin.SIGNING_CERTIFICATE, certificateRefWrapper.getOrigin()); } } }
lgpl-2.1
maximehamm/jspresso-ce
application/src/main/java/org/jspresso/framework/application/frontend/file/ConnectorValueGetterCallback.java
2642
/* * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved. * * This file is part of the Jspresso framework. * * Jspresso 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. * * Jspresso 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 Jspresso. If not, see <http://www.gnu.org/licenses/>. */ package org.jspresso.framework.application.frontend.file; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.jspresso.framework.action.IActionHandler; import org.jspresso.framework.application.action.AbstractActionContextAware; import org.jspresso.framework.model.descriptor.IFileFilterable; import org.jspresso.framework.model.descriptor.IModelDescriptor; /** * Default handler implementation to deal with getting binary properties storing * them in files. * * @author Vincent Vandenschrick */ public class ConnectorValueGetterCallback extends AbstractActionContextAware implements IFileSaveCallback { /** * {@inheritDoc} */ @Override public void cancel(IActionHandler actionHandler, Map<String, Object> context) { // NO-OP } /** * {@inheritDoc} */ @Override public void fileChosen(String name, OutputStream out, IActionHandler actionHandler, Map<String, Object> context) throws IOException { OutputStream os = new BufferedOutputStream(out); // Do not use getSelectedModel() since it will return // the component holding the binary property Object connectorValue = getViewConnector(context).getConnectorValue(); byte[] content; if (connectorValue instanceof String) { content = ((String) connectorValue).getBytes(); } else { content = (byte[]) connectorValue; } if (connectorValue != null) { os.write(content); os.flush(); } } /** * {@inheritDoc} */ @Override public String getFileName(Map<String, Object> context) { IModelDescriptor modelDescriptor = getModelDescriptor(context); if (modelDescriptor instanceof IFileFilterable) { return ((IFileFilterable) modelDescriptor).getFileName(); } return null; } }
lgpl-3.0
hdsdi3g/MyDMAM
app/hd3gtv/archivecircleapi/ACFile.java
3178
/* * This file is part of MyDMAM. * * This program 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 * 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 Lesser General Public License for more details. * * Copyright (C) hdsdi3g for hd3g.tv 2016 * */ package hd3gtv.archivecircleapi; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import hd3gtv.mydmam.gson.GsonIgnore; public class ACFile { public String self; public int max = 0; public int offset = 0; public String sort; public ACOrder order; public String share; public String path; public long creationDate = 0; public long modificationDate = 0; public ACFileType type; public int count = 0; public int size = 0; public long date_min = 0; public long date_max = 0; public ACQuotas quota; @GsonIgnore public ACItemLocations sub_locations; @GsonIgnore public ArrayList<ACFileLocations> this_locations; /** * Only for file */ public ACAccessibility accessibility; public ACLocationType bestLocation; @GsonIgnore public ArrayList<String> files; ACFile() { } public boolean isOnTape() { if (this_locations == null) { return false; } return this_locations.stream().anyMatch(location -> { return location instanceof ACFileLocationTape; }); } /** * @return null if this is not archived */ public List<String> getTapeBarcodeLocations() { if (this_locations == null) { return null; } return this_locations.stream().filter(location -> { return location instanceof ACFileLocationTape; }).map(location -> { return (ACFileLocationTape) location; }).flatMap(tape_location -> { return tape_location.tapes.stream(); }).map(tape -> { return tape.barcode; }).collect(Collectors.toList()); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + ((share == null) ? 0 : share.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ACFile other = (ACFile) obj; if (path == null) { if (other.path != null) { return false; } } else if (!path.equals(other.path)) { return false; } if (share == null) { if (other.share != null) { return false; } } else if (!share.equals(other.share)) { return false; } if (type != other.type) { return false; } return true; } public String toString() { if (type == ACFileType.directory) { return "[D] " + share + "/" + path; } else { return share + "/" + path + " (" + accessibility.name().toLowerCase() + ")"; } } }
lgpl-3.0
Albloutant/Galacticraft
common/micdoodle8/mods/galacticraft/core/client/model/GCCoreModelFlag.java
4121
package micdoodle8.mods.galacticraft.core.client.model; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityFlag; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.FMLClientHandler; /** * GCCoreModelFlag.java * * This file is part of the Galacticraft project * * @author micdoodle8 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class GCCoreModelFlag extends ModelBase { ModelRenderer base; ModelRenderer pole; ModelRenderer flag; ModelRenderer picSide1; ModelRenderer picSide2; ModelRenderer picSide3; ModelRenderer picSide4; public GCCoreModelFlag() { this.textureWidth = 128; this.textureHeight = 64; this.base = new ModelRenderer(this, 4, 0); this.base.addBox(-1.5F, 0F, -1.5F, 3, 1, 3); this.base.setRotationPoint(0F, 23F, 0F); this.base.setTextureSize(128, 64); this.base.mirror = true; this.setRotation(this.base, 0F, 0F, 0F); this.pole = new ModelRenderer(this, 0, 0); this.pole.addBox(-0.5F, -40F, -0.5F, 1, 40, 1); this.pole.setRotationPoint(0F, 23F, 0F); this.pole.setTextureSize(128, 64); this.pole.mirror = true; this.setRotation(this.pole, 0F, 0F, 0F); this.flag = new ModelRenderer(this, 86, 0); this.flag.addBox(0F, 0F, 0F, 20, 12, 1); this.flag.setRotationPoint(0.5F, -16F, -0.5F); this.flag.setTextureSize(128, 64); this.flag.mirror = true; this.setRotation(this.flag, 0F, 0F, 0F); this.picSide1 = new ModelRenderer(this, 16, 16); this.picSide1.addBox(0F, 0F, 0F, 16, 16, 0); this.picSide1.setRotationPoint(29F, -28F, 1.1F); this.picSide1.setTextureSize(128, 64); this.picSide1.mirror = true; this.setRotation(this.picSide1, 0F, 0F, 0F); this.picSide2 = new ModelRenderer(this, 16, 16); this.picSide2.addBox(0F, 0F, 0F, 16, 16, 0); this.picSide2.setRotationPoint(13F, -28F, -1.1F); this.picSide2.setTextureSize(128, 64); this.picSide2.mirror = false; this.setRotation(this.picSide2, 0F, 0F, 0F); this.picSide3 = new ModelRenderer(this, 80, 16); this.picSide3.addBox(0F, 0F, 0F, 16, 16, 0); this.picSide3.setRotationPoint(29F, -28F, 1.11F); this.picSide3.setTextureSize(128, 64); this.picSide3.mirror = true; this.setRotation(this.picSide3, 0F, 0F, 0F); this.picSide4 = new ModelRenderer(this, 80, 16); this.picSide4.addBox(0F, 0F, 0F, 16, 16, 0); this.picSide4.setRotationPoint(13F, -28F, -1.11F); this.picSide4.setTextureSize(128, 64); this.picSide4.mirror = false; this.setRotation(this.picSide4, 0F, 0F, 0F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); this.setRotationAngles(entity, f, f1, f2, f3, f4, f5); this.base.render(f5); this.pole.render(f5); this.flag.render(f5); if (((GCCoreEntityFlag) entity).getType() != 0) { GCCoreEntityFlag flag = (GCCoreEntityFlag) entity; ResourceLocation resourcelocation = AbstractClientPlayer.locationStevePng; if (flag.getOwner() != null && flag.getOwner().length() > 0) { resourcelocation = AbstractClientPlayer.getLocationSkin(flag.getOwner()); AbstractClientPlayer.getDownloadImageSkin(resourcelocation, flag.getOwner()); } FMLClientHandler.instance().getClient().renderEngine.bindTexture(resourcelocation); GL11.glScalef(0.5F, 0.5F, 0.5F); this.picSide1.render(f5); this.picSide2.render(f5); this.picSide3.render(f5); this.picSide4.render(f5); } } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } public void setRotationAngles(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); this.picSide1.rotateAngleY = (float) Math.PI; this.picSide3.rotateAngleY = (float) Math.PI; } }
lgpl-3.0
robosphinx/QuartzPlus
src/main/java/robosphinx/mods/quartz/block/SlabItemBlock.java
5628
package robosphinx.mods.quartz.block; /** * @author robosphinx */ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import robosphinx.mods.quartz.init.QuartzPlusBlocks; import net.minecraft.block.Block; import net.minecraft.block.BlockSlab; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class SlabItemBlock extends ItemBlock { /* * What are our sub-block variants? */ private static final String[] subNames = { "smoky", "rose" }; private final boolean fullBlock; private final BlockSlab singleSlab; private final BlockSlab doubleSlab; /* * Tells the game that this block has sub-types. */ public SlabItemBlock (Block id) { super(id); this.singleSlab = (BlockSlab) QuartzPlusBlocks.quartz_slab; this.doubleSlab = (BlockSlab) QuartzPlusBlocks.double_quartz_slab; this.fullBlock = false; setHasSubtypes(true); } /* * Gets the damage value so we know which sub-block this is. */ @Override public int getMetadata (int damageValue) { return damageValue; } /* * Allows us to set different names for each sub-block. */ @Override public String getUnlocalizedName (ItemStack stack) { return getUnlocalizedName() + "." + subNames[stack.getItemDamage()]; } /** * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return True if something happen and * false if it don't. This is for ITEMS, not BLOCKS */ public boolean onItemUse (ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int i, float f1, float f2, float f3) { if (this.fullBlock) { return super.onItemUse(stack, player, world, x, y, z, i, f1, f2, f3); } else if (stack.stackSize == 0) { return false; } else if (!player.canPlayerEdit(x, y, z, i, stack)) { return false; } else { Block block = world.getBlock(x, y, z); int i1 = world.getBlockMetadata(x, y, z); int j1 = i1 & 7; boolean flag = (i1 & 8) != 0; if ((i == 1 && !flag || i == 0 && flag) && block == this.singleSlab && j1 == stack.getItemDamage()) { if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z)) && world.setBlock(x, y, z, this.doubleSlab, j1, 3)) { world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), this.doubleSlab.stepSound.func_150496_b(), (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, this.doubleSlab.stepSound.getPitch() * 0.8F); --stack.stackSize; } return true; } else { return this.func_150946_a(stack, player, world, x, y, z, i) ? true : super.onItemUse(stack, player, world, x, y, z, i, f1, f2, f3); } } } @SideOnly (Side.CLIENT) public boolean func_150936_a (World world, int x, int y, int z, int i, EntityPlayer player, ItemStack stack) { int i1 = x; int j1 = y; int k1 = z; Block block = world.getBlock(x, y, z); int l1 = world.getBlockMetadata(x, y, z); int i2 = l1 & 7; boolean flag = (l1 & 8) != 0; if ((i == 1 && !flag || i == 0 && flag) && block == this.singleSlab && i2 == stack.getItemDamage()) { return true; } else { if (i == 0) { --y; } if (i == 1) { ++y; } if (i == 2) { --z; } if (i == 3) { ++z; } if (i == 4) { --x; } if (i == 5) { ++x; } Block block1 = world.getBlock(x, y, z); int j2 = world.getBlockMetadata(x, y, z); i2 = j2 & 7; return block1 == this.singleSlab && i2 == stack.getItemDamage() ? true : super.func_150936_a(world, i1, j1, k1, i, player, stack); } } private boolean func_150946_a (ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int i) { if (i == 0) { --y; } if (i == 1) { ++y; } if (i == 2) { --z; } if (i == 3) { ++z; } if (i == 4) { --x; } if (i == 5) { ++x; } Block block = world.getBlock(x, y, z); int i1 = world.getBlockMetadata(x, y, z); int j1 = i1 & 7; if (block == this.singleSlab && j1 == stack.getItemDamage()) { if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z)) && world.setBlock(x, y, z, this.doubleSlab, j1, 3)) { world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), this.doubleSlab.stepSound.func_150496_b(), (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, this.doubleSlab.stepSound.getPitch() * 0.8F); --stack.stackSize; } return true; } else { return false; } } }
lgpl-3.0
daniel-he/community-edition
projects/repository/source/java/org/alfresco/repo/workflow/jscript/JscriptWorkflowTask.java
9364
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.workflow.jscript; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.alfresco.model.ApplicationModel; import org.alfresco.model.ContentModel; import org.alfresco.repo.jscript.BaseScopableProcessorExtension; import org.alfresco.repo.jscript.ScriptNode; import org.alfresco.repo.jscript.ScriptableHashMap; import org.alfresco.repo.jscript.ScriptableQNameMap; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.dictionary.DictionaryService; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.MutableAuthenticationService; import org.alfresco.service.cmr.workflow.WorkflowNode; import org.alfresco.service.cmr.workflow.WorkflowService; import org.alfresco.service.cmr.workflow.WorkflowTask; import org.alfresco.service.cmr.workflow.WorkflowTaskState; import org.alfresco.service.cmr.workflow.WorkflowTransition; import org.alfresco.service.namespace.NamespacePrefixResolver; import org.alfresco.service.namespace.NamespacePrefixResolverProvider; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; /** * This class represents a workflow task (an instance of a workflow task definition) * * @author glenj * @author Nick Smith */ public class JscriptWorkflowTask extends BaseScopableProcessorExtension implements Serializable { static final long serialVersionUID = -8285971359421912313L; /** Service Registry object */ private final ServiceRegistry serviceRegistry; private final NodeService nodeService; private final WorkflowService workflowService; private final DictionaryService dictionaryService; private MutableAuthenticationService authenticationService; private final DefaultNamespaceProvider namespaceProvider; private WorkflowTask task; /** * Creates a new instance of a workflow task from a WorkflowTask from the CMR workflow object model * * @param task * an instance of WorkflowTask from CMR workflow object model * @param serviceRegistry * Service Registry object */ public JscriptWorkflowTask(WorkflowTask task, ServiceRegistry serviceRegistry, Scriptable scope) { this.serviceRegistry = serviceRegistry; this.namespaceProvider = new DefaultNamespaceProvider(serviceRegistry.getNamespaceService()); this.workflowService = serviceRegistry.getWorkflowService(); this.nodeService = serviceRegistry.getNodeService(); this.dictionaryService = serviceRegistry.getDictionaryService(); this.authenticationService = serviceRegistry.getAuthenticationService(); this.task = task; this.setScope(scope); } /** * Gets the value of the <code>id</code> property * * @return the id */ public String getId() { return task.getId(); } /** * Gets the value of the <code>name</code> property * * @return the name */ public String getName() { return task.getName(); } /** * Gets the value of the <code>title</code> property * * @return the title */ public String getTitle() { return task.getTitle(); } /** * Gets the value of the <code>description</code> property * * @return the description */ public String getDescription() { return task.getDescription(); } /** * Gets the value of the <code>properties</code> property * * @return the properties */ public Scriptable getProperties() { // instantiate ScriptableQNameMap<String, Serializable> properties // from WorkflowTasks's Map<QName, Serializable> properties ScriptableQNameMap<String, Serializable> properties = new ScriptableQNameMap<String, Serializable>(namespaceProvider); properties.putAll(task.getProperties()); return properties; } /** * Sets the properties on the underlying {@link WorkflowTask}. * * @param properties * the properties to set */ public void setProperties(ScriptableQNameMap<String, Serializable> properties) { Map<QName, Serializable> qNameProps = properties.getMapOfQNames(); this.task = workflowService.updateTask(task.getId(), qNameProps, null, null); } /** * Returns whether the task is complete 'true':complete, 'false':in-progress * * @return the complete */ public boolean isComplete() { return task.getState().equals(WorkflowTaskState.COMPLETED); } /** * Returns whether this task is pooled or not * * @return 'true': task is pooled, 'false': task is not pooled */ public boolean isPooled() { String authority = authenticationService.getCurrentUserName(); return workflowService.isTaskClaimable(task, authority); } /** * @deprecated pooled state cannot be altered. * */ @Deprecated public void setPooled(boolean pooled) { } /** * End the task * * @param transitionId * transition to end the task for */ public void endTask(String transitionId) { workflowService.endTask(task.getId(), transitionId); } /** * Get the available transition ids. * * @return */ public ScriptableHashMap<String, String> getTransitions() { ScriptableHashMap<String, String> transitions = new ScriptableHashMap<String, String>(); WorkflowNode workflowNode = task.getPath().getNode(); if (workflowNode != null) { for (WorkflowTransition transition : workflowNode.getTransitions()) { transitions.put(transition.getId(), transition.getTitle()); } } return transitions; } /** * Get the packe resources (array of noderefs) * * @return */ public Scriptable getPackageResources() { List<NodeRef> contents = workflowService.getPackageContents(task.getId()); List<ScriptNode> resources = new ArrayList<ScriptNode>(contents.size()); Collection<QName> allowedTypes = getAllowedPackageResourceTypes(); for (NodeRef node : contents) { if (isValidResource(node, allowedTypes)) { ScriptNode scriptNode = new ScriptNode(node, serviceRegistry, getScope()); resources.add(scriptNode); } } return Context.getCurrentContext().newArray(getScope(), resources.toArray()); } private Collection<QName> getAllowedPackageResourceTypes() { // look for content nodes or links to content // NOTE: folders within workflow packages are ignored for now Collection<QName> allowedTypes = dictionaryService.getSubTypes(ContentModel.TYPE_CONTENT, true); allowedTypes.addAll(dictionaryService.getSubTypes(ApplicationModel.TYPE_FILELINK, true)); return allowedTypes; } private boolean isValidResource(NodeRef node, Collection<QName> allowedTypes) { if (nodeService.exists(node)) { //Check if the node is one of the allowedTypes. return allowedTypes.contains(nodeService.getType(node)); } return false; } private static class DefaultNamespaceProvider implements NamespacePrefixResolverProvider { private static final long serialVersionUID = -7015209142379905617L; private final NamespaceService namespaceService; public DefaultNamespaceProvider(NamespaceService namespaceService) { this.namespaceService = namespaceService; } /** * {@inheritDoc} */ public NamespacePrefixResolver getNamespacePrefixResolver() { return namespaceService; } } }
lgpl-3.0
fdi2-epsilon/teams-game
android-app/src/main/java/eu/unipv/epsilon/enigma/ui/main/card/CollectionCardHolder.java
3545
package eu.unipv.epsilon.enigma.ui.main.card; import android.content.Context; import android.content.Intent; import android.support.annotation.LayoutRes; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import eu.unipv.epsilon.enigma.QuizActivity; import eu.unipv.epsilon.enigma.R; import eu.unipv.epsilon.enigma.quest.QuestCollection; import eu.unipv.epsilon.enigma.status.QuestCollectionStatus; import eu.unipv.epsilon.enigma.ui.bitmap.AssetsURLImageLoader; import eu.unipv.epsilon.enigma.ui.bitmap.ImageLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; /** The base collection card holder with a title and background image. */ public class CollectionCardHolder extends CardHolder { private static final Logger LOG = LoggerFactory.getLogger(CollectionCardHolder.class); private QuestCollection boundCollection; protected TextView titleRef; protected ImageView imageRef; protected CollectionCardHolder(ViewGroup parent, @LayoutRes int layoutResource) { this(parent, layoutResource, false); } protected CollectionCardHolder(ViewGroup parent, @LayoutRes int layoutResource, boolean isFullSpan) { super(parent, layoutResource, isFullSpan); bindLayoutElements(); } protected void bindLayoutElements() { // Store references to view elements to avoid potentially expensive lookups later. titleRef = (TextView) itemView.findViewById(R.id.card_title); imageRef = (ImageView) itemView.findViewById(R.id.card_image); getItemView().setOnClickListener(new ClickListener()); } public void updateViewFromData(QuestCollection collection, QuestCollectionStatus collectionStatus) { boundCollection = collection; // Update local references view content from given data titleRef.setText(collection.getTitle()); loadImage(collection.getIconUrl()); } // Hook to get effective ImageView size for sampled image loading protected void loadImage(final URL path) { imageRef.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { imageRef.getViewTreeObserver().removeOnPreDrawListener(this); try { ImageLoader loader = new AssetsURLImageLoader(path); imageRef.setImageBitmap(loader.decodeSampledBitmap(imageRef.getMeasuredWidth(), imageRef.getMeasuredHeight())); } catch (IOException e) { LOG.warn("The image was not found", e); } return true; } }); } /** * Creates a new QuizActivity displaying the content of the QuestCollection currently bound to this card. */ private class ClickListener implements View.OnClickListener { @Override public void onClick(View v) { Context context = v.getContext(); if (!boundCollection.isEmpty()) { Intent intent = new Intent(context, QuizActivity.class); intent.putExtra(QuizActivity.PARAM_COLLECTION_ID, boundCollection.getId()); context.startActivity(intent); } else Toast.makeText(context, R.string.main_toast_no_content, Toast.LENGTH_SHORT).show(); } } }
lgpl-3.0
anandswarupv/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/properties/SingleDictionaryPropertyWidget.java
4764
/** * DataCleaner (community edition) * Copyright (C) 2014 Neopost - Customer Information Management * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.widgets.properties; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.inject.Inject; import javax.inject.Provider; import javax.swing.JButton; import org.datacleaner.descriptors.ConfiguredPropertyDescriptor; import org.datacleaner.job.builder.ComponentBuilder; import org.datacleaner.reference.Dictionary; import org.datacleaner.panels.DCPanel; import org.datacleaner.user.DictionaryChangeListener; import org.datacleaner.user.MutableReferenceDataCatalog; import org.datacleaner.util.IconUtils; import org.datacleaner.util.WidgetFactory; import org.datacleaner.widgets.DCComboBox; import org.datacleaner.widgets.DCComboBox.Listener; import org.datacleaner.widgets.ReferenceDataComboBoxListRenderer; import org.datacleaner.windows.ReferenceDataDialog; import org.jdesktop.swingx.HorizontalLayout; public class SingleDictionaryPropertyWidget extends AbstractPropertyWidget<Dictionary> implements DictionaryChangeListener { private final DCComboBox<Dictionary> _comboBox; private final MutableReferenceDataCatalog _referenceDataCatalog; private final Provider<ReferenceDataDialog> _referenceDataDialogProvider; @Inject public SingleDictionaryPropertyWidget(ConfiguredPropertyDescriptor propertyDescriptor, ComponentBuilder componentBuilder, MutableReferenceDataCatalog referenceDataCatalog, Provider<ReferenceDataDialog> referenceDataDialogProvider) { super(componentBuilder, propertyDescriptor); _referenceDataCatalog = referenceDataCatalog; _referenceDataDialogProvider = referenceDataDialogProvider; _comboBox = new DCComboBox<Dictionary>(); _comboBox.setRenderer(new ReferenceDataComboBoxListRenderer()); _comboBox.setEditable(false); if (!propertyDescriptor.isRequired()) { _comboBox.addItem(null); } final String[] dictionaryNames = referenceDataCatalog.getDictionaryNames(); for (String name : dictionaryNames) { _comboBox.addItem(referenceDataCatalog.getDictionary(name)); } Dictionary currentValue = getCurrentValue(); _comboBox.setSelectedItem(currentValue); _comboBox.addListener(new Listener<Dictionary>() { @Override public void onItemSelected(Dictionary item) { fireValueChanged(); } }); final JButton dialogButton = WidgetFactory.createSmallButton(IconUtils.MENU_OPTIONS); dialogButton.setToolTipText("Configure dictionaries"); dialogButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ReferenceDataDialog dialog = _referenceDataDialogProvider.get(); dialog.selectDictionariesTab(); dialog.setVisible(true); } }); final DCPanel outerPanel = new DCPanel(); outerPanel.setLayout(new HorizontalLayout(2)); outerPanel.add(_comboBox); outerPanel.add(dialogButton); add(outerPanel); } @Override public void onPanelAdd() { super.onPanelAdd(); _referenceDataCatalog.addDictionaryListener(this); } @Override public void onPanelRemove() { super.onPanelRemove(); _referenceDataCatalog.removeDictionaryListener(this); } @Override public Dictionary getValue() { return (Dictionary) _comboBox.getSelectedItem(); } @Override protected void setValue(Dictionary value) { _comboBox.setEditable(true); _comboBox.setSelectedItem(value); _comboBox.setEditable(false); } @Override public void onAdd(Dictionary dictionary) { _comboBox.addItem(dictionary); } @Override public void onRemove(Dictionary dictionary) { _comboBox.removeItem(dictionary); } }
lgpl-3.0
masp/MRPG
src/masp/plugins/mlight/config/SkillClassConfiguration.java
2623
package masp.plugins.mlight.config; import java.io.File; import java.io.IOException; import masp.plugins.mlight.MRPG; import masp.plugins.mlight.data.Attribute; import masp.plugins.mlight.data.effects.types.MEffect; public class SkillClassConfiguration extends Configuration { public SkillClassConfiguration(MRPG plugin, File dir) { super("skill-classes", plugin, dir); } @Override public void onCreate() { getConfig().set("skill-classes.damage.cost", 1); getConfig().set("skill-classes.damage.max-level", 100); getConfig().set("skill-classes.damage.description", "Increases The Player's Damage!"); getConfig().set("skill-classes.damage.effects.general_damage", 5); try { getConfig().save(getFile()); } catch (IOException e) { e.printStackTrace(); } } @Override public void onRead() { if (getConfig().getConfigurationSection("skill-classes") != null) { for (String skillName : getConfig().getConfigurationSection("skill-classes").getKeys(false)) { int cost = getConfig().getInt("skill-classes." + skillName + ".cost", 1); int maxLevel = getConfig().getInt("skill-classes." + skillName + ".max-level", 100); String description = getConfig().getString("skill-classes." + skillName + ".description", "Default skill description :/"); Attribute skill = new Attribute(skillName, description, cost, maxLevel); if (getConfig().getConfigurationSection("skill-classes." + skillName + ".effects") != null) { for (String effectName : getConfig().getConfigurationSection("skill-classes." + skillName + ".effects").getKeys(false)) { MEffect effect = MRPG.getEffectManager().getEffect(effectName); if (effect != null) { String sValue = getConfig().getString("skill-classes." + skillName + ".effects." + effectName); if (sValue.contains("%")) { try { skill.setEffectPercent(effect, Double.parseDouble(sValue.replaceAll("%", ""))); } catch (NumberFormatException ex) { getPlugin().getLogger().info("Configuration Error: Effect value must be a number for effect " + effectName + " for skill " + skillName); } } else { try { skill.setEffectDecimal(effect, Double.parseDouble(sValue)); } catch (NumberFormatException ex) { getPlugin().getLogger().info("Configuration Error: Effect value must be a number for effect " + effectName + " for skill " + skillName); } } } } } MRPG.getAttributeManager().addSkill(skill); } } } }
lgpl-3.0
mr-justin/gate-semano
src/semano/rulebaseeditor/JapelateTreePanel.java
4128
package semano.rulebaseeditor; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.tree.TreeSelectionModel; import semano.ontoviewer.CheckRenderer; /** * A GUI component showing a list of japelates used on the right-hand side within the rule base editor. * @author nadeschda * */ public class JapelateTreePanel extends JPanel implements TreePanel { private HashMap<String, Boolean> currentJapelateSelection = new HashMap<>(); /** Instance of JTree used to store information about ontology items */ protected JList<String> ontologyTree; /** ToolBars that displays the different options */ private JToolBar leftToolBar; // /** // * OntologyTreeListener that listens to the selection of ontology // classes // */ // protected OntologyTreeListener ontoTreeListener; /** Instance of ontology Viewer */ private RuleBaseViewer ruleBaseViewer; /** * Indicates whether the annotation window is being shown or not */ protected boolean showingAnnotationWindow = false; /** Constructor */ public JapelateTreePanel(RuleBaseViewer ruleBaseViewer) { super(); this.ruleBaseViewer = ruleBaseViewer; initGUI(); } /** Initialize the GUI */ private void initGUI() { ontologyTree = new JList<String>(); ToolTipManager.sharedInstance().registerComponent(ontologyTree); ontologyTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); this.setLayout(new BorderLayout()); this.add(new JScrollPane(ontologyTree), BorderLayout.CENTER); MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent mouseEvent) { if(SwingUtilities.isLeftMouseButton(mouseEvent)) { int index = ontologyTree.locationToIndex(mouseEvent.getPoint()); if(index >= 0) { String o = ontologyTree.getModel().getElementAt(index); if(getCurrentOResource2IsSelectedMap()!=null && getCurrentOResource2IsSelectedMap().get(o)!=null){ boolean isSelected = !getCurrentOResource2IsSelectedMap().get(o); setSelected(o, isSelected); ontologyTree.repaint(); ruleBaseViewer.refleshRuleTable(); } } } } }; ontologyTree.addMouseListener(mouseListener); leftToolBar = new JToolBar(JToolBar.VERTICAL); leftToolBar.setFloatable(false); CheckRenderer cellRenderer = new CheckRenderer(this); ontologyTree.setCellRenderer(cellRenderer); } /** A method to show an empty tree */ public void showEmptyOntologyTree() { setCurrentJapelateSelection(null); ontologyTree.setVisible(false); } public Component getGUI() { return this; } public void showJapelates(String[] data) { setCurrentJapelateSelection(ruleBaseViewer.japelateSelectionMap); ontologyTree.setListData(data); // ((CheckRenderer)ontologyTree.getCellRenderer()).selectAll(); ontologyTree.invalidate(); } public void setSelected(String row, boolean value) { getCurrentJapelateSelection().put(row, new Boolean(value)); } @Override public HashMap<String, Boolean> getCurrentOResource2IsSelectedMap() { return getCurrentJapelateSelection(); } @Override public HashMap<String, Color> getCurrentOResource2ColorMap() { return new HashMap<>(); } /** * @return the currentJapelateSelection */ private HashMap<String, Boolean> getCurrentJapelateSelection() { return currentJapelateSelection; } /** * @param currentJapelateSelection the currentJapelateSelection to set */ private void setCurrentJapelateSelection(HashMap<String, Boolean> currentJapelateSelection) { this.currentJapelateSelection = currentJapelateSelection; } }
lgpl-3.0
openstreetview/android
app/src/main/java/com/telenav/osv/manager/network/parser/UserDataParser.java
4351
package com.telenav.osv.manager.network.parser; import org.json.JSONObject; import com.telenav.osv.item.AccountData; import com.telenav.osv.item.network.UserData; import com.telenav.osv.utils.Log; /** * JSON parser for user profile data * Created by kalmanb on 8/1/17. */ public class UserDataParser extends ApiResponseParser<UserData> { private static final String TAG = "UserProfileParser"; @Override public UserData getHolder() { return new UserData(); } public UserData parse(String json) { UserData userData = super.parse(json); if (json != null && !json.isEmpty()) { final String userName; final String name; final String obdDistance; final String totalDistance; final double totalTracks; final String levelName; int rank = 0; int weeklyRank = 0; int score = 0; int level = 0; int xpProgress = 0; int xpTarget = 0; double totalPhotos; try { JSONObject obj = new JSONObject(json); JSONObject osv = obj.getJSONObject("osv"); String id = osv.getString("id"); userData.setUserId(id); userName = osv.getString("username"); userData.setUserName(userName); name = osv.getString("full_name"); userData.setDisplayName(name); String userType = osv.getString("type"); userData.setUserType(AccountData.getUserTypeForString(userType)); obdDistance = osv.getString("obdDistance"); totalDistance = osv.getString("totalDistance"); totalPhotos = osv.getDouble("totalPhotos"); userData.setTotalPhotos(totalPhotos); totalTracks = osv.getDouble("totalTracks"); userData.setTotalTracks(totalTracks); weeklyRank = osv.getInt("weeklyRank"); userData.setWeeklyRank(weeklyRank); try { JSONObject gamification = osv.getJSONObject("gamification"); if (gamification.has("rank")) { rank = gamification.getInt("rank"); } userData.setOverallRank(rank); if (gamification.has("total_user_points")) { score = gamification.getInt("total_user_points"); } userData.setTotalPoints(score); level = gamification.getInt("level"); userData.setLevel(level); levelName = gamification.getString("level_name"); userData.setLevelName(levelName); if(gamification.has("level_progress")){ xpProgress = gamification.getInt("level_progress"); } userData.setLevelProgress(xpProgress); if (gamification.has("level_target")) { xpTarget = gamification.getInt("level_target"); } userData.setLevelTarget(xpTarget); } catch (Exception e) { Log.w(TAG, "requestFinished: " + Log.getStackTraceString(e)); } double totalDistanceNum = 0; double obdDistanceNum = 0; try { if (totalDistance != null) { totalDistanceNum = Double.parseDouble(totalDistance); } } catch (NumberFormatException e) { Log.w(TAG, "getUserProfileDetails: " + Log.getStackTraceString(e)); } userData.setTotalDistance(totalDistanceNum); try { if (obdDistance != null) { obdDistanceNum = Double.parseDouble(obdDistance); } } catch (NumberFormatException e) { Log.w(TAG, "getUserProfileDetails: " + Log.getStackTraceString(e)); } userData.setObdDistance(obdDistanceNum); } catch (Exception e) { e.printStackTrace(); } } return userData; } }
lgpl-3.0
Kogoro/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/jobs/MarkerUpdateJob.java
1590
package de.tubs.variantsync.core.jobs; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ui.progress.UIJob; import de.tubs.variantsync.core.VariantSyncPlugin; import de.tubs.variantsync.core.data.CodeMapping; import de.tubs.variantsync.core.data.Context; import de.tubs.variantsync.core.data.SourceFile; import de.tubs.variantsync.core.patch.interfaces.IMarkerInformation; import de.tubs.variantsync.core.utilities.LogOperations; import de.tubs.variantsync.core.utilities.MarkerUtils; public class MarkerUpdateJob extends UIJob { private IFile file; public MarkerUpdateJob(IFile file) { super("Update markers"); this.file = file; } @Override public IStatus runInUIThread(IProgressMonitor monitor) { try { MarkerUtils.cleanResource(file); } catch (CoreException e) { LogOperations.logError("Cannot clear all markers from: " + file.getFullPath(), e); } Context context = VariantSyncPlugin.getDefault().getActiveEditorContext(); if (context != null) { List<IMarkerInformation> markers = new ArrayList<>(); SourceFile sourceFile = context.getMapping(file); if (sourceFile != null) { for (CodeMapping codeMapping : sourceFile.getMappings()) { markers.add(codeMapping.getMarkerInformation()); } } if (!markers.isEmpty()) MarkerUtils.setMarker(file, markers); } return Status.OK_STATUS; } }
lgpl-3.0
Centril/aTetria
aTetria-main/src/se/centril/atetria/framework/geom/Position3.java
5497
/* * This file is part of aTetria. * * aTetria 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. * * aTetria 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 aTetria. If not, see <http://www.gnu.org/licenses/>. */ package se.centril.atetria.framework.geom; /** * <p>Position3 models a three-dimensional position using integers.<br/> * Whether or not it is immutable is up to the implementing class.</p> * * <p><strong>NOTE:</strong> Position3D is <strong>NOT</strong> a Vector,<br/> * but some operations common to vector classes are provided such as add, mul, etc. * * @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad. * @version 1.0 * @since May 26, 2013 */ public interface Position3 extends Position { /** * Returns the z-axis-component of the coordinate. * * @return The z-axis-component of the coordinate. */ public int z(); /** * Sets the z-axis-component of the coordinate. * * @param z the new z value. * @return the Position2D with the new z-axis-component. */ public Position3 z( int z ); /** * Alias of {@link #z()}. * * @see #z() */ public int getZ(); /** * Sets both the x- and y-axis-component of the coordinate. * * @param x the new x value. * @param y the new x value. * @param z the new z value. * @return the Position3D with the new x, y & z-axis-component. */ public Position3 set( int x, int y, int z ); /** * Adds x, z & y to the x and y-axis-component of the coordinate. * * @param x the x value to add to x-axis-component. * @param y the y value to add to y-axis-component. * @param z the z value to add to z-axis-component. * @return the Position3D with x, y & z added. */ public Position3 add( int x, int y, int z ); /** * Adds z to the z-axis-component of the coordinate. * * @param z the z value to add to x-axis-component. * @return the Position3D with x added. */ public Position3 addZ( int z ); /** * Subtracts x, z & y to the x and y-axis-component of the coordinate. * * @param x the x value to add to x-axis-component. * @param y the y value to add to y-axis-component. * @return the Position3D with x, y, z subtracted. */ public Position3 sub( int x, int y, int z ); /** * Adds x to the x-axis-component of the coordinate. * * @param x the x value to add to x-axis-component. * @return the Position2D with x added. */ public Position3 subZ( int x ); /** * Returns all values as an array: [{@link #x()}, {@link #y()}, {@link #z()}]. * * @return all values as an array. */ public int[] values(); /** * Returns a string describing this position on the form "(x,y,z)". * * @return a string describing this position. */ public String toString(); /* -------------------------------------------- * Changed type + Aliases: * -------------------------------------------- */ /** * Alias of {@link #z(int)}. * * @see #z(int) */ public Position3 setZ( int z ); public Position3 x( int x ); public Position3 y( int y ); public Position3 set( int x, int y ); public Position3 setX( int x ); public Position3 setY( int y ); public Position3 add( int x, int y ); public Position3 addX( int x ); public Position3 addY( int y ); public Position3 sub( int x, int y ); public Position3 subX( int x ); public Position3 subY( int y ); public Position3 set( Position pos ); public Position3 add( Position pos ); public Position3 sub( Position pos ); /** * Adds the coordinates of another position object to this position. * * @param pos the position to use values from. * @return the Position3D with the added x, y & z-values. */ public Position3 add( Position3 pos ); /** * Subtracts the coordinates of another position object to this position. * * @param pos the position to use values from. * @return the Position3D with the subtracted x, y & z-values. */ public Position3 sub( Position3 pos ); /** * Copies the coordinate of another position object. * * @param pos the position to copy values from. * @return the Position3D with the new x, y & z-axis-component. */ public Position3 set( Position3 pos ); public Position3 mul( int factor ); public Position3 distance( Position rhs ); public Position3 distance( Position3 rhs ); public Position3 scale( int factor ); public Position3 move( Direction direction ); public Position3 move( Direction direction, int scale ); public Position3 cpy(); public Position3 clone(); /** * The method <tt>compareTo</tt> first compares {@link #x()} of the<br/> * position to decide if the given position is less or greater than this.<br/> * If they have the same {@link #x()}, {@link #y()} decides, and so on... * * @param rhs The position to compare with. * @return An integer smaller than 0 if this position < rhs,<br/> * 0 position == rhs, and a positive integer otherwise. */ public int compareTo( Position3 rhs ); public boolean contains( Position3 pos ); public boolean containedIn( Position3 dim ); }
lgpl-3.0
svn2github/dynamicreports-jasper
dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/expression/AddExpression.java
1569
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2015 Ricardo Mariaca * http://www.dynamicreports.org * * This file is part of DynamicReports. * * DynamicReports 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. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.report.builder.expression; import java.math.BigDecimal; import net.sf.dynamicreports.report.constant.Constants; import net.sf.dynamicreports.report.definition.expression.DRIExpression; /** * @author Ricardo Mariaca (r.mariaca@dynamicreports.org) */ public class AddExpression extends CalculationExpression { private static final long serialVersionUID = Constants.SERIAL_VERSION_UID; public AddExpression(DRIExpression<? extends Number> ...expressions) { super(expressions); } @Override protected BigDecimal calculate(BigDecimal value1, BigDecimal value2) { return value1.add(value2); } }
lgpl-3.0
vamsirajendra/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/step/ExecuteVisitorsStep.java
2425
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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 this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.step; import java.util.List; import java.util.Map; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.server.computation.component.ComponentVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.component.VisitorsCrawler; public class ExecuteVisitorsStep implements ComputationStep { private static final Logger LOGGER = Loggers.get(ExecuteVisitorsStep.class); private final TreeRootHolder treeRootHolder; private final List<ComponentVisitor> visitors; public ExecuteVisitorsStep(TreeRootHolder treeRootHolder, List<ComponentVisitor> visitors) { this.treeRootHolder = treeRootHolder; this.visitors = visitors; } @Override public String getDescription() { return "Execute component visitors"; } @Override public void execute() { VisitorsCrawler visitorsCrawler = new VisitorsCrawler(visitors); visitorsCrawler.visit(treeRootHolder.getRoot()); logVisitorExecutionDurations(visitors, visitorsCrawler); } private static void logVisitorExecutionDurations(List<ComponentVisitor> visitors, VisitorsCrawler visitorsCrawler) { LOGGER.info(" Execution time for each component visitor:"); Map<ComponentVisitor, Long> cumulativeDurations = visitorsCrawler.getCumulativeDurations(); for (ComponentVisitor visitor : visitors) { LOGGER.info(" - {} | time={}ms", visitor.getClass().getSimpleName(), cumulativeDurations.get(visitor)); } } }
lgpl-3.0
ntenhoeve/Introspect-Framework
reflect/reflect-infrastructure-xml-converter/src/main/java/nth/reflect/infra/generic/xml/transform/CurrencyTransform.java
2666
/* * CurrencyTransform.java May 2007 * * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net> * * 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 nth.reflect.infra.generic.xml.transform; import java.util.Currency; /** * The <code>CurrencyTransform</code> is used to transform currency * values to and from string representations, which will be inserted * in the generated XML document as the value place holder. The * value must be readable and writable in the same format. Fields * and methods annotated with the XML attribute annotation will use * this to persist and retrieve the value to and from the XML source. * <pre> * * &#64;Attribute * private Currency currency; * * </pre> * As well as the XML attribute values using transforms, fields and * methods annotated with the XML element annotation will use this. * Aside from the obvious difference, the element annotation has an * advantage over the attribute annotation in that it can maintain * any references using the <code>CycleStrategy</code> object. * * @author Niall Gallagher */ class CurrencyTransform implements Transform<Currency> { /** * This method is used to convert the string value given to an * appropriate representation. This is used when an object is * being deserialized from the XML document and the value for * the string representation is required. * * @param symbol the string representation of the currency * * @return this returns an appropriate instanced to be used */ public Currency read(String symbol) { return Currency.getInstance(symbol); } /** * This method is used to convert the provided value into an XML * usable format. This is used in the serialization process when * there is a need to convert a field value in to a string so * that that value can be written as a valid XML entity. * * @param currency this is the value to be converted to a string * * @return this is the string representation of the given value */ public String write(Currency currency) { return currency.toString(); } }
lgpl-3.0
hannoman/xxl
src/xxl/core/indexStructures/keyRanges/ShortKeyRange.java
2702
/* * XXL: The eXtensible and fleXible Library for data processing * * Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger Head of the Database Research Group Department * of Mathematics and Computer Science University of Marburg Germany * * This library is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; * If not, see <http://www.gnu.org/licenses/>. * * http://code.google.com/p/xxl/ */ package xxl.core.indexStructures.keyRanges; import xxl.core.functions.AbstractFunction; import xxl.core.functions.Function; import xxl.core.indexStructures.BPlusTree.KeyRange; /** * {@link xxl.core.indexStructures.BPlusTree.KeyRange KeyRange} represents key ranges (i.e. * intervals of keys). It is used to specify (range) queries on the <tt>BPlusTree</tt> and to hold * the key range of the data objects stored in the tree in the member field <tt>rootDescriptor</tt>.<br/> * <br/> * * This class extends <tt>KeyRange</tt> for using <b>Shorts</b> as keys.<br/> * <br/> * * You will find a <b>list of all available implemented KeyRanges</b> in * {@link xxl.core.indexStructures.keyRanges.KeyRangeFactory KeyRangeFactory} class. * * @author Marcus Pinnecke (pinnecke@mathematik.uni-marburg.de) * * @see xxl.core.indexStructures.BPlusTree.KeyRange */ public class ShortKeyRange extends KeyRange { /** * Used for a functional like programming style which creates in this case a new ranges. */ public static Function<Object, ShortKeyRange> FACTORY_FUNCTION = new AbstractFunction<Object, ShortKeyRange>() { @Override public ShortKeyRange invoke(Object argument0, Object argument1) { return new ShortKeyRange((Short) argument0, (Short) argument1); } }; /** * @see xxl.core.indexStructures.BPlusTree.KeyRange */ public ShortKeyRange(short min, short max) { super(min, max); } /** * @see xxl.core.indexStructures.BPlusTree.KeyRange */ public ShortKeyRange(Short min, Short max) { super(min, max); } @Override public Object clone() { return new ShortKeyRange(new Short((Short) this.sepValue), new Short( (Short) this.maxBound)); } }
lgpl-3.0
erwinwinder/molgenis
molgenis-file-ingester/src/main/java/org/molgenis/file/ingest/impl/FileIngesterLoggerImpl.java
5143
package org.molgenis.file.ingest.impl; import java.io.File; import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.molgenis.auth.MolgenisUser; import org.molgenis.data.DataService; import org.molgenis.data.Entity; import org.molgenis.data.jobs.JobMetaData; import org.molgenis.data.meta.EntityMetaDataMetaData; import org.molgenis.data.support.DefaultEntity; import org.molgenis.file.FileDownloadController; import org.molgenis.file.FileMeta; import org.molgenis.file.ingest.FileIngesterLogger; import org.molgenis.file.ingest.meta.FileIngestJobMetaDataMetaData; import org.molgenis.file.ingest.meta.FileIngestMetaData; import org.molgenis.framework.db.EntityImportReport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; public class FileIngesterLoggerImpl implements FileIngesterLogger { private static final Logger LOG = LoggerFactory.getLogger(FileIngesterLoggerImpl.class); private final DataService dataService; private final FileIngestJobMetaDataMetaData fileIngestJobMetaDataMetaData; private final JavaMailSender mailSender; private Entity fileIngestJobMetaData; private String entityName; private String failureEmail; private String downloadUrl; public FileIngesterLoggerImpl(DataService dataService, FileIngestJobMetaDataMetaData fileIngestJobMetaDataMetaData, JavaMailSender mailSender) { this.dataService = dataService; this.fileIngestJobMetaDataMetaData = fileIngestJobMetaDataMetaData; this.mailSender = mailSender; } @Override public synchronized String start(Entity fileIngest) { Entity entityMetaData = fileIngest.getEntity(FileIngestMetaData.ENTITY_META_DATA); entityName = entityMetaData.getString(EntityMetaDataMetaData.FULL_NAME); failureEmail = fileIngest.getString(FileIngestMetaData.FAILURE_EMAIL); downloadUrl = fileIngest.getString(FileIngestMetaData.URL); fileIngestJobMetaData = new DefaultEntity(fileIngestJobMetaDataMetaData, dataService); fileIngestJobMetaData.set(JobMetaData.PROGRESS_MESSAGE, "Downloading file from '" + fileIngest.getString(FileIngestMetaData.URL) + "'"); fileIngestJobMetaData.set(JobMetaData.START_DATE, new Date()); fileIngestJobMetaData.set(JobMetaData.SUBMISSION_DATE, new Date()); fileIngestJobMetaData.set(JobMetaData.STATUS, "RUNNING"); fileIngestJobMetaData.set(JobMetaData.TYPE, "FileIngesterJob"); fileIngestJobMetaData.set(JobMetaData.USER, dataService.query(MolgenisUser.ENTITY_NAME).eq(MolgenisUser.USERNAME, "admin").findOne());// TODO system // user? fileIngestJobMetaData.set(FileIngestJobMetaDataMetaData.FILE_INGEST, fileIngest); dataService.add(fileIngestJobMetaDataMetaData.getName(), fileIngestJobMetaData); return fileIngestJobMetaData.getString(JobMetaData.IDENTIFIER); } @Override public synchronized void downloadFinished(File file, String contentType) { String id = fileIngestJobMetaData.getString(JobMetaData.IDENTIFIER); FileMeta fileMeta = new FileMeta(dataService); fileMeta.setId(id); fileMeta.setContentType(contentType); fileMeta.setSize(file.length()); fileMeta.setFilename(id + '/' + file.getName()); fileMeta.setUrl(FileDownloadController.URI + '/' + id); dataService.add(FileMeta.ENTITY_NAME, fileMeta); fileIngestJobMetaData.set(FileIngestJobMetaDataMetaData.FILE, fileMeta); fileIngestJobMetaData.set(JobMetaData.PROGRESS_MESSAGE, "Importing..."); dataService.update(fileIngestJobMetaDataMetaData.getName(), fileIngestJobMetaData); } @Override public synchronized void success(EntityImportReport report) { Integer count = report.getNrImportedEntitiesMap().get(entityName); count = count != null ? count : 0; fileIngestJobMetaData.set(JobMetaData.STATUS, "SUCCESS"); fileIngestJobMetaData.set(JobMetaData.PROGRESS_MESSAGE, String.format("Successfully imported %d %s entities.", count, entityName)); fileIngestJobMetaData.set(JobMetaData.END_DATE, new Date()); dataService.update(fileIngestJobMetaDataMetaData.getName(), fileIngestJobMetaData); } @Override public synchronized void failure(Exception e) { try { fileIngestJobMetaData.set(JobMetaData.STATUS, "FAILED"); fileIngestJobMetaData.set(JobMetaData.PROGRESS_MESSAGE, "Import failed. Errormessage:" + e.getMessage()); fileIngestJobMetaData.set(JobMetaData.END_DATE, new Date()); dataService.update(fileIngestJobMetaDataMetaData.getName(), fileIngestJobMetaData); } finally { if (StringUtils.isNotBlank(failureEmail)) { emailFailure(failureEmail, downloadUrl, e); } } } private void emailFailure(String email, String url, Exception e) { try { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(email); mailMessage.setSubject("Molgenis import failed"); mailMessage.setText("The scheduled import of url '" + url + "' failed. Error:\n" + e.getMessage()); mailSender.send(mailMessage); } catch (MailException mce) { LOG.error("Could not send error email", e); } } }
lgpl-3.0
sdennisen/LightVoting
src/main/java/org/lightvoting/simulation/action/message/random_basic/CSendRB.java
5806
/** * @cond LICENSE * ###################################################################################### * # LGPL License # * # # * # This file is part of LightVoting by Sophie Dennisen. # * # Copyright (c) 2017, Sophie Dennisen (sophie.dennisen@tu-clausthal.de) # * # This program 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. # * # # * # 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 Lesser General Public License for more details. # * # # * # You should have received a copy of the GNU Lesser General Public License # * # along with this program. If not, see http://www.gnu.org/licenses/ # * ###################################################################################### * @endcond */ package org.lightvoting.simulation.action.message.random_basic; import org.lightjason.agentspeak.action.IBaseAction; import org.lightjason.agentspeak.agent.IAgent; import org.lightjason.agentspeak.common.CPath; import org.lightjason.agentspeak.common.IPath; import org.lightjason.agentspeak.language.CLiteral; import org.lightjason.agentspeak.language.CRawTerm; import org.lightjason.agentspeak.language.ITerm; import org.lightjason.agentspeak.language.execution.IContext; import org.lightjason.agentspeak.language.fuzzy.CFuzzyValue; import org.lightjason.agentspeak.language.fuzzy.IFuzzyValue; import org.lightjason.agentspeak.language.instantiable.plan.trigger.CTrigger; import org.lightjason.agentspeak.language.instantiable.plan.trigger.ITrigger; import org.lightvoting.simulation.agent.random_basic.CVotingAgentRB; import javax.annotation.Nonnull; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Action to send messages for communication. * Based on/credits to https://lightjason.github.io/tutorials/communication/ */ public final class CSendRB extends IBaseAction { /** * serialUID */ private static final long serialVersionUID = 1967930733823348568L; /** * thread-safe map for storing name and agent object */ private final Map<String, CVotingAgentRB> m_agents = new ConcurrentHashMap<>(); /** Register a new agent. * @param p_agent agent object * @return object of registered agent */ public final CVotingAgentRB register( final CVotingAgentRB p_agent ) { m_agents.put( p_agent.name(), p_agent ); return p_agent; } /** Unregisters agent * Removes agent from map * @param p_agent agent object * @return object of unregistered agent */ public final CVotingAgentRB unregister( final CVotingAgentRB p_agent ) { m_agents.remove( p_agent.name() ); return p_agent; } @Override public final IPath name() { return CPath.from( "message/send" ); } @Override public final int minimalArgumentNumber() { return 2; } @Nonnull @Override public final IFuzzyValue<Boolean> execute( final boolean p_parallel, @Nonnull final IContext p_context, @Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return ) { /** * first parameter of the action is the name of the receiving agent */ final IAgent<?> l_receiver = m_agents.get( p_argument.get( 0 ).<String>raw() ); // if the agent is it not found, action fails if ( l_receiver == null ) return CFuzzyValue.from( false ); // create the receiving goal-trigger of the message l_receiver.trigger( CTrigger.from( ITrigger.EType.ADDGOAL, // create the goal literal "message/receive(M,S)" with M is the message literal // and S the sending agent name CLiteral.from( "message/receive", // message literal CLiteral.from( "message", // first argument is the agent name so copy all other arguments to the message literal p_argument.subList( 1, p_argument.size() ).stream().map( i -> CRawTerm.from( i.raw() ) ) ), // name of the sending agent in this the agent which calls the send action is read from // context and translate in the communication agent, the communication agent has got the // method name() to read the agent name CLiteral.from( "from", CRawTerm.from( p_context.agent().<CVotingAgentRB>raw().name() ) ) ) ) ); return CFuzzyValue.from( true ); } }
lgpl-3.0
racodond/sonar-jproperties-plugin
jproperties-frontend/src/main/java/org/sonar/plugins/jproperties/api/visitors/package-info.java
996
/* * SonarQube Java Properties Analyzer * Copyright (C) 2015-2017 David RACODON * david.racodon@gmail.com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ @ParametersAreNonnullByDefault package org.sonar.plugins.jproperties.api.visitors; import javax.annotation.ParametersAreNonnullByDefault;
lgpl-3.0
delphiprogramming/gisgraphy
src/main/java/com/gisgraphy/helper/GisFeatureHelper.java
4130
/******************************************************************************* * Gisgraphy Project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA * * Copyright 2008 Gisgraphy project * * David Masclet <davidmasclet@gisgraphy.com> ******************************************************************************/ package com.gisgraphy.helper; import javax.persistence.Transient; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import com.gisgraphy.domain.geoloc.entity.Country; import com.gisgraphy.domain.geoloc.entity.GisFeature; import com.gisgraphy.domain.repository.ICountryDao; @Service public class GisFeatureHelper implements ApplicationContextAware{ /** * this method avoid the necessary injection in gisfeature */ public static GisFeatureHelper getInstance(){ if (applicationContext!=null){ return (GisFeatureHelper) applicationContext.getBean("gisFeatureHelper"); } else throw new RuntimeException("the application context is not injected"); } @Autowired public ICountryDao countryDao; //it is not a good idea to have a static property here but i need the get instance to be static to avoid //injection in gisFeature private static ApplicationContext applicationContext; /** * Returns a name of the form : (adm1Name et adm2Name are printed) Paris, * Département de Ville-De-Paris, Ile-De-France, (FR) * * @param withCountry * Whether the country information should be added * @return a name with the Administrative division and Country */ @Transient public String getFullyQualifiedName(GisFeature gisFeature ,boolean withCountry) { StringBuilder completeCityName = new StringBuilder(); completeCityName.append(gisFeature.getName()); String adm2Name = gisFeature.getAdm2Name(); if (adm2Name != null && !adm2Name.trim().equals("")) { completeCityName.append(", " + adm2Name); } String adm1Name = gisFeature.getAdm1Name(); if (adm1Name != null && !adm1Name.trim().equals("")) { completeCityName.append(", " + adm1Name); } if (withCountry) { Country countryObj = getCountry(gisFeature.getCountryCode()); if (countryObj != null && countryObj.getName() != null && !countryObj.getName().trim().equals("")) { completeCityName.append(" , " + countryObj.getName() + ""); } } return completeCityName.toString(); } /** * @return a name with the Administrative division (but without Country) */ @Transient public String getFullyQualifiedName(GisFeature gisFeature) { return getFullyQualifiedName(gisFeature,false); } /** * @return the country from the country code. Return null if the country Code * is null or if no country is found */ @Transient public Country getCountry(String countryCode) { Country country = null; if (countryCode != null) { country = countryDao.getByIso3166Alpha2Code(countryCode); } return country; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { GisFeatureHelper.applicationContext = applicationContext; } }
lgpl-3.0
leodmurillo/sonar
sonar-core/src/main/java/org/sonar/core/plugins/RemotePlugin.java
2934
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.core.plugins; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import java.io.File; import java.util.List; public class RemotePlugin { private String pluginKey; private List<String> filenames = Lists.newArrayList(); private boolean core; public RemotePlugin(String pluginKey, boolean core) { this.pluginKey = pluginKey; this.core = core; } public static RemotePlugin create(DefaultPluginMetadata metadata) { RemotePlugin result = new RemotePlugin(metadata.getKey(), metadata.isCore()); result.addFilename(metadata.getFile().getName()); for (File file : metadata.getDeprecatedExtensions()) { result.addFilename(file.getName()); } return result; } public static RemotePlugin unmarshal(String row) { String[] fields = StringUtils.split(row, ","); RemotePlugin result = new RemotePlugin(fields[0], Boolean.parseBoolean(fields[1])); if (fields.length > 2) { for (int index = 2; index < fields.length; index++) { result.addFilename(fields[index]); } } return result; } public String marshal() { StringBuilder sb = new StringBuilder(); sb.append(pluginKey).append(","); sb.append(String.valueOf(core)); for (String filename : filenames) { sb.append(",").append(filename); } return sb.toString(); } public String getKey() { return pluginKey; } public boolean isCore() { return core; } public RemotePlugin addFilename(String s) { filenames.add(s); return this; } public List<String> getFilenames() { return filenames; } public String getPluginFilename() { return (!filenames.isEmpty() ? filenames.get(0) : null); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RemotePlugin that = (RemotePlugin) o; return pluginKey.equals(that.pluginKey); } @Override public int hashCode() { return pluginKey.hashCode(); } }
lgpl-3.0
hongliangpan/manydesigns.cn
trunk/portofino-database/liquibase-core-2.0.5-sources/liquibase/diff/DiffResult.java
37629
package liquibase.diff; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.ConstraintsConfig; import liquibase.change.core.*; import liquibase.changelog.ChangeSet; import liquibase.database.Database; import liquibase.database.structure.*; import liquibase.database.typeconversion.TypeConverter; import liquibase.database.typeconversion.TypeConverterFactory; import liquibase.exception.DatabaseException; import liquibase.executor.ExecutorService; import liquibase.logging.LogFactory; import liquibase.parser.core.xml.LiquibaseEntityResolver; import liquibase.parser.core.xml.XMLChangeLogSAXParser; import liquibase.serializer.ChangeLogSerializer; import liquibase.serializer.ChangeLogSerializerFactory; import liquibase.serializer.core.xml.XMLChangeLogSerializer; import liquibase.snapshot.DatabaseSnapshot; import liquibase.statement.DatabaseFunction; import liquibase.statement.core.RawSqlStatement; import liquibase.util.ISODateFormat; import liquibase.util.StringUtils; import liquibase.util.csv.CSVWriter; import liquibase.util.xml.DefaultXmlWriter; import liquibase.util.xml.XmlWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.*; public class DiffResult { private String idRoot = String.valueOf(new Date().getTime()); private int changeNumber = 1; private DatabaseSnapshot referenceSnapshot; private DatabaseSnapshot targetSnapshot; private DiffComparison productName; private DiffComparison productVersion; private SortedSet<Table> missingTables = new TreeSet<Table>(); private SortedSet<Table> unexpectedTables = new TreeSet<Table>(); private SortedSet<View> missingViews = new TreeSet<View>(); private SortedSet<View> unexpectedViews = new TreeSet<View>(); private SortedSet<View> changedViews = new TreeSet<View>(); private SortedSet<Column> missingColumns = new TreeSet<Column>(); private SortedSet<Column> unexpectedColumns = new TreeSet<Column>(); private SortedSet<Column> changedColumns = new TreeSet<Column>(); private SortedSet<ForeignKey> missingForeignKeys = new TreeSet<ForeignKey>(); private SortedSet<ForeignKey> unexpectedForeignKeys = new TreeSet<ForeignKey>(); private SortedSet<Index> missingIndexes = new TreeSet<Index>(); private SortedSet<Index> unexpectedIndexes = new TreeSet<Index>(); private SortedSet<PrimaryKey> missingPrimaryKeys = new TreeSet<PrimaryKey>(); private SortedSet<PrimaryKey> unexpectedPrimaryKeys = new TreeSet<PrimaryKey>(); private SortedSet<UniqueConstraint> missingUniqueConstraints = new TreeSet<UniqueConstraint>(); private SortedSet<UniqueConstraint> unexpectedUniqueConstraints = new TreeSet<UniqueConstraint>(); private SortedSet<Sequence> missingSequences = new TreeSet<Sequence>(); private SortedSet<Sequence> unexpectedSequences = new TreeSet<Sequence>(); private boolean diffData = false; private String dataDir = null; private String changeSetContext; private String changeSetAuthor; private ChangeLogSerializerFactory serializerFactory = ChangeLogSerializerFactory.getInstance(); public DiffResult(DatabaseSnapshot referenceDatabaseSnapshot, DatabaseSnapshot targetDatabaseSnapshot) { this.referenceSnapshot = referenceDatabaseSnapshot; if (targetDatabaseSnapshot == null) { targetDatabaseSnapshot = new DatabaseSnapshot( referenceDatabaseSnapshot.getDatabase(), null); } this.targetSnapshot = targetDatabaseSnapshot; } public DiffComparison getProductName() { return productName; } public void setProductName(DiffComparison productName) { this.productName = productName; } public DiffComparison getProductVersion() { return productVersion; } public void setProductVersion(DiffComparison product) { this.productVersion = product; } public void addMissingTable(Table table) { missingTables.add(table); } public SortedSet<Table> getMissingTables() { return missingTables; } public void addUnexpectedTable(Table table) { unexpectedTables.add(table); } public SortedSet<Table> getUnexpectedTables() { return unexpectedTables; } public void addMissingView(View viewName) { missingViews.add(viewName); } public SortedSet<View> getMissingViews() { return missingViews; } public void addUnexpectedView(View viewName) { unexpectedViews.add(viewName); } public SortedSet<View> getUnexpectedViews() { return unexpectedViews; } public void addChangedView(View viewName) { changedViews.add(viewName); } public SortedSet<View> getChangedViews() { return changedViews; } public void addMissingColumn(Column columnName) { missingColumns.add(columnName); } public SortedSet<Column> getMissingColumns() { return missingColumns; } public void addUnexpectedColumn(Column columnName) { unexpectedColumns.add(columnName); } public SortedSet<Column> getUnexpectedColumns() { return unexpectedColumns; } public void addChangedColumn(Column columnName) { changedColumns.add(columnName); } public SortedSet<Column> getChangedColumns() { return changedColumns; } public void addMissingForeignKey(ForeignKey fkName) { missingForeignKeys.add(fkName); } public SortedSet<ForeignKey> getMissingForeignKeys() { return missingForeignKeys; } public void addUnexpectedForeignKey(ForeignKey fkName) { unexpectedForeignKeys.add(fkName); } public SortedSet<ForeignKey> getUnexpectedForeignKeys() { return unexpectedForeignKeys; } public void addMissingIndex(Index fkName) { missingIndexes.add(fkName); } public SortedSet<Index> getMissingIndexes() { return missingIndexes; } public void addUnexpectedIndex(Index fkName) { unexpectedIndexes.add(fkName); } public SortedSet<Index> getUnexpectedIndexes() { return unexpectedIndexes; } public void addMissingPrimaryKey(PrimaryKey primaryKey) { missingPrimaryKeys.add(primaryKey); } public SortedSet<PrimaryKey> getMissingPrimaryKeys() { return missingPrimaryKeys; } public void addUnexpectedPrimaryKey(PrimaryKey primaryKey) { unexpectedPrimaryKeys.add(primaryKey); } public SortedSet<PrimaryKey> getUnexpectedPrimaryKeys() { return unexpectedPrimaryKeys; } public void addMissingSequence(Sequence sequence) { missingSequences.add(sequence); } public SortedSet<Sequence> getMissingSequences() { return missingSequences; } public void addUnexpectedSequence(Sequence sequence) { unexpectedSequences.add(sequence); } public SortedSet<Sequence> getUnexpectedSequences() { return unexpectedSequences; } public void addMissingUniqueConstraint(UniqueConstraint uniqueConstraint) { missingUniqueConstraints.add(uniqueConstraint); } public SortedSet<UniqueConstraint> getMissingUniqueConstraints() { return this.missingUniqueConstraints; } public void addUnexpectedUniqueConstraint(UniqueConstraint uniqueConstraint) { unexpectedUniqueConstraints.add(uniqueConstraint); } public SortedSet<UniqueConstraint> getUnexpectedUniqueConstraints() { return unexpectedUniqueConstraints; } public boolean shouldDiffData() { return diffData; } public void setDiffData(boolean diffData) { this.diffData = diffData; } public String getDataDir() { return dataDir; } public void setDataDir(String dataDir) { this.dataDir = dataDir; } public String getChangeSetContext() { return changeSetContext; } public void setChangeSetContext(String changeSetContext) { this.changeSetContext = changeSetContext; } public boolean differencesFound() throws DatabaseException,IOException{ boolean differencesInData=false; if(shouldDiffData()) { List<ChangeSet> changeSets = new ArrayList<ChangeSet>(); addInsertDataChanges(changeSets, dataDir); differencesInData=!changeSets.isEmpty(); } return getMissingColumns().size()>0 || getMissingForeignKeys().size()>0 || getMissingIndexes().size()>0 || getMissingPrimaryKeys().size()>0 || getMissingSequences().size()>0 || getMissingTables().size()>0 || getMissingUniqueConstraints().size()>0 || getMissingViews().size()>0 || getUnexpectedColumns().size()>0 || getUnexpectedForeignKeys().size()>0 || getUnexpectedIndexes().size()>0 || getUnexpectedPrimaryKeys().size()>0 || getUnexpectedSequences().size()>0 || getUnexpectedTables().size()>0 || getUnexpectedUniqueConstraints().size()>0 || getUnexpectedViews().size()>0 || differencesInData; } public void printResult(PrintStream out) throws DatabaseException { out.println("Reference Database: " + referenceSnapshot.getDatabase()); out.println("Target Database: " + targetSnapshot.getDatabase()); printComparision("Product Name", productName, out); printComparision("Product Version", productVersion, out); printSetComparison("Missing Tables", getMissingTables(), out); printSetComparison("Unexpected Tables", getUnexpectedTables(), out); printSetComparison("Missing Views", getMissingViews(), out); printSetComparison("Unexpected Views", getUnexpectedViews(), out); printSetComparison("Changed Views", getChangedViews(), out); printSetComparison("Missing Columns", getMissingColumns(), out); printSetComparison("Unexpected Columns", getUnexpectedColumns(), out); printColumnComparison(getChangedColumns(), out); printSetComparison("Missing Foreign Keys", getMissingForeignKeys(), out); printSetComparison("Unexpected Foreign Keys", getUnexpectedForeignKeys(), out); printSetComparison("Missing Primary Keys", getMissingPrimaryKeys(), out); printSetComparison("Unexpected Primary Keys", getUnexpectedPrimaryKeys(), out); printSetComparison("Unexpected Unique Constraints", getUnexpectedUniqueConstraints(), out); printSetComparison("Missing Unique Constraints", getMissingUniqueConstraints(), out); printSetComparison("Missing Indexes", getMissingIndexes(), out); printSetComparison("Unexpected Indexes", getUnexpectedIndexes(), out); printSetComparison("Missing Sequences", getMissingSequences(), out); printSetComparison("Unexpected Sequences", getUnexpectedSequences(), out); } private void printSetComparison(String title, SortedSet<?> objects, PrintStream out) { out.print(title + ": "); if (objects.size() == 0) { out.println("NONE"); } else { out.println(); for (Object object : objects) { out.println(" " + object); } } } private void printColumnComparison(SortedSet<Column> changedColumns, PrintStream out) { out.print("Changed Columns: "); if (changedColumns.size() == 0) { out.println("NONE"); } else { out.println(); for (Column column : changedColumns) { out.println(" " + column); Column baseColumn = referenceSnapshot.getColumn(column .getTable().getName(), column.getName()); if (baseColumn != null) { if (baseColumn.isDataTypeDifferent(column)) { out.println(" from " + TypeConverterFactory.getInstance().findTypeConverter(referenceSnapshot.getDatabase()).convertToDatabaseTypeString(baseColumn, referenceSnapshot.getDatabase()) + " to " + TypeConverterFactory.getInstance().findTypeConverter(targetSnapshot.getDatabase()).convertToDatabaseTypeString(targetSnapshot.getColumn(column.getTable().getName(), column.getName()), targetSnapshot.getDatabase())); } if (baseColumn.isNullabilityDifferent(column)) { Boolean nowNullable = targetSnapshot.getColumn( column.getTable().getName(), column.getName()) .isNullable(); if (nowNullable == null) { nowNullable = Boolean.TRUE; } if (nowNullable) { out.println(" now nullable"); } else { out.println(" now not null"); } } } } } } private void printComparision(String title, DiffComparison comparison, PrintStream out) { out.print(title + ":"); if (comparison == null) { out.print("NULL"); return; } if (comparison.areTheSame()) { out.println(" EQUAL"); } else { out.println(); out.println(" Reference: '" + comparison.getReferenceVersion() + "'"); out.println(" Target: '" + comparison.getTargetVersion() + "'"); } } public void printChangeLog(String changeLogFile, Database targetDatabase) throws ParserConfigurationException, IOException, DatabaseException { ChangeLogSerializer changeLogSerializer = serializerFactory.getSerializer(changeLogFile); this.printChangeLog(changeLogFile, targetDatabase, changeLogSerializer); } public void printChangeLog(PrintStream out, Database targetDatabase) throws ParserConfigurationException, IOException, DatabaseException { this.printChangeLog(out, targetDatabase, new XMLChangeLogSerializer()); } public void printChangeLog(String changeLogFile, Database targetDatabase, ChangeLogSerializer changeLogSerializer) throws ParserConfigurationException, IOException, DatabaseException { File file = new File(changeLogFile); if (!file.exists()) { LogFactory.getLogger().info(file + " does not exist, creating"); FileOutputStream stream = new FileOutputStream(file); printChangeLog(new PrintStream(stream), targetDatabase, changeLogSerializer); stream.close(); } else { LogFactory.getLogger().info(file + " exists, appending"); ByteArrayOutputStream out = new ByteArrayOutputStream(); printChangeLog(new PrintStream(out), targetDatabase, changeLogSerializer); String xml = new String(out.toByteArray()); xml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", ""); xml = xml.replaceFirst("</databaseChangeLog>", ""); xml = xml.trim(); if ("".equals( xml )) { LogFactory.getLogger().info("No changes found, nothing to do"); return; } String lineSeparator = System.getProperty("line.separator"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); String line; long offset = 0; while ((line = fileReader.readLine()) != null) { int index = line.indexOf("</databaseChangeLog>"); if (index >= 0) { offset += index; } else { offset += line.getBytes().length; offset += lineSeparator.getBytes().length; } } fileReader.close(); fileReader = new BufferedReader(new FileReader(file)); fileReader.skip(offset); fileReader.close(); // System.out.println("resulting XML: " + xml.trim()); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.seek(offset); randomAccessFile.writeBytes(" "); randomAccessFile.write( xml.getBytes() ); randomAccessFile.writeBytes(lineSeparator); randomAccessFile.writeBytes("</databaseChangeLog>" + lineSeparator); randomAccessFile.close(); // BufferedWriter fileWriter = new BufferedWriter(new // FileWriter(file)); // fileWriter.append(xml); // fileWriter.close(); } } /** * Prints changeLog that would bring the target database to be the same as * the reference database */ public void printChangeLog(PrintStream out, Database targetDatabase, ChangeLogSerializer changeLogSerializer) throws ParserConfigurationException, IOException, DatabaseException { List<ChangeSet> changeSets = new ArrayList<ChangeSet>(); addMissingTableChanges(changeSets, targetDatabase); addMissingColumnChanges(changeSets, targetDatabase); addChangedColumnChanges(changeSets); addMissingPrimaryKeyChanges(changeSets); addUnexpectedPrimaryKeyChanges(changeSets); addUnexpectedForeignKeyChanges(changeSets); addMissingUniqueConstraintChanges(changeSets); addUnexpectedUniqueConstraintChanges(changeSets); if (diffData) { addInsertDataChanges(changeSets, dataDir); } addMissingForeignKeyChanges(changeSets); addUnexpectedIndexChanges(changeSets); addMissingIndexChanges(changeSets); addUnexpectedColumnChanges(changeSets); addMissingSequenceChanges(changeSets); addUnexpectedSequenceChanges(changeSets); addMissingViewChanges(changeSets); addUnexpectedViewChanges(changeSets); addChangedViewChanges(changeSets); addUnexpectedTableChanges(changeSets); changeLogSerializer.write(changeSets, out); out.flush(); } private ChangeSet generateChangeSet(Change change) { ChangeSet changeSet = generateChangeSet(); changeSet.addChange(change); return changeSet; } private ChangeSet generateChangeSet() { return new ChangeSet(generateId(), getChangeSetAuthor(), false, false, null, getChangeSetContext(), null); } private String getChangeSetAuthor() { if (changeSetAuthor != null) { return changeSetAuthor; } String author = System.getProperty("user.name"); if (StringUtils.trimToNull(author) == null) { return "diff-generated"; } else { return author + " (generated)"; } } public void setChangeSetAuthor(String changeSetAuthor) { this.changeSetAuthor = changeSetAuthor; } public void setIdRoot(String idRoot) { this.idRoot = idRoot; } protected String generateId() { return idRoot + "-" + changeNumber++; } private void addUnexpectedIndexChanges(List<ChangeSet> changes) { for (Index index : getUnexpectedIndexes()) { if (index.getAssociatedWith().contains(Index.MARK_PRIMARY_KEY) || index.getAssociatedWith().contains(Index.MARK_FOREIGN_KEY) || index.getAssociatedWith().contains(Index.MARK_UNIQUE_CONSTRAINT)) { continue; } DropIndexChange change = new DropIndexChange(); change.setTableName(index.getTable().getName()); change.setSchemaName(index.getTable().getSchema()); change.setIndexName(index.getName()); change.setAssociatedWith(index.getAssociatedWithAsString()); changes.add(generateChangeSet(change)); } } private void addMissingIndexChanges(List<ChangeSet> changes) { for (Index index : getMissingIndexes()) { CreateIndexChange change = new CreateIndexChange(); change.setTableName(index.getTable().getName()); change.setTablespace(index.getTablespace()); change.setSchemaName(index.getTable().getSchema()); change.setIndexName(index.getName()); change.setUnique(index.isUnique()); change.setAssociatedWith(index.getAssociatedWithAsString()); if (index.getAssociatedWith().contains(Index.MARK_PRIMARY_KEY) || index.getAssociatedWith().contains(Index.MARK_FOREIGN_KEY) || index.getAssociatedWith().contains(Index.MARK_UNIQUE_CONSTRAINT)) { continue; } for (String columnName : index.getColumns()) { ColumnConfig column = new ColumnConfig(); column.setName(columnName); change.addColumn(column); } changes.add(generateChangeSet(change)); } } private void addUnexpectedPrimaryKeyChanges(List<ChangeSet> changes) { for (PrimaryKey pk : getUnexpectedPrimaryKeys()) { if (!getUnexpectedTables().contains(pk.getTable())) { DropPrimaryKeyChange change = new DropPrimaryKeyChange(); change.setTableName(pk.getTable().getName()); change.setSchemaName(pk.getTable().getSchema()); change.setConstraintName(pk.getName()); changes.add(generateChangeSet(change)); } } } private void addMissingPrimaryKeyChanges(List<ChangeSet> changes) { for (PrimaryKey pk : getMissingPrimaryKeys()) { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName(pk.getTable().getName()); change.setSchemaName(pk.getTable().getSchema()); change.setConstraintName(pk.getName()); change.setColumnNames(pk.getColumnNames()); change.setTablespace(pk.getTablespace()); changes.add(generateChangeSet(change)); } } private void addUnexpectedUniqueConstraintChanges(List<ChangeSet> changes) { for (UniqueConstraint uc : getUnexpectedUniqueConstraints()) { // Need check for nulls here due to NullPointerException using Postgres if (null != uc) { if (null != uc.getTable()) { DropUniqueConstraintChange change = new DropUniqueConstraintChange(); change.setTableName(uc.getTable().getName()); change.setSchemaName(uc.getTable().getSchema()); change.setConstraintName(uc.getName()); changes.add(generateChangeSet(change)); } } } } private void addMissingUniqueConstraintChanges(List<ChangeSet> changes) { for (UniqueConstraint uc : getMissingUniqueConstraints()) { // Need check for nulls here due to NullPointerException using Postgres if (null != uc) if (null != uc.getTable()) { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName(uc.getTable().getName()); change.setTablespace(uc.getTablespace()); change.setSchemaName(uc.getTable().getSchema()); change.setConstraintName(uc.getName()); change.setColumnNames(uc.getColumnNames()); change.setDeferrable(uc.isDeferrable()); change.setInitiallyDeferred(uc.isInitiallyDeferred()); change.setDisabled(uc.isDisabled()); changes.add(generateChangeSet(change)); } } } private void addUnexpectedForeignKeyChanges(List<ChangeSet> changes) { for (ForeignKey fk : getUnexpectedForeignKeys()) { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setConstraintName(fk.getName()); change.setBaseTableName(fk.getForeignKeyTable().getName()); change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingForeignKeyChanges(List<ChangeSet> changes) { for (ForeignKey fk : getMissingForeignKeys()) { AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange(); change.setConstraintName(fk.getName()); change.setReferencedTableName(fk.getPrimaryKeyTable().getName()); change.setReferencedTableSchemaName(fk.getPrimaryKeyTable() .getSchema()); change.setReferencedColumnNames(fk.getPrimaryKeyColumns()); change.setBaseTableName(fk.getForeignKeyTable().getName()); change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema()); change.setBaseColumnNames(fk.getForeignKeyColumns()); change.setDeferrable(fk.isDeferrable()); change.setInitiallyDeferred(fk.isInitiallyDeferred()); change.setOnUpdate(fk.getUpdateRule()); change.setOnDelete(fk.getDeleteRule()); change.setReferencesUniqueColumn(fk.getReferencesUniqueColumn()); changes.add(generateChangeSet(change)); } } private void addUnexpectedSequenceChanges(List<ChangeSet> changes) { for (Sequence sequence : getUnexpectedSequences()) { DropSequenceChange change = new DropSequenceChange(); change.setSequenceName(sequence.getName()); change.setSchemaName(sequence.getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingSequenceChanges(List<ChangeSet> changes) { for (Sequence sequence : getMissingSequences()) { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName(sequence.getName()); change.setSchemaName(sequence.getSchema()); changes.add(generateChangeSet(change)); } } private void addUnexpectedColumnChanges(List<ChangeSet> changes) { for (Column column : getUnexpectedColumns()) { if (!shouldModifyColumn(column)) { continue; } DropColumnChange change = new DropColumnChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); changes.add(generateChangeSet(change)); } } private void addMissingViewChanges(List<ChangeSet> changes) { for (View view : getMissingViews()) { CreateViewChange change = new CreateViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); String selectQuery = view.getDefinition(); if (selectQuery == null) { selectQuery = "COULD NOT DETERMINE VIEW QUERY"; } change.setSelectQuery(selectQuery); changes.add(generateChangeSet(change)); } } private void addChangedViewChanges(List<ChangeSet> changes) { for (View view : getChangedViews()) { CreateViewChange change = new CreateViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); String selectQuery = view.getDefinition(); if (selectQuery == null) { selectQuery = "COULD NOT DETERMINE VIEW QUERY"; } change.setSelectQuery(selectQuery); change.setReplaceIfExists(true); changes.add(generateChangeSet(change)); } } private void addChangedColumnChanges(List<ChangeSet> changes) { for (Column column : getChangedColumns()) { if (!shouldModifyColumn(column)) { continue; } TypeConverter targetTypeConverter = TypeConverterFactory.getInstance().findTypeConverter(targetSnapshot.getDatabase()); boolean foundDifference = false; Column referenceColumn = referenceSnapshot.getColumn(column.getTable().getName(), column.getName()); if (column.isDataTypeDifferent(referenceColumn)) { ModifyDataTypeChange change = new ModifyDataTypeChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setNewDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); changes.add(generateChangeSet(change)); foundDifference = true; } if (column.isNullabilityDifferent(referenceColumn)) { if (referenceColumn.isNullable() == null || referenceColumn.isNullable()) { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setColumnDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); changes.add(generateChangeSet(change)); foundDifference = true; } else { AddNotNullConstraintChange change = new AddNotNullConstraintChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setColumnDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); Object defaultValue = column.getDefaultValue(); String defaultValueString; if (defaultValue != null) { defaultValueString = targetTypeConverter.getDataType(defaultValue).convertObjectToString(defaultValue, targetSnapshot.getDatabase()); if (defaultValueString != null) { change.setDefaultNullValue(defaultValueString); } } changes.add(generateChangeSet(change)); foundDifference = true; } } if (!foundDifference) { throw new RuntimeException("Unknown difference"); } } } private boolean shouldModifyColumn(Column column) { return column.getView() == null && !referenceSnapshot.getDatabase().isLiquibaseTable( column.getTable().getName()); } private void addUnexpectedViewChanges(List<ChangeSet> changes) { for (View view : getUnexpectedViews()) { DropViewChange change = new DropViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingColumnChanges(List<ChangeSet> changes, Database database) { for (Column column : getMissingColumns()) { if (!shouldModifyColumn(column)) { continue; } AddColumnChange change = new AddColumnChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); String dataType = TypeConverterFactory.getInstance().findTypeConverter(database).convertToDatabaseTypeString(column, database); columnConfig.setType(dataType); Object defaultValue = column.getDefaultValue(); if (defaultValue != null) { String defaultValueString = TypeConverterFactory.getInstance() .findTypeConverter(database).getDataType(defaultValue) .convertObjectToString(defaultValue, database); if (defaultValueString != null) { defaultValueString = defaultValueString.replaceFirst("'", "").replaceAll("'$", ""); } columnConfig.setDefaultValue(defaultValueString); } if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } ConstraintsConfig constraintsConfig = columnConfig.getConstraints(); if (column.isNullable() != null && !column.isNullable()) { if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); } constraintsConfig.setNullable(false); } if (column.isUnique()) { if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); } constraintsConfig.setUnique(true); } if (constraintsConfig != null) { columnConfig.setConstraints(constraintsConfig); } change.addColumn(columnConfig); changes.add(generateChangeSet(change)); } } private void addMissingTableChanges(List<ChangeSet> changes, Database database) { for (Table missingTable : getMissingTables()) { if (referenceSnapshot.getDatabase().isLiquibaseTable( missingTable.getName())) { continue; } CreateTableChange change = new CreateTableChange(); change.setTableName(missingTable.getName()); change.setSchemaName(missingTable.getSchema()); if (missingTable.getRemarks() != null) { change.setRemarks(missingTable.getRemarks()); } for (Column column : missingTable.getColumns()) { ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); columnConfig.setType(TypeConverterFactory.getInstance().findTypeConverter(database).convertToDatabaseTypeString(column, database)); ConstraintsConfig constraintsConfig = null; if (column.isPrimaryKey()) { PrimaryKey primaryKey = null; for (PrimaryKey pk : getMissingPrimaryKeys()) { if (pk.getTable().getName().equalsIgnoreCase(missingTable.getName())) { primaryKey = pk; } } if (primaryKey == null || primaryKey.getColumnNamesAsList().size() == 1) { constraintsConfig = new ConstraintsConfig(); constraintsConfig.setPrimaryKey(true); constraintsConfig.setPrimaryKeyTablespace(column.getTablespace()); if (primaryKey != null) { constraintsConfig.setPrimaryKeyName(primaryKey.getName()); getMissingPrimaryKeys().remove(primaryKey); } } } if (column.isAutoIncrement()) { columnConfig.setAutoIncrement(true); } if (column.isNullable() != null && !column.isNullable()) { if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); } constraintsConfig.setNullable(false); } // if (column.isUnique()) { // if (constraintsConfig == null) { // constraintsConfig = new ConstraintsConfig(); // } // constraintsConfig.setUnique(true); // } if (constraintsConfig != null) { columnConfig.setConstraints(constraintsConfig); } Object defaultValue = column.getDefaultValue(); if (defaultValue == null) { // do nothing } else if (column.isAutoIncrement()) { // do nothing } else if (defaultValue instanceof Date) { columnConfig.setDefaultValueDate((Date) defaultValue); } else if (defaultValue instanceof Boolean) { columnConfig.setDefaultValueBoolean(((Boolean) defaultValue)); } else if (defaultValue instanceof Number) { columnConfig.setDefaultValueNumeric(((Number) defaultValue)); } else if (defaultValue instanceof DatabaseFunction) { columnConfig.setDefaultValueComputed((DatabaseFunction) defaultValue); } else { columnConfig.setDefaultValue(defaultValue.toString()); } if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } change.addColumn(columnConfig); } changes.add(generateChangeSet(change)); } } private void addUnexpectedTableChanges(List<ChangeSet> changes) { for (Table unexpectedTable : getUnexpectedTables()) { DropTableChange change = new DropTableChange(); change.setTableName(unexpectedTable.getName()); change.setSchemaName(unexpectedTable.getSchema()); changes.add(generateChangeSet(change)); } } private void addInsertDataChanges(List<ChangeSet> changeSets, String dataDir) throws DatabaseException, IOException { try { String schema = referenceSnapshot.getSchema(); for (Table table : referenceSnapshot.getTables()) { List<Change> changes = new ArrayList<Change>(); List<Map> rs = ExecutorService.getInstance().getExecutor(referenceSnapshot.getDatabase()).queryForList(new RawSqlStatement("SELECT * FROM "+ referenceSnapshot.getDatabase().escapeTableName(schema,table.getName()))); if (rs.size() == 0) { continue; } List<String> columnNames = new ArrayList<String>(); for (Column column : table.getColumns()) { columnNames.add(column.getName()); } // if dataOutputDirectory is not null, print out a csv file and use loadData // tag if (dataDir != null) { String fileName = table.getName().toLowerCase() + ".csv"; if (dataDir != null) { fileName = dataDir + "/" + fileName; } File parentDir = new File(dataDir); if (!parentDir.exists()) { parentDir.mkdirs(); } if (!parentDir.isDirectory()) { throw new RuntimeException(parentDir + " is not a directory"); } CSVWriter outputFile = new CSVWriter(new BufferedWriter(new FileWriter(fileName))); String[] dataTypes = new String[columnNames.size()]; String[] line = new String[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { line[i] = columnNames.get(i); } outputFile.writeNext(line); for (Map row : rs) { line = new String[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { Object value = row.get(columnNames.get(i).toUpperCase()); if (dataTypes[i] == null && value != null) { if (value instanceof Number) { dataTypes[i] = "NUMERIC"; } else if (value instanceof Boolean) { dataTypes[i] = "BOOLEAN"; } else if (value instanceof Date) { dataTypes[i] = "DATE"; } else { dataTypes[i] = "STRING"; } } if (value == null) { line[i] = "NULL"; } else { if (value instanceof Date) { line[i] = new ISODateFormat().format(((Date) value)); } else { line[i] = value.toString(); } } } outputFile.writeNext(line); } outputFile.flush(); outputFile.close(); LoadDataChange change = new LoadDataChange(); change.setFile(fileName); change.setEncoding("UTF-8"); change.setSchemaName(schema); change.setTableName(table.getName()); for (int i = 0; i < columnNames.size(); i++) { String colName = columnNames.get(i); LoadDataColumnConfig columnConfig = new LoadDataColumnConfig(); columnConfig.setHeader(colName); columnConfig.setName(colName); columnConfig.setType(dataTypes[i]); change.addColumn(columnConfig); } changes.add(change); } else { // if dataOutputDirectory is null, build and use insert tags for (Map row : rs) { InsertDataChange change = new InsertDataChange(); change.setSchemaName(schema); change.setTableName(table.getName()); // loop over all columns for this row for (int i = 0; i < columnNames.size(); i++) { ColumnConfig column = new ColumnConfig(); column.setName(columnNames.get(i)); Object value = row.get(columnNames.get(i).toUpperCase()); if (value == null) { column.setValue(null); } else if (value instanceof Number) { column.setValueNumeric((Number) value); } else if (value instanceof Boolean) { column.setValueBoolean((Boolean) value); } else if (value instanceof Date) { column.setValueDate((Date) value); } else { // string column.setValue(value.toString().replace("\\","\\\\")); } change.addColumn(column); } // for each row, add a new change // (there will be one group per table) changes.add(change); } } if (changes.size() > 0) { ChangeSet changeSet = generateChangeSet(); for (Change change : changes) { changeSet.addChange(change); } changeSets.add(changeSet); } } } catch (Exception e) { throw new RuntimeException(e); } } }
lgpl-3.0
Javlo/javlo
src/main/java/org/javlo/service/PDFLayout.java
4384
package org.javlo.service; import java.lang.reflect.InvocationTargetException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.javlo.helper.StringHelper; import org.javlo.utils.JSONMap; public class PDFLayout { public static final String REQUEST_KEY = "jv_pdfLayout"; public static final String KEY = "pdfLayout"; public static final String LANDSCAPE = "landscape"; public static final String PORTRAIT = "portrait"; private String height = "29.67cm"; private String width = "21cm"; private String backgroundSize = width; private String pageSize = "A4"; private String fontFamily = "Verdana, Helvetica, sans-serif"; private String fontSize = "11px"; private String marginTop = "1cm"; private String marginBottom = "1cm"; private String marginLeft = "1cm"; private String marginRight = "1cm"; private String orientation = PORTRAIT; private String backgroundImage = null; public static final PDFLayout getInstance(HttpServletRequest request) { PDFLayout outPDFLayout = (PDFLayout) request.getAttribute(KEY); if (outPDFLayout == null) { outPDFLayout = new PDFLayout(); request.setAttribute(KEY, outPDFLayout); } return outPDFLayout; } public static final PDFLayout getInstance(String data) throws IllegalAccessException, InvocationTargetException { PDFLayout outPDFLayout = new PDFLayout(); outPDFLayout.setValues(data); return outPDFLayout; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getWidth() { return width; } public String getContainerWidth() { String ext = null; if (getWidth().endsWith("px") && getMarginLeft().endsWith("px") && getMarginRight().endsWith("px")) { ext = "px"; } if (getWidth().endsWith("%") && getMarginLeft().endsWith("%") && getMarginRight().endsWith("%")) { ext = "%"; } if (getWidth().endsWith("cm") && getMarginLeft().endsWith("cm") && getMarginRight().endsWith("cm")){ ext = "cm"; } if (ext != null) { return (Integer.parseInt(getWidth().replace(ext, ""))-Integer.parseInt(getMarginLeft().replace(ext, "")))-Integer.parseInt(getMarginRight().replace(ext, ""))+ext; } else { return "auto"; } } public void setWidth(String width) { this.width = width; } public String getPageSize() { return pageSize; } public void setPageSize(String pageSize) { this.pageSize = pageSize; } public String getFontFamily() { return fontFamily; } public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; } public String getFontSize() { return fontSize; } public void setFontSize(String fontSize) { this.fontSize = fontSize; } public String getBackgroundImage() { return backgroundImage; } public void setBackgroundImage(String backgroundImage) { this.backgroundImage = backgroundImage; } public String getMarginTop() { return marginTop; } public void setMarginTop(String marginTop) { this.marginTop = marginTop; } public String getMarginBottom() { return marginBottom; } public void setMarginBottom(String marginBottom) { this.marginBottom = marginBottom; } public String getMarginLeft() { return marginLeft; } public void setMarginLeft(String marginLeft) { this.marginLeft = marginLeft; } public String getMarginRight() { return marginRight; } public void setMarginRight(String marginRight) { this.marginRight = marginRight; } public String getOrientation() { return orientation; } public void setOrientation(String orientation) { this.orientation = orientation; } public static String getLandscape() { return LANDSCAPE; } public static String getPortrait() { return PORTRAIT; } public String store() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } public void setValues(String jsonString) throws IllegalAccessException, InvocationTargetException { if (!StringHelper.isEmpty(jsonString)) { JSONMap map = (JSONMap) JSONMap.parse(jsonString); BeanUtils.copyProperties(this, map); } } public String getBackgroundSize() { return backgroundSize; } public void setBackgroundSize(String backgroundSize) { this.backgroundSize = backgroundSize; } }
lgpl-3.0
Godin/sonar
plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/package-info.java
958
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ @ParametersAreNonnullByDefault package org.sonar.xoo.lang; import javax.annotation.ParametersAreNonnullByDefault;
lgpl-3.0
Team-Fruit/SignPicture
src/main/java/com/kamesuta/mc/signpic/gui/GuiMain.java
20461
package com.kamesuta.mc.signpic.gui; import java.awt.Toolkit; import java.awt.datatransfer.Transferable; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.lwjgl.input.Keyboard; import com.kamesuta.mc.bnnwidget.WBase; import com.kamesuta.mc.bnnwidget.WEvent; import com.kamesuta.mc.bnnwidget.WFrame; import com.kamesuta.mc.bnnwidget.WPanel; import com.kamesuta.mc.bnnwidget.component.FunnyButton; import com.kamesuta.mc.bnnwidget.component.MButton; import com.kamesuta.mc.bnnwidget.component.MChatTextField; import com.kamesuta.mc.bnnwidget.component.MPanel; import com.kamesuta.mc.bnnwidget.motion.CompoundMotion; import com.kamesuta.mc.bnnwidget.motion.Easings; import com.kamesuta.mc.bnnwidget.motion.Motion; import com.kamesuta.mc.bnnwidget.position.Area; import com.kamesuta.mc.bnnwidget.position.Coord; import com.kamesuta.mc.bnnwidget.position.Point; import com.kamesuta.mc.bnnwidget.position.R; import com.kamesuta.mc.bnnwidget.render.OpenGL; import com.kamesuta.mc.bnnwidget.render.RenderOption; import com.kamesuta.mc.bnnwidget.render.WRenderer; import com.kamesuta.mc.bnnwidget.var.V; import com.kamesuta.mc.bnnwidget.var.VMotion; import com.kamesuta.mc.signpic.Apis; import com.kamesuta.mc.signpic.Client; import com.kamesuta.mc.signpic.Config; import com.kamesuta.mc.signpic.Log; import com.kamesuta.mc.signpic.asm.ASMDeobfNames; import com.kamesuta.mc.signpic.attr.AttrWriters; import com.kamesuta.mc.signpic.attr.AttrWriters.AttrWriter; import com.kamesuta.mc.signpic.attr.prop.OffsetData.OffsetBuilder; import com.kamesuta.mc.signpic.attr.prop.RotationData.RotationBuilder; import com.kamesuta.mc.signpic.attr.prop.SizeData.SizeBuilder; import com.kamesuta.mc.signpic.entry.Entry; import com.kamesuta.mc.signpic.entry.EntryId; import com.kamesuta.mc.signpic.entry.EntryIdBuilder; import com.kamesuta.mc.signpic.entry.content.Content; import com.kamesuta.mc.signpic.entry.content.ContentId; import com.kamesuta.mc.signpic.entry.content.ContentManager; import com.kamesuta.mc.signpic.gui.GuiMain.SignEditor.MainTextField; import com.kamesuta.mc.signpic.gui.GuiRotation.RefRotation; import com.kamesuta.mc.signpic.gui.file.McUiUpload; import com.kamesuta.mc.signpic.handler.SignHandler; import com.kamesuta.mc.signpic.http.shortening.ShortenerApiUtil; import com.kamesuta.mc.signpic.information.Informations; import com.kamesuta.mc.signpic.mode.CurrentMode; import com.kamesuta.mc.signpic.reflect.lib.ReflectClass; import com.kamesuta.mc.signpic.reflect.lib.ReflectMethod; import com.kamesuta.mc.signpic.util.FileUtilitiy; import com.kamesuta.mc.signpic.util.Sign; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreenBook; import net.minecraft.client.gui.inventory.GuiEditSign; import net.minecraft.client.resources.I18n; import net.minecraft.tileentity.TileEntitySign; public class GuiMain extends WFrame { private @Nonnull EntryId signid = CurrentMode.instance.getEntryId(); private @Nullable SignEditor editor; public void setURL(final @Nonnull String url) { final SignEditor editor = this.editor; if (editor!=null) { editor.signbuilder.setURI(url); editor.field.setText(url); editor.field.apply(); } } public void setId(final @Nonnull EntryId id) { this.signid = id; exportId(); } public @Nonnull EntryId getId() { return this.signid; } public void exportId() { CurrentMode.instance.setEntryId(this.signid); } private @Nonnull GuiSettings settings; { this.settings = new GuiSettings(new R()); } private @Nonnull final ReflectMethod<GuiScreenBook, Void> bookwriter = ReflectClass.fromClass(GuiScreenBook.class).getMethodFromName(ASMDeobfNames.GuiScreenBookPageInsertIntoCurrent, null, void.class, String.class); public GuiMain(final @Nullable GuiScreen parent) { super(parent); } public GuiMain() { } @Override public void initGui() { super.initGui(); Keyboard.enableRepeatEvents(true); OverlayFrame.instance.delegate(); setGuiPauseGame(false); } @Override protected void initWidget() { if (CurrentMode.instance.isMode(CurrentMode.Mode.PLACE)) CurrentMode.instance.setState(CurrentMode.State.PREVIEW, false); CurrentMode.instance.setMode(); add(new WPanel(new R()) { @Override protected void initWidget() { add(new WBase(new R()) { VMotion m = V.pm(0); @Override public void draw(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final float frame, final float popacity, final @Nonnull RenderOption opt) { WRenderer.startShape(); OpenGL.glColor4f(0f, 0f, 0f, this.m.get()); draw(getGuiPosition(pgp)); } protected boolean b = !CurrentMode.instance.isState(CurrentMode.State.PREVIEW); @Override public void update(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p) { if (CurrentMode.instance.isState(CurrentMode.State.PREVIEW)) { if (!this.b) { this.b = true; this.m.stop().add(Easings.easeLinear.move(.2f, 0f)).start(); } } else if (this.b) { this.b = false; this.m.stop().add(Easings.easeLinear.move(.2f, .5f)).start(); } super.update(ev, pgp, p); } @Override public boolean onCloseRequest() { this.m.stop().add(Easings.easeLinear.move(.25f, 0f)).start(); return false; } @Override public boolean onClosing(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point mouse) { return this.m.isFinished(); } }); // final MTab tab = new MTab(new R(Coord.left(0f), Coord.right(75f)), CoordSide.Top, 15, 15); // tab.addTab("Sign", new WidgetBuilder<WCommon>() { // @Override // public WCommon build() { // return GuiMain.this.editor = new SignEditor(new R()); // } // }); // tab.addTab("E", new WPanel(new R())); // add(tab); add(GuiMain.this.editor = new SignEditor(new R(Coord.left(0f), Coord.right(75f)))); final VMotion p = V.am(-65).add(Easings.easeOutBack.move(.25f, 0)).start(); add(new WPanel(new R(Coord.top(0), Coord.right(p), Coord.width(80), Coord.bottom(0))) { @Override protected void initWidget() { float top = -15f; add(new FunnyButton(new R(Coord.right(5), Coord.top(top += 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { CurrentMode.instance.setState(CurrentMode.State.SEE, !CurrentMode.instance.isState(CurrentMode.State.SEE)); return true; } @Override public boolean isHighlight() { return CurrentMode.instance.isState(CurrentMode.State.SEE); } }.setText(I18n.format("signpic.gui.editor.see"))); add(new FunnyButton(new R(Coord.right(5), Coord.top(top += 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { final boolean state = CurrentMode.instance.isState(CurrentMode.State.PREVIEW); CurrentMode.instance.setState(CurrentMode.State.PREVIEW, !state); if (!state) { CurrentMode.instance.setMode(CurrentMode.Mode.SETPREVIEW); requestClose(); } else { if (CurrentMode.instance.isMode(CurrentMode.Mode.SETPREVIEW)) CurrentMode.instance.setMode(); Sign.preview.setVisible(false); } return true; } @Override public boolean isHighlight() { return CurrentMode.instance.isState(CurrentMode.State.PREVIEW); } }.setText(I18n.format("signpic.gui.editor.preview"))); add(new FunnyButton(new R(Coord.right(5), Coord.top(top += 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { McUiUpload.instance.setVisible(!McUiUpload.instance.isVisible()); return true; } @Override public boolean isHighlight() { return McUiUpload.instance.isVisible(); } }.setText(I18n.format("signpic.gui.editor.file"))); add(new MButton(new R(Coord.right(5), Coord.top(top += 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { final SignEditor editor = GuiMain.this.editor; if (editor!=null) Client.openURL(editor.signbuilder.getURI()); return true; } }.setText(I18n.format("signpic.gui.editor.openurl"))); add(new MButton(new R(Coord.right(5), Coord.top(top += 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { try { final Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); FileUtilitiy.transfer(transferable, null); } catch (final Exception e) { Log.notice(I18n.format("signpic.gui.notice.paste.unsupported", e)); } return true; } }.setText(I18n.format("signpic.gui.editor.paste"))); float bottom = 20*3+5; add(new FunnyButton(new R(Coord.right(5), Coord.bottom(bottom -= 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { CurrentMode.instance.setState(CurrentMode.State.CONTINUE, !CurrentMode.instance.isState(CurrentMode.State.CONTINUE)); return true; } @Override public boolean isHighlight() { return CurrentMode.instance.isState(CurrentMode.State.CONTINUE); } }.setText(I18n.format("signpic.gui.editor.continue"))); add(new FunnyButton(new R(Coord.right(5), Coord.bottom(bottom -= 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { CurrentMode.instance.setMode(CurrentMode.Mode.OPTION); CurrentMode.instance.setState(CurrentMode.State.SEE, true); requestClose(); return true; } @Override public boolean isHighlight() { return CurrentMode.instance.isMode(CurrentMode.Mode.OPTION); } }.setText(I18n.format("signpic.gui.editor.option"))); add(new FunnyButton(new R(Coord.right(5), Coord.bottom(bottom -= 20), Coord.left(5), Coord.height(15))) { @Override protected boolean onClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { final Entry entry = CurrentMode.instance.getEntryId().entry(); if (entry.isValid()) { final GuiScreen screen = getParent(); if (screen instanceof GuiChat) { final Content content = entry.getContent(); if (content!=null) { final GuiChat chat = new GuiChat(content.id.getURI()); chat.setWorldAndResolution(mc, (int) width(), (int) height()); setParent(chat); } } if (screen instanceof GuiEditSign) { final GuiEditSign guiEditSign = (GuiEditSign) screen; final TileEntitySign entitySign = SignHandler.guiEditSignTileEntity.get(guiEditSign); entry.id.toEntity(entitySign); } if (screen instanceof GuiScreenBook) { final GuiScreenBook book = (GuiScreenBook) screen; GuiMain.this.bookwriter.invoke(book, entry.id.id()); } } if (!entry.id.isPlaceable()) { final Content content = entry.getContent(); if (content!=null) ShortenerApiUtil.requestShoretning(content.id); } CurrentMode.instance.setMode(CurrentMode.Mode.PLACE); CurrentMode.instance.setState(CurrentMode.State.PREVIEW, true); requestClose(); return true; } @Override public boolean isHighlight() { return CurrentMode.instance.isMode(CurrentMode.Mode.PLACE); } @Override public boolean isEnabled() { return !CurrentMode.instance.isMode(CurrentMode.Mode.PLACE); } }.setText(I18n.format("signpic.gui.editor.place"))); } @Override public boolean onCloseRequest() { p.stop().add(Easings.easeInBack.move(.25f, -65)).start(); return false; } @Override public boolean onClosing(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point mouse) { return p.isFinished(); } }); add(GuiMain.this.settings); add(OverlayFrame.instance.pane); } }); if (Informations.instance.shouldCheck(Config.getConfig().informationJoinBeta.get() ? TimeUnit.HOURS.toMillis(6) : TimeUnit.DAYS.toMillis(1l))) Informations.instance.onlineCheck(null); if (!Config.getConfig().guiExperienced.get()) Config.getConfig().guiExperienced.set(true); } public @Nullable MainTextField getTextField() { if (this.editor!=null) return this.editor.field; return null; } @Override public void onGuiClosed() { super.onGuiClosed(); Keyboard.enableRepeatEvents(false); OverlayFrame.instance.release(); } public static boolean setContentId(final @Nonnull String id) { if (Client.mc.currentScreen instanceof GuiMain) { final GuiMain editor = (GuiMain) Client.mc.currentScreen; editor.setURL(id); return true; } else { final EntryId entryId = CurrentMode.instance.getEntryId(); final EntryIdBuilder signbuilder = new EntryIdBuilder().load(entryId); signbuilder.setURI(id); CurrentMode.instance.setEntryId(signbuilder.build()); return false; } } public static boolean setContentId(final @Nonnull EntryId id) { if (Client.mc.currentScreen instanceof GuiMain) { final GuiMain editor = (GuiMain) Client.mc.currentScreen; editor.setId(id); return true; } else { CurrentMode.instance.setEntryId(id); return false; } } public class SignEditor extends WPanel { private final @Nonnull EntryIdBuilder signbuilder = new EntryIdBuilder().load(getId()); private @Nonnull MainTextField field; private final VMotion mfield = V.am(-15).start(); { this.field = new MainTextField(new R(Coord.left(5), Coord.bottom(this.mfield), Coord.right(5), Coord.height(15))) { @Override public boolean onCloseRequest() { super.onCloseRequest(); SignEditor.this.mfield.stop().add(Easings.easeInBack.move(.25f, -15)).start(); return false; } @Override public boolean onClosing(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point mouse) { return SignEditor.this.mfield.isFinished(); } }; } public SignEditor(final R position) { super(position); } public void export() { setId(this.signbuilder.build()); exportId(); } @Override public void onAdded() { super.onAdded(); this.mfield.stop().add(Easings.easeOutBack.move(.5f, 5)).start(); } @Override protected void initWidget() { add(new GuiSize(new R(Coord.top(5), Coord.left(5), Coord.width(15*8), Coord.height(15*2))) { @Override protected void onUpdate() { export(); } @Override protected @Nonnull SizeBuilder size() { final AttrWriter attr = SignEditor.this.signbuilder.getMeta().getFrame(0); return attr.add(attr.size).size; } }); add(new GuiOffset(new R(Coord.top(15*3+10), Coord.left(5), Coord.width(15*8), Coord.height(15*3))) { @Override protected void onUpdate() { export(); } @Override protected @Nonnull OffsetBuilder offset() { final AttrWriter attr = SignEditor.this.signbuilder.getMeta().getFrame(0); return attr.add(attr.offset).offset; } }); add(new GuiRotation(new R(Coord.top(15*8), Coord.left(5), Coord.width(15*8), Coord.height(15*4)), new RefRotation() { @Override public @Nonnull RotationBuilder rotation() { final AttrWriter attr = SignEditor.this.signbuilder.getMeta().getFrame(0); return attr.add(attr.rotation).rotation; } @Override public boolean isFirst() { return true; } }) { @Override protected void onUpdate() { export(); } }); add(this.field); final VMotion m = V.pm(-1f); add(new WPanel(new R(Coord.top(m), Coord.left(15*8+5), Coord.right(0), Coord.pheight(1f))) { @Override protected void initWidget() { add(new MPanel(new R(Coord.top(5), Coord.left(5), Coord.right(5), Coord.bottom(25))) { { add(new SignPicLabel(new R(Coord.top(5), Coord.left(5), Coord.right(5), Coord.bottom(5)), ContentManager.instance) { @Override public @Nonnull EntryId getEntryId() { return CurrentMode.instance.getEntryId(); } }); } protected boolean b = !CurrentMode.instance.isState(CurrentMode.State.PREVIEW); @Override public void update(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p) { if (CurrentMode.instance.isState(CurrentMode.State.PREVIEW)) { if (!this.b) { this.b = true; m.stop().add(Easings.easeInBack.move(.25f, -1f)).start(); } } else if (this.b) { this.b = false; m.stop().add(Easings.easeOutBack.move(.25f, 0f)).start(); } super.update(ev, pgp, p); } @Override public boolean mouseClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { final Area a = getGuiPosition(pgp); if (a.pointInside(p)) if (Informations.instance.isUpdateRequired()) { GuiMain.this.settings.show(); return true; } return false; } }); } @Override public boolean onCloseRequest() { m.stop().add(Easings.easeInBack.move(.25f, -1f)).start(); return false; } @Override public boolean onClosing(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point mouse) { return m.isFinished(); } }); // add(new GuiVariable(new R(Coord.top(5), Coord.left(15*8+5), Coord.right(5), Coord.bottom(5)), this.signbuilder.getMeta()) { // @Override // protected void onUpdate() { // export(); // } // }); } public class MainTextField extends MChatTextField { public MainTextField(final @Nonnull R position) { super(position); } @Override public void onAdded() { super.onAdded(); setMaxStringLength(Integer.MAX_VALUE); setWatermark(I18n.format("signpic.gui.editor.textfield")); final EntryId id = CurrentMode.instance.getEntryId(); Content content = null; if ((content = id.entry().getContent())!=null) setText(content.id.getID()); } @Override public void onFocusChanged() { apply(); } public void apply() { final EntryId entryId = EntryId.from(getText()); final AttrWriters atb = entryId.getMetaBuilder(); if (atb!=null) SignEditor.this.signbuilder.setMeta(atb); final ContentId cid = entryId.getContentId(); if (cid!=null) { String url = cid.getURI(); setText(url = Apis.instance.replaceURL(url)); SignEditor.this.signbuilder.setURI(url); } else SignEditor.this.signbuilder.setURI(""); export(); if (atb!=null) GuiMain.this.event.bus.post(new PropertyChangeEvent()); } @Override public boolean mouseClicked(final @Nonnull WEvent ev, final @Nonnull Area pgp, final @Nonnull Point p, final int button) { final boolean b = super.mouseClicked(ev, pgp, p, button); final Area a = getGuiPosition(pgp); if (a.pointInside(p)) if (ev.isDoubleClick()) { final String clip = GuiScreen.getClipboardString(); if (clip!=null) setText(clip); } return b; } } } private @Nonnull final CompoundMotion closeCooldown = new CompoundMotion().start(); @Override public void requestClose() { if (this.closeCooldown.isFinished()) { this.closeCooldown.add(Motion.blank(3f)); super.requestClose(); } } }
lgpl-3.0
racodond/sonar-css-plugin
css-frontend/src/main/java/org/sonar/css/model/property/standard/BorderInlineStartWidth.java
1324
/* * SonarQube CSS / SCSS / Less Analyzer * Copyright (C) 2013-2017 David RACODON * mailto: david.racodon@gmail.com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package org.sonar.css.model.property.standard; import org.sonar.css.model.property.StandardProperty; import org.sonar.css.model.property.validator.ValidatorFactory; public class BorderInlineStartWidth extends StandardProperty { public BorderInlineStartWidth() { setExperimental(true); addLinks("http://dev.w3.org/csswg/css-logical-props/#propdef-border-inline-start-width"); addValidators(ValidatorFactory.getBorderWidthValidator()); } }
lgpl-3.0